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
pytorch__pytorch
torch/utils/serialization/config.py
{ "start": 265, "end": 487 }
class ____: mmap: bool = False endianness: _Optional["_LoadEndianess"] = None # MAP_PRIVATE = 2 mmap_flags: int | None = None if sys.platform == "win32" else 2 calculate_storage_offsets: bool = False
load
python
pytorch__pytorch
test/distributed/_composable/test_replicate_with_fsdp.py
{ "start": 1148, "end": 9872 }
class ____(MultiProcessTestCase): @property def world_size(self) -> int: return 4 def init_replicate_tp_mesh(self) -> DeviceMesh: # Prefer to test with >=4 GPUs, but for 2 GPUs, use 2-way TP replicate_size = 2 return init_device_mesh( "cuda", (replica...
ReplicateTest
python
numba__numba
numba/tests/test_nrt.py
{ "start": 9661, "end": 13280 }
class ____(TestCase): def test_issue_with_refct_op_pruning(self): """ GitHub Issue #1244 https://github.com/numba/numba/issues/1244 """ @njit def calculate_2D_vector_mag(vector): x, y = vector return math.sqrt(x ** 2 + y ** 2) @njit d...
TestNRTIssue
python
ApeWorX__ape
src/ape/api/query.py
{ "start": 4277, "end": 4462 }
class ____(_BaseBlockQuery): """ A ``QueryType`` that collects properties of ``BlockAPI`` over a range of blocks between ``start_block`` and ``stop_block``. """
BlockQuery
python
Textualize__textual
tests/test_validation.py
{ "start": 1204, "end": 2338 }
class ____(Validator): def validate(self, value: str) -> ValidationResult: return self.failure() def describe_failure(self, failure: Failure) -> str | None: return "describe_failure" def test_Failure_description_priorities_parameter_only(): number_validator = Number(failure_description="A...
ValidatorWithDescribeFailure
python
joke2k__faker
tests/providers/test_person.py
{ "start": 49914, "end": 54023 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("pl_PL") Faker.seed(0) def test_identity_card_number_checksum(self): assert pl_checksum_identity_card_number(["A", "I", "S", 8, 5, 0, 2, 1, 4]) == 8 assert pl_checksum_identity_card_number(["A", "U", "L", 9, 2, 7,...
TestPlPL
python
apache__airflow
airflow-core/tests/unit/cli/commands/test_api_server_command.py
{ "start": 1169, "end": 12536 }
class ____(_CommonCLIUvicornTestClass): main_process_regexp = r"airflow api-server" @pytest.mark.parametrize( "args", [ pytest.param( ["api-server", "--port", "9092", "--host", "somehost", "--dev"], id="dev mode with port and host", ), ...
TestCliApiServer
python
google__pytype
pytype/tests/test_functions1.py
{ "start": 96, "end": 1962 }
class ____(test_base.BaseTest): """Tests for generators.""" def test_first(self): self.Check(""" def two(): yield 1 yield 2 for i in two(): print(i) """) def test_partial_generator(self): self.Check(""" from functools import partial def f(a,b): ...
TestGenerators
python
walkccc__LeetCode
solutions/884. Uncommon Words from Two Sentences/884.py
{ "start": 0, "end": 198 }
class ____: def uncommonFromSentences(self, A: str, B: str) -> list[str]: count = collections.Counter((A + ' ' + B).split()) return [word for word, freq in count.items() if freq == 1]
Solution
python
huggingface__transformers
tests/utils/test_offline.py
{ "start": 794, "end": 7954 }
class ____(TestCasePlus): @require_torch @unittest.skip("This test is failing on main") # TODO matt/ydshieh, this test needs to be fixed def test_offline_mode(self): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too la...
OfflineTests
python
pypa__warehouse
tests/common/db/packaging.py
{ "start": 3983, "end": 4176 }
class ____(WarehouseFactory): class Meta: model = Role role_name = "Owner" user = factory.SubFactory(UserFactory) project = factory.SubFactory(ProjectFactory)
RoleFactory
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 12211, "end": 12961 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): occurences = helper_functions.get_value("ClassOccurences") min_value = np.iinfo(np.int64).max if len(y.shape) == 2: for i in range(y.shape[1]): for num_occurences in occurences[i].values(): ...
ClassProbabilityMin
python
plotly__plotly.py
plotly/graph_objs/histogram2d/_ybins.py
{ "start": 233, "end": 7476 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram2d" _path_str = "histogram2d.ybins" _valid_props = {"end", "size", "start"} @property def end(self): """ Sets the end value for the y axis bins. The last bin may not end exactly at this value, we increment the...
YBins
python
pypa__warehouse
warehouse/accounts/models.py
{ "start": 12150, "end": 12329 }
class ____(enum.Enum): SpamComplaint = "spam complaint" HardBounce = "hard bounce" SoftBounce = "soft bounce" DomainInvalid = "domain status invalid"
UnverifyReasons
python
pytorch__pytorch
benchmarks/tensorexpr/microbenchmarks.py
{ "start": 180, "end": 9199 }
class ____: def __enter__(self): self.scope = te.KernelScope() def __exit__(self, typ, val, traceback): self.scope = None unary_ops = [ ("sin", torch.sin), ("cos", torch.cos), ("tan", torch.tan), ("asin", torch.asin), ("acos", torch.acos), ("atan", torch.atan), ("s...
kernel_arena_scope
python
wireservice__csvkit
tests/test_convert/test_convert.py
{ "start": 46, "end": 915 }
class ____(unittest.TestCase): def test_guess_fixed(self): self.assertEqual('fixed', convert.guess_format('testdata')) def test_guess_xls(self): self.assertEqual('xls', convert.guess_format('testdata.xls')) def test_guess_xls_uppercase(self): self.assertEqual('xls', convert.guess_...
TestConvert
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 727479, "end": 745285 }
class ____( ColorDef, MarkPropDefGradientstringnull ): r""" FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull schema wrapper. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, and type aggregate : dict, :class...
FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull
python
tensorflow__tensorflow
tensorflow/lite/python/interpreter_test.py
{ "start": 14681, "end": 17278 }
class ____(test_util.TensorFlowTestCase): # Model must have at least 7 bytes to hold model identifier def testTooShortModelContent(self): with self.assertRaisesRegex(ValueError, 'The model is not a valid Flatbuffer buffer'): interpreter_wrapper.Interpreter(model_content=b'...
InterpreterTestErrorPropagation
python
tensorflow__tensorflow
tensorflow/python/ops/linalg/linear_operator_low_rank_update.py
{ "start": 1537, "end": 19968 }
class ____(linear_operator.LinearOperator): """Perturb a `LinearOperator` with a rank `K` update. This operator acts like a [batch] matrix `A` with shape `[B1,...,Bb, M, N]` for some `b >= 0`. The first `b` indices index a batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is an `M x N`...
LinearOperatorLowRankUpdate
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_thumbnail_cleanup.py
{ "start": 434, "end": 5036 }
class ____(test.BaseTest): def setUp(self): super().setUp() self.storage = test.TemporaryStorage() # Create a source image filename = self.create_image(self.storage, "test.jpg") self.source_image_path = self.storage.open(filename).name # Save a test image in both s...
ThumbnailCleanupTest
python
joerick__pyinstrument
test/test_profiler.py
{ "start": 587, "end": 12201 }
class ____: def long_method(self): time.sleep(0.25) @staticmethod def long_static_method(): time.sleep(0.25) @classmethod def long_class_method(cls): time.sleep(0.25) # Tests # def test_collapses_multiple_calls_by_default(): profiler = Profiler() with fake_time...
ClassWithMethods
python
patrick-kidger__equinox
equinox/internal/_noinline.py
{ "start": 8985, "end": 11163 }
class ____: def __init__(self, val): self.val = val def _noinline_mlir(ctx, *dynamic, treedef, static, flatten, **kwargs): assert len(kwargs) == 0 assert flatten.called() dynamic = [_MlirWrapper(x) for x in dynamic] abstract_dynamic = [_MlirWrapper(x) for x in ctx.avals_in] # This is r...
_MlirWrapper
python
apache__airflow
devel-common/src/docs/build_docs.py
{ "start": 6175, "end": 6335 }
class ____(NamedTuple): """Result of building documentation.""" package_name: str log_file_name: Path errors: list[DocBuildError]
BuildDocsResult
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/two_step_game.py
{ "start": 155, "end": 3726 }
class ____(MultiAgentEnv): action_space = Discrete(2) def __init__(self, env_config): super().__init__() self.action_space = Discrete(2) self.state = None self.agent_1 = 0 self.agent_2 = 1 # MADDPG emits action logits instead of actual discrete actions se...
TwoStepGame
python
google__flatbuffers
tests/MyGame/Example/TestEnum.py
{ "start": 92, "end": 146 }
class ____(object): A = 0 B = 1 C = 2
TestEnum
python
python-attrs__attrs
src/attr/exceptions.py
{ "start": 1270, "end": 1443 }
class ____(RuntimeError): """ A class with ``auto_attribs=True`` has a field without a type annotation. .. versionadded:: 17.3.0 """
UnannotatedAttributeError
python
astropy__astropy
astropy/nddata/tests/test_compat.py
{ "start": 3263, "end": 4855 }
class ____(NDDataArray): """ Subclass for test initialization of subclasses in NDData._arithmetic and NDData.convert_unit_to """ def __init__(self, *arg, **kwd): super().__init__(*arg, **kwd) if self.unit is None: raise ValueError("Unit for subclass must be specified") ...
SubNDData
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_pair_values_to_be_equal.py
{ "start": 2178, "end": 14504 }
class ____(ColumnPairMapExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectColumnPairValuesToBeEqual is a \ Column Pair Map Expectation. Column Pair Map Expectations are evaluated for a pair of columns and ask a yes/no question about the row-wise relationship between those two columns. ...
ExpectColumnPairValuesToBeEqual
python
redis__redis-py
redis/backoff.py
{ "start": 1960, "end": 2695 }
class ____(AbstractBackoff): """Full jitter backoff upon failure""" def __init__(self, cap: float = DEFAULT_CAP, base: float = DEFAULT_BASE) -> None: """ `cap`: maximum backoff time in seconds `base`: base backoff time in seconds """ self._cap = cap self._base = ...
FullJitterBackoff
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-minio/llama_index/readers/minio/boto3_client/base.py
{ "start": 378, "end": 5534 }
class ____(BaseReader): """ General reader for any S3 file or directory. A loader that fetches a file or iterates through a directory on minio using boto3. """ def __init__( self, *args: Any, bucket: str, key: Optional[str] = None, prefix: Optional[str] = ""...
BotoMinioReader
python
encode__django-rest-framework
rest_framework/schemas/generators.py
{ "start": 4667, "end": 7995 }
class ____: endpoint_inspector_cls = EndpointEnumerator # 'pk' isn't great as an externally exposed name for an identifier, # so by default we prefer to use the actual model field name for schemas. # Set by 'SCHEMA_COERCE_PATH_PK'. coerce_path_pk = None def __init__(self, title=None, url=None,...
BaseSchemaGenerator
python
django__django
tests/test_utils/test_serializemixin.py
{ "start": 450, "end": 655 }
class ____(SerializeMixin, SimpleTestCase): lockfile = __file__ def test_usage(self): # Running this test ensures that the lock/unlock functions have passed. pass
TestSerializeMixinUse
python
huggingface__transformers
src/transformers/models/lilt/modeling_lilt.py
{ "start": 7825, "end": 13009 }
class ____(nn.Module): def __init__(self, config, layer_idx=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the num...
LiltSelfAttention
python
jackfrued__Python-100-Days
Day31-35/code/test_example01.py
{ "start": 417, "end": 1520 }
class ____(TestCase): """测试查找函数的测试用例""" # 执行每个测试函数之前要执行的方法 def setUp(self): self.data1 = [35, 97, 12, 68, 55, 73, 81, 40] self.data2 = [12, 35, 40, 55, 68, 73, 81, 97] # 执行每个测试函数之后要执行的方法 def tearDown(self): pass def test_seq_search(self): """测试顺序查找""" s...
TestExample01
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 57844, "end": 59270 }
class ____: @mock.patch(VERTEX_AI_PATH.format("dataset.Dataset.to_dict")) @mock.patch(VERTEX_AI_PATH.format("dataset.DatasetHook")) def test_execute(self, mock_hook, to_dict_mock): page_token = "page_token" page_size = 42 filter = "filter" read_mask = "read_mask" orde...
TestVertexAIListDatasetsOperator
python
fastai__fastai
fastai/vision/core.py
{ "start": 3814, "end": 4953 }
class ____(Image.Image, metaclass=BypassNewMeta): "Base class for a Pillow `Image` that can show itself and convert to a Tensor" _bypass_type=Image.Image _show_args = {'cmap':'viridis'} _open_args = {'mode': 'RGB'} @classmethod def create(cls, fn:Path|str|Tensor|ndarray|bytes|Image.Image, **kwar...
PILBase
python
pennersr__django-allauth
allauth/socialaccount/providers/vimeo_oauth2/views.py
{ "start": 269, "end": 1060 }
class ____(OAuth2Adapter): provider_id = "vimeo_oauth2" access_token_url = "https://api.vimeo.com/oauth/access_token" # nosec authorize_url = "https://api.vimeo.com/oauth/authorize" profile_url = "https://api.vimeo.com/me/" def complete_login(self, request, app, token, **kwargs): resp = ( ...
VimeoOAuth2Adapter
python
ansible__ansible
lib/ansible/module_utils/facts/network/sunos.py
{ "start": 4650, "end": 4752 }
class ____(NetworkCollector): _fact_class = SunOSNetwork _platform = 'SunOS'
SunOSNetworkCollector
python
google__jax
examples/examples_test.py
{ "start": 1293, "end": 2086 }
class ____(parameterized.TestCase): def setUp(self): self.rng = np.random.default_rng(zlib.adler32(self.__class__.__name__.encode())) def testKernelRegressionGram(self): n, d = 100, 20 xs = self.rng.normal(size=(n, d)) kernel = lambda x, y: jnp.dot(x, y) np.testing.assert_allclose(kernel_lsq.g...
ExamplesTest
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/utils/mixins.py
{ "start": 2227, "end": 2383 }
class ____(Protocol): """Protocol for on_kill method.""" _hook: DatabricksHook log: Logger statement_id: str task_id: str
OnKillHasFields
python
dagster-io__dagster
examples/project_fully_featured/project_fully_featured/assets/dbt/hacker_news.py
{ "start": 223, "end": 739 }
class ____(DagsterDbtTranslator): def get_asset_key(self, dbt_resource_props: Mapping[str, Any]) -> AssetKey: return super().get_asset_key(dbt_resource_props).with_prefix("snowflake") @dbt_assets( manifest=dbt_project.manifest_path, io_manager_key="warehouse_io_manager", dagster_dbt_translator...
CustomDagsterDbtTranslator
python
django__django
tests/admin_inlines/tests.py
{ "start": 74820, "end": 104247 }
class ____(AdminSeleniumTestCase): available_apps = ["admin_inlines"] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) @screenshot_cases(["desktop_size", "mobile_size", "dark"...
SeleniumTests
python
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 11617, "end": 12123 }
class ____(nn.Module): def __init__(self, config: ViTMSNConfig): super().__init__() self.attention = ViTMSNSelfAttention(config) self.output = ViTMSNSelfOutput(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: self_attn_output, _ = self.attention(hidden_sta...
ViTMSNAttention
python
apache__airflow
providers/ftp/src/airflow/providers/ftp/operators/ftp.py
{ "start": 7699, "end": 8283 }
class ____(FTPFileTransmitOperator): """ FTPSFileTransmitOperator for transferring files from remote host to local or vice a versa. This operator uses an FTPSHook to open ftps transport channel that serve as basis for file transfer. .. seealso:: For more information on how to use this operator...
FTPSFileTransmitOperator
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 927, "end": 985 }
class ____: # trailing comment pass
TestTrailingComment2
python
Textualize__textual
docs/examples/styles/outline_all.py
{ "start": 100, "end": 886 }
class ____(App): CSS_PATH = "outline_all.tcss" def compose(self): yield Grid( Label("ascii", id="ascii"), Label("blank", id="blank"), Label("dashed", id="dashed"), Label("double", id="double"), Label("heavy", id="heavy"), Label("hi...
AllOutlinesApp
python
huggingface__transformers
src/transformers/models/idefics2/modeling_idefics2.py
{ "start": 1802, "end": 3582 }
class ____(ModelOutput): r""" last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, ...
Idefics2BaseModelOutputWithPast
python
has2k1__plotnine
plotnine/_utils/__init__.py
{ "start": 26743, "end": 31515 }
class ____: """ Ignore Warnings Context Manager Wrap around warnings.catch_warnings to make ignoring warnings easier. Parameters ---------- *categories : tuple Warning categories to ignore e.g UserWarning, FutureWarning, RuntimeWarning, ... """ _cm: warnings.catch_...
ignore_warnings
python
numpy__numpy
numpy/_core/tests/test_conversion_utils.py
{ "start": 3749, "end": 4016 }
class ____(StringConverterTestCase): """ Tests of PyArray_SearchsideConverter """ conv = mt.run_searchside_converter def test_valid(self): self._check('left', 'NPY_SEARCHLEFT') self._check('right', 'NPY_SEARCHRIGHT')
TestSearchsideConverter
python
getsentry__sentry
src/sentry/api/endpoints/organization_traces.py
{ "start": 2446, "end": 2749 }
class ____(TypedDict): project: str | None sdkName: str | None start: int end: int sliceStart: int sliceEnd: int sliceWidth: int kind: Literal["project", "missing", "other"] duration: int isRoot: bool components: NotRequired[list[tuple[int, int]]]
TraceInterval
python
pytorch__pytorch
torch/multiprocessing/spawn.py
{ "start": 620, "end": 973 }
class ____(Exception): __slots__ = ["error_index", "error_pid"] def __init__(self, msg: str, error_index: int, pid: int): super().__init__(msg) self.msg = msg self.error_index = error_index self.pid = pid def __reduce__(self): return type(self), (self.msg, self.erro...
ProcessException
python
huggingface__transformers
tests/models/efficientloftr/test_image_processing_efficientloftr.py
{ "start": 5010, "end": 25120 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = EfficientLoFTRImageProcessor if is_vision_available() else None fast_image_processing_class = EfficientLoFTRImageProcessorFast if is_torchvision_available() else None def setUp(self) -> None: super().setUp() s...
EfficientLoFTRImageProcessingTest
python
Pylons__pyramid
tests/test_integration.py
{ "start": 15471, "end": 15767 }
class ____(IntegrationBase, unittest.TestCase): # test bug reported by delijati 2010/2/3 (http://pastebin.com/d4cc15515) package = 'tests.pkgs.restbugapp' def test_it(self): res = self.testapp.get('/pet', status=200) self.assertEqual(res.body, b'gotten')
TestRestBugApp
python
plotly__plotly.py
tests/test_optional/optional_utils.py
{ "start": 555, "end": 4298 }
class ____(object): """Provides some helper functions to make testing easier.""" def _format_path(self, path): str_path = [repr(p) for p in path] return "[" + "][".join(sp for sp in str_path) + "]" def assert_fig_equal(self, d1, d2, msg=None, ignore=["uid"]): """ Helper fun...
NumpyTestUtilsMixin
python
fastai__fastai
fastai/data/transforms.py
{ "start": 8668, "end": 9112 }
class ____(): "Label `item` with regex `pat`." def __init__(self, pat, match=False): self.pat = re.compile(pat) self.matcher = self.pat.match if match else self.pat.search def __call__(self, o): o = str(o).replace(os.sep, posixpath.sep) res = self.matcher(o) assert r...
RegexLabeller
python
PyCQA__pylint
tests/functional/a/arguments_renamed.py
{ "start": 1637, "end": 1914 }
class ____: def test1(self, arg, barg): print(f"Argument values are {arg} and {barg}") def test2(self, arg, barg): print(f"Argument values are {arg} and {barg}!") def test3(self, arg1, arg2): print(f"arguments: {arg1} {arg2}")
ParentDefaults
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 18905, "end": 19153 }
class ____(models.Model): title = models.CharField(max_length=20, verbose_name='verbose title') text = models.CharField(max_length=100) @property def description(self): return self.title + ": " + self.text
OrderingFilterModel
python
walkccc__LeetCode
solutions/1433. Check If a String Can Break Another String/1433.py
{ "start": 0, "end": 548 }
class ____: def checkIfCanBreak(self, s1: str, s2: str) -> bool: count1 = collections.Counter(s1) count2 = collections.Counter(s2) def canBreak(count1: dict[str, int], count2: dict[str, int]) -> bool: """Returns True if count1 can break count2.""" diff = 0 for c in string.ascii_lowercas...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1022481, "end": 1023269 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateEnterpriseMembersCanInviteCollaboratorsSetting """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "message") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") ...
UpdateEnterpriseMembersCanInviteCollaboratorsSettingPayload
python
pypa__setuptools
_distutils_hack/__init__.py
{ "start": 2658, "end": 2845 }
class ____: def __init__(self, *patterns) -> None: self._patterns = patterns def match(self, string): return all(pat in string for pat in self._patterns)
_TrivialRe
python
apache__airflow
task-sdk/src/airflow/sdk/exceptions.py
{ "start": 7121, "end": 7225 }
class ____(AirflowException): """Raise when there is a timeout on the deferral."""
TaskDeferralTimeout
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 88875, "end": 93806 }
class ____: x1 = np.array([[0, 2], [1, 1], [2, 0]]).T res1 = np.array([[1., -1.], [-1., 1.]]) x2 = np.array([0.0, 1.0, 2.0], ndmin=2) frequencies = np.array([1, 4, 1]) x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T res2 = np.array([[0.4, -0.4], [-0.4, 0.4]]) unit_frequen...
TestCov
python
astropy__astropy
astropy/table/groups.py
{ "start": 7356, "end": 10558 }
class ____(BaseGroups): def __init__(self, parent_column, indices=None, keys=None): self.parent_column = parent_column # parent Column self.parent_table = parent_column.info.parent_table self._indices = indices self._keys = keys @property def indices(self): # If the...
ColumnGroups
python
huggingface__transformers
src/transformers/models/reformer/modeling_reformer.py
{ "start": 12106, "end": 12690 }
class ____(nn.Module): """Constructs conventional position embeddings of shape `[max_pos_embeddings, hidden_size]`.""" def __init__(self, config): super().__init__() self.dropout = config.hidden_dropout_prob self.embedding = nn.Embedding(config.max_position_embeddings, config.hidden_siz...
PositionEmbeddings
python
ray-project__ray
rllib/evaluation/collectors/agent_collector.py
{ "start": 1276, "end": 30961 }
class ____: """Collects samples for one agent in one trajectory (episode). The agent may be part of a multi-agent environment. Samples are stored in lists including some possible automatic "shift" buffer at the beginning to be able to save memory when storing things like NEXT_OBS, PREV_REWARDS, etc...
AgentCollector
python
allegroai__clearml
clearml/automation/cloud_driver.py
{ "start": 1381, "end": 6568 }
class ____(ABC): # git git_user = attr.ib() git_pass = attr.ib() # clearml extra_clearml_conf = attr.ib() api_server = attr.ib() web_server = attr.ib() files_server = attr.ib() access_key = attr.ib() secret_key = attr.ib() auth_token = attr.ib() # Other extra_vm_bas...
CloudDriver
python
kamyu104__LeetCode-Solutions
Python/construct-quad-tree.py
{ "start": 324, "end": 1336 }
class ____(object): def construct(self, grid): """ :type grid: List[List[int]] :rtype: Node """ def dfs(grid, x, y, l): if l == 1: return Node(grid[x][y] == 1, True, None, None, None, None) half = l // 2 topLeftNode = dfs(gr...
Solution
python
PrefectHQ__prefect
src/prefect/_internal/compatibility/starlette.py
{ "start": 237, "end": 1836 }
class ____: """ Compatibility wrapper that maintains old status code names while using new ones where available. Maps these renamed codes from RFC 9110: - HTTP_422_UNPROCESSABLE_ENTITY -> HTTP_422_UNPROCESSABLE_CONTENT - HTTP_413_REQUEST_ENTITY_TOO_LARGE -> HTTP_413_CONTENT_TOO_LARGE - HTTP_414...
_StatusCompatibility
python
huggingface__transformers
tests/models/qwen3_omni_moe/test_modeling_qwen3_omni_moe.py
{ "start": 9606, "end": 24912 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `Qwen3OmniMoeThinkerForConditionalGeneration`. """ all_model_classes = (Qwen3OmniMoeThinkerForConditionalGeneration,) if is_torch_available() else () all_generative_model_classes = (Qwen3OmniMoeThinkerForCo...
Qwen3OmniMoeThinkerForConditionalGenerationModelTest
python
getsentry__sentry
src/sentry/ingest/billing_metrics_consumer.py
{ "start": 1053, "end": 4656 }
class ____(ProcessingStrategy[KafkaPayload]): """A metrics consumer that generates an accepted outcome for each processed (as opposed to indexed) transaction or span, processing a bucket at a time. The transaction / span count is directly taken from the `c:transactions/usage@none` or `c:spans/usage@none` co...
BillingTxCountMetricConsumerStrategy
python
realpython__materials
python-self-type/stack_typevar.py
{ "start": 77, "end": 552 }
class ____: def __init__(self) -> None: self.items: list[Any] = [] def push(self: TStack, item: Any) -> TStack: self.items.append(item) return self def pop(self) -> Any: if self.__bool__(): return self.items.pop() else: raise ValueError("Stac...
Stack
python
django__django
tests/model_fields/models.py
{ "start": 15466, "end": 15783 }
class ____(models.Model): field = models.UUIDField() field_copy = models.GeneratedField( expression=F("field"), output_field=models.UUIDField(), db_persist=True, ) class Meta: required_db_features = {"supports_stored_generated_columns"}
GeneratedModelFieldWithConverters
python
pandas-dev__pandas
pandas/tests/frame/methods/test_infer_objects.py
{ "start": 91, "end": 1241 }
class ____: def test_infer_objects(self): # GH#11221 df = DataFrame( { "a": ["a", 1, 2, 3], "b": ["b", 2.0, 3.0, 4.1], "c": [ "c", datetime(2016, 1, 1), datetime(2016, 1, 2), ...
TestInferObjects
python
getsentry__sentry
src/sentry/testutils/hybrid_cloud.py
{ "start": 3788, "end": 5943 }
class ____: alias: str def __init__(self, alias: str): self.alias = alias def __call__(self, execute: Callable[..., Any], *params: Any) -> Any: if not in_test_transaction_enforcement.enabled: return execute(*params) open_transactions = simulated_transaction_watermarks....
EnforceNoCrossTransactionWrapper
python
django__django
django/contrib/postgres/lookups.py
{ "start": 1856, "end": 1991 }
class ____(PostgresOperatorLookup): lookup_name = "trigram_strict_word_similar" postgres_operator = "%%>>"
TrigramStrictWordSimilar
python
pydata__xarray
xarray/core/variable.py
{ "start": 101430, "end": 116932 }
class ____(Variable): """Wrapper for accommodating a pandas.Index in an xarray.Variable. IndexVariable preserve loaded values in the form of a pandas.Index instead of a NumPy array. Hence, their values are immutable and must always be one- dimensional. They also have a name property, which is the ...
IndexVariable
python
pytest-dev__pytest
doc/en/example/fixtures/test_fixtures_order_autouse_temp_effects.py
{ "start": 480, "end": 639 }
class ____: def test_req(self, order, c1): assert order == ["c1"] def test_no_req(self, order): assert order == []
TestClassWithoutAutouse
python
Textualize__textual
src/textual/css/model.py
{ "start": 492, "end": 792 }
class ____(Enum): """Type of selector.""" UNIVERSAL = 1 """i.e. * operator""" TYPE = 2 """A CSS type, e.g Label""" CLASS = 3 """CSS class, e.g. .loaded""" ID = 4 """CSS ID, e.g. #main""" NESTED = 5 """Placeholder for nesting operator, i.e &"""
SelectorType
python
psf__requests
tests/testserver/server.py
{ "start": 412, "end": 3845 }
class ____(threading.Thread): """Dummy server using for unit testing""" WAIT_EVENT_TIMEOUT = 5 def __init__( self, handler=None, host="localhost", port=0, requests_to_handle=1, wait_to_close_event=None, ): super().__init__() self.handler...
Server
python
squidfunk__mkdocs-material
material/plugins/search/plugin.py
{ "start": 13172, "end": 20510 }
class ____(HTMLParser): """ This parser divides the given string of HTML into a list of sections, each of which are preceded by a h1-h6 level heading. A white- and blacklist of tags dictates which tags should be preserved as part of the index, and which should be ignored in their entirety. """ ...
Parser
python
walkccc__LeetCode
solutions/2109. Adding Spaces to a String/2109.py
{ "start": 0, "end": 273 }
class ____: def addSpaces(self, s: str, spaces: list[int]) -> str: ans = [] j = 0 # spaces' index for i, c in enumerate(s): if j < len(spaces) and i == spaces[j]: ans.append(' ') j += 1 ans.append(c) return ''.join(ans)
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 644231, "end": 644726 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("is_author", "is_commenter", "reviewer") is_author = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="isAuthor" ) is_commenter = sgqlc.types.Field( ...
SuggestedReviewer
python
huggingface__transformers
tests/models/paligemma2/test_modeling_paligemma2.py
{ "start": 5871, "end": 10743 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `PaliGemmaForConditionalGeneration`. """ all_model_classes = (PaliGemmaForConditionalGeneration,) if is_torch_available() else () pipeline_model_mapping = {"image-text-to-text": PaliGemmaForConditionalGener...
PaliGemma2ForConditionalGenerationModelTest
python
getsentry__sentry
src/sentry/web/frontend/out.py
{ "start": 338, "end": 721 }
class ____(View): def get(self, request: Request) -> HttpResponseBase: if not is_self_hosted(): raise Http404 install_id = options.get("sentry:install-id") if install_id: query = "?install_id=" + install_id else: query = "" return HttpResp...
OutView
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 243156, "end": 258205 }
class ____(ConditionalStringFieldDef): r""" ConditionalPredicateStringFieldDef schema wrapper. Parameters ---------- test : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :class:`LogicalOrPredicate`, :clas...
ConditionalPredicateStringFieldDef
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py
{ "start": 1057, "end": 1155 }
class ____(enum.Enum): A = enum.auto(), 0 B = enum.auto(), 1 C = enum.auto(), 0
FakeEnum12
python
huggingface__transformers
src/transformers/models/emu3/modular_emu3.py
{ "start": 11979, "end": 12207 }
class ____(SiglipAttention): def __init__(self, config: Emu3VQVAEConfig): super().__init__(config) # for compatibility with the attention interface self.num_key_value_groups = 1
Emu3VQVAEAttentionBlock
python
kamyu104__LeetCode-Solutions
Python/integer-to-roman.py
{ "start": 29, "end": 644 }
class ____(object): def intToRoman(self, num): """ :type num: int :rtype: str """ numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", \ 10: "X", 40: "XL", 50: "L", 90: "XC", \ 100: "C", 400: "CD", 500: "D", 900: "CM", \ ...
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_bash_code_execution_tool_result_block.py
{ "start": 537, "end": 689 }
class ____(BaseModel): content: Content tool_use_id: str type: Literal["bash_code_execution_tool_result"]
BetaBashCodeExecutionToolResultBlock
python
wandb__wandb
wandb/sdk/internal/tb_watcher.py
{ "start": 12121, "end": 12513 }
class ____: """An event wrapper to enable priority queueing.""" def __init__(self, event: "ProtoEvent", namespace: Optional[str]): self.event = event self.namespace = namespace self.created_at = time.time() def __lt__(self, other: "Event") -> bool: if self.event.wall_time <...
Event
python
apache__airflow
providers/atlassian/jira/tests/unit/atlassian/jira/notifications/test_jira.py
{ "start": 1247, "end": 4459 }
class ____: @mock.patch.object(JiraHook, "get_conn") def test_jira_notifier(self, mock_jira_hook, create_dag_without_db): notifier = send_jira_notification( jira_conn_id="jira_default", project_id=10000, description="Test operator failed", summary="Test Ji...
TestJiraNotifier
python
spack__spack
lib/spack/spack/relocate_text.py
{ "start": 11357, "end": 11827 }
class ____(BinaryTextReplaceError): def __init__(self, old, new, full_old_string): # Just interpolate binary string to not risk issues with invalid unicode, which would be # really bad user experience: error in error. We have no clue if we actually deal with a # real C-string nor what encodi...
CannotShrinkCString
python
hyperopt__hyperopt
hyperopt/mongoexp.py
{ "start": 4698, "end": 4795 }
class ____(Exception): """ Exception for telling mongo_worker loop to quit """
Shutdown
python
marshmallow-code__apispec
tests/schemas.py
{ "start": 1878, "end": 1929 }
class ____(fields.Integer): pass
CustomIntegerField
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_abc_inheritance.py
{ "start": 1022, "end": 9826 }
class ____(fixtures.MappedTest): __requires__ = ("foreign_key_cycles_w_cascade",) @classmethod def define_tables(cls, metadata): parent, child, direction = cls.parent, cls.child, cls.direction ta = ["a", metadata] ta.append( Column( "id", ...
ABCTest
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 64963, "end": 72495 }
class ____: def test_not_validity(self): with pytest.raises(TypeError): x509.PrivateKeyUsagePeriod("notValidBefore", "notValidAfter") # type:ignore[arg-type] def test_repr(self): period = x509.PrivateKeyUsagePeriod( not_before=datetime.datetime(2012, 1, 1), ...
TestPrivateKeyUsagePeriodExtension
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 104152, "end": 104727 }
class ____(TestCase): def test_graph_break(self): @nested_compile_region def gn(x): torch._dynamo.graph_break() return torch.cos(x) def fn(x): return gn(x) x = torch.randn(8, 8, requires_grad=True) with self.assertRaisesRegex( ...
NegativeTesting
python
tensorflow__tensorflow
tensorflow/python/types/core.py
{ "start": 6298, "end": 13383 }
class ____(Callable, metaclass=abc.ABCMeta): """Base class for polymorphic graph functions. Graph functions are Python callable objects that dispatch calls to a TensorFlow graph. Polymorphic graph functions can be backed by multiple TF graphs, and automatically select the appropriate specialization based on th...
PolymorphicFunction
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 1621, "end": 2101 }
class ____(AbstractTemplate): def generic(self, args, kws): # For ordered comparisons, units must be compatible left, right = args if not all(isinstance(tp, types.NPTimedelta) for tp in args): return if (npdatetime_helpers.can_cast_timedelta_units(left.unit, right.unit) ...
TimedeltaOrderedCmpOp
python
PyCQA__pylint
pylint/utils/pragma_parser.py
{ "start": 3110, "end": 5052 }
class ____(PragmaParserError): """Thrown in case the pragma is invalid.""" def parse_pragma(pylint_pragma: str) -> Generator[PragmaRepresenter]: action: str | None = None messages: list[str] = [] assignment_required = False previous_token = "" for mo in re.finditer(TOK_REGEX, pylint_pragma): ...
InvalidPragmaError