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
doocs__leetcode
solution/2100-2199/2100.Find Good Days to Rob the Bank/Solution.py
{ "start": 0, "end": 527 }
class ____: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: n = len(security) if n <= time * 2: return [] left, right = [0] * n, [0] * n for i in range(1, n): if security[i] <= security[i - 1]: left[i] = left[i - 1] + ...
Solution
python
django-guardian__django-guardian
example_project/articles/models.py
{ "start": 795, "end": 932 }
class ____(UserObjectPermissionBase): content_object = models.ForeignKey(Article, on_delete=models.CASCADE)
ArticleUserObjectPermission
python
xlwings__xlwings
tests/test_table.py
{ "start": 120, "end": 4968 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.book = xw.Book() cls.sheet = cls.book.sheets[0] cls.sheet["A1"].value = [["a", "b"], [1, 2]] cls.test_table = cls.sheet.tables.add(source=cls.sheet["A1"].expand()) @classmethod def tearDownClass(cls): ...
TestTable
python
ray-project__ray
python/ray/data/expressions.py
{ "start": 31412, "end": 36964 }
class ____(Expr): """Expression that represents all columns from the input. This is a special expression used in projections to indicate that all existing columns should be preserved at this position in the output. It's typically used internally by operations like with_column() and rename_columns()...
StarExpr
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 2972, "end": 3358 }
class ____(nodes.Element, not_smartquotable): """Helper base class for injecting a fixed list of classes. Use as the first base class. """ classes: list[str] = [] def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self['classes'].extend(self.c...
_desc_classes_injector
python
numpy__numpy
numpy/_core/tests/test_unicode.py
{ "start": 5456, "end": 5611 }
class ____(CreateValues): """Check the creation of valued arrays (size 2, UCS4 values)""" ulen = 2 ucs_value = ucs4_value
TestCreateValues_2_UCS4
python
astropy__astropy
astropy/extern/configobj/configobj.py
{ "start": 11977, "end": 13202 }
class ____(InterpolationEngine): """Behaves like string.Template.""" _cookie = '$' _delimiter = '$' _KEYCRE = re.compile(r""" \$(?: (?P<escaped>\$) | # Two $ signs (?P<named>[_a-z][_a-z0-9]*) | # $name format {(?P<braced>[^}]*)} # ${na...
TemplateInterpolation
python
google__pytype
pytype/abstract/_classes.py
{ "start": 41020, "end": 47466 }
class ____(ParameterizedClass, mixin.HasSlots): # pytype: disable=signature-mismatch """The class of a heterogeneous tuple. The formal_type_parameters attribute stores the types of the individual tuple elements under their indices and the overall element type under "T". So for Tuple[str, int] formal_type_...
TupleClass
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 7225, "end": 7308 }
class ____(PydanticTypeError): msg_template = 'value is not a valid set'
SetError
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/pyodbc.py
{ "start": 20285, "end": 22358 }
class ____(MSExecutionContext): _embedded_scope_identity = False def pre_exec(self): """where appropriate, issue "select scope_identity()" in the same statement. Background on why "scope_identity()" is preferable to "@@identity": https://msdn.microsoft.com/en-us/library/ms19031...
MSExecutionContext_pyodbc
python
pytorch__pytorch
torch/distributed/checkpoint/storage.py
{ "start": 511, "end": 5543 }
class ____(abc.ABC): """ Interface used by ``save_state_dict`` to write to storage. One StorageWriter instance acts as both the coordinator and the follower in a distributed checkpoint. As part of initialization, each instance is told its role. A subclass should expect the following sequence o...
StorageWriter
python
apache__airflow
providers/alibaba/tests/unit/alibaba/cloud/hooks/test_oss.py
{ "start": 1260, "end": 7393 }
class ____: def setup_method(self): with mock.patch( OSS_STRING.format("OSSHook.__init__"), new=mock_oss_hook_default_project_id, ): self.hook = OSSHook(oss_conn_id=MOCK_OSS_CONN_ID) def test_parse_oss_url(self): parsed = self.hook.parse_oss_url(f"oss...
TestOSSHook
python
pandas-dev__pandas
pandas/tests/indexing/test_loc.py
{ "start": 8917, "end": 59817 }
class ____: # Tests for loc that do not depend on subclassing Base def test_loc_npstr(self): # GH#45580 df = DataFrame(index=date_range("2021", "2022")) result = df.loc[np.array(["2021/6/1"])[0] :] expected = df.iloc[151:] tm.assert_frame_equal(result, expected) @pyt...
TestLocBaseIndependent
python
TheAlgorithms__Python
machine_learning/polynomial_regression.py
{ "start": 1346, "end": 7650 }
class ____: __slots__ = "degree", "params" def __init__(self, degree: int) -> None: """ @raises ValueError: if the polynomial degree is negative """ if degree < 0: raise ValueError("Polynomial degree must be non-negative") self.degree = degree self.p...
PolynomialRegression
python
kamyu104__LeetCode-Solutions
Python/power-of-heroes.py
{ "start": 59, "end": 381 }
class ____(object): def sumOfPower(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 nums.sort() result = dp = 0 for x in nums: result = (result+(x**2)*(dp+x))%MOD dp = (dp+(dp+x))%MOD return result
Solution
python
getsentry__sentry
src/sentry/db/models/fields/bounded.py
{ "start": 1011, "end": 1764 }
class ____(models.IntegerField): """ This type allows storing a full unsigned `u32` value by manually wrapping it around, so it is stored as a signed `i32` value in the database. """ MIN_VALUE = 0 MAX_VALUE = U32_MAX def get_prep_value(self, value: int) -> int: if value: ...
WrappingU32IntegerField
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/operators/search_ads.py
{ "start": 6257, "end": 8246 }
class ____(_GoogleSearchAdsBaseOperator): """ Retrieve metadata for resource(s) or field(s) by the query syntax. .. seealso: For API documentation check: https://developers.google.com/search-ads/reporting/api/reference/rest/v0/searchAds360Fields/search .. seealso:: For more inf...
GoogleSearchAdsSearchFieldsOperator
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/image_ops/decode_raw_op_test.py
{ "start": 984, "end": 4869 }
class ____(test.TestCase): def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): for dtype in [dtypes.bool, dtypes.int8, dtypes.uint8, dtypes.int16, dtypes.uint16, dtypes.int32, dtypes.int64, dtypes.float16, ...
DecodeRawOpTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict9.py
{ "start": 531, "end": 597 }
class ____(TypedDict): y: str z: Literal[""] | Inner3
Outer2
python
pytorch__pytorch
test/distributed/tensor/test_utils.py
{ "start": 18575, "end": 22402 }
class ____(TestCase): def test_compute_global_tensor_info_unsupported_placement(self): class MockDeviceMesh: def size(self, x): return x class FakePlacement(Placement): pass device_mesh: Any = MockDeviceMesh() local_tensor = torch.tensor([1])...
UtilSingleDeviceTest
python
google__jax
jax/_src/core.py
{ "start": 113570, "end": 113957 }
class ____: def __init__(self, obj): self.id = id(obj) def __repr__(self): return f'<axis {hex(self.id)}>' def __hash__(self): return hash(self.id) def __eq__(self, other): return type(other) is _TempAxisName and self.id == other.id def __lt__(self, other): return type(other) is _Temp...
_TempAxisName
python
kamyu104__LeetCode-Solutions
Python/product-of-two-run-length-encoded-arrays.py
{ "start": 33, "end": 885 }
class ____(object): def findRLEArray(self, encoded1, encoded2): """ :type encoded1: List[List[int]] :type encoded2: List[List[int]] :rtype: List[List[int]] """ result = [] i = j = remain1 = remain2 = 0 while (remain1 or i < len(encoded1)) and (remain2 ...
Solution
python
pytorch__pytorch
torch/utils/_contextlib.py
{ "start": 4819, "end": 5915 }
class ____: """Allow a context manager to be used as a decorator.""" def __call__(self, orig_func: F) -> F: if inspect.isclass(orig_func): warnings.warn( "Decorating classes is deprecated and will be disabled in " "future versions. You should only decorate fu...
_DecoratorContextManager
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI052.py
{ "start": 3708, "end": 3750 }
class ____(Enum): FOO = 0 BAR = 1
Foo
python
pennersr__django-allauth
allauth/socialaccount/providers/discogs/provider.py
{ "start": 433, "end": 696 }
class ____(OAuthProvider): id = "discogs" name = "discogs" account_class = DiscogsAccount oauth_adapter_class = DiscogsOAuthAdapter def extract_uid(self, data): return str(data["id"]) provider_classes = [DiscogsProvider]
DiscogsProvider
python
getsentry__sentry
src/sentry/integrations/bitbucket/webhook.py
{ "start": 2220, "end": 2431 }
class ____(SentryAPIException): status_code = 400 code = f"{PROVIDER_NAME}.webhook.unsupported-signature-method" message = "Signature method is not supported"
WebhookUnsupportedSignatureMethodException
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 31273, "end": 33323 }
class ____(LossFunctionWrapper): """Computes the squared hinge loss between `y_true` and `y_pred`. `loss = square(maximum(1 - y_true * y_pred, 0))` `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. Standalone usage: >>> y_true = [[0., 1.]...
SquaredHinge
python
huggingface__transformers
src/transformers/models/modernbert/modeling_modernbert.py
{ "start": 60067, "end": 64414 }
class ____(ModernBertPreTrainedModel): def __init__(self, config: ModernBertConfig): super().__init__(config) self.num_labels = config.num_labels self.model = ModernBertModel(config) self.head = ModernBertPredictionHead(config) self.drop = torch.nn.Dropout(config.classifier_...
ModernBertForQuestionAnswering
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/versions/v2025_08_10.py
{ "start": 1128, "end": 1912 }
class ____(VersionChange): """Add the `state` field to DagRun model and `/dag-runs/{dag_id}/previous` endpoint.""" description = __doc__ instructions_to_migrate_to_previous_version = ( schema(DagRun).field("state").didnt_exist, endpoint("/dag-runs/{dag_id}/previous", ["GET"]).didnt_exist, ...
AddDagRunStateFieldAndPreviousEndpoint
python
tensorflow__tensorflow
tensorflow/python/distribute/v1/input_lib.py
{ "start": 13079, "end": 14666 }
class ____(input_lib._SingleWorkerDatasetIteratorBase): # pylint: disable=protected-access """Iterator for a single DistributedDatasetV1 instance.""" def _make_iterator(self): """Make appropriate iterator on the dataset.""" with ops.device(self._worker): if self._options is not None: self._i...
_SingleWorkerDatasetIterator
python
pandas-dev__pandas
asv_bench/benchmarks/pandas_vb_common.py
{ "start": 1329, "end": 1740 }
class ____: """ Base class for IO benchmarks """ fname = None def remove(self, f): """Remove created files""" try: os.remove(f) except OSError: # On Windows, attempting to remove a file that is in use # causes an exception to be raised ...
BaseIO
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 8612, "end": 8939 }
class ____(graphene.ObjectType): """Output indicating that a run failed to terminate.""" run = graphene.NonNull(GrapheneRun) message = graphene.NonNull(graphene.String) class Meta: interfaces = (GrapheneTerminatePipelineExecutionFailure,) name = "TerminateRunFailure"
GrapheneTerminateRunFailure
python
astropy__astropy
astropy/io/ascii/tdat.py
{ "start": 25311, "end": 26881 }
class ____(core.TableOutputter): """ Output the table as an astropy.table.Table object. """ def __call__(self, cols, meta): """ READ: Override the default outputter. TDAT files may (optionally) specify which field lines should be used as the primary index and secondary i...
TdatOutputter
python
pydantic__pydantic
pydantic/networks.py
{ "start": 27609, "end": 28128 }
class ____(_BaseMultiHostUrl): """A type that will accept any NATS DSN. NATS is a connective technology built for the ever increasingly hyper-connected world. It is a single technology that enables applications to securely communicate across any combination of cloud vendors, on-premise, edge, web and m...
NatsDsn
python
Lightning-AI__lightning
tests/tests_pytorch/plugins/precision/test_double.py
{ "start": 944, "end": 1298 }
class ____(Dataset): def __init__(self, size, length): self.len = length self.float_data = torch.randn(length, size) self.int_data = torch.randint(10, (length, 1)) def __getitem__(self, index): return self.float_data[index], self.int_data[index] def __len__(self): r...
RandomFloatIntDataset
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/models/cloud_run_v2.py
{ "start": 527, "end": 8210 }
class ____(BaseModel): """ JobV2 is a data model for a job that will be run on Cloud Run with the V2 API. """ name: str uid: str generation: str labels: Dict[str, str] = Field(default_factory=dict) annotations: Dict[str, str] = Field(default_factory=dict) createTime: str updateT...
JobV2
python
numba__numba
numba/cuda/stubs.py
{ "start": 4835, "end": 5131 }
class ____(Stub): ''' match_any_sync(mask, value) Nvvm intrinsic for performing a compare and broadcast across a warp. Returns a mask of threads that have same value as the given value from within the masked warp. ''' _description_ = '<match_any_sync()>'
match_any_sync
python
readthedocs__readthedocs.org
readthedocs/integrations/migrations/0009_migrate_headers_data.py
{ "start": 972, "end": 1178 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("integrations", "0008_add_new_jsonfields"), ] operations = [migrations.RunPython(forwards_func)]
Migration
python
apache__airflow
providers/apache/pinot/tests/unit/apache/pinot/hooks/test_pinot.py
{ "start": 14885, "end": 16256 }
class ____: def setup_method(self): self.conn = conn = mock.MagicMock() self.conn.host = "host" self.conn.port = "1000" self.conn.conn_type = "http" self.conn.login = "user" self.conn.password = "pwd" self.conn.extra_dejson = {"endpoint": "query/sql"} ...
TestPinotDbApiHookWithAuth
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/apps.py
{ "start": 36, "end": 150 }
class ____(AppConfig): name = 'easy_thumbnails.tests' label = 'easy_thumbnails_tests'
EasyThumbnailsTestConfig
python
django__django
tests/check_framework/test_security.py
{ "start": 7441, "end": 8281 }
class ____(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(base.check_sts(None), [base.W004]) ...
CheckStrictTransportSecurityTest
python
apache__airflow
providers/google/src/airflow/providers/google/suite/transfers/local_to_drive.py
{ "start": 1263, "end": 5850 }
class ____(BaseOperator): """ Upload a list of files to a Google Drive folder. This operator uploads a list of local files to a Google Drive folder. The local files can optionally be deleted after upload. .. seealso:: For more information on how to use this operator, take a look at the gui...
LocalFilesystemToGoogleDriveOperator
python
Netflix__metaflow
metaflow/plugins/env_escape/client_modules.py
{ "start": 277, "end": 4304 }
class ____(object): def __init__(self, loader, prefix, exports, client): self._loader = loader self._prefix = prefix self._client = client is_match = re.compile( r"^%s\.([a-zA-Z_][a-zA-Z0-9_]*)$" % prefix.replace(".", r"\.") # noqa W605 ) self._exports = ...
_WrappedModule
python
kamyu104__LeetCode-Solutions
Python/satisfiability-of-equality-equations.py
{ "start": 1141, "end": 2338 }
class ____(object): def equationsPossible(self, equations): """ :type equations: List[str] :rtype: bool """ graph = [[] for _ in xrange(26)] for eqn in equations: x = ord(eqn[0]) - ord('a') y = ord(eqn[3]) - ord('a') if eqn[1] == '...
Solution2
python
getsentry__sentry
tests/sentry/services/test_organization_actions.py
{ "start": 9610, "end": 11401 }
class ____(TestCase): def test_slug_under_size_limit(self) -> None: slug = generate_deterministic_organization_slug( desired_slug_base="santry", desired_org_name="santry", owning_user_id=42 ) assert slug == "santry-095a9012d" def test_slug_above_size_limit(self) -> None: ...
TestGenerateDeterministicOrganizationSlug
python
automl__auto-sklearn
test/test_pipeline/components/classification/test_multinomial_nb.py
{ "start": 272, "end": 1832 }
class ____(BaseClassificationComponentTest): __test__ = True res = dict() res["default_iris"] = 0.97999999999999998 res["iris_n_calls"] = None res["default_iris_iterative"] = 0.97999999999999998 res["default_iris_proba"] = 0.5865733413579101 res["default_iris_sparse"] = 0.54 res["defau...
MultinomialNBComponentTest
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_field_common.py
{ "start": 5667, "end": 11569 }
class ____(TypeError): """ Raised when trying to assign a value with a type that doesn't match the declared type. Attributes: source_class -- The class of the record field -- Field name expected_types -- Types allowed for the field actual_type -- The non matching type """ def __ini...
PTypeError
python
gevent__gevent
src/gevent/tests/known_failures.py
{ "start": 4249, "end": 4454 }
class ____(_Action): __slots__ = () def __init__(self, reason='', when=ALWAYS, ignore_coverage=NEVER): _Action.__init__(self, reason, run_alone=when, ignore_coverage=ignore_coverage)
RunAlone
python
pypa__installer
tests/test_core.py
{ "start": 1051, "end": 3286 }
class ____(WheelSource): def __init__(self, *, distribution, version, regular_files, dist_info_files): super().__init__(distribution, version) self.dist_info_files = { file: textwrap.dedent(content.decode("utf-8")) for file, content in dist_info_files.items() } ...
FakeWheelSource
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image12.py
{ "start": 315, "end": 916 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image12.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(...
TestCompareXLSXFiles
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 204945, "end": 212694 }
class ____(Response): """ Response of datasets.get_versions endpoint. :param versions: List of versions :type versions: Sequence[Version] """ _service = "datasets" _action = "get_versions" _version = "2.23" _schema = { "definitions": { "stat_count": { ...
GetVersionsResponse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1537755, "end": 1538849 }
class ____(sgqlc.types.Type, Node): """Represents an 'unmarked_as_duplicate' event on a given issue or pull request. """ __schema__ = github_schema __field_names__ = ("actor", "canonical", "created_at", "duplicate", "is_cross_repository") actor = sgqlc.types.Field(Actor, graphql_name="actor") ...
UnmarkedAsDuplicateEvent
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType32.py
{ "start": 286, "end": 370 }
class ____(Foo[T]): ... def func(x: Contra[Foo[int]]): v: Contra[Bar[int]] = x
Bar
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_format05.py
{ "start": 315, "end": 1137 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_format05.xlsx") def test_create_file(self): """Test the creation of a file with user defined default format""" workbook = ...
TestCompareXLSXFiles
python
sphinx-doc__sphinx
sphinx/ext/linkcode.py
{ "start": 872, "end": 3040 }
class ____(SphinxError): category = 'linkcode error' def doctree_read(app: Sphinx, doctree: Node) -> None: env = app.env resolve_target = getattr(env.config, 'linkcode_resolve', None) if not callable(env.config.linkcode_resolve): msg = 'Function `linkcode_resolve` is not given in conf.py' ...
LinkcodeError
python
zarr-developers__zarr-python
src/zarr/codecs/sharding.py
{ "start": 7434, "end": 25286 }
class ____( ArrayBytesCodec, ArrayBytesCodecPartialDecodeMixin, ArrayBytesCodecPartialEncodeMixin ): """Sharding codec""" chunk_shape: tuple[int, ...] codecs: tuple[Codec, ...] index_codecs: tuple[Codec, ...] index_location: ShardingCodecIndexLocation = ShardingCodecIndexLocation.end def _...
ShardingCodec
python
OmkarPathak__pygorithm
tests/test_geometry.py
{ "start": 22527, "end": 39892 }
class ____(unittest.TestCase): def setUp(self): random.seed() def test_constructor_standard(self): poly = polygon2.Polygon2([ vector2.Vector2(0, 1), vector2.Vector2(1, 1), vector2.Vector2(1, 0), ...
TestPolygon
python
pytorch__pytorch
test/inductor/test_quantization.py
{ "start": 727, "end": 1200 }
class ____(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(1, 64) self.fc2 = torch.nn.Linear(64, 64) self.fc3 = torch.nn.Linear(64, 64) self.fc4 = torch.nn.Linear(64, 1) def forward(self, x): x = torch.relu(self.fc1(x)) ...
FeedforwardNN
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_types.py
{ "start": 2254, "end": 9280 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = oracle.OracleDialect() def test_no_clobs_for_string_params(self): """test that simple string params get a DBAPI type of VARCHAR, not CLOB. This is to prevent setinputsizes from setting up cx_oracle.CLOBs on string-...
DialectTypesTest
python
huggingface__transformers
tests/models/sam2/test_processor_sam2.py
{ "start": 1034, "end": 4595 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Sam2Processor def prepare_image_inputs(self): """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, or a list of PyTorch tensors if one specifies torchify=True. """ ...
Sam2ProcessorTest
python
sphinx-doc__sphinx
tests/test_ext_napoleon/test_ext_napoleon.py
{ "start": 2590, "end": 3888 }
class ____: def test_unknown_app_type(self) -> None: setup(object()) # type: ignore[arg-type] def test_add_config_values(self) -> None: app = mock.Mock(Sphinx) setup(app) for name, _default, _rebuild, _types in Config._config_values: has_config = False f...
TestSetup
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 81307, "end": 84221 }
class ____(CIntLike, CNumericType): is_int = 1 typedef_flag = 0 exception_value = -1 def get_to_py_type_conversion(self): if self.rank < list(rank_to_type_name).index('int'): # This assumes sizeof(short) < sizeof(int) return "PyLong_FromLong" # PyLong_From[Unsi...
CIntType
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 17607, "end": 17665 }
class ____(TreeTestCase): pass
IntraTreeMovementTestCase
python
ansible__ansible
test/units/playbook/test_base.py
{ "start": 8992, "end": 9343 }
class ____(base.Base): test_attr_parent_string = FieldAttribute(isa='string', default='A string attr for a class that may be a parent for testing') def __init__(self): super(ExampleParentBaseSubClass, self).__init__() self._dep_chain = None def get_dep_chain(self): return self._de...
ExampleParentBaseSubClass
python
pytorch__pytorch
torch/_inductor/cpu_vec_isa.py
{ "start": 12073, "end": 16673 }
class ____(VecISA): _bit_width = 0 _macro = [""] _arch_flags = "" _dtype_nelements = {} def __str__(self) -> str: return "INVALID_VEC_ISA" def __bool__(self) -> bool: # type: ignore[override] return False __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore...
InvalidVecISA
python
tiangolo__fastapi
tests/test_security_openid_connect_optional.py
{ "start": 298, "end": 2488 }
class ____(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(oid)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: Optional[User] = Depends(get_current_user)): ...
User
python
facebook__pyre-check
client/commands/initialize.py
{ "start": 817, "end": 9241 }
class ____(Exception): pass def _create_source_directory_element(source: str) -> Union[str, Dict[str, str]]: if source == ".": return source if not Path(source).is_dir(): raise InitializationException(f"No directory found at `{source}`.") # Imports are likely relative to the parent of ...
InitializationException
python
tensorflow__tensorflow
tensorflow/lite/python/lite_flex_test.py
{ "start": 1864, "end": 5472 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.named_parameters( ('EnableMlirConverter', True), # enable mlir ('DisableMlirConverter', False)) # disable mlir def testFlexMode(self, enable_mlir): with ops.Graph().as_default(): in_tensor = array_ops.placehold...
FromSessionTest
python
python-markdown__markdown
tests/test_syntax/extensions/test_code_hilite.py
{ "start": 29738, "end": 29922 }
class ____(treeprocessors.Treeprocessor): def run(self, root: etree.Element): pre = etree.SubElement(root, 'pre') etree.SubElement(pre, 'code')
_AddCodeTagTreeprocessor
python
chardet__chardet
chardet/chardistribution.py
{ "start": 4663, "end": 5429 }
class ____(CharDistributionAnalysis): def __init__(self) -> None: super().__init__() self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER self._table_size = EUCTW_TABLE_SIZE self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO def get_order(self, byte_str: Union[byt...
EUCTWDistributionAnalysis
python
huggingface__transformers
src/transformers/models/align/processing_align.py
{ "start": 975, "end": 2358 }
class ____(ProcessorMixin): r""" Constructs an ALIGN processor which wraps [`EfficientNetImageProcessor`] and [`BertTokenizer`]/[`BertTokenizerFast`] into a single processor that inherits both the image processor and tokenizer functionalities. See the [`~AlignProcessor.__call__`] and [`~OwlViTProcessor....
AlignProcessor
python
django__django
tests/auth_tests/test_validators.py
{ "start": 7648, "end": 11907 }
class ____(TestCase): def test_validate(self): user = User.objects.create_user( username="testclient", password="password", email="testclient@example.com", first_name="Test", last_name="Client", ) expected_error = "The password is t...
UserAttributeSimilarityValidatorTest
python
ApeWorX__ape
src/ape/api/address.py
{ "start": 9569, "end": 10215 }
class ____(BaseAddress): """ A generic blockchain address. Typically, this is used when we do not know the contract type at a given address, or to refer to an EOA the user doesn't personally control. """ def __init__(self, address: AddressType): self._address = address @property ...
Address
python
dask__distributed
distributed/objects.py
{ "start": 496, "end": 682 }
class ____(dict): """A dictionary of all keys and which workers have that key.""" def _repr_html_(self): return get_template("who_has.html.j2").render(who_has=self)
WhoHas
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/impl.py
{ "start": 3260, "end": 21868 }
class ____: """Sentinel passed over multiprocessing Queue when launch is successful in subprocess.""" def _report_run_failed_if_not_finished( instance: DagsterInstance, run_id: str ) -> Generator[DagsterEvent, None, None]: check.inst_param(instance, "instance", DagsterInstance) dagster_run = instance....
StartRunInSubprocessSuccessful
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py
{ "start": 854, "end": 939 }
class ____(Model): asset_key: str filename: str
SimplePipesScriptComponentModel
python
pytorch__pytorch
test/dynamo/test_functions.py
{ "start": 81134, "end": 81737 }
class ____(torch.nn.Module): def forward(self, L_lambda0_keywords_y_: "f32[2, 2]"): l_lambda0_keywords_y_ = L_lambda0_keywords_y_ mul: "f32[2, 2]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_ mul_1: "f32[2, 2]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_; l_lambda0_keywords_y_ = Non...
GraphModule
python
django__django
tests/generic_relations/tests.py
{ "start": 35404, "end": 37754 }
class ____(TestCase): def test_default_behavior(self): """ The default for for_concrete_model should be True """ base = ForConcreteModelModel() base.obj = rel = ProxyRelatedModel.objects.create() base.save() base = ForConcreteModelModel.objects.get(pk=base.pk...
ProxyRelatedModelTest
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 33739, "end": 34095 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("es_ES") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in EsEsProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in EsEs...
TestEsEs
python
kamyu104__LeetCode-Solutions
Python/lru-cache.py
{ "start": 1620, "end": 2359 }
class ____(object): def __init__(self, capacity): self.list = LinkedList() self.dict = {} self.capacity = capacity def get(self, key): if key not in self.dict: return -1 val = self.dict[key].val self.__update(key, val) return val def put...
LRUCache2
python
ray-project__ray
doc/source/serve/doc_code/faker.py
{ "start": 0, "end": 196 }
class ____: """Mock Faker class to test fake_email_creator.py. Meant to mock https://github.com/joke2k/faker package. """ def email(self) -> str: return "fake@fake.com"
Faker
python
pytorch__pytorch
test/custom_backend/backend.py
{ "start": 1057, "end": 1939 }
class ____(torch.nn.Module): """ Simple model used for testing that to_backend API supports saving, loading, and executing in C++. """ def forward(self, a, b): return (a + b, a - b) def main(): parser = argparse.ArgumentParser(description="Lower a Module to a custom backend") pars...
Model
python
scipy__scipy
benchmarks/benchmarks/stats.py
{ "start": 25426, "end": 25960 }
class ____(Benchmark): param_names = ['d', 'radius', 'ncandidates', 'n'] params = [ [1, 3, 5], [0.2, 0.1, 0.05], [30, 60, 120], [30, 100, 300] ] def setup(self, d, radius, ncandidates, n): self.rng = np.random.default_rng(168525179735951991038384544) def tim...
BenchPoissonDisk
python
huggingface__transformers
tests/models/conditional_detr/test_modeling_conditional_detr.py
{ "start": 21566, "end": 25082 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50") if is_vision_available() else None ) def test_inference_no_head(self): ...
ConditionalDetrModelIntegrationTests
python
getsentry__sentry
src/sentry/seer/sentry_data_models.py
{ "start": 2466, "end": 2579 }
class ____(BaseModel): transaction_name: str project_id: int issues: list[IssueDetails]
TransactionIssues
python
spack__spack
lib/spack/spack/cmd/common/arguments.py
{ "start": 5492, "end": 5869 }
class ____(argparse.Action): """Creates a flag of valid dependency types from a deptype argument.""" def __call__(self, parser, namespace, values, option_string=None): if not values or values == "all": deptype = dt.ALL else: deptype = dt.canonicalize(values.split(",")) ...
DeptypeAction
python
doocs__leetcode
lcof2/剑指 Offer II 101. 分割等和子串/Solution2.py
{ "start": 0, "end": 434 }
class ____: def canPartition(self, nums: List[int]) -> bool: s = sum(nums) if s % 2 != 0: return False m, n = len(nums), (s >> 1) + 1 dp = [False] * n dp[0] = True if nums[0] < n: dp[nums[0]] = True for i in range(1, m): f...
Solution
python
doocs__leetcode
solution/3300-3399/3387.Maximize Amount After Two Days of Conversions/Solution.py
{ "start": 0, "end": 853 }
class ____: def maxAmount( self, initialCurrency: str, pairs1: List[List[str]], rates1: List[float], pairs2: List[List[str]], rates2: List[float], ) -> float: d1 = self.build(pairs1, rates1, initialCurrency) d2 = self.build(pairs2, rates2, initialC...
Solution
python
pandas-dev__pandas
pandas/tests/extension/base/constructors.py
{ "start": 189, "end": 5623 }
class ____: def test_from_sequence_from_cls(self, data): result = type(data)._from_sequence(data, dtype=data.dtype) tm.assert_extension_array_equal(result, data) data = data[:0] result = type(data)._from_sequence(data, dtype=data.dtype) tm.assert_extension_array_equal(result...
BaseConstructorsTests
python
plotly__plotly.py
plotly/graph_objs/scatter3d/_hoverlabel.py
{ "start": 233, "end": 11255 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatter3d" _path_str = "scatter3d.hoverlabel" _valid_props = { "align", "alignsrc", "bgcolor", "bgcolorsrc", "bordercolor", "bordercolorsrc", "font", "namelength", "namelengthsrc"...
Hoverlabel
python
redis__redis-py
tests/test_connection_pool.py
{ "start": 9190, "end": 15172 }
class ____: def test_hostname(self): pool = redis.ConnectionPool.from_url("redis://my.host") assert pool.connection_class == redis.Connection assert pool.connection_kwargs == {"host": "my.host"} def test_quoted_hostname(self): pool = redis.ConnectionPool.from_url("redis://my %2F...
TestConnectionPoolURLParsing
python
google__jax
tests/state_test.py
{ "start": 42045, "end": 43499 }
class ____(NamedTuple): vmap_index_param: VmappableIndexParam bat_ref: np.ndarray bat_val: np.ndarray bat_idxs: tuple[np.ndarray, ...] @hps.composite def set_vmap_params(draw): vmap_index_param: VmappableIndexParam = draw(vmappable_index_params( op_type="swap")) bat_ref = draw(hnp.arrays(np.float32, vm...
SetVmapParams
python
getsentry__sentry
tests/sentry/integrations/vercel/test_integration.py
{ "start": 1160, "end": 20892 }
class ____(IntegrationTestCase): provider = VercelIntegrationProvider # Vercel Variables project_id = "Qme9NXBpguaRxcXssZ1NWHVaM98MAL6PHDXUs1jPrgiM8H" team_id = "my_team_id" config_id = "my_config_id" def assert_setup_flow(self, is_team=False, multi_config_org=None, no_name=False): res...
VercelIntegrationTest
python
chroma-core__chroma
chromadb/quota/simple_quota_enforcer/__init__.py
{ "start": 396, "end": 1495 }
class ____(QuotaEnforcer): """ A naive implementation of a quota enforcer that allows all requests. """ def __init__(self, system: System) -> None: super().__init__(system) @override def set_context(self, context: Dict[str, Any]) -> None: pass @override def enforce( ...
SimpleQuotaEnforcer
python
kamyu104__LeetCode-Solutions
Python/patching-array.py
{ "start": 1333, "end": 1748 }
class ____(object): def minPatches(self, nums, n): """ :type nums: List[int] :type n: int :rtype: int """ patch, miss, i = 0, 1, 0 while miss <= n: if i < len(nums) and nums[i] <= miss: miss += nums[i] i += 1 ...
Solution3
python
rushter__MLAlgorithms
mla/knn.py
{ "start": 151, "end": 1682 }
class ____(BaseEstimator): def __init__(self, k=5, distance_func=euclidean): """Base class for Nearest neighbors classifier and regressor. Parameters ---------- k : int, default 5 The number of neighbors to take into account. If 0, all the training examples a...
KNNBase
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 176225, "end": 179505 }
class ____(rv_continuous): r"""Jones and Faddy skew-t distribution. %(before_notes)s Notes ----- The probability density function for `jf_skew_t` is: .. math:: f(x; a, b) = C_{a,b}^{-1} \left(1+\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{a+1/2} ...
jf_skew_t_gen
python
getsentry__sentry
src/sentry/integrations/jira_server/integration.py
{ "start": 4667, "end": 4752 }
class ____(TypedDict): choices: list[tuple[str, str]] placeholder: str
_Choices
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 17335, "end": 17638 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneDisplayableEvent) name = "HandledOutputEvent" output_name = graphene.NonNull(graphene.String) manager_key = graphene.NonNull(graphene.String)
GrapheneHandledOutputEvent
python
sqlalchemy__sqlalchemy
test/orm/test_unitofwork.py
{ "start": 102709, "end": 106660 }
class ____(fixtures.MappedTest): class SomeEnum: # Implements PEP 435 in the minimal fashion needed by SQLAlchemy __members__ = OrderedDict() def __init__(self, name, value, alias=None): self.name = name self.value = value self.__members__[name] = self ...
EnsurePKSortableTest