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
readthedocs__readthedocs.org
readthedocs/organizations/views/public.py
{ "start": 3131, "end": 3901 }
class ____(FilterContextMixin, OrganizationTeamView, ListView): template_name = "organizations/team_list.html" context_object_name = "teams" admin_only = False filterset_class = OrganizationTeamListFilterSet strict = True def get_context_data(self, **kwargs): context = super().get_cont...
ListOrganizationTeams
python
palantir__python-language-server
test/plugins/test_jedi_rename.py
{ "start": 347, "end": 2507 }
class ____(Test1): pass ''' DOC_NAME_EXTRA = 'test2.py' DOC_EXTRA = '''from test1 import Test1 x = Test1() ''' @pytest.fixture def tmp_workspace(temp_workspace_factory): return temp_workspace_factory({ DOC_NAME: DOC, DOC_NAME_EXTRA: DOC_EXTRA }) @pytest.mark.skipif(LT_PY36, reason='Jedi...
Test2
python
django__django
tests/model_inheritance/models.py
{ "start": 811, "end": 881 }
class ____(CommonInfo): job = models.CharField(max_length=50)
Worker
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 3199, "end": 3311 }
class ____(HashAlgorithm): # noqa: N801 name = "sha3-512" digest_size = 64 block_size = None
SHA3_512
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/basedialog.py
{ "start": 275, "end": 1626 }
class ____(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) # Set style of all QPushButton's inside the dialog. css = qstylizer.style.StyleSheet() css.QPushButton.setValues( padding='3px 15px 3px 15px', ) self.setStyleSheet(css.t...
BaseDialog
python
pypa__warehouse
warehouse/packaging/services.py
{ "start": 2289, "end": 3858 }
class ____: def __init__(self, base): # This class should not be used in production, it's trivial for it to # be used to read arbitrary files from the disk. It is intended ONLY # for local development with trusted users. To make this clear, we'll # raise a warning. warnings.w...
GenericLocalBlobStorage
python
pytorch__pytorch
benchmarks/transformer/sdp.py
{ "start": 2467, "end": 10906 }
class ____(torch.nn.Module): def __init__(self, num_heads, in_proj_weight, in_proj_bias, out_proj): super().__init__() self.in_proj_weight = in_proj_weight self.in_proj_bias = in_proj_bias self.out_proj = out_proj self.num_heads = num_heads def forward(self, query, key, ...
CompositeMHA
python
scikit-learn__scikit-learn
sklearn/externals/array_api_compat/common/_typing.py
{ "start": 883, "end": 1109 }
class ____(Protocol): @property def __class__(self, /) -> type[int]: ... @__class__.setter def __class__(self, value: type[int], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride] @final
JustInt
python
coleifer__peewee
tests/models.py
{ "start": 154326, "end": 155327 }
class ____(ModelTestCase): requires = [Transaction, TUser] def test_max_alias(self): with self.database.atomic(): charlie = TUser.create(username='charlie') huey = TUser.create(username='huey') data = ( (charlie, 10.), (charlie, 20.),...
TestMaxAlias
python
getsentry__sentry-python
tests/integrations/beam/test_beam.py
{ "start": 794, "end": 992 }
class ____: def __init__(self, fn): self.r = "We are in A" self.fn = fn self._inspect_fn = _wrap_inspect_call(self, "fn") def process(self): return self.fn()
A
python
kamyu104__LeetCode-Solutions
Python/russian-doll-envelopes.py
{ "start": 84, "end": 889 }
class ____(object): def maxEnvelopes(self, envelopes): """ :type envelopes: List[List[int]] :rtype: int """ def insert(target): left, right = 0, len(result) - 1 while left <= right: mid = left + (right - left) / 2 if res...
Solution
python
huggingface__transformers
src/transformers/models/distilbert/modeling_distilbert.py
{ "start": 11999, "end": 16819 }
class ____(DistilBertPreTrainedModel): def __init__(self, config: PreTrainedConfig): super().__init__(config) self.embeddings = Embeddings(config) # Embeddings self.transformer = Transformer(config) # Encoder # Initialize weights and apply final processing self.post_init(...
DistilBertModel
python
ray-project__ray
python/ray/data/_internal/arrow_block.py
{ "start": 6007, "end": 16513 }
class ____(TableBlockAccessor): ROW_TYPE = ArrowRow def __init__(self, table: "pyarrow.Table"): if pyarrow is None: raise ImportError("Run `pip install pyarrow` for Arrow support") super().__init__(table) self._max_chunk_size: Optional[int] = None def _get_row(self, ind...
ArrowBlockAccessor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 10213, "end": 10300 }
class ____(tuple): def __new__(cls: Type[NonGeneric2]) -> NonGeneric2: ...
NonGeneric2
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 14083, "end": 15657 }
class ____: _suffixes: Tuple[Tuple[DQLDMLClauseElement, str], ...] = () _has_suffixes_traverse_internals: _TraverseInternalsType = [ ("_suffixes", InternalTraversal.dp_prefix_sequence) ] @_generative @_document_text_coercion( "suffixes", ":meth:`_expression.HasSuffixes.suff...
HasSuffixes
python
gevent__gevent
src/gevent/tests/test__destroy_default_loop.py
{ "start": 70, "end": 2199 }
class ____(unittest.TestCase): def tearDown(self): self._reset_hub() super(TestDestroyDefaultLoop, self).tearDown() def _reset_hub(self): from gevent._hub_local import set_hub from gevent._hub_local import set_loop from gevent._hub_local import get_hub_if_exists ...
TestDestroyDefaultLoop
python
pydantic__pydantic
pydantic-core/tests/validators/test_union.py
{ "start": 1694, "end": 4215 }
class ____: class ModelA: pass class ModelB: pass @pytest.fixture(scope='class') def schema_validator(self) -> SchemaValidator: return SchemaValidator( schema=core_schema.union_schema( choices=[ core_schema.model_schema( ...
TestModelClass
python
walkccc__LeetCode
solutions/2008. Maximum Earnings From Taxi/2008.py
{ "start": 0, "end": 501 }
class ____: def maxTaxiEarnings(self, n: int, rides: list[list[int]]) -> int: startToEndAndEarns = [[] for _ in range(n)] # dp[i] := the maximum dollars you can earn starting at i dp = [0] * (n + 1) for start, end, tip in rides: earn = end - start + tip startToEndAndEarns[start].append((e...
Solution
python
hyperopt__hyperopt
hyperopt/tests/unit/test_rand.py
{ "start": 312, "end": 959 }
class ____(unittest.TestCase): def test_seeding(self): # -- assert that the seeding works a particular way domain = coin_flip() docs = rand.suggest( list(range(10)), domain, Trials(), seed=np.random.PCG64(123) ) trials = trials_from_docs(docs) idxs, vals ...
TestRand
python
pennersr__django-allauth
allauth/headless/contrib/ninja/security.py
{ "start": 1246, "end": 1760 }
class ____(AuthBase): openapi_type: str = "apiKey" def __call__(self, request: HttpRequest): token = get_authorization_credential( request, app_settings.JWT_AUTHORIZATION_HEADER_SCHEME ) if token is None: return None user_payload = validate_access_token(...
JWTTokenAuth
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 405950, "end": 407810 }
class ____(Response): """ Response of tasks.stopped endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "stopped" _version = "2.20" _schema = { ...
StoppedResponse
python
pypa__warehouse
tests/unit/search/test_tasks.py
{ "start": 4374, "end": 5461 }
class ____: def __init__(self): self.indices = {} self.aliases = {} self.put_settings = pretend.call_recorder(lambda *a, **kw: None) self.delete = pretend.call_recorder(lambda *a, **kw: None) self.create = pretend.call_recorder(lambda *a, **kw: None) def exists_alias(se...
FakeESIndices
python
django-debug-toolbar__django-debug-toolbar
example/test_views.py
{ "start": 237, "end": 388 }
class ____(TestCase): def test_index(self): response = self.client.get(reverse("home")) assert response.status_code == 200
ViewTestCase
python
facebook__pyre-check
client/json_rpc.py
{ "start": 539, "end": 668 }
class ____(Enum): """Message type for an LSP warning message.""" WARNING = 2 INFORMATION = 3
LanguageServerMessageType
python
numba__numba
numba/core/caching.py
{ "start": 5416, "end": 5891 }
class ____(_SourceFileBackedLocatorMixin, _CacheLocator): """ A locator for functions backed by a regular Python module with a writable __pycache__ directory. """ def __init__(self, py_func, py_file): self._py_file = py_file self._lineno = py_func.__code__.co_firstlineno sel...
InTreeCacheLocator
python
Lightning-AI__lightning
tests/tests_fabric/strategies/test_fsdp_integration.py
{ "start": 2599, "end": 3899 }
class ____(BasicTrainer): def get_model(self): model = torch.nn.Sequential(torch.nn.Linear(32, 32), torch.nn.ReLU(), torch.nn.Linear(32, 2)) self.num_wrapped = 4 return model def step(self, model, batch): wrapped_layers = [m for m in model.modules() if isinstance(m, FullySharded...
_Trainer
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 5682, "end": 5808 }
class ____(BaseModel): index: int id: str | None = None type: str | None = None function: Function
ToolCallDelta
python
walkccc__LeetCode
solutions/130. Surrounded Regions/130-2.py
{ "start": 0, "end": 683 }
class ____: def solve(self, board: list[list[str]]) -> None: if not board: return m = len(board) n = len(board[0]) def dfs(i: int, j: int) -> None: """Marks the grids with 'O' that stretch from the four sides to '*'.""" if i < 0 or i == m or j < 0 or j == n: return if...
Solution
python
huggingface__transformers
src/transformers/integrations/flex_attention.py
{ "start": 1431, "end": 13337 }
class ____: """ We are doing a singleton class so that flex attention is compiled once when it's first called. """ _instance = None _is_flex_compiled = False _compiled_flex_attention = None def __new__(cls, *args, **kwargs): if cls._instance is None: # Create a new inst...
WrappedFlexAttention
python
django__django
tests/foreign_object/tests.py
{ "start": 31278, "end": 32616 }
class ____(TestCase): @skipUnlessDBFeature("supports_table_check_constraints") def test_validate_constraints_with_foreign_object(self): customer_tab = CustomerTab(customer_id=1500) with self.assertRaisesMessage(ValidationError, "customer_id_limit"): customer_tab.validate_constraints(...
ForeignObjectModelValidationTests
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-increments-on-subarrays-to-form-a-target-array.py
{ "start": 29, "end": 302 }
class ____(object): def minNumberOperations(self, target): """ :type target: List[int] :rtype: int """ return sum(max((target[i] if i < len(target) else 0)-(target[i-1] if i-1 >= 0 else 0), 0) for i in xrange(len(target)+1))
Solution
python
psf__black
src/black/linegen.py
{ "start": 33281, "end": 78665 }
class ____(Enum): head = auto() body = auto() tail = auto() def left_hand_split( line: Line, _features: Collection[Feature], mode: Mode ) -> Iterator[Line]: """Split line into many lines, starting with the first matching bracket pair. Note: this usually looks weird, only use this for function...
_BracketSplitComponent
python
celery__celery
t/smoke/workers/alt.py
{ "start": 251, "end": 1671 }
class ____(SmokeWorkerContainer): """Alternative worker with different name, but same configurations.""" @classmethod def worker_name(cls) -> str: return "alt_smoke_tests_worker" # Build the image like the dev worker celery_alt_dev_worker_image = build( path=".", dockerfile="t/smoke/worke...
AltSmokeWorkerContainer
python
gevent__gevent
src/greentest/3.13/test_selectors.py
{ "start": 15395, "end": 17552 }
class ____: # see issue #18963 for why it's skipped on older OS X versions @support.requires_mac_ver(10, 5) @unittest.skipUnless(resource, "Test needs resource module") @support.requires_resource('cpu') def test_above_fd_setsize(self): # A scalable implementation should have no problem with...
ScalableSelectorMixIn
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/grant_types/client_credentials.py
{ "start": 200, "end": 5051 }
class ____(GrantTypeBase): """`Client Credentials Grant`_ The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control, or those of another resource owner that...
ClientCredentialsGrant
python
jazzband__django-formtools
tests/wizard/namedwizardtests/tests.py
{ "start": 15886, "end": 16102 }
class ____(NamedFormTests, TestCase): formwizard_class = TestNamedUrlSessionWizardView wizard_urlname = 'nwiz_session' @override_settings(ROOT_URLCONF='tests.wizard.namedwizardtests.urls')
NamedSessionFormTests
python
ApeWorX__ape
tests/functional/test_test.py
{ "start": 11344, "end": 14385 }
class ____: def test_from_test_item(self, item): actual = FixtureMap.from_test_item(item) assert actual[Scope.SESSION] == ["foo"] assert actual[Scope.MODULE] == ["bar"] assert actual[Scope.CLASS] == ["baz"] def test_names(self, fixture_map): """ Show that we have...
TestFixtureMap
python
doocs__leetcode
solution/3100-3199/3117.Minimum Sum of Values by Dividing Array/Solution.py
{ "start": 0, "end": 631 }
class ____: def minimumValueSum(self, nums: List[int], andValues: List[int]) -> int: @cache def dfs(i: int, j: int, a: int) -> int: if n - i < m - j: return inf if j == m: return 0 if i == n else inf a &= nums[i] if a < ...
Solution
python
getsentry__sentry-python
sentry_sdk/client.py
{ "start": 8026, "end": 42519 }
class ____(BaseClient): """ The client is internally responsible for capturing the events and forwarding them to sentry through the configured transport. It takes the client options as keyword arguments and optionally the DSN as first argument. Alias of :py:class:`sentry_sdk.Client`. (Was crea...
_Client
python
pydantic__pydantic
tests/test_edge_cases.py
{ "start": 89215, "end": 95349 }
class ____(BaseModel): type Int = int a: Int """, globs, ) A = globs['A'] assert A(a=1).a == 1 def test_method_descriptors_default() -> None: class SomeModel(BaseModel): @staticmethod def default_int_factory() -> int: ... int_factory: Callable[[], int] = Field(...
A
python
catalyst-team__catalyst
catalyst/data/sampler.py
{ "start": 13723, "end": 16898 }
class ____(Sampler): """ Sampler iterates mini epochs from the dataset used by ``mini_epoch_len``. Args: data_len: Size of the dataset mini_epoch_len: Num samples from the dataset used in one mini epoch. drop_last: If ``True``, sampler will drop the last batches ...
MiniEpochSampler
python
apache__airflow
providers/pagerduty/tests/unit/pagerduty/hooks/test_pagerduty.py
{ "start": 1531, "end": 2888 }
class ____: def test_get_token_from_password(self, pagerduty_connections): hook = PagerdutyHook(pagerduty_conn_id=DEFAULT_CONN_ID) assert hook.token == "token", "token initialised." assert hook.routing_key == "integration_key" def test_without_routing_key_extra(self): hook = Pag...
TestPagerdutyHook
python
tensorflow__tensorflow
tensorflow/python/distribute/multi_worker_test_base.py
{ "start": 21711, "end": 25619 }
class ____(test.TestCase): """Testing infra for independent workers.""" def _make_mock_run_std_server(self): def _mock_run_std_server(*args, **kwargs): """Returns the std server once all threads have started it.""" with skip_if_grpc_server_cant_be_started(self): ret = original_run_std_serv...
IndependentWorkerTestBase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-genesys/source_genesys/source.py
{ "start": 4609, "end": 4896 }
class ____(GenesysStream): """ API Docs: https://developer.genesys.cloud/telephony/telephony-apis """ primary_key = "id" cursor_field = "dateModified" def path(self, **kwargs) -> str: return "telephony/providers/edges/phones"
TelephonyProvidersEdgesPhones
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 8360, "end": 8569 }
class ____(BaseModel): """ Dag Serializer for updatable bodies. """ model_config = ConfigDict( extra="forbid", ) is_paused: Annotated[bool, Field(title="Is Paused")]
DAGPatchBody
python
bokeh__bokeh
src/bokeh/models/tiles.py
{ "start": 4244, "end": 4807 }
class ____(MercatorTileSource): ''' Contains tile config info and provides urls for tiles based on a templated url e.g. ``http://your.tms.server.host/{Z}/{X}/{Y}.png``. The defining feature of TMS is the tile-origin in located at the bottom-left. ``TMSTileSource`` can also be helpful in implementing ti...
TMSTileSource
python
mwaskom__seaborn
tests/_core/test_plot.py
{ "start": 42546, "end": 44127 }
class ____: def test_scale_setup(self): x = y = color = ["a", "b"] bad_palette = "not_a_palette" p = Plot(x, y, color=color).add(MockMark()).scale(color=bad_palette) msg = "Scale setup failed for the `color` variable." with pytest.raises(PlotSpecError, match=msg) as err: ...
TestExceptions
python
kubernetes-client__python
kubernetes/base/leaderelection/leaderelectionrecord.py
{ "start": 589, "end": 911 }
class ____: # Annotation used in the lock object def __init__(self, holder_identity, lease_duration, acquire_time, renew_time): self.holder_identity = holder_identity self.lease_duration = lease_duration self.acquire_time = acquire_time self.renew_time = renew_time
LeaderElectionRecord
python
Pylons__pyramid
tests/test_config/test_predicates.py
{ "start": 50, "end": 19833 }
class ____(unittest.TestCase): def _makeOne(self): from pyramid import predicates from pyramid.config.predicates import PredicateList inst = PredicateList() for name, factory in ( ('xhr', predicates.XHRPredicate), ('request_method', predicates.RequestMethodPr...
TestPredicateList
python
numba__numba
numba/tests/test_caching.py
{ "start": 3159, "end": 5880 }
class ____(SerialMixin, TestCase): def run_test(self, func): func() res = run_in_new_process_caching(func) self.assertEqual(res['exitcode'], 0) def test_constant_unicode_cache(self): self.run_test(check_constant_unicode_cache) def test_dict_cache(self): self.run_tes...
TestCaching
python
getsentry__sentry
src/sentry/web/frontend/error_500.py
{ "start": 207, "end": 377 }
class ____(View): def dispatch(self, request: HttpRequest) -> HttpResponse: return render_to_response("sentry/500.html", status=500, request=request)
Error500View
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/proto/descriptor_source_test_base.py
{ "start": 1196, "end": 6861 }
class ____(test.TestCase): """Base class for testing descriptor sources.""" def __init__(self, decode_module, encode_module, methodName='runTest'): # pylint: disable=invalid-name """DescriptorSourceTestBase initializer. Args: decode_module: a module containing the `decode_proto_op` method enc...
DescriptorSourceTestBase
python
huggingface__transformers
src/transformers/models/ovis2/modeling_ovis2.py
{ "start": 15722, "end": 16677 }
class ____(nn.Module): def __init__(self, config: Ovis2VisionConfig): super().__init__() self.config = config self.embeddings = Ovis2VisionEmbeddings(config) self.encoder = Ovis2VisionEncoder(config) self.rms_norm = Ovis2RMSNorm(config.hidden_size, config.rms_norm_eps) ...
Ovis2VisionTransformer
python
ipython__ipython
tests/test_guarded_eval.py
{ "start": 7392, "end": 7506 }
class ____: def __new__(self) -> frozenset: # type:ignore[misc] return frozenset()
InitReturnsFrozenset
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/utils/plus/defs_state_storage.py
{ "start": 1057, "end": 3883 }
class ____(DefsStateStorage[T_DagsterInstance]): """DefsStateStorage that can be instantiated from a DagsterPlusCliConfig, intended for use within the CLI. """ def __init__(self, url: str, api_token: str, deployment: str, graphql_client): self._url = url self._api_token = api_token ...
DagsterPlusCliDefsStateStorage
python
walkccc__LeetCode
solutions/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/1465.py
{ "start": 0, "end": 510 }
class ____: def maxArea( self, h: int, w: int, horizontalCuts: list[int], verticalCuts: list[int], ) -> int: MOD = 1_000_000_007 # the maximum gap of each direction maxGapX = max(b - a for a, b in itertools.pairwise( [0] + sorted(hori...
Solution
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 41423, "end": 41734 }
class ____(fftw_info): section = 'fftw3' dir_env_var = 'ARMPL_DIR' notfounderror = FFTWNotFoundError ver_info = [{'name': 'fftw3', 'libs': ['armpl_lp64_mp'], 'includes': ['fftw3.h'], 'macros': [('SCIPY_FFTW3_H', None)]}]
fftw3_armpl_info
python
numba__numba
numba/core/types/functions.py
{ "start": 24093, "end": 24582 }
class ____(Function): """ A named native function (resolvable by LLVM) accepting an explicit signature. For internal use only. """ def __init__(self, symbol, sig): from numba.core import typing self.symbol = symbol self.sig = sig template = typing.make_concrete_templ...
ExternalFunction
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_lower_triangular_test.py
{ "start": 1178, "end": 6731 }
class ____( linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" @staticmethod def skip_these_tests(): # Cholesky does not make sense for triangular matrices. return ["cholesky"] def operator_and_matrix(self, build...
LinearOperatorLowerTriangularTest
python
django__django
django/contrib/auth/forms.py
{ "start": 4888, "end": 7515 }
class ____: """ Form mixin that allows setting an unusable password for a user. This mixin should be used in combination with `SetPasswordMixin`. """ usable_password_help_text = _( "Whether the user will be able to authenticate using a password or not. " "If disabled, they may stil...
SetUnusablePasswordMixin
python
vyperlang__vyper
vyper/ast/pre_parser.py
{ "start": 6389, "end": 8085 }
class ____: def __init__(self): self.locations = [] self._tokens = [] self._state = ParserState.NOT_RUNNING def consume(self, token, result): # prepare to check if the next token is a STRING if self._state == ParserState.NOT_RUNNING: if token.type == NAME and...
HexStringParser
python
networkx__networkx
networkx/algorithms/assortativity/tests/test_correlation.py
{ "start": 244, "end": 2681 }
class ____(BaseTestDegreeMixing): def test_degree_assortativity_undirected(self): r = nx.degree_assortativity_coefficient(self.P4) np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4) def test_degree_assortativity_node_kwargs(self): G = nx.Graph() edges = [(0, 1), (0, 3), (1, ...
TestDegreeMixingCorrelation
python
sympy__sympy
sympy/physics/secondquant.py
{ "start": 11384, "end": 15397 }
class ____(SqOperator): @property def is_restricted(self): """ Is this FermionicOperator restricted with respect to fermi level? Returns ======= 1 : restricted to orbits above fermi 0 : no restriction -1 : restricted to orbits below fermi Exa...
FermionicOperator
python
pennersr__django-allauth
allauth/socialaccount/providers/fivehundredpx/provider.py
{ "start": 486, "end": 1128 }
class ____(OAuthProvider): id = "500px" name = "500px" package = "allauth.socialaccount.providers.fivehundredpx" account_class = FiveHundredPxAccount oauth_adapter_class = FiveHundredPxOAuthAdapter def get_default_scope(self): return [] def extract_uid(self, data): return s...
FiveHundredPxProvider
python
pytorch__pytorch
torch/_export/serde/serialize.py
{ "start": 5227, "end": 5363 }
class ____: exported_program: bytes state_dict: bytes constants: bytes example_inputs: bytes @dataclass
SerializedArtifact
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 9899, "end": 9963 }
class ____(sqltypes.Date): render_bind_cast = True
AsyncpgDate
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/execution_plan_tests/test_external_step.py
{ "start": 22817, "end": 24398 }
class ____(CacheableAssetsDefinition): _cacheable_data = AssetsDefinitionCacheableData( keys_by_output_name={"result": dg.AssetKey("foo")} ) def compute_cacheable_data(self): # used for tracking how many times this function gets called over an execution # since we're crossing proces...
MyCacheableAssetsDefinition
python
walkccc__LeetCode
solutions/87. Scramble String/87.py
{ "start": 0, "end": 492 }
class ____: @functools.lru_cache(None) def isScramble(self, s1: str, s2: str) -> bool: if s1 == s2: return True if collections.Counter(s1) != collections.Counter(s2): return False for i in range(1, len(s1)): if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]): ...
Solution
python
pydantic__pydantic
pydantic-core/tests/serializers/test_model_root.py
{ "start": 359, "end": 593 }
class ____: __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value)
BaseModel
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 108723, "end": 108883 }
class ____(spack.error.SpackError): """ Raised when gpg2 is not in PATH """ def __init__(self, msg): super().__init__(msg)
NoGpgException
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 28986, "end": 30567 }
class ____(ToolBase): description = 'Print tool list, shortcuts and description' default_keymap = property(lambda self: mpl.rcParams['keymap.help']) image = 'mpl-data/images/help' @staticmethod def format_shortcut(key_sequence): """ Convert a shortcut string from the notation used i...
ToolHelpBase
python
pytorch__pytorch
test/dynamo/test_modes.py
{ "start": 1538, "end": 3960 }
class ____(torch._dynamo.test_case.TestCase): @classmethod def setUpClass(cls): super().setUpClass() @classmethod def tearDownClass(cls): super().tearDownClass() def test_torch_dispatch_ignore_compile_internals(self): counters.clear() from torch.utils._python_dispat...
TorchDispatchModeTests
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/selector.py
{ "start": 7364, "end": 7973 }
class ____: location_name: str repository_name: str resource_name: str def to_graphql_input(self): return { "repositoryLocationName": self.location_name, "repositoryName": self.repository_name, "resourceName": self.resource_name, } @staticmethod ...
ResourceSelector
python
getsentry__sentry
tests/sentry/workflow_engine/models/test_action.py
{ "start": 400, "end": 6529 }
class ____(TestCase): def setUp(self) -> None: mock_group_event = Mock(spec=GroupEvent) self.group = self.create_group() self.mock_event = WorkflowEventData(event=mock_group_event, group=self.group) self.action = Action(type=Action.Type.SLACK) self.config_schema = { ...
TestAction
python
getsentry__sentry
tests/sentry/grouping/test_components.py
{ "start": 1080, "end": 17619 }
class ____(TestCase): def setUp(self) -> None: self.contributing_system_frame = { "function": "handleRequest", "filename": "/node_modules/express/router.js", "context_line": "return handler(request);", } self.non_contributing_system_frame = { "...
ComponentTest
python
apache__airflow
airflow-core/src/airflow/utils/state.py
{ "start": 1256, "end": 1646 }
class ____(str, Enum): """States that a Task Instance can be in that indicate it is not yet in a terminal or running state.""" SCHEDULED = "scheduled" QUEUED = "queued" RESTARTING = "restarting" UP_FOR_RETRY = "up_for_retry" UP_FOR_RESCHEDULE = "up_for_reschedule" DEFERRED = "deferred" ...
IntermediateTIState
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 83513, "end": 86730 }
class ____(torch.nn.Module): def forward(self, primals_1: "Sym(s77)", primals_2: "f32[s77, 16]"): partitioned_fw_subgraph_0_1 = self.partitioned_fw_subgraph_0_1 invoke_subgraph_8 = torch.ops.higher_order.invoke_subgraph(partitioned_fw_subgraph_0_1, 'partitioned_fw_subgraph_0_1', primals_1, primals_2...
GraphModule
python
huggingface__transformers
src/transformers/models/aria/modular_aria.py
{ "start": 40389, "end": 40512 }
class ____(ImagesKwargs, total=False): split_image: bool max_image_size: int min_image_size: int
AriaImagesKwargs
python
RaRe-Technologies__gensim
gensim/models/tfidfmodel.py
{ "start": 7398, "end": 21472 }
class ____(interfaces.TransformationABC): """Objects of this class realize the transformation between word-document co-occurrence matrix (int) into a locally/globally weighted TF-IDF matrix (positive floats). Examples -------- .. sourcecode:: pycon >>> import gensim.downloader as api ...
TfidfModel
python
jazzband__django-formtools
tests/wizard/namedwizardtests/tests.py
{ "start": 15006, "end": 15400 }
class ____: def test_revalidation(self): request = get_request() testform = self.formwizard_class.as_view( [('start', Step1), ('step2', Step2)], url_name=self.wizard_urlname) response, instance = testform(request, step='done') instance.render_done(None) ...
NamedFormTests
python
tiangolo__fastapi
docs_src/dependencies/tutorial008b_an.py
{ "start": 278, "end": 785 }
class ____(Exception): pass def get_username(): try: yield "Rick" except OwnerError as e: raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): if item_id not in data:...
OwnerError
python
explosion__spaCy
spacy/lang/lb/__init__.py
{ "start": 401, "end": 515 }
class ____(Language): lang = "lb" Defaults = LuxembourgishDefaults __all__ = ["Luxembourgish"]
Luxembourgish
python
run-llama__llama_index
llama-index-core/tests/vector_stores/test_simple.py
{ "start": 2260, "end": 17196 }
class ____(unittest.TestCase): def test_query_without_filters_returns_all_rows_sorted_by_similarity(self) -> None: simple_vector_store = SimpleVectorStore() simple_vector_store.add(_node_embeddings_for_test()) query = VectorStoreQuery(query_embedding=[1.0, 1.0], similarity_top_k=3) ...
SimpleVectorStoreTest
python
jazzband__django-model-utils
model_utils/tracker.py
{ "start": 7112, "end": 10903 }
class ____: def __init__(self, instance: models.Model, fields: Iterable[str], field_map: Mapping[str, str]): self.instance = cast('_AugmentedModel', instance) self.fields = fields self.field_map = field_map self.context = FieldsContext(self, *self.fields) def __enter__(self) -> ...
FieldInstanceTracker
python
fluentpython__example-code-2e
24-class-metaprog/evaltime/builderlib.py
{ "start": 60, "end": 668 }
class ____: # <1> print('@ Builder body') def __init_subclass__(cls): # <2> print(f'@ Builder.__init_subclass__({cls!r})') def inner_0(self): # <3> print(f'@ SuperA.__init_subclass__:inner_0({self!r})') cls.method_a = inner_0 def __init__(self): super().__i...
Builder
python
pytorch__pytorch
torch/testing/_internal/common_modules.py
{ "start": 8037, "end": 8182 }
class ____(Enum): """ Enumerates when error is raised when testing modules. """ CONSTRUCTION_ERROR = 0 FORWARD_ERROR = 1
ModuleErrorEnum
python
huggingface__transformers
src/transformers/models/sam2/modular_sam2.py
{ "start": 38909, "end": 39760 }
class ____(SamTwoWayAttentionBlock, GradientCheckpointingLayer): def __init__(self, config: Sam2MaskDecoderConfig, skip_first_layer_pe: bool = False): nn.Module.__init__(self) self.self_attn = Sam2Attention(config, downsample_rate=1) self.layer_norm1 = nn.LayerNorm(config.hidden_size) ...
Sam2TwoWayAttentionBlock
python
facebookresearch__faiss
tests/test_io.py
{ "start": 10554, "end": 11804 }
class ____(unittest.TestCase): """ test read and write IndexLSH. """ def test_io_lsh(self): xt, xb, xq = get_dataset_2(d, nt, nb, nq) index_lsh = faiss.IndexLSH(d, 32, True, True) index_lsh.train(xt) index_lsh.add(xb) D, I = index_lsh.search(xq, 10) fd, f...
Test_IO_IndexLSH
python
django__django
django/db/migrations/questioner.py
{ "start": 11902, "end": 13568 }
class ____(MigrationQuestioner): def __init__( self, defaults=None, specified_apps=None, dry_run=None, verbosity=1, log=None, ): self.verbosity = verbosity self.log = log super().__init__( defaults=defaults, specifie...
NonInteractiveMigrationQuestioner
python
getsentry__sentry
tests/sentry/models/test_project.py
{ "start": 29960, "end": 33174 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.options_dict = { "sentry:resolve_age": 1, "sentry:scrub_data": False, "sentry:scrub_defaults": False, } self.other_project = self.create_proj...
CopyProjectSettingsTest
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 858511, "end": 858687 }
class ____(VegaLiteSchema): """Parse schema wrapper.""" _schema = {"$ref": "#/definitions/Parse"} def __init__(self, **kwds): super().__init__(**kwds)
Parse
python
lepture__authlib
authlib/integrations/base_client/async_app.py
{ "start": 308, "end": 2425 }
class ____(OAuth1Base): async def request(self, method, url, token=None, **kwargs): async with self._get_oauth_client() as session: return await _http_request(self, session, method, url, token, kwargs) async def create_authorization_url(self, redirect_uri=None, **kwargs): """Generat...
AsyncOAuth1Mixin
python
pytorch__pytorch
torch/testing/_internal/common_device_type.py
{ "start": 54875, "end": 56017 }
class ____: def __init__(self, device_type, dtype=None): self.device_type = device_type self.dtype = dtype def __call__(self, fn): @wraps(fn) def efail_fn(slf, *args, **kwargs): if ( not hasattr(slf, "device_type") and hasattr(slf, "de...
expectedFailure
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/graph/base_asset_graph.py
{ "start": 3402, "end": 6657 }
class ____(BaseEntityNode[AssetKey]): key: AssetKey parent_keys: AbstractSet[AssetKey] child_keys: AbstractSet[AssetKey] @property def parent_entity_keys(self) -> AbstractSet[AssetKey]: return self.parent_keys @property def child_entity_keys(self) -> AbstractSet[EntityKey]: ...
BaseAssetNode
python
ipython__ipython
IPython/core/interactiveshell.py
{ "start": 9158, "end": 10612 }
class ____: """The result of a call to :meth:`InteractiveShell.run_cell` Stores information about what took place. """ execution_count: Optional[int] = None error_before_exec: Optional[BaseException] = None error_in_exec: Optional[BaseException] = None info = None result = None de...
ExecutionResult
python
PyCQA__pylint
doc/data/messages/a/assigning-non-slot/good.py
{ "start": 0, "end": 203 }
class ____: __slots__ = ("name", "surname") def __init__(self, name, surname): self.name = name self.surname = surname self.setup() def setup(self): pass
Student
python
pallets__werkzeug
src/werkzeug/datastructures/structures.py
{ "start": 35517, "end": 41356 }
class ____(cabc.MutableSet[str]): """Similar to the :class:`ETags` class this implements a set-like structure. Unlike :class:`ETags` this is case insensitive and used for vary, allow, and content-language headers. If not constructed using the :func:`parse_set_header` function the instantiation work...
HeaderSet
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 41325, "end": 44554 }
class ____(SinglePatternODESolver): r""" Solves separable 1st order differential equations. This is any differential equation that can be written as `P(y) \tfrac{dy}{dx} = Q(x)`. The solution can then just be found by rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`. This h...
Separable
python
scrapy__scrapy
tests/test_spidermiddleware_output_chain.py
{ "start": 7910, "end": 8453 }
class ____(_BaseSpiderMiddleware): def process_spider_output(self, response, result): out = [] for r in result: r["processed"].append(f"{self.__class__.__name__}.process_spider_output") out.append(r) return out def process_spider_exception(self, response, excepti...
_NotGeneratorDoNothingMiddleware
python
pandas-dev__pandas
pandas/_config/config.py
{ "start": 11744, "end": 27125 }
class ____: """provide attribute-style access to a nested dict""" d: dict[str, Any] def __init__(self, d: dict[str, Any], prefix: str = "") -> None: object.__setattr__(self, "d", d) object.__setattr__(self, "prefix", prefix) def __setattr__(self, key: str, val: Any) -> None: p...
DictWrapper