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
lepture__authlib
authlib/oauth2/rfc6749/requests.py
{ "start": 1576, "end": 4614 }
class ____(OAuth2Payload): def __init__(self, method: str, uri: str, body=None, headers=None): InsecureTransportError.check(uri) #: HTTP method self.method = method self.uri = uri #: HTTP headers self.headers = headers or {} # Store body for backward compatib...
OAuth2Request
python
PrefectHQ__prefect
src/prefect/server/utilities/messaging/__init__.py
{ "start": 684, "end": 917 }
class ____(Protocol): """ A protocol representing a message sent to a message broker. """ @property def data(self) -> Union[str, bytes]: ... @property def attributes(self) -> Mapping[str, Any]: ...
Message
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/appflow.py
{ "start": 5956, "end": 7214 }
class ____(AppflowBaseOperator): """ Execute an AppFlow run as is. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:AppflowRunOperator` :param flow_name: The flow name :param poll_interval: how often in seconds to check t...
AppflowRunOperator
python
django__django
tests/servers/tests.py
{ "start": 12968, "end": 13625 }
class ____(LiveServerBase): def test_fixtures_loaded(self): """ Fixtures are properly loaded and visible to the live server thread. """ with self.urlopen("/model_view/") as f: self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"]) def test_database_writes...
LiveServerDatabase
python
numba__numba
numba/tests/test_exceptions.py
{ "start": 1192, "end": 2987 }
class ____(Exception): def __init__(self, arg, value0): super(UDENoArgSuper, self).__init__() self.deferarg = arg self.value0 = value0 def __eq__(self, other): if not isinstance(other, self.__class__): return False same = True same |= self.args == oth...
UDENoArgSuper
python
dask__dask
dask/array/tests/test_dispatch.py
{ "start": 8283, "end": 8980 }
class ____: __array_ufunc__ = None def __mul__(self, other): return 42 __rmul__ = __mul__ @pytest.mark.parametrize("arr", [da.from_array([1, 2]), np.asarray([1, 2])]) def test_delegation_unknown_scalar(arr): s = UnknownScalar() assert arr * s == 42 assert s * arr == 42 with pytes...
UnknownScalar
python
pyqtgraph__pyqtgraph
pyqtgraph/GraphicsScene/exportDialog.py
{ "start": 254, "end": 467 }
class ____(QtWidgets.QListWidgetItem): def __init__(self, expClass, *args, **kwargs): QtWidgets.QListWidgetItem.__init__(self, *args, **kwargs) self.expClass = expClass
FormatExportListWidgetItem
python
tensorflow__tensorflow
tensorflow/compiler/tests/pooling_ops_3d_test.py
{ "start": 1453, "end": 14947 }
class ____(xla_test.XLATestCase): def _VerifyValues(self, pool_func, input_sizes, window, strides, padding, expected): """Verifies the output values of the pooling function. Args: pool_func: Function to be called: co.MaxPool, co.AvgPool. input_sizes: Input tensor dimensions. ...
Pooling3DTest
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/cloud/jobs.py
{ "start": 36998, "end": 43782 }
class ____(JobBlock): """ Block that holds the information and methods to interact with a dbt Cloud job. Attributes: dbt_cloud_credentials: The credentials to use to authenticate with dbt Cloud. job_id: The id of the dbt Cloud job. timeout_seconds: The number of seconds to wait for ...
DbtCloudJob
python
pytorch__pytorch
test/dynamo/test_misc.py
{ "start": 421911, "end": 432800 }
class ____(torch._inductor.test_case.TestCase): @parametrize_pytree_module def test_tracing_pytree(self, pytree): def fn(xs): flat_xs, spec = pytree.tree_flatten(xs) res = [x.clone() for x in flat_xs] if pytree.__name__ == "optree": # The treespec argu...
MiscTestsPyTree
python
joke2k__faker
faker/providers/ssn/he_IL/__init__.py
{ "start": 41, "end": 830 }
class ____(SsnProvider): def ssn(self) -> str: """ Returns an Israeli identity number, known as Teudat Zehut ("tz"). https://en.wikipedia.org/wiki/Israeli_identity_card """ newID = str(self.generator.random.randrange(111111, 99999999)) newID = newID.zfill(8) ...
Provider
python
scipy__scipy
benchmarks/benchmarks/optimize.py
{ "start": 16991, "end": 20664 }
class ____(Benchmark): """ Benchmark the global optimizers using the go_benchmark_functions suite """ timeout = 180 _functions = dict([ item for item in inspect.getmembers(gbf, inspect.isclass) if (issubclass(item[1], gbf.Benchmark) and item[0] not in ('Benchmark') a...
BenchGlobal
python
ray-project__ray
rllib/models/torch/modules/multi_head_attention.py
{ "start": 459, "end": 2467 }
class ____(nn.Module): """A multi-head attention layer described in [1].""" def __init__( self, in_dim: int, out_dim: int, num_heads: int, head_dim: int, **kwargs ): """ in_dim: Dimension of input out_dim: Dimension of output num_heads: Number of attention heads ...
MultiHeadAttention
python
gevent__gevent
src/greentest/3.10/test_context.py
{ "start": 449, "end": 10625 }
class ____(unittest.TestCase): def test_context_var_new_1(self): with self.assertRaisesRegex(TypeError, 'takes exactly 1'): contextvars.ContextVar() with self.assertRaisesRegex(TypeError, 'must be a str'): contextvars.ContextVar(1) c = contextvars.ContextVar('aaa') ...
ContextTest
python
jina-ai__jina
jina/enums.py
{ "start": 5381, "end": 5867 }
class ____(BetterEnum): """ Gateway communication protocol """ GRPC = 0 HTTP = 1 WEBSOCKET = 2 @classmethod def from_string_list(cls, string_list: List[Union[str, 'ProtocolType']]): """ Returns a list of Enums from a list of strings or enums :param string_list: ...
ProtocolType
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_checkpoint.py
{ "start": 9459, "end": 9940 }
class ____(nn.Module): def __init__(self, checkpoint: bool = False, use_reentrant: bool = True): super().__init__() self.seq = nn.Sequential(*[nn.Linear(100, 100) for _ in range(4)]) self.checkpoint = checkpoint self.use_reentrant = use_reentrant def forward(self, x): re...
CheckpointModule
python
django__django
tests/known_related_objects/models.py
{ "start": 300, "end": 495 }
class ____(models.Model): name = models.CharField(max_length=30) tournament = models.ForeignKey(Tournament, models.CASCADE) organiser = models.ForeignKey(Organiser, models.CASCADE)
Pool
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py
{ "start": 4242, "end": 7105 }
class ____(EcsBaseTestCase): @pytest.mark.parametrize( ("return_state", "expected"), [("ACTIVE", True), ("PROVISIONING", False), ("DEPROVISIONING", False)] ) def test_default_values_poke(self, return_state, expected): task = self.create_rendered_task(EcsClusterStateSensor, cluster_name=TEST_...
TestEcsClusterStateSensor
python
pypa__warehouse
warehouse/manage/views/organizations.py
{ "start": 20869, "end": 26152 }
class ____: def __init__(self, organization, request): self.organization = organization self.request = request self.billing_service = request.find_service(IBillingService, context=None) self.subscription_service = request.find_service( ISubscriptionService, context=None ...
ManageOrganizationBillingViews
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-people-that-can-be-caught-in-tag.py
{ "start": 65, "end": 631 }
class ____(object): def catchMaximumAmountofPeople(self, team, dist): """ :type team: List[int] :type dist: int :rtype: int """ result = i = j = 0 while i < len(team) and j < len(team): if i+dist < j or team[i] != 1: i += 1 ...
Solution
python
PrefectHQ__prefect
tests/test_exceptions.py
{ "start": 3464, "end": 4285 }
class ____: def test_from_bad_params(self): expected = ( "Function expects parameters ['dog', 'cat'] but was provided with" " parameters ['puppy', 'kitty']" ) signature_mismatch_error = SignatureMismatchError.from_bad_params( ["dog", "cat"], ["puppy", "kit...
TestSignatureMismatchError
python
getsentry__sentry
src/social_auth/backends/__init__.py
{ "start": 6663, "end": 8528 }
class ____(SocialAuthBackend): """OAuth authentication backend base class. EXTRA_DATA defines a set of name that will be stored in extra_data field. It must be a list of tuples with name and alias. Also settings will be inspected to get more values names that should be st...
OAuthBackend
python
pydantic__pydantic
pydantic/experimental/pipeline.py
{ "start": 22852, "end": 23582 }
class ____(Protocol): def __len__(self) -> int: ... _NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt) _NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe) _NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt) _NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.Suppor...
_SupportsLen
python
pandas-dev__pandas
pandas/tests/reshape/concat/test_dataframe.py
{ "start": 158, "end": 9154 }
class ____: @pytest.mark.xfail(reason="GH#62888 the `mi[2][1] is 1` check fails") def test_concat_multiindex_level_bool_and_numeric(self): # GH#21108, GH#45101 left = DataFrame([123, 456], columns=["data"], index=[True, False]) right = DataFrame( [55, 983, 69, 112, 0], column...
TestDataFrameConcat
python
apache__airflow
dev/breeze/src/airflow_breeze/commands/main_command.py
{ "start": 2897, "end": 12565 }
class ____(BreezeGroup): def get_command(self, ctx: Context, cmd_name: str): # Aliases for important commands moved to sub-commands or deprecated commands rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv if cmd_name == "static-checks": ...
MainGroupWithAliases
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 518327, "end": 519530 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "pull_requests") field = sgqlc.types.Field( sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field" ) pull_requests = sgqlc.types.Field(...
ProjectV2ItemFieldPullRequestValue
python
numpy__numpy
numpy/random/tests/test_smoke.py
{ "start": 2411, "end": 2557 }
class ____: bit_generator: type[np.random.BitGenerator] advance: int seed: list[int] rg: Generator seed_vector_bits: int
RNGData
python
celery__celery
t/unit/app/test_log.py
{ "start": 3973, "end": 10490 }
class ____: def setup_logger(self, *args, **kwargs): self.app.log.setup_logging_subsystem(*args, **kwargs) return logging.root def setup_method(self): self.get_logger = lambda n=None: get_logger(n) if n else logging.root signals.setup_logging.receivers[:] = [] self.app...
test_default_logger
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_vertex_ai.py
{ "start": 1566, "end": 2626 }
class ____: def test_class_attributes(self): assert VertexAIRayClusterLink.key == EXPECTED_VERTEX_AI_RAY_CLUSTER_LINK_KEY assert VertexAIRayClusterLink.name == EXPECTED_VERTEX_AI_RAY_CLUSTER_LINK_NAME assert VertexAIRayClusterLink.format_str == EXPECTED_VERTEX_AI_RAY_CLUSTER_LINK_FORMAT_STR ...
TestVertexAIRayClusterLink
python
PyCQA__flake8
tests/unit/test_base_formatter.py
{ "start": 5400, "end": 5777 }
class ____(base.BaseFormatter): """Subclass for testing after_init.""" def after_init(self): """Define method to verify operation.""" self.post_initialized = True def test_after_init_is_always_called(): """Verify after_init is called.""" formatter = AfterInitFormatter(options()) a...
AfterInitFormatter
python
pyqtgraph__pyqtgraph
pyqtgraph/Transform3D.py
{ "start": 101, "end": 1935 }
class ____(QtGui.QMatrix4x4): """ Extension of QMatrix4x4 with some helpful methods added. """ def __init__(self, *args): if len(args) == 1: if isinstance(args[0], (list, tuple, np.ndarray)): args = [x for y in args[0] for x in y] if len(args) != 16: ...
Transform3D
python
Textualize__textual
src/textual/css/query.py
{ "start": 1284, "end": 1587 }
class ____(QueryError): """Query result was not of the correct type.""" QueryType = TypeVar("QueryType", bound="Widget") """Type variable used to type generic queries.""" ExpectType = TypeVar("ExpectType") """Type variable used to further restrict queries.""" @rich.repr.auto(angular=True)
WrongType
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 11436, "end": 11572 }
class ____(DistanceLookupFromFunction): lookup_name = "distance_gte" op = ">=" @BaseSpatialField.register_lookup
DistanceGTELookup
python
cython__cython
docs/examples/userguide/extension_types/dict_animal.py
{ "start": 15, "end": 217 }
class ____: number_of_legs: cython.int __dict__: dict def __cinit__(self, number_of_legs: cython.int): self.number_of_legs = number_of_legs dog = Animal(4) dog.has_tail = True
Animal
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_tm_future_annotations_sync.py
{ "start": 109625, "end": 115232 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): __dialect__ = "default" def test_mapped_column_omit_fn(self, decl_base): class MixinOne: name: Mapped[str] x: Mapped[int] y: Mapped[int] = mapped_column() class A(MixinOne, decl_base): __...
MixinTest
python
Lightning-AI__lightning
src/lightning/pytorch/plugins/precision/transformer_engine.py
{ "start": 765, "end": 1940 }
class ____(Precision, FabricTEPrecision): """Plugin for training with fp8 precision via nvidia's `Transformer Engine <https://docs.nvidia.com/deeplearning/transformer-engine>`__. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Args: dtype: The weights dtype ...
TransformerEnginePrecision
python
huggingface__transformers
src/transformers/models/deformable_detr/modeling_deformable_detr.py
{ "start": 33076, "end": 36963 }
class ____(GradientCheckpointingLayer): def __init__(self, config: DeformableDetrConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = DeformableDetrMultiscaleDeformableAttention( config, num_heads=config.encoder_attention_heads, n_p...
DeformableDetrEncoderLayer
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_correctness_ragged_training_test.py
{ "start": 954, "end": 1441 }
class ____( tpu_embedding_v2_correctness_base_test.TPUEmbeddingCorrectnessBaseTest): @parameterized.parameters( ['sgd', 'adagrad', 'adam', 'ftrl', 'adagrad_momentum']) def test_embedding(self, optimizer_name): if optimizer_name != 'sgd': self.skip_if_oss() self._test_embedding( opti...
TPUEmbeddingCorrectnessTest
python
Netflix__metaflow
test/core/tests/resume_recursive_switch_inside_foreach.py
{ "start": 63, "end": 2271 }
class ____(MetaflowTest): RESUME = True PRIORITY = 2 ONLY_GRAPHS = ["recursive_switch_inside_foreach"] @steps(0, ["start"], required=True) def step_start(self): if not is_resumed(): self.items = [ {"id": "A", "iterations": 3}, {"id": "B", "iterati...
ResumeRecursiveSwitchInsideForeachFlowTest
python
fluentpython__example-code
19-dyn-attr-prop/oscon/explore1.py
{ "start": 1059, "end": 1870 }
class ____: """A read-only façade for navigating a JSON-like object using attribute notation """ # BEGIN EXPLORE1 def __init__(self, mapping): self.__data = {} for key, value in mapping.items(): if keyword.iskeyword(key): # <1> key += '_' self...
FrozenJSON
python
getsentry__sentry
tests/sentry/db/test_transactions.py
{ "start": 5011, "end": 5165 }
class ____(CaseMixin, TransactionTestCase): def test_collect_transaction_queries(self) -> None: return
TestDjangoTransactionTestCaseTransactions
python
keon__algorithms
tests/test_graph.py
{ "start": 9729, "end": 10359 }
class ____(unittest.TestCase): def test_cycle_detection_with_cycle(self): graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['F'], 'D': ['E', 'F'], 'E': ['B'], 'F': []} self.assertTrue(cycle_detection.contains_cycle(graph)...
TestCycleDetection
python
django__django
django/contrib/postgres/aggregates/statistics.py
{ "start": 904, "end": 964 }
class ____(StatAggregate): function = "REGR_AVGX"
RegrAvgX
python
astropy__astropy
astropy/io/fits/tests/test_header.py
{ "start": 2075, "end": 103493 }
class ____(FitsTestCase): """Test Header and Card objects.""" def test_rename_keyword(self): """Test renaming keyword with rename_keyword.""" header = fits.Header([("A", "B", "C"), ("D", "E", "F")]) header.rename_keyword("A", "B") assert "A" not in header assert "B" in h...
TestHeaderFunctions
python
ApeWorX__ape
tests/functional/test_query.py
{ "start": 2223, "end": 3265 }
class ____(BaseInterfaceModel): number: int timestamp: int def test_column_expansion(): columns = validate_and_expand_columns(["*"], Model) assert columns == list(Model.model_fields) def test_column_validation(eth_tester_provider, ape_caplog): with pytest.raises(ValueError) as exc_info: ...
Model
python
bokeh__bokeh
src/bokeh/models/glyphs.py
{ "start": 11168, "end": 12230 }
class ____(LRTBGlyph): ''' Render rectangular regions, given a lower-left corner coordinate, width, and height. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) __example__ = "examples/reference/mod...
Block
python
ray-project__ray
ci/ray_ci/bisect/test_bisector.py
{ "start": 246, "end": 1613 }
class ____(Validator): def __init__(self, return_value: bool) -> None: self.return_value = return_value def run(self, test: Test, revision: str) -> bool: return self.return_value @mock.patch("ci.ray_ci.bisect.bisector.Bisector._checkout_and_validate") @mock.patch("ci.ray_ci.bisect.bisector.Bi...
MockValidator
python
allegroai__clearml
clearml/utilities/plotlympl/mplexporter/renderers/fake_renderer.py
{ "start": 77, "end": 2132 }
class ____(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are free to do anything you wish within ...
FakeRenderer
python
spyder-ide__spyder
spyder/utils/stylesheet.py
{ "start": 25921, "end": 29703 }
class ____(BaseDockTabBarStyleSheet): """Style for vertical dockwidget tab bars.""" SCROLL_BUTTONS_BORDER_POS = 'bottom' def set_stylesheet(self): super().set_stylesheet() # -- Main constants css = self.get_stylesheet() margin_size = AppStyle.MarginSize # -- Basic...
VerticalDockTabBarStyleSheet
python
PyCQA__pylint
tests/functional/n/not_async_context_manager.py
{ "start": 792, "end": 1511 }
class ____(InheritExit): def __aenter__(self): pass async def bad_coro(): async with 42: # [not-async-context-manager] pass async with ctx_manager(): # [not-async-context-manager] pass async with ContextManager(): # [not-async-context-manager] pass async with Partia...
SecondGoodAsyncManager
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 91956, "end": 92832 }
class ____(MeanMetricWrapper): """Computes the mean absolute error between the labels and predictions. Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. Standalone usage: >>> m = tf.keras.metrics.MeanAbsoluteError() >>> m.update_state([[0, ...
MeanAbsoluteError
python
numba__numba
numba/cuda/tests/doc_examples/test_reduction.py
{ "start": 201, "end": 2274 }
class ____(CUDATestCase): """ Test shared memory reduction """ def setUp(self): # Prevent output from this test showing up when running the test suite self._captured_stdout = captured_stdout() self._captured_stdout.__enter__() super().setUp() def tearDown(self): ...
TestReduction
python
ZoranPandovski__al-go-rithms
cryptography/blockchain/python/blockchain.py
{ "start": 829, "end": 1682 }
class ____: def __init__(self, index, data, previous_hash, reward): self.index = index self.data = data self.previous_hash = previous_hash self.timestamp = str(datetime.datetime.now()) hash_data = str(self.index) + str(self.previous_hash) + str(self.timestamp) + json.dumps(se...
Block
python
mlflow__mlflow
tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_dataset_source.py
{ "start": 224, "end": 1535 }
class ____(DatasetSource): def __init__(self, uri): self._uri = uri @property def uri(self): return self._uri @staticmethod def _get_source_type() -> str: return "dummy" def load(self) -> str: # Ignore the "dummy" URI scheme and download the local path ...
DummyDatasetSource
python
realpython__materials
python-contact-book/source_code_step_5/rpcontacts/model.py
{ "start": 160, "end": 1051 }
class ____: def __init__(self): self.model = self._createModel() @staticmethod def _createModel(): """Create and set up the model.""" tableModel = QSqlTableModel() tableModel.setTable("contacts") tableModel.setEditStrategy(QSqlTableModel.OnFieldChange) tableM...
ContactsModel
python
getsentry__sentry
src/sentry_plugins/sessionstack/plugin.py
{ "start": 997, "end": 6575 }
class ____(CorePluginMixin, Plugin2): description = "Watch SessionStack recordings in Sentry." title = "SessionStack" slug = "sessionstack" conf_title = title conf_key = slug required_field = "account_email" feature_descriptions = [ FeatureDescription( """ Wa...
SessionStackPlugin
python
PrefectHQ__prefect
src/prefect/server/schemas/core.py
{ "start": 38504, "end": 40541 }
class ____(ORMBaseModel): """An ORM representation of a work pool""" name: NonEmptyishName = Field( description="The name of the work pool.", ) description: Optional[str] = Field( default=None, description="A description of the work pool." ) type: str = Field(description="The wo...
WorkPool
python
pytorch__pytorch
benchmarks/dynamo/pr_time_benchmarks/benchmarks/dtensor.py
{ "start": 1110, "end": 1731 }
class ____(BenchmarkDTensorDispatch): def __init__(self, world_size) -> None: super().__init__(operator="detach", world_size=world_size) def _work(self) -> None: self.a.detach() def main(): world_size = 256 fake_store = FakeStore() torch.distributed.init_process_group( "fa...
BenchmarkDetach
python
pydantic__pydantic
tests/test_json_schema.py
{ "start": 96657, "end": 192893 }
class ____(BaseModel): my_enum_2: MyEnum """ ) class Model(BaseModel): my_model_1: module_1.MyModel my_model_2: module_2.MyModel assert len(Model.model_json_schema()['$defs']) == 4 assert set(Model.model_json_schema()['$defs']) == { f'{module_1.__name__}__MyEnum', ...
MyModel
python
sympy__sympy
sympy/polys/agca/modules.py
{ "start": 12822, "end": 14257 }
class ____(FreeModule): """ Free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of the ring instead: Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(3) >>> F QQ[x]**3...
FreeModulePolyRing
python
coleifer__peewee
tests/prefetch_tests.py
{ "start": 21761, "end": 25610 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [X, Z, A, B, C, C1, C2] def test_prefetch_multirefs(self): x1, x2, x3 = [X.create(name=n) for n in ('x1', 'x2', 'x3')] for i, x in enumerate((x1, x2, x3), 1): for j in range(i): Z.create(x=x, nam...
TestPrefetchMultiRefs
python
getsentry__sentry
src/sentry/insights/migrations/0001_squashed_0001_add_starred_transactions_model.py
{ "start": 325, "end": 3140 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 64036, "end": 64253 }
class ____(IPInterface): """A IPv4 Network Interface field.""" default_error_messages = {"invalid_ip_interface": "Not a valid IPv4 interface."} DESERIALIZATION_CLASS = ipaddress.IPv4Interface
IPv4Interface
python
pypa__virtualenv
src/virtualenv/seed/seeder.py
{ "start": 74, "end": 1155 }
class ____(ABC): """A seeder will install some seed packages into a virtual environment.""" def __init__(self, options, enabled) -> None: """ Create. :param options: the parsed options as defined within :meth:`add_parser_arguments` :param enabled: a flag weather the seeder is e...
Seeder
python
yaml__pyyaml
lib/yaml/events.py
{ "start": 479, "end": 667 }
class ____(Event): def __init__(self, anchor, start_mark=None, end_mark=None): self.anchor = anchor self.start_mark = start_mark self.end_mark = end_mark
NodeEvent
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 12851, "end": 13021 }
class ____(str, Enum): SUCCESS = "success" FAILED = "failed" SKIPPED = "skipped" UPSTREAM_FAILED = "upstream_failed" REMOVED = "removed"
TerminalTIState
python
fluentpython__example-code-2e
10-dp-1class-func/untyped/strategy_best.py
{ "start": 1587, "end": 3097 }
class ____: # the Context def __init__(self, customer, cart, promotion=None): self.customer = customer self.cart = list(cart) self.promotion = promotion def total(self): if not hasattr(self, '__total'): self.__total = sum(item.total() for item in self.cart) ...
Order
python
celery__celery
t/unit/utils/test_imports.py
{ "start": 3901, "end": 4064 }
class ____: def test_no_module(self): app = Mock() app.name == '__main__' assert gen_task_name(app, 'foo', 'axsadaewe')
test_gen_task_name
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 6620, "end": 7847 }
class ____: param_names = ["shapes", "how", "sort"] params = [ get_benchmark_shapes("TimeMerge"), ["left", "inner"], [True, False], ] def setup(self, shapes, how, sort): self.df1 = generate_dataframe("int", *shapes[0], RAND_LOW, RAND_HIGH) self.df2 = generate_dat...
TimeMerge
python
walkccc__LeetCode
solutions/3275. K-th Nearest Obstacle Queries/3275.py
{ "start": 0, "end": 328 }
class ____: def resultsArray(self, queries: list[list[int]], k: int) -> list[int]: ans = [] maxHeap = [] for x, y in queries: heapq.heappush(maxHeap, -(abs(x) + abs(y))) if len(maxHeap) > k: heapq.heappop(maxHeap) ans.append(-maxHeap[0] if len(maxHeap) == k else -1) return ...
Solution
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/rolling.py
{ "start": 1221, "end": 1279 }
class ____(UnaryOp): pass @dataclass(frozen=True)
RankOp
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_runner_strategy.py
{ "start": 1107, "end": 1358 }
class ____(TestCase): @given(st.runner()) def test_runner_is_self(self, runner): assert runner is self @given(st.runner(default=3)) def test_runner_is_self_even_with_default(self, runner): assert runner is self
TestStuff
python
scikit-learn__scikit-learn
sklearn/_loss/link.py
{ "start": 5593, "end": 8132 }
class ____(BaseLink): """The symmetric multinomial logit function. Convention: - y_pred.shape = raw_prediction.shape = (n_samples, n_classes) Notes: - The inverse link h is the softmax function. - The sum is over the second axis, i.e. axis=1 (n_classes). We have to choose addi...
MultinomialLogit
python
numba__numba
numba/misc/firstlinefinder.py
{ "start": 134, "end": 3253 }
class ____(ast.NodeVisitor): """ Attributes ---------- first_stmt_line : int or None This stores the first statement line number if the definition is found. Or, ``None`` if the definition is not found. """ def __init__(self, name, firstlineno): """ Parameters ...
FindDefFirstLine
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 13277, "end": 13711 }
class ____(serializers.Serializer): code = serializers.SerializerMethodField() name = serializers.SerializerMethodField() def get_code(self, programming_language): return programming_language def get_name(self, programming_language): for code, name in PROGRAMMING_LANGUAGES: ...
ProgrammingLanguageSerializer
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 162585, "end": 168870 }
class ____: def setup_method(self): self.rng = np.random.default_rng(333348228) def test_rvs(self): states = [-1, 0, 1, 2, 3, 4] probability = [0.0, 0.3, 0.4, 0.0, 0.3, 0.0] samples = 1000 r = stats.rv_discrete(name='sample', values=(states, probability)) x = r.r...
TestRvDiscrete
python
doocs__leetcode
solution/0300-0399/0303.Range Sum Query - Immutable/Solution.py
{ "start": 0, "end": 337 }
class ____: def __init__(self, nums: List[int]): self.s = list(accumulate(nums, initial=0)) def sumRange(self, left: int, right: int) -> int: return self.s[right + 1] - self.s[left] # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange...
NumArray
python
django__django
tests/file_storage/test_generate_filename.py
{ "start": 2329, "end": 9420 }
class ____(SimpleTestCase): def test_storage_dangerous_paths(self): candidates = [ ("/tmp/..", ".."), ("\\tmp\\..", ".."), ("/tmp/.", "."), ("\\tmp\\.", "."), ("..", ".."), (".", "."), ("", ""), ] s = FileSys...
GenerateFilenameStorageTests
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 6861, "end": 7322 }
class ____(HypothesisWarning, FutureWarning): """A deprecation warning issued by Hypothesis. Actually inherits from FutureWarning, because DeprecationWarning is hidden by the default warnings filter. You can configure the :mod:`python:warnings` module to handle these warnings differently to others...
HypothesisDeprecationWarning
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_correctness_hd_sparse_forward_test.py
{ "start": 954, "end": 1440 }
class ____( tpu_embedding_v2_correctness_base_test.TPUEmbeddingCorrectnessBaseTest): @parameterized.parameters( ['sgd', 'adagrad', 'adam', 'ftrl', 'adagrad_momentum']) def test_embedding(self, optimizer_name): if optimizer_name != 'sgd': self.skip_if_oss() self._test_embedding( opti...
TPUEmbeddingCorrectnessTest
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/tutorial/connecting/resources/__init__.py
{ "start": 43, "end": 175 }
class ____(ConfigurableResource): num_days: int = 4 def get_signups(self): return [1, 2, 3, 4, 5]
DataGeneratorResource
python
kamyu104__LeetCode-Solutions
Python/super-pow.py
{ "start": 50, "end": 587 }
class ____(object): def superPow(self, a, b): """ :type a: int :type b: List[int] :rtype: int """ def myPow(a, n, b): result = 1 x = a % b while n: if n & 1: result = result * x % b ...
Solution
python
openai__openai-python
src/openai/types/responses/response_code_interpreter_call_in_progress_event.py
{ "start": 219, "end": 767 }
class ____(BaseModel): item_id: str """The unique identifier of the code interpreter tool call item.""" output_index: int """ The index of the output item in the response for which the code interpreter call is in progress. """ sequence_number: int """The sequence number of this eve...
ResponseCodeInterpreterCallInProgressEvent
python
pytorch__pytorch
test/distributed/_tools/test_runtime_estimator.py
{ "start": 655, "end": 2030 }
class ____(nn.Module): def __init__(self, conv_args: ConvArgs): super().__init__() image_size = conv_args.image_size num_classes = conv_args.num_classes self.image_size = image_size self.conv1 = nn.Conv2d(3, 32, kernel_size=5) self.pool = nn.MaxPool2d(2, 2) se...
SimpleCNN
python
pandas-dev__pandas
pandas/tests/frame/methods/test_set_axis.py
{ "start": 3269, "end": 3945 }
class ____(SharedSetAxisTests): @pytest.fixture def obj(self): df = DataFrame( {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2], "C": [4.4, 5.5, 6.6]}, index=[2010, 2011, 2012], ) return df def test_set_axis_with_allows_duplicate_labels_false(self): # GH#4...
TestDataFrameSetAxis
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 49650, "end": 51303 }
class ____(Action): """Base class for Actions that operate on Work Pools and need to infer them from events""" source: Literal["selected", "inferred"] = Field( "selected", description=( "Whether this Action applies to a specific selected " "work pool (given by `work_...
WorkPoolAction
python
astropy__astropy
astropy/units/tests/test_quantity_array_methods.py
{ "start": 391, "end": 2762 }
class ____: """ Test whether arrays are properly copied/used in place """ def test_copy_on_creation(self): v = np.arange(1000.0) q_nocopy = u.Quantity(v, "km/s", copy=False) q_copy = u.Quantity(v, "km/s", copy=True) v[0] = -1.0 assert q_nocopy[0].value == v[0] ...
TestQuantityArrayCopy
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py
{ "start": 17508, "end": 19254 }
class ____(StreamSlicer): def __init__(self, cursor: Optional[ConcurrentCursor]) -> None: self._cursor = cursor def get_request_params( self, *, stream_state: Optional[StreamState] = None, stream_slice: Optional[StreamSlice] = None, next_page_token: Optional[Mapp...
BulkDatetimeStreamSlicer
python
django__django
tests/gis_tests/gdal_tests/test_raster.py
{ "start": 27123, "end": 35282 }
class ____(SimpleTestCase): rs_path = os.path.join(os.path.dirname(__file__), "../data/rasters/raster.tif") def test_band_data(self): rs = GDALRaster(self.rs_path) band = rs.bands[0] self.assertEqual(band.width, 163) self.assertEqual(band.height, 174) self.assertEqual(ba...
GDALBandTests
python
docker__docker-py
docker/errors.py
{ "start": 2697, "end": 2747 }
class ____(DockerException): pass
InvalidVersion
python
pypa__warehouse
warehouse/utils/wsgi.py
{ "start": 835, "end": 4484 }
class ____: def __init__(self, app, token, ip_salt: str, num_proxies=1): self.app = app self.token = token self.ip_salt = ip_salt self.num_proxies = num_proxies def __call__(self, environ, start_response): # Determine if the request comes from a trusted proxy or not by l...
ProxyFixer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/tags.py
{ "start": 505, "end": 769 }
class ____(graphene.ObjectType): key = graphene.NonNull(graphene.String) value = graphene.NonNull(graphene.String) class Meta: name = "EventTag" def __init__(self, key, value): super().__init__(key=key, value=value)
GrapheneEventTag
python
sqlalchemy__sqlalchemy
test/typing/plain_files/orm/mapped_column.py
{ "start": 588, "end": 5329 }
class ____(Base): __tablename__ = "x" # these are fine - pk, column is not null, have the attribute be # non-optional, fine id: Mapped[int] = mapped_column(primary_key=True) int_id: Mapped[int] = mapped_column(Integer, primary_key=True) # but this is also "fine" because the developer may wish ...
X
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 7352, "end": 8144 }
class ____(HTTPClientError): status_code = 405 def __init__( self, method: str, allowed_methods: Iterable[str], *, headers: LooseHeaders | None = None, reason: str | None = None, text: str | None = None, content_type: str | None = None, ) -> N...
HTTPMethodNotAllowed
python
PrefectHQ__prefect
tests/utilities/schema_tools/test_hydration.py
{ "start": 11819, "end": 15131 }
class ____: @pytest.mark.parametrize( "input_object, expected_output, ctx", [ ( # The workspace variable is resolved first. # It returns a jinja template that renders # and outputs a JSON string of '"4"'. # the JSON string i...
TestNestedHydration
python
doocs__leetcode
solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/Solution2.py
{ "start": 0, "end": 157 }
class ____: def minStartValue(self, nums: List[int]) -> int: s = list(accumulate(nums)) return 1 if min(s) >= 0 else abs(min(s)) + 1
Solution
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item_retrieve_event.py
{ "start": 235, "end": 559 }
class ____(BaseModel): item_id: str """The ID of the item to retrieve.""" type: Literal["conversation.item.retrieve"] """The event type, must be `conversation.item.retrieve`.""" event_id: Optional[str] = None """Optional client-generated ID used to identify this event."""
ConversationItemRetrieveEvent
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_python_ast_rule.py
{ "start": 447, "end": 6676 }
class ____: """Test the _extract_python_code_blocks function.""" def test_extract_single_code_block(self): """Test extracting a single Python code block.""" docstring = """ This is a docstring. .. code-block:: python def hello(): ret...
TestExtractPythonCodeBlocks
python
astropy__astropy
astropy/io/ascii/fastbasic.py
{ "start": 9243, "end": 9690 }
class ____(FastBasic): """ A faster version of the ordinary :class:`Tab` reader that uses the optimized C parsing engine. """ _format_name = "fast_tab" _description = "Tab-separated values table using the fast C engine" _fast = True def __init__(self, **kwargs): super().__init_...
FastTab
python
PyCQA__pylint
pylint/reporters/ureports/base_writer.py
{ "start": 725, "end": 3440 }
class ____: """Base class for ureport writers.""" def format( self, layout: BaseLayout, stream: TextIO = sys.stdout, encoding: str | None = None, ) -> None: """Format and write the given layout into the stream object. unicode policy: unicode strings may be f...
BaseWriter