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
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 15266, "end": 16674 }
class ____(PreTrainedModel): config: ViTMSNConfig base_model_prefix = "vit" main_input_name = "pixel_values" input_modalities = ("image",) supports_gradient_checkpointing = True _no_split_modules = ["ViTMSNAttention", "ViTMSNSdpaAttention"] _supports_sdpa = True _supports_flash_attn = Tr...
ViTMSNPreTrainedModel
python
pandas-dev__pandas
asv_bench/benchmarks/join_merge.py
{ "start": 10963, "end": 11984 }
class ____: params = [ [ ("ns", "ns"), ("ms", "ms"), ("ns", "ms"), ], [None, "Europe/Brussels"], [True, False], ] param_names = ["units", "tz", "monotonic"] def setup(self, units, tz, monotonic): unit_left, unit_right = units ...
MergeDatetime
python
anthropics__anthropic-sdk-python
src/anthropic/lib/bedrock/_beta_messages.py
{ "start": 496, "end": 1376 }
class ____(SyncAPIResource): create = FirstPartyMessagesAPI.create @cached_property def with_raw_response(self) -> MessagesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the the raw response object instead of the parsed content. ...
Messages
python
numba__numba
numba/tests/test_datamodel.py
{ "start": 1782, "end": 1873 }
class ____(test_factory()): fe_type = types.Array(types.int32, 0, 'C')
Test0DArrayOfInt32
python
pandas-dev__pandas
pandas/tests/frame/test_arithmetic.py
{ "start": 43314, "end": 74927 }
class ____: def test_frame_add_tz_mismatch_converts_to_utc(self): rng = pd.date_range("1/1/2011", periods=10, freq="h", tz="US/Eastern") df = DataFrame( np.random.default_rng(2).standard_normal(len(rng)), index=rng, columns=["a"] ) df_moscow = df.tz_convert("Europe/Mosco...
TestFrameArithmeticUnsorted
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/typing_extensions.py
{ "start": 75379, "end": 134499 }
class ____(typing._Final, _root=True): __slots__ = ('_name', '__doc__', '_getitem') def __init__(self, getitem): self._getitem = getitem self._name = getitem.__name__ self.__doc__ = getitem.__doc__ def __getattr__(self, item): if item in {'__name__', '__qualname__'}: ...
_SpecialForm
python
pypa__warehouse
tests/common/db/organizations.py
{ "start": 5658, "end": 5791 }
class ____(WarehouseFactory): class Meta: model = Team.Event source = factory.SubFactory(TeamFactory)
TeamEventFactory
python
viewflow__viewflow
viewflow/workflow/flow/views/mixins.py
{ "start": 2299, "end": 2770 }
class ____(object): """List of templates for a process view.""" template_filename = None def get_template_names(self): if self.template_name is None: opts = self.flow_class.instance return ( f"{opts.app_label}/{opts.flow_label}/{self.template_filename}", ...
ProcessViewTemplateNames
python
PyCQA__flake8
src/flake8/plugins/pyflakes.py
{ "start": 2174, "end": 3894 }
class ____(pyflakes.checker.Checker): """Subclass the Pyflakes checker to conform with the flake8 API.""" with_doctest = False def __init__(self, tree: ast.AST, filename: str) -> None: """Initialize the PyFlakes plugin with an AST tree and filename.""" super().__init__( tree, f...
FlakesChecker
python
eventlet__eventlet
tests/hub_test.py
{ "start": 7976, "end": 8780 }
class ____(tests.LimitedTestCase): TEST_TIMEOUT = 10 def test_block_detect(self): def look_im_blocking(): import time time.sleep(2) from eventlet import debug debug.hub_blocking_detection(True) gt = eventlet.spawn(look_im_blocking) self.assertRais...
TestHubBlockingDetector
python
pytorch__pytorch
torch/_inductor/ops_handler.py
{ "start": 34563, "end": 34947 }
class ____(NoopHandler): def __init__(self, device: Optional[torch.device]): self.device = device def constant(self, value: Any, dtype: torch.dtype) -> torch._inductor.ir.Constant: from torch._inductor import ir return ir.Constant( value=value, dtype=dtype, device=self.devi...
ExtractConstantsHandler
python
joke2k__faker
faker/providers/currency/de_AT/__init__.py
{ "start": 48, "end": 293 }
class ____(CurrencyProvider): price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"] def pricetag(self) -> str: return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}\N{EURO SIGN}"
Provider
python
tox-dev__tox
src/tox/report.py
{ "start": 739, "end": 2980 }
class ____(local): """A thread local variable that inherits values from its parent.""" _ident_to_data: ClassVar[dict[int | None, str]] = {} def __init__(self, out_err: OutErr) -> None: self.name = self._ident_to_data.get(getattr(current_thread(), "parent_ident", None), "ROOT") self.out_err...
_LogThreadLocal
python
ray-project__ray
python/ray/train/v2/_internal/execution/controller/state.py
{ "start": 5142, "end": 5406 }
class ____(TrainControllerState): def __init__( self, training_failed_error: TrainingFailedError, ): super().__init__(state_type=TrainControllerStateType.ERRORED) self.training_failed_error = training_failed_error
ErroredState
python
getsentry__sentry
tests/sentry/event_manager/test_event_manager.py
{ "start": 137311, "end": 163816 }
class ____(TestCase): def setUp(self) -> None: self.environment1 = Environment.get_or_create(self.project, "prod") self.environment2 = Environment.get_or_create(self.project, "staging") self.timestamp = float(int(time() - 300)) self.redis_client = get_redis_client_for_ds() def m...
DSLatestReleaseBoostTest
python
numpy__numpy
numpy/_core/code_generators/genapi.py
{ "start": 3934, "end": 4601 }
class ____: def __init__(self, version): """ Version should be the normal NumPy version, e.g. "1.25" """ major, minor = version.split(".") self.version = f"NPY_{major}_{minor}_API_VERSION" def __str__(self): # Used by version hashing: return self.version def add_gua...
MinVersion
python
django__django
tests/template_tests/syntax_tests/test_partials.py
{ "start": 1384, "end": 24053 }
class ____(SimpleTestCase): libraries = {"bad_tag": "template_tests.templatetags.bad_tag"} @setup({name: gen_partial_template(name) for name in valid_partialdef_names}) def test_valid_partialdef_names(self): for template_name in valid_partialdef_names: with self.subTest(template_name=te...
PartialTagTests
python
pandas-dev__pandas
pandas/io/pytables.py
{ "start": 163323, "end": 165471 }
class ____(AppendableFrameTable): """a table that read/writes the generic pytables table format""" pandas_kind = "frame_table" table_type = "generic_table" ndim = 2 obj_type = DataFrame levels: list[Hashable] @property def pandas_type(self) -> str: return self.pandas_kind ...
GenericTable
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/query_constructor/parser.py
{ "start": 1799, "end": 8560 }
class ____(Transformer): """Transform a query string into an intermediate representation.""" def __init__( self, *args: Any, allowed_comparators: Sequence[Comparator] | None = None, allowed_operators: Sequence[Operator] | None = None, allowed_attributes: Sequence[str] | ...
QueryTransformer
python
ray-project__ray
python/ray/train/v2/_internal/execution/checkpoint/checkpoint_manager.py
{ "start": 2346, "end": 16381 }
class ____(_CheckpointManager, ReportCallback, WorkerGroupCallback): def __init__( self, checkpoint_config: CheckpointConfig, storage_context: StorageContext, ): self._storage_context = storage_context self._checkpoint_config = checkpoint_config # This tracks the...
CheckpointManager
python
pytorch__pytorch
test/functorch/dim/test_getsetitem.py
{ "start": 171, "end": 8171 }
class ____(TestCase): """Comprehensive tests for first-class dimension indexing operations.""" def setUp(self): super().setUp() """Set up common test fixtures.""" self.batch, self.height, self.width = dims(3) def test_basic_dim_indexing(self): """Test basic indexing with a ...
TestGetSetItem
python
scipy__scipy
scipy/io/_idl.py
{ "start": 17887, "end": 27000 }
class ____(dict): ''' A case-insensitive dictionary with access via item, attribute, and call notations: >>> from scipy.io._idl import AttrDict >>> d = AttrDict() >>> d['Variable'] = 123 >>> d['Variable'] 123 >>> d.Variable 123 >>> d.variable ...
AttrDict
python
numpy__numpy
benchmarks/benchmarks/bench_io.py
{ "start": 2084, "end": 3113 }
class ____(Benchmark): # benchmarks for np.loadtxt comment handling # when reading in CSV files params = [10, int(1e2), int(1e4), int(1e5)] param_names = ['num_lines'] def setup(self, num_lines): data = ['1,2,3 # comment'] * num_lines # unfortunately, timeit will only run setup() ...
LoadtxtCSVComments
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta_error_response.py
{ "start": 255, "end": 378 }
class ____(BaseModel): error: BetaError request_id: Optional[str] = None type: Literal["error"]
BetaErrorResponse
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 4125, "end": 5507 }
class ____(util.MdCase): """Test title cases.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'auto_title': True, "auto_title_map": { "Python Console Session": "Python" } } } ...
TestHighlightAutoTitleOverride
python
apache__airflow
airflow-core/tests/unit/always/test_connection.py
{ "start": 2983, "end": 32728 }
class ____: def setup_method(self): self.patcher = mock.patch("airflow.models.connection.mask_secret", autospec=True) self.mask_secret = self.patcher.start() def teardown_method(self): self.patcher.stop() @conf_vars({("core", "fernet_key"): ""}) def test_connection_extra_no_enc...
TestConnection
python
getsentry__sentry
src/sentry/flags/endpoints/secrets.py
{ "start": 741, "end": 919 }
class ____(TypedDict): createdAt: str createdBy: int id: int provider: str secret: str @register(FlagWebHookSigningSecretModel)
FlagWebhookSigningSecretResponse
python
uqfoundation__dill
dill/_shims.py
{ "start": 3549, "end": 6635 }
class ____(Reduce): # A version of Reduce for functions. Used to trick pickler.save_reduce into # thinking that Reduce objects of functions are themselves meaningful functions. def __call__(self, *args, **kwargs): reduction = self.__reduce__() func = reduction[0] f_args = reduction[1...
_CallableReduce
python
getsentry__sentry
src/sentry/snuba/metrics/query.py
{ "start": 1267, "end": 3158 }
class ____: op: MetricOperationType | None metric_mri: str params: dict[str, None | str | int | float | Sequence[tuple[str | int, ...]]] | None = None alias: str = "" def __post_init__(self) -> None: # Validate that it is a valid MRI format parsed_mri = parse_mri(self.metric_mri) ...
MetricField
python
numpy__numpy
tools/swig/test/testFortran.py
{ "start": 1674, "end": 1941 }
class ____(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" ######################################################################
ucharTestCase
python
networkx__networkx
networkx/algorithms/tests/test_euler.py
{ "start": 1334, "end": 3712 }
class ____: def test_eulerian_circuit_cycle(self): G = nx.cycle_graph(4) edges = list(nx.eulerian_circuit(G, source=0)) nodes = [u for u, v in edges] assert nodes == [0, 3, 2, 1] assert edges == [(0, 3), (3, 2), (2, 1), (1, 0)] edges = list(nx.eulerian_circuit(G, so...
TestEulerianCircuit
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/both_link_and_build_dep_c/package.py
{ "start": 217, "end": 689 }
class ____(Package): """ Structure where c occurs as a build dep down the line and as a direct link dep. Useful for testing situations where you copy the parent spec just with link deps, and you want to make sure b is not part of that. a <--build-- b <-link-- c a <--link--- c """ homepa...
BothLinkAndBuildDepC
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared_tests/test_check.py
{ "start": 33930, "end": 52286 }
class ____: ... def test_sequence_param(): assert check.sequence_param([], "sequence_param") == [] assert check.sequence_param(tuple(), "sequence_param") == tuple() assert check.sequence_param(["foo"], "sequence_param", of_type=str) == ["foo"] with pytest.raises(ParameterCheckError): check.s...
SomeRecord
python
getsentry__sentry
src/sentry/tagstore/snuba/backend.py
{ "start": 4345, "end": 5167 }
class ____[U](Protocol): def __call__( self, *, key: str, value: object, times_seen: int, first_seen: datetime, last_seen: datetime ) -> U: ... def _make_result[T, U]( key: str, totals: dict[str, int], result: dict[str, dict[str, Any]], key_ctor: _KeyCallable[T, U], value_ctor: _Va...
_ValueCallable
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/antlr_asset_selection/generated/AssetSelectionLexer.py
{ "start": 24983, "end": 27734 }
class ____(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [DFA(ds, i) for i, ds in enumerate(atn.decisionToState)] EQUAL = 1 AND = 2 OR = 3 NOT = 4 STAR = 5 PLUS = 6 DIGITS = 7 COLON = 8 LPAREN = 9 RPAREN = 10 COMMA = 11 KEY = 12 ...
AssetSelectionLexer
python
kamyu104__LeetCode-Solutions
Python/ways-to-express-an-integer-as-sum-of-powers.py
{ "start": 47, "end": 490 }
class ____(object): def numberOfWays(self, n, x): """ :type n: int :type x: int :rtype: int """ MOD = 10**9+7 dp = [0]*(n+1) dp[0] = 1 for i in xrange(1, n+1): i_pow_x = i**x if i_pow_x > n: break ...
Solution
python
PyCQA__pyflakes
pyflakes/checker.py
{ "start": 11336, "end": 12020 }
class ____(Importation): """A binding created by a 'from x import *' statement.""" def __init__(self, name, source): super().__init__('*', source) # Each star importation needs a unique name, and # may not be the module name otherwise it will be deemed imported self.name = name ...
StarImportation
python
falconry__falcon
falcon/routing/compiled.py
{ "start": 39488, "end": 39629 }
class ____: # This a base element only to aid pep484 def src(self, indentation: int) -> str: raise NotImplementedError
_CxChild
python
jazzband__django-formtools
formtools/preview.py
{ "start": 273, "end": 6251 }
class ____: preview_template = 'formtools/preview.html' form_template = 'formtools/form.html' # METHODS SUBCLASSES SHOULDN'T OVERRIDE ################################### def __init__(self, form): # form should be a Form class, not an instance. self.form, self.state = form, {} def ...
FormPreview
python
apache__airflow
providers/google/tests/unit/google/cloud/utils/test_credentials_provider.py
{ "start": 3659, "end": 4226 }
class ____: def test_build_gcp_conn_path(self): value = "test" conn = build_gcp_conn(key_file_path=value) assert conn == "google-cloud-platform://?key_path=test" def test_build_gcp_conn_scopes(self): value = ["test", "test2"] conn = build_gcp_conn(scopes=value) a...
TestHelper
python
django__django
tests/admin_views/models.py
{ "start": 25542, "end": 25640 }
class ____(models.Model): name = models.CharField(max_length=20, unique=True)
ReferencedByParent
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/3_Sarsa_maze/RL_brain.py
{ "start": 1529, "end": 2131 }
class ____(RL): def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9): super(QLearningTable, self).__init__(actions, learning_rate, reward_decay, e_greedy) def learn(self, s, a, r, s_): self.check_state_exist(s_) q_predict = self.q_table.loc[s, a] if s_...
QLearningTable
python
openai__openai-python
examples/parsing_tools.py
{ "start": 140, "end": 242 }
class ____(str, Enum): orders = "orders" customers = "customers" products = "products"
Table
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/executors/utils/base_config_keys.py
{ "start": 822, "end": 1169 }
class ____: """Base Implementation of the Config Keys class. Implements iteration for child classes to inherit.""" def __iter__(self): """Return an iterator of values of non dunder attributes of Config Keys.""" return iter({value for (key, value) in self.__class__.__dict__.items() if not key.st...
BaseConfigKeys
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 47816, "end": 50322 }
class ____(SingleContinuousDistribution): _argnames = ('k', 'theta') set = Interval(0, oo) @staticmethod def check(k, theta): _value_check(k > 0, "k must be positive") _value_check(theta > 0, "Theta must be positive") def pdf(self, x): k, theta = self.k, self.theta ...
GammaDistribution
python
pytorch__pytorch
test/inductor/test_triton_extension_backend.py
{ "start": 2226, "end": 4015 }
class ____(BaseExtensionBackendTests): """ Test creating a backend for inductor with Triton scheduling. """ def test_open_device_registration(self): torch._register_device_module("privateuseone", self.module) register_backend_for_device( "privateuseone", ExtensionScheduling,...
TritonExtensionBackendTests
python
keras-team__keras
guides/making_new_layers_and_models_via_subclassing.py
{ "start": 3309, "end": 4076 }
class ____(keras.layers.Layer): def __init__(self, units=32, input_dim=32): super().__init__() self.w = self.add_weight( shape=(input_dim, units), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(units,), ...
Linear
python
nedbat__coveragepy
coverage/exceptions.py
{ "start": 1092, "end": 1172 }
class ____(NoSource): """We couldn't find any code at all.""" pass
NoCode
python
simplejson__simplejson
simplejson/tests/test_for_json.py
{ "start": 372, "end": 447 }
class ____(list): def for_json(self): return ['list']
ListForJson
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1303152, "end": 1303456 }
class ____( sgqlc.types.Type, Node, AuditEntry, EnterpriseAuditEntryData, OrganizationAuditEntryData, RepositoryAuditEntryData ): """Audit log entry for a private_repository_forking.disable event.""" __schema__ = github_schema __field_names__ = ()
PrivateRepositoryForkingDisableAuditEntry
python
walkccc__LeetCode
solutions/1876. Substrings of Size Three with Distinct Characters/1876.py
{ "start": 0, "end": 203 }
class ____: def countGoodSubstrings(self, s: str) -> int: ans = 0 for a, b, c in zip(s, s[1:], s[2:]): if a == b or a == c or b == c: continue ans += 1 return ans
Solution
python
pandas-dev__pandas
pandas/tests/io/formats/test_to_string.py
{ "start": 4426, "end": 6460 }
class ____: def test_to_string_with_column_specific_col_space_raises(self): df = DataFrame( np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"] ) msg = ( "Col_space length\\(\\d+\\) should match " "DataFrame number of columns\\(\\d+\\)" ...
TestDataFrameToStringColSpace
python
django__django
django/contrib/gis/db/backends/oracle/introspection.py
{ "start": 145, "end": 1910 }
class ____(DatabaseIntrospection): # Associating any OBJECTVAR instances with GeometryField. This won't work # right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, but it is the # only object type supported within Django anyways. @cached_property def data_types_reverse(self): return { ...
OracleIntrospection
python
tensorflow__tensorflow
tensorflow/python/checkpoint/restore.py
{ "start": 1815, "end": 35555 }
class ____(object): """Indicates a position within a `_CheckpointRestoreCoordinator`.""" __slots__ = ["_checkpoint", "_proto_id", "skip_restore", "callback"] def __init__(self, checkpoint, proto_id): """Specify an object within a checkpoint. Args: checkpoint: A _CheckpointRestoreCoordinator objec...
CheckpointPosition
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 52432, "end": 54922 }
class ____(Module): r"""Applies the element-wise PReLU function. .. math:: \text{PReLU}(x) = \max(0,x) + a * \min(0,x) or .. math:: \text{PReLU}(x) = \begin{cases} x, & \text{ if } x \ge 0 \\ ax, & \text{ otherwise } \end{cases} Here :math:`a` is a...
PReLU
python
pytorch__pytorch
torch/_inductor/codegen/cpp_template_kernel.py
{ "start": 1412, "end": 23741 }
class ____(CppKernel): def __init__(self, kernel_name, num_threads): super().__init__(None, num_threads) self.kernel_name = kernel_name self.render_hooks = {} self.local_buffers = {} def render(self, template, **kwargs): return PartialRender( template.render(...
CppTemplateKernel
python
astropy__astropy
astropy/units/format/generic.py
{ "start": 1071, "end": 12689 }
class ____(_ParsingFormatMixin): """Provide the parser used by Generic, FITS and VOUnit.""" _tokens: ClassVar[tuple[str, ...]] = ( "COMMA", "POWER", "PRODUCT", "DIVISION", "OPEN_PAREN", "CLOSE_PAREN", "FUNCNAME", "UNIT", "SIGN", "U...
_GenericParserMixin
python
django__django
tests/check_framework/test_security.py
{ "start": 357, "end": 2547 }
class ____(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is...
CheckSessionCookieSecureTest
python
getsentry__sentry
src/sentry/tasks/store.py
{ "start": 1676, "end": 2806 }
class ____(Exception): pass def should_process(data: Mapping[str, Any]) -> bool: """Quick check if processing is needed at all.""" from sentry.plugins.base import plugins if data.get("type") == "transaction": return False for plugin in plugins.all(version=2): processors = safe_ex...
RetryProcessing
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/serialized_objects.py
{ "start": 7088, "end": 7589 }
class ____(Generic[T_EntityKey]): """A union of an AutomatConditionEvaluation and the set of run IDs that have been launched in response to it. """ evaluation: AutomationConditionEvaluation[T_EntityKey] run_ids: frozenset[str] @property def key(self) -> T_EntityKey: return self.eva...
AutomationConditionEvaluationWithRunIds
python
huggingface__transformers
src/transformers/models/owlvit/modeling_owlvit.py
{ "start": 41074, "end": 49664 }
class ____(OwlViTPreTrainedModel): config: OwlViTConfig def __init__(self, config: OwlViTConfig): super().__init__(config) if not isinstance(config.text_config, OwlViTTextConfig): raise TypeError( "config.text_config is expected to be of type OwlViTTextConfig but is...
OwlViTModel
python
kamyu104__LeetCode-Solutions
Python/minimum-increment-to-make-array-unique.py
{ "start": 33, "end": 562 }
class ____(object): def minIncrementForUnique(self, A): """ :type A: List[int] :rtype: int """ A.sort() A.append(float("inf")) result, duplicate = 0, 0 for i in xrange(1, len(A)): if A[i-1] == A[i]: duplicate += 1 ...
Solution
python
django__django
tests/migrations/test_migrations_squashed_loop/2_squashed.py
{ "start": 35, "end": 229 }
class ____(migrations.Migration): replaces = [("migrations", "2_auto")] dependencies = [("migrations", "1_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
Migration
python
dask__dask
dask/dataframe/dask_expr/_shuffle.py
{ "start": 30286, "end": 35452 }
class ____(BaseSetIndexSortValues): _parameters = [ "frame", "by", "ascending", "na_position", "npartitions", "partition_size", "sort_function", "sort_function_kwargs", "upsample", "ignore_index", "shuffle_method", "opti...
SortValues
python
pytorch__pytorch
torch/distributed/elastic/events/api.py
{ "start": 626, "end": 1685 }
class ____: """ The class represents the generic event that occurs during the torchelastic job execution. The event can be any kind of meaningful action. Args: name: event name. source: the event producer, e.g. agent or worker timestamp: timestamp in milliseconds when event occ...
Event
python
dask__distributed
distributed/diagnostics/plugin.py
{ "start": 20528, "end": 21815 }
class ____: INSTALLER = "conda" packages: list[str] conda_options: list[str] def __init__(self, packages: list[str], conda_options: list[str] | None = None): self.packages = packages self.conda_options = conda_options or [] def __call__(self) -> None: logger.info( ...
_CondaInstaller
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/constructor.py
{ "start": 2070, "end": 2139 }
class ____(MarkedYAMLFutureWarning): pass
DuplicateKeyFutureWarning
python
streamlit__streamlit
lib/tests/streamlit/elements/plotly_chart_test.py
{ "start": 982, "end": 10908 }
class ____(DeltaGeneratorTestCase): def test_basic(self): """Test that plotly object works.""" df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title="Life expectancy in Canada") st.plotly_chart(fig) el = self.get_delta_from_queue(...
PyDeckTest
python
django__django
tests/syndication_tests/feeds.py
{ "start": 4488, "end": 4842 }
class ____(TestRss2Feed): """ A feed to test defining item titles and descriptions with templates. """ title_template = "syndication/title.html" description_template = "syndication/description.html" # Defining a template overrides any item_title definition def item_title(self): ret...
TemplateFeed
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 12932, "end": 13068 }
class ____(PydanticValueError): code = 'date.not_in_the_future' msg_template = 'date is not in the future'
DateNotInTheFutureError
python
walkccc__LeetCode
solutions/2961. Double Modular Exponentiation/2961.py
{ "start": 0, "end": 230 }
class ____: def getGoodIndices( self, variables: list[list[int]], target: int, ) -> list[int]: return [i for i, (a, b, c, m) in enumerate(variables) if pow(pow(a, b, 10), c, m) == target]
Solution
python
tensorflow__tensorflow
tensorflow/python/keras/layers/merge.py
{ "start": 10399, "end": 11242 }
class ____(_Merge): """Layer that multiplies (element-wise) a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). >>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1), ... np.arange(5, 10).reshape...
Multiply
python
ansible__ansible
test/units/module_utils/facts/test_facts.py
{ "start": 2629, "end": 2809 }
class ____(BaseTestFactsPlatform): platform_id = 'GNU' fact_class = hardware.hurd.HurdHardware collector_class = hardware.hurd.HurdHardwareCollector
TestHurdFactsPlatform
python
run-llama__llama_index
llama-index-core/llama_index/core/base/llms/types.py
{ "start": 14534, "end": 15075 }
class ____(BaseModel): """A representation of cited content from past messages.""" block_type: Literal["citation"] = "citation" cited_content: Annotated[ Union[TextBlock, ImageBlock], Field(discriminator="block_type") ] source: str title: str additional_location_info: Dict[str, int]...
CitationBlock
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverlap1.py
{ "start": 6604, "end": 6638 }
class ____(E1, Generic[TE1]): ...
E2
python
google__pytype
pytype/rewrite/overlays/special_builtins_test.py
{ "start": 362, "end": 831 }
class ____(SpecialBuiltinsTest): def test_types_match(self): assert_type_func = self.load_builtin_function('assert_type') var = self.ctx.consts[0].to_variable() typ = abstract.SimpleClass(self.ctx, 'int', {}).to_variable() ret = assert_type_func.call(abstract.Args(posargs=(var, typ))) self.assert...
AssertTypeTest
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 2764, "end": 4061 }
class ____(PreTrainedModel): config: Qwen3OmniMoeConfig base_model_prefix = "model" input_modalities = ("image", "video", "audio", "text") supports_gradient_checkpointing = True _no_split_modules = ["Qwen3OmniMoeDecoderLayer", "Qwen3OmniMoeVisionBlock"] _skip_keys_device_placement = "past_key_va...
Qwen3OmniMoePreTrainedModel
python
numpy__numpy
numpy/ma/tests/test_old_ma.py
{ "start": 26978, "end": 29518 }
class ____: def _create_data(self): return (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),) def test_testUfuncRegression(self): f_invalid_ignore = [ 'sqrt', 'arctanh', 'arcsin', 'arccos', ...
TestUfuncs
python
scrapy__scrapy
tests/test_pipelines.py
{ "start": 1479, "end": 1818 }
class ____: async def process_item(self, item): d = Deferred() loop = asyncio.get_event_loop() loop.call_later(0, d.callback, None) await deferred_to_future(d) await asyncio.sleep(0.2) item["pipeline_passed"] = await get_from_asyncio_queue(True) return item
AsyncDefAsyncioPipeline
python
fastai__fastai
fastai/vision/augment.py
{ "start": 45159, "end": 46051 }
class ____(): def __init__(self, max_lighting=0.2, p=0.75, draw=None, batch=False): store_attr() def _def_draw(self, x): if not self.batch: res = x.new_empty(x.size(0)).uniform_(math.log(1-self.max_lighting), -math.log(1-self.max_lighting)) else: res = x.new_zeros(x.size(0)) + random.uniform(ma...
_ContrastLogit
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_getlimits.py
{ "start": 1767, "end": 2981 }
class ____(TestCase): @skipIf(numpy.__version__ < "1.23", reason=".smallest_normal is new") def test_basic(self): dts = list( zip( ["f2", "f4", "f8", "c8", "c16"], [np.float16, np.float32, np.float64, np.complex64, np.complex128], ) ) ...
TestFinfo
python
dagster-io__dagster
python_modules/dagster/dagster/_core/system_config/composite_descent.py
{ "start": 968, "end": 1529 }
class ____( NamedTuple("_SolidConfigEntry", [("handle", NodeHandle), ("solid_config", OpConfig)]) ): def __new__(cls, handle: NodeHandle, op_config: OpConfig): return super().__new__( cls, check.inst_param(handle, "handle", NodeHandle), check.inst_param(op_config, "so...
OpConfigEntry
python
pytorch__pytorch
test/test_overrides.py
{ "start": 12440, "end": 39097 }
class ____(TestCase): def test_dtype_override(self): class MyDtype: def __torch_function__(self, *args, **kwargs): return 4 self.assertEqual(torch.empty(4).view(MyDtype()), 4) def test_mean_semantics(self): """Test that a function with one argument can be ov...
TestTorchFunctionOverride
python
PyCQA__pylint
tests/functional/n/not_callable.py
{ "start": 893, "end": 1519 }
class ____: """ class """ def __init__(self): self.attr = 4 @property def test(self): """ Get the attribute """ return self.attr @test.setter def test(self, value): """ Set the attribute """ self.attr = value @MyProperty def custom(self): ...
PropertyTest
python
huggingface__transformers
src/transformers/models/aimv2/modeling_aimv2.py
{ "start": 19551, "end": 22362 }
class ____(Aimv2PreTrainedModel): main_input_name = "input_ids" _can_record_outputs = { "hidden_states": Aimv2EncoderLayer, "attentions": Aimv2Attention, } def __init__(self, config: Aimv2TextConfig): super().__init__(config) self.config = config self.embeddings...
Aimv2TextModel
python
FactoryBoy__factory_boy
factory/errors.py
{ "start": 117, "end": 224 }
class ____(FactoryError): """Exception for Factory subclasses lacking Meta.model."""
AssociatedClassError
python
facebook__pyre-check
scripts/tests/shape_type_coverage_test.py
{ "start": 13196, "end": 14594 }
class ____(unittest.TestCase): def assert_extract_text_as( self, corpus: List[str], start: Position, stop: Position, expected: str, ) -> None: self.assertEqual(_extract_multiline_text(corpus, start, stop), expected) def test_extract_text(self) -> None: ...
ExtractMultilineTextTests
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 70641, "end": 73630 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8, 8]", L_y_: "f32[16, 16]"): l_x_ = L_x_ l_y_ = L_y_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_); subgraph_0 = l_x_ = None getitem: "f32[8, 8...
GraphModule
python
oauthlib__oauthlib
oauthlib/openid/connect/core/grant_types/dispatchers.py
{ "start": 1284, "end": 2489 }
class ____(Dispatcher): """ This is an adapter class that will route simple Authorization requests, those that have `id_token` in `response_type` and a scope including `openid` to either the `default_grant` or the `oidc_grant` based on the scopes requested. """ def __init__(self, default_gra...
ImplicitTokenGrantDispatcher
python
great-expectations__great_expectations
docs/sphinx_api_docs_source/build_sphinx_api_docs.py
{ "start": 1291, "end": 1529 }
class ____: """Paths and metadata for a sidebar entry.""" name: str definition: Definition class_min_dotted_path: str | None md_relpath: pathlib.Path mdx_relpath: pathlib.Path type: SidebarEntryType
SidebarEntry
python
pytorch__pytorch
test/distributed/checkpoint/test_tp_checkpoint.py
{ "start": 693, "end": 1125 }
class ____(torch.nn.Module): def __init__(self, device): super().__init__() torch.manual_seed(5) self.net1 = torch.nn.Linear(5, 10, device=device) self.relu = torch.nn.ReLU() self.net2 = torch.nn.Linear(10, 15, device=device) self.net3 = torch.nn.Linear(15, 1, device=...
UnevenShardedModel
python
huggingface__transformers
src/transformers/models/bert/modeling_bert.py
{ "start": 21849, "end": 22166 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) def forward(self, sequence_output: torch.Tensor) -> torch.Tensor: prediction_scores = self.predictions(sequence_output) return prediction_scores
BertOnlyMLMHead
python
huggingface__transformers
src/transformers/models/florence2/modeling_florence2.py
{ "start": 16114, "end": 18555 }
class ____(nn.Module): def __init__( self, config: Florence2VisionConfig, stage_idx: int, drop_path_rate: float, ): super().__init__() self.conv1 = nn.Conv2d( config.embed_dim[stage_idx], config.embed_dim[stage_idx], kernel_siz...
Florence2VisionSpatialBlock
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 23667, "end": 24547 }
class ____(object): """* jina gRPC service to trigger a restore at the Executor Runtime. """ @staticmethod def restore( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wai...
JinaExecutorRestore
python
TheAlgorithms__Python
neural_network/two_hidden_layers_neural_network.py
{ "start": 278, "end": 11626 }
class ____: def __init__(self, input_array: np.ndarray, output_array: np.ndarray) -> None: """ This function initializes the TwoHiddenLayerNeuralNetwork class with random weights for every layer and initializes predicted output with zeroes. input_array : input values for training th...
TwoHiddenLayerNeuralNetwork
python
keras-team__keras
keras/src/ops/core_test.py
{ "start": 46018, "end": 49222 }
class ____(testing.TestCase): """Test the dtype to verify that the behavior matches JAX.""" ALL_DTYPES = [ x for x in dtypes.ALLOWED_DTYPES if x not in ( "string", "complex64", "complex128", # Remove 64-bit dtypes. "flo...
CoreOpsDtypeTest
python
django__django
tests/queries/test_query.py
{ "start": 847, "end": 6750 }
class ____(SimpleTestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._met...
TestQuery
python
fluentpython__example-code
08-obj-ref/haunted_bus.py
{ "start": 716, "end": 1035 }
class ____: """A bus model haunted by ghost passengers""" def __init__(self, passengers=[]): # <1> self.passengers = passengers # <2> def pick(self, name): self.passengers.append(name) # <3> def drop(self, name): self.passengers.remove(name) # END HAUNTED_BUS_CLASS
HauntedBus
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 239712, "end": 240487 }
class ____(sgqlc.types.Input): """Autogenerated input type of GrantEnterpriseOrganizationsMigratorRole """ __schema__ = github_schema __field_names__ = ("enterprise_id", "login", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId") "...
GrantEnterpriseOrganizationsMigratorRoleInput
python
mlflow__mlflow
examples/pydanticai/tracing.py
{ "start": 458, "end": 1029 }
class ____: """This is a fake database for example purposes. In reality, you'd be connecting to an external database (e.g. PostgreSQL) to get information about customers. """ @classmethod async def customer_name(cls, *, id: int) -> str | None: if id == 123: return "John" ...
DatabaseConn