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
hyperopt__hyperopt
hyperopt/spark.py
{ "start": 841, "end": 12302 }
class ____(Trials): """ Implementation of hyperopt.Trials supporting distributed execution using Apache Spark clusters. This requires fmin to be run on a Spark cluster. Plugging SparkTrials into hyperopt.fmin() allows hyperopt to send model training and evaluation tasks to Spark workers, pa...
SparkTrials
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 131173, "end": 131363 }
class ____(str, Enum): """ Storage on disk (rocksdb storage) """ def __str__(self) -> str: return str(self.value) ON_DISK = "on_disk"
SparseVectorStorageTypeOneOf
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 11986, "end": 12398 }
class ____(Token): """ Represents 'continue' in C/Python ('cycle' in Fortran) Use the premade instance ``continue_`` or instantiate manually. Examples ======== >>> from sympy import ccode, fcode >>> from sympy.codegen.ast import continue_ >>> ccode(continue_) 'continue' >>> fcode(...
ContinueToken
python
huggingface__transformers
src/transformers/models/gpt_neox/modular_gpt_neox.py
{ "start": 8577, "end": 10972 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx): super().__init__() self.use_parallel_residual = config.use_parallel_residual self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.post_attention_layernorm = nn.LayerNorm(...
GPTNeoXLayer
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/map_test.py
{ "start": 66395, "end": 69078 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.v2_only_combinations(), combinations.combine( dataset_range=[100], num_parallel_calls=[None, 2, dataset_ops.AUTOTUNE], deterministic...
MapGlobalShuffleTest
python
plotly__plotly.py
plotly/graph_objs/sankey/link/_line.py
{ "start": 233, "end": 4565 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "sankey.link" _path_str = "sankey.link.line" _valid_props = {"color", "colorsrc", "width", "widthsrc"} @property def color(self): """ Sets the color of the `line` around each `link`. The 'color' property is a color and...
Line
python
getsentry__sentry
src/sentry/codecov/endpoints/test_suites/test_suites.py
{ "start": 824, "end": 2224 }
class ____(CodecovEndpoint): __test__ = False owner = ApiOwner.CODECOV publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieve test suites belonging to a repository's test results", parameters=[ GlobalParams.ORG_ID_OR_SLUG, ...
TestSuitesEndpoint
python
django__django
tests/staticfiles_tests/test_management.py
{ "start": 13002, "end": 15537 }
class ____(CollectionTestCase): overwrite_warning_msg = "This will overwrite existing files!" delete_warning_msg = "This will DELETE ALL FILES in this location!" files_copied_msg = "static files copied" @staticmethod def mock_input(stdout): def _input(msg): stdout.write(msg) ...
TestInteractiveMessages
python
django__django
tests/staticfiles_tests/test_handlers.py
{ "start": 401, "end": 1621 }
class ____(StaticFilesTestCase): async_request_factory = AsyncRequestFactory() async def test_get_async_response(self): request = self.async_request_factory.get("/static/test/file.txt") handler = ASGIStaticFilesHandler(ASGIHandler()) response = await handler.get_response_async(request) ...
TestASGIStaticFilesHandler
python
django__django
tests/gis_tests/test_geoforms.py
{ "start": 374, "end": 8632 }
class ____(SimpleTestCase): def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ("blah", 3, "FoO", None, 0): with self.subTest(bad_default=bad_default): with self.assertRaises(ValidationError): ...
GeometryFieldTest
python
django__django
tests/delete_regress/tests.py
{ "start": 14614, "end": 15122 }
class ____(TestCase): def test_set_querycount(self): policy = Policy.objects.create() version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create( version=version, location=location, locat...
SetQueryCountTests
python
pypa__pip
src/pip/_vendor/rich/measure.py
{ "start": 262, "end": 5305 }
class ____(NamedTuple): """Stores the minimum and maximum widths (in characters) required to render an object.""" minimum: int """Minimum number of cells required to render.""" maximum: int """Maximum number of cells required to render.""" @property def span(self) -> int: """Get di...
Measurement
python
google__pytype
pytype/state.py
{ "start": 7029, "end": 14576 }
class ____(utils.ContextWeakrefMixin): """An interpreter frame. This contains the local value and block stacks and the associated code and pointer. The most complex usage is with generators in which a frame is stored and then repeatedly reactivated. Other than that frames are created executed and then discar...
Frame
python
pypa__setuptools
setuptools/_vendor/jaraco/collections/__init__.py
{ "start": 9127, "end": 10882 }
class ____(dict): """ A dict subclass that transforms the keys before they're used. Subclasses may override the default transform_key to customize behavior. """ @staticmethod def transform_key(key): # pragma: nocover return key def __init__(self, *args, **kargs): super()._...
KeyTransformingDict
python
psf__black
tests/data/cases/dummy_implementations.py
{ "start": 3201, "end": 3251 }
class ____: def f(self): ... # Comment 2
ClassF
python
walkccc__LeetCode
solutions/3514. Number of Unique XOR Triplets II/3515.py
{ "start": 0, "end": 322 }
class ____: def uniqueXorTriplets(self, nums: list[int]) -> int: n = len(nums) if n == 1: return 1 pairs = set(nums[i] ^ nums[j] for i, j in itertools.combinations(range(n), 2)) return len(set(pair ^ num for pair in pairs for num in nums))
Solution
python
PrefectHQ__prefect
tests/events/server/test_in_memory_ordering.py
{ "start": 6210, "end": 8115 }
class ____: async def test_event_seen_tracking( self, causal_ordering: CausalOrdering, event_one: ReceivedEvent ): # Initially not seen assert not await causal_ordering.event_has_been_seen(event_one) assert not await causal_ordering.event_has_been_seen(event_one.id) # Re...
TestEventSeenTracking
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 224365, "end": 243603 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('type', _nvmlClockType_t), ('pstate', _nvmlPstates_t), ('clockOffsetMHz', c_int), ('minClockOffsetMHz', c_int), ('maxClockOffsetMHz', c_int), ] nvmlClockOffset_v1 = 0x1000018 def nvmlDeviceGetCl...
c_nvmlClockOffset_t
python
ray-project__ray
python/ray/dag/dag_node.py
{ "start": 754, "end": 29422 }
class ____(DAGNodeBase): """Abstract class for a node in a Ray task graph. A node has a type (e.g., FunctionNode), data (e.g., function options and body), arguments (Python values, DAGNodes, and DAGNodes nested within Python argument values) and options (Ray API .options() used for function, class ...
DAGNode
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 62739, "end": 63077 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float) def forward(self, x): x = self.conv(x) return x def get_example_inputs(self) -> tuple[Any, ...]: return (torch.rand(1, ...
ConvModel
python
crytic__slither
slither/tools/upgradeability/checks/abstract_checks.py
{ "start": 369, "end": 983 }
class ____(ComparableEnum): HIGH = 0 MEDIUM = 1 LOW = 2 INFORMATIONAL = 3 UNIMPLEMENTED = 999 classification_colors: Dict[CheckClassification, Callable[[str], str]] = { CheckClassification.INFORMATIONAL: green, CheckClassification.LOW: yellow, CheckClassification.MEDIUM: yellow, Ch...
CheckClassification
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/ai.py
{ "start": 884, "end": 2305 }
class ____: branch_name: str pr_title: str def load_prompt_template(prompt_filename: str, context: str) -> str: """Load a prompt template and inject context. Args: prompt_filename: The name of the prompt file (e.g., 'branch_name_only.md') context: The context to inject into the prompt...
ExtractedNames
python
huggingface__transformers
src/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
{ "start": 4569, "end": 14376 }
class ____(BaseImageProcessor): r""" Constructs a LayoutLMv2 image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to `(size["height"], size["width"])`. Can be overridden by `do_resize` in `preproc...
LayoutLMv2ImageProcessor
python
pytorch__pytorch
torch/utils/data/dataloader.py
{ "start": 34792, "end": 36106 }
class ____(_BaseDataLoaderIter): def __init__(self, loader) -> None: super().__init__(loader) if self._timeout != 0: raise AssertionError("_SingleProcessDataLoaderIter requires timeout == 0") if self._num_workers != 0: raise AssertionError( "_SinglePro...
_SingleProcessDataLoaderIter
python
modin-project__modin
modin/pandas/resample.py
{ "start": 1373, "end": 13126 }
class ____(ClassLogger): _dataframe: Union[DataFrame, Series] _query_compiler: BaseQueryCompiler def __init__( self, dataframe: Union[DataFrame, Series], rule, axis=0, closed=None, label=None, convention="start", kind=None, on=None, ...
Resampler
python
huggingface__transformers
src/transformers/generation/candidate_generator.py
{ "start": 3334, "end": 17462 }
class ____(CandidateGenerator): """ `CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates candidates through the use of a smaller model. Read the following blog post for more information: https://huggingface.co/blog/assisted-generation Args: ...
AssistedCandidateGenerator
python
pytorch__pytorch
torch/_higher_order_ops/invoke_subgraph.py
{ "start": 1443, "end": 1632 }
class ____: num_fw_outs: Optional[int] = None indexes_with_symint: set[int] = field(default_factory=set) indexes_with_no_grad: set[int] = field(default_factory=set)
OutputMetadata
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/nn_functional.py
{ "start": 19066, "end": 20507 }
class ____(Operator): """Operator for torch.nn.functional.gelu (Gaussian Error Linear Unit).""" def __init__(self): super().__init__("torch.nn.functional.gelu") @property def torch_op_name(self) -> str | None: """Return the torch operation name.""" return "torch.nn.functional.g...
GELUOperator
python
matplotlib__matplotlib
lib/matplotlib/backends/qt_editor/_formlayout.py
{ "start": 1770, "end": 3157 }
class ____(QtWidgets.QPushButton): """ Color choosing push button """ colorChanged = QtCore.Signal(QtGui.QColor) def __init__(self, parent=None): super().__init__(parent) self.setFixedSize(20, 20) self.setIconSize(QtCore.QSize(12, 12)) self.clicked.connect(self.choos...
ColorButton
python
joke2k__faker
faker/providers/currency/uz_UZ/__init__.py
{ "start": 46, "end": 5889 }
class ____(CurrencyProvider): # Format: (code, name) currencies = ( ("AED", "BAA Dirhami"), ("AFN", "Afg‘oni"), ("ALL", "Lek"), ("AMD", "Arman dramasi"), ("ANG", "Niderlandiya Antil guldeni"), ("AOA", "Kvanza"), ("ARS", "Argentina pesosi"), ("AUD",...
Provider
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_row05.py
{ "start": 315, "end": 1077 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_row05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/x_clip/modeling_x_clip.py
{ "start": 4250, "end": 8166 }
class ____(nn.Module): def __init__(self, config: XCLIPVisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.class_embedding = nn.Parameter(torch.randn(s...
XCLIPVisionEmbeddings
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 105653, "end": 110610 }
class ____: # The decimal precision to be used for comparing results. # This value will be passed as the 'decimal' keyword argument of # assert_array_almost_equal(). # Since correlate may chose to use FFT method which converts # longdoubles to doubles internally don't expect better precision # f...
TestCorrelateComplex
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/k8s_model.py
{ "start": 1040, "end": 2101 }
class ____(ABC): """ Airflow Kubernetes models are here for backwards compatibility reasons only. Ideally clients should use the kubernetes API and the process of client input -> Airflow k8s models -> k8s models can be avoided. All of these models implement the `attach_to_pod` method ...
K8SModel
python
getsentry__sentry
tests/sentry/issues/endpoints/test_team_groups_old.py
{ "start": 335, "end": 3119 }
class ____(APITestCase): endpoint = "sentry-api-0-team-oldest-issues" def test_simple(self) -> None: project1 = self.create_project(teams=[self.team], slug="foo") project2 = self.create_project(teams=[self.team], slug="bar") group1 = self.create_group( project=project1, ...
TeamGroupsOldTest
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 5399, "end": 5484 }
class ____(PipError): """General exception during installation"""
InstallationError
python
mahmoud__boltons
boltons/setutils.py
{ "start": 19552, "end": 33482 }
class ____: """ helper class for complement() that implements the set methods """ __slots__ = ('_included', '_excluded') def __init__(self, included=None, excluded=None): if included is None: assert type(excluded) in (set, frozenset) elif excluded is None: as...
_ComplementSet
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/util.py
{ "start": 20123, "end": 21850 }
class ____(sql_util.ColumnAdapter): """ColumnAdapter subclass which excludes adaptation of entities from non-matching mappers. """ __slots__ = ("role", "mapper", "is_aliased_class", "aliased_insp") is_aliased_class: bool aliased_insp: Optional[AliasedInsp[Any]] def __init__( self...
ORMAdapter
python
PyCQA__pylint
tests/functional/c/class_attributes.py
{ "start": 415, "end": 450 }
class ____: _class_prop: int
Base
python
ansible__ansible
test/lib/ansible_test/_internal/commands/coverage/xml.py
{ "start": 5673, "end": 5775 }
class ____(CoverageCombineConfig): """Configuration for the coverage xml command."""
CoverageXmlConfig
python
huggingface__transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
{ "start": 29671, "end": 32924 }
class ____(nn.Module): def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False): """ A transformer block with four layers: (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on sparse...
SamHQTwoWayAttentionBlock
python
getsentry__sentry
src/sentry/migrations/0914_increase_orgmember_user_email_max_length.py
{ "start": 155, "end": 1503 }
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
Textualize__textual
docs/examples/how-to/center01.py
{ "start": 80, "end": 350 }
class ____(App): """How to center things.""" CSS = """ Screen { align: center middle; } """ def compose(self) -> ComposeResult: yield Static("Hello, World!") if __name__ == "__main__": app = CenterApp() app.run()
CenterApp
python
apache__airflow
providers/fab/src/airflow/providers/fab/www/security/permissions.py
{ "start": 2568, "end": 3698 }
class ____(TypedDict): """Details of a resource (actions and prefix).""" actions: set[str] prefix: str # Keeping DAG_ACTIONS to keep the compatibility with outdated versions of FAB provider DAG_ACTIONS = {ACTION_CAN_READ, ACTION_CAN_EDIT, ACTION_CAN_DELETE} RESOURCE_DETAILS_MAP = { RESOURCE_DAG: Res...
ResourceDetails
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/endpoints/revocation.py
{ "start": 438, "end": 5212 }
class ____(BaseEndpoint): """Token revocation endpoint. Endpoint used by authenticated clients to revoke access and refresh tokens. Commonly this will be part of the Authorization Endpoint. """ valid_token_types = ('access_token', 'refresh_token') valid_request_methods = ('POST',) def __...
RevocationEndpoint
python
pypa__packaging
src/packaging/licenses/__init__.py
{ "start": 1938, "end": 5837 }
class ____(ValueError): """Raised when a license-expression string is invalid >>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' """ def canonicalize_license_expression( ...
InvalidLicenseExpression
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/links/analytics_admin.py
{ "start": 1674, "end": 2161 }
class ____(GoogleAnalyticsBaseLink): """Helper class for constructing Google Analytics Property Link.""" name = "Data Analytics Property" key = "data_analytics_property" format_str = "p{property_id}/" @staticmethod def persist( context: Context, property_id: str, ): ...
GoogleAnalyticsPropertyLink
python
altair-viz__altair
altair/utils/core.py
{ "start": 27211, "end": 31851 }
class ____: channel_to_name: dict[type[SchemaBase], str] name_to_channel: dict[str, dict[_ChannelType, type[SchemaBase]]] @classmethod def from_cache(cls) -> _ChannelCache: global _CHANNEL_CACHE try: cached = _CHANNEL_CACHE except NameError: cached = cls....
_ChannelCache
python
mlflow__mlflow
tests/tracing/test_fluent.py
{ "start": 1793, "end": 2259 }
class ____: @mlflow.trace() async def predict(self, x, y): z = x + y z = await self.add_one(z) z = await mlflow.trace(self.square)(z) return z # noqa: RET504 @mlflow.trace(span_type=SpanType.LLM, name="add_one_with_custom_name", attributes={"delta": 1}) async def add_on...
DefaultAsyncTestModel
python
protocolbuffers__protobuf
python/google/protobuf/descriptor.py
{ "start": 10261, "end": 17951 }
class ____(_NestedDescriptorBase): """Descriptor for a protocol message type. Attributes: name (str): Name of this protocol message type. full_name (str): Fully-qualified name of this protocol message type, which will include protocol "package" name and the name of any enclosing types. ...
Descriptor
python
plotly__plotly.py
plotly/graph_objs/histogram2d/_stream.py
{ "start": 233, "end": 3531 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram2d" _path_str = "histogram2d.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is s...
Stream
python
astropy__astropy
astropy/cosmology/_src/io/connect.py
{ "start": 9949, "end": 12683 }
class ____(io_registry.UnifiedReadWrite): """Transform this Cosmology to another format. This function provides the Cosmology interface to the astropy unified I/O layer. This allows easily transforming to supported data formats using syntax such as:: >>> from astropy.cosmology import Planck18 ...
CosmologyToFormat
python
Netflix__metaflow
metaflow/_vendor/click/parser.py
{ "start": 5916, "end": 6075 }
class ____(object): def __init__(self, rargs): self.opts = {} self.largs = [] self.rargs = rargs self.order = []
ParsingState
python
pytorch__pytorch
torch/fx/graph.py
{ "start": 1553, "end": 4553 }
class ____(NamedTuple): """Additional objs that we add to every graph's globals. The repr() for some standard library objects is not valid Python code without an import. For common objects of this sort, we bundle them in the globals of every FX graph. """ # How to import this object from the s...
_CustomBuiltin
python
kamyu104__LeetCode-Solutions
Python/find-the-maximum-achievable-number.py
{ "start": 38, "end": 218 }
class ____(object): def theMaximumAchievableX(self, num, t): """ :type num: int :type t: int :rtype: int """ return num+2*t
Solution
python
kamyu104__LeetCode-Solutions
Python/inorder-successor-in-bst.py
{ "start": 29, "end": 623 }
class ____(object): def inorderSuccessor(self, root, p): """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ # If it has right subtree. if p and p.right: p = p.right while p.left: p = p.left retur...
Solution
python
apache__airflow
airflow-ctl/tests/airflow_ctl/api/test_operations.py
{ "start": 36692, "end": 39251 }
class ____: dag_id = "dag_id" dag_run_id = "dag_run_id" dag_run_response = DAGRunResponse( dag_display_name=dag_run_id, dag_run_id=dag_run_id, dag_id=dag_id, logical_date=datetime.datetime(2025, 1, 1, 0, 0, 0), queued_at=datetime.datetime(2025, 1, 1, 0, 0, 0), ...
TestDagRunOperations
python
getsentry__sentry
src/sentry/auth_v2/endpoints/auth_merge_user_accounts.py
{ "start": 717, "end": 1044 }
class ____(CamelSnakeSerializer): verification_code = serializers.CharField(required=True) ids_to_merge = serializers.ListField(child=serializers.IntegerField(), required=True) ids_to_delete = serializers.ListField(child=serializers.IntegerField(), required=True) @control_silo_endpoint
AuthMergeUserAccountsValidator
python
getsentry__sentry
tests/sentry/integrations/github/test_client.py
{ "start": 68440, "end": 71610 }
class ____(GitHubClientFileBlameBase): """ Tests that rate limits are handled correctly """ def setUp(self) -> None: super().setUp() self.file = SourceLineInfo( path="src/sentry/integrations/github/client_1.py", lineno=10, ref="master", re...
GitHubClientFileBlameRateLimitTest
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/oxylabs_web/base.py
{ "start": 697, "end": 4848 }
class ____(BasePydanticReader): """ Scrape any website with Oxylabs Web Scraper API and get results in Markdown format. [See the API documentation](https://developers.oxylabs.io/scraper-apis/web-scraper-api/other-websites) Args: username: Oxylabs API username. password: Oxylabs API pas...
OxylabsWebReader
python
EpistasisLab__tpot
tpot/builtin_modules/nn.py
{ "start": 9516, "end": 11249 }
class ____(PytorchClassifier): """Multilayer Perceptron, implemented in PyTorch, for use with TPOT. """ def __init__( self, num_epochs=10, batch_size=8, learning_rate=0.01, weight_decay=0, verbose=False ): self.num_epochs = num_epochs self...
PytorchMLPClassifier
python
pytorch__pytorch
.github/scripts/test_pytest_caching_utils.py
{ "start": 99, "end": 3157 }
class ____(TestCase): def test_merged_lastfailed_content_with_overlap(self) -> None: last_failed_source = { "tools/tests/test_foo.py::test_num1": True, "tools/tests/test_foo.py::test_num2": True, "tools/tests/test_bar.py::test_num1": True, } last_failed_de...
TestPytestCachingUtils
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 9285, "end": 11552 }
class ____: @pytest.mark.parametrize( "initial_state_type", [ states.StateType.SCHEDULED, states.StateType.PENDING, ], ) @pytest.mark.parametrize( "proposed_state_type", [ states.StateType.PENDING, states.StateType.RUNNI...
TestCopyTaskParametersID
python
walkccc__LeetCode
solutions/2457. Minimum Addition to Make Integer Beautiful/2457.py
{ "start": 0, "end": 431 }
class ____: def makeIntegerBeautiful(self, n: int, target: int) -> int: ans = 0 power = 1 # e.g. n = 123. After tunning off the last bit by adding 7, n = 130. # Effectively, we can think n as 13. That's why we do n = (n / 10) + 1. while sum(map(int, str(n))) > target: # the cost to turn off...
Solution
python
explosion__spaCy
spacy/pipeline/span_ruler.py
{ "start": 3751, "end": 18993 }
class ____(Pipe): """The SpanRuler lets you add spans to the `Doc.spans` using token-based rules or exact phrase matches. DOCS: https://spacy.io/api/spanruler USAGE: https://spacy.io/usage/rule-based-matching#spanruler """ def __init__( self, nlp: Language, name: str = ...
SpanRuler
python
numba__numba
numba/tests/test_typeinfer.py
{ "start": 15987, "end": 18310 }
class ____(unittest.TestCase): """ Tests for typing.Context.resolve_overload(). """ def assert_resolve_overload(self, cases, args, expected): ctx = typing.Context() got = ctx.resolve_overload("foo", cases, args, {}) self.assertEqual(got, expected) def test_non_ambiguous_mat...
TestResolveOverload
python
google__pytype
pytype/tests/test_decorators2.py
{ "start": 4790, "end": 9426 }
class ____(test_base.BaseTest): """Test decorators.""" def test_annotated_super_call_under_bad_decorator(self): self.InferWithErrors(""" class Foo: def Run(self) -> None: ... class Bar(Foo): @bad_decorator # name-error def Run(self): return super(Bar, self).Run() ...
DecoratorsTest
python
facebook__pyre-check
api/query.py
{ "start": 1265, "end": 1343 }
class ____: type_name: str start: Position stop: Position
Annotation
python
pytorch__pytorch
test/mobile/test_lite_script_module.py
{ "start": 17846, "end": 21217 }
class ____(QuantizationLiteTestCase): def test_single_layer(self): input = torch.rand(2, 5, dtype=torch.float) quantized_model = self._create_quantized_model( model_class=AnnotatedSingleLayerLinearModel, qengine="qnnpack" ) self._compare_script_and_mobile(model=quantized_...
TestLiteScriptQuantizedModule
python
redis__redis-py
redis/multidb/healthcheck.py
{ "start": 6128, "end": 10025 }
class ____(HealthCheck): """ Health check available for Redis Enterprise deployments. Verify via REST API that the database is healthy based on different lags. """ def __init__( self, rest_api_port: int = 9443, lag_aware_tolerance: int = DEFAULT_LAG_AWARE_TOLERANCE, ...
LagAwareHealthCheck
python
Lightning-AI__lightning
tests/tests_pytorch/core/test_datamodules.py
{ "start": 14022, "end": 14201 }
class ____(LightningDataModule): def __init__(self, arg0, arg1, kwarg0=None): super().__init__() self.save_hyperparameters() # single arg
DataModuleWithHparams_0
python
PrefectHQ__prefect
src/prefect/client/orchestration/_blocks_schemas/client.py
{ "start": 418, "end": 3386 }
class ____(BaseClient): def create_block_schema(self, block_schema: "BlockSchemaCreate") -> "BlockSchema": """ Create a block schema in the Prefect API. """ try: response = self.request( "POST", "/block_schemas/", json=block...
BlocksSchemaClient
python
python__mypy
mypy/nodes.py
{ "start": 82749, "end": 83196 }
class ____(Expression): """Dictionary literal expression {key: value, ...}.""" __slots__ = ("items",) __match_args__ = ("items",) items: list[tuple[Expression | None, Expression]] def __init__(self, items: list[tuple[Expression | None, Expression]]) -> None: super().__init__() se...
DictExpr
python
spyder-ide__spyder
spyder/plugins/outlineexplorer/main_widget.py
{ "start": 610, "end": 708 }
class ____: Main = 'main_section' DisplayOptions = 'display_options'
OutlineExplorerSections
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/readers.py
{ "start": 50365, "end": 51606 }
class ____(dataset_ops.DatasetV1Adapter): """A `Dataset` consisting of the results from a SQL query.""" @functools.wraps(SqlDatasetV2.__init__) def __init__(self, driver_name, data_source_name, query, output_types): wrapped = SqlDatasetV2(driver_name, data_source_name, query, output_types) super(SqlDatas...
SqlDatasetV1
python
ansible__ansible
lib/ansible/modules/apt_repository.py
{ "start": 15900, "end": 30694 }
class ____(SourcesList): # prefer api.launchpad.net over launchpad.net/api # see: https://github.com/ansible/ansible/pull/81978#issuecomment-1767062178 LP_API = 'https://api.launchpad.net/1.0/~%s/+archive/%s' PPA_URI = 'https://ppa.launchpadcontent.net' def __init__(self, module): self.mod...
UbuntuSourcesList
python
MongoEngine__mongoengine
mongoengine/context_managers.py
{ "start": 5880, "end": 12184 }
class ____: """Query_counter context manager to get the number of queries. This works by updating the `profiling_level` of the database so that all queries get logged, resetting the db.system.profile collection at the beginning of the context and counting the new entries. This was designed for debuggin...
query_counter
python
django__django
tests/filtered_relation/models.py
{ "start": 3053, "end": 3382 }
class ____(models.Model): book = models.ForeignKey(Book, models.CASCADE, related_name="daily_sales") sale_date = models.DateField() currency = models.ForeignKey(Currency, models.CASCADE) seller = models.ForeignKey(Seller, models.CASCADE) sales = models.DecimalField(max_digits=10, decimal_places=2)
BookDailySales
python
pyca__cryptography
src/cryptography/x509/base.py
{ "start": 3908, "end": 3959 }
class ____(utils.Enum): v1 = 0 v3 = 2
Version
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType38.py
{ "start": 363, "end": 1048 }
class ____(Generic[_T]): def __init__(self, _: ClassA[_T]): ... v1 = ClassA(0) v2 = ClassB(v1) v3 = ClassB(ClassA(0)) reveal_type(v1, expected_text="ClassA[int]") reveal_type(v2, expected_text="ClassB[int]") reveal_type(v3, expected_text="ClassB[int]") def func1(x: list[_T], /) -> list[_T]: return x def ...
ClassB
python
tornadoweb__tornado
tornado/test/gen_test.py
{ "start": 18407, "end": 18599 }
class ____(RequestHandler): @gen.coroutine def prepare(self): yield gen.moment raise HTTPError(403) def get(self): self.finish("ok")
AsyncPrepareErrorHandler
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 73146, "end": 74600 }
class ____(rv_continuous): r"""A folded Cauchy continuous random variable. %(before_notes)s Notes ----- The probability density function for `foldcauchy` is: .. math:: f(x, c) = \frac{1}{\pi (1+(x-c)^2)} + \frac{1}{\pi (1+(x+c)^2)} for :math:`x \ge 0` and :math:`c \ge 0`. `...
foldcauchy_gen
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/repository/event.py
{ "start": 1070, "end": 1318 }
class ____(BaseEvent): """Event dispatched when file processing starts.""" file_path: str file_type: str @classmethod def class_name(cls) -> str: return "GitHubFileProcessingStartedEvent"
GitHubFileProcessingStartedEvent
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py
{ "start": 2562, "end": 5394 }
class ____: """Helper class for preprocess of transfer job body.""" def __init__( self, body: dict, aws_conn_id: str | None = "aws_default", default_schedule: bool = False ) -> None: self.body = body self.aws_conn_id = aws_conn_id self.default_schedule = default_schedule ...
TransferJobPreprocessor
python
boto__boto3
tests/unit/resources/test_action.py
{ "start": 6076, "end": 10141 }
class ____(BaseTestCase): def setUp(self): super().setUp() self.action_def = {'request': {'operation': 'GetFrobs', 'params': []}} @property def model(self): return Action('test', self.action_def, {}) def test_batch_action_gets_pages_from_collection(self): collection = ...
TestBatchActionCall
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py
{ "start": 58903, "end": 61775 }
class ____(nn.Module): def __init__(self, config: Phi4MultimodalConfig): super().__init__() self.config = config self.layer_idx = config.audio_config.feature_layer self.drop = nn.Dropout(config.embd_pdrop) self.encoder = Phi4MultimodalAudioModel._from_config(config.audio_con...
Phi4MultimodalAudioEmbedding
python
apache__thrift
lib/py/test/test_sslsocket.py
{ "start": 1752, "end": 3591 }
class ____(threading.Thread): def __init__(self, server, expect_failure=False): super(ServerAcceptor, self).__init__() self.daemon = True self._server = server self._listening = threading.Event() self._port = None self._port_bound = threading.Event() self._cli...
ServerAcceptor
python
getsentry__sentry
tests/sentry/integrations/slack/webhooks/actions/test_enable_notifications.py
{ "start": 403, "end": 4615 }
class ____(BaseEventTest): def setUp(self) -> None: super().setUp() self.slack_id = "UXXXXXXX1" self.team_id = "TXXXXXXX1" def test_enable_all_slack_no_identity(self) -> None: with assume_test_silo_mode(SiloMode.CONTROL): Identity.objects.delete_identity( ...
EnableNotificationsActionTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-twilio/components.py
{ "start": 2917, "end": 3881 }
class ____(StateMigration): """ Migrates legacy `alerts` state to low-code shape. Previously, the stream incorrectly used per partition state. Initial: { "states" : [ { "partition" : {}, "cursor" : { "date_generated" : "2025-08-05T16:43:50Z" ...
TwilioAlertsStateMigration
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_core.py
{ "start": 14699, "end": 16200 }
class ____(FSDPTest): @skip_if_lt_x_gpu(2) @parametrize("mixed_precision", [True, False]) def test_transformer_no_grad(self, mixed_precision): """Tests that for an FSDP-wrapped transformer model with shared parameters, after training for one iteration, running a forward pass in ``eva...
TestNoGrad
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1070295, "end": 1082840 }
class ____(sgqlc.types.Type, Node): """A branch protection rule.""" __schema__ = github_schema __field_names__ = ( "allows_deletions", "allows_force_pushes", "blocks_creations", "branch_protection_rule_conflicts", "bypass_force_push_allowances", "bypass_pull_...
BranchProtectionRule
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataflow.py
{ "start": 30294, "end": 38385 }
class ____(GoogleCloudBaseOperator): """ Launch a Dataflow YAML job and return the result. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataflowStartYamlJobOperator` .. warning:: This operator requires ``gcloud`` ...
DataflowStartYamlJobOperator
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/DateAxisItem.py
{ "start": 2639, "end": 4587 }
class ____: """ Specifies the properties for a set of date ticks and computes ticks within a given utc timestamp range """ def __init__(self, spacing, stepper, format, autoSkip=None): """ ============= ========================================================== Arguments spaci...
TickSpec
python
pytest-dev__pytest
src/_pytest/outcomes.py
{ "start": 1870, "end": 1990 }
class ____(OutcomeException): """Raised from an explicit call to pytest.fail().""" __module__ = "builtins"
Failed
python
google__pytype
pytype/tests/test_cmp2.py
{ "start": 2727, "end": 3385 }
class ____(test_base.BaseTest): """Tests comparisons on class objects with a custom metaclass.""" def test_compare_types(self): # See b/205755440 - this is the wrong error message to be raising, and the # test should fail once the bug is fixed. For now we test that we don't # crash due to b/205333186. ...
MetaclassTest
python
openai__openai-python
src/openai/types/responses/input_token_count_response.py
{ "start": 200, "end": 310 }
class ____(BaseModel): input_tokens: int object: Literal["response.input_tokens"]
InputTokenCountResponse
python
tiangolo__fastapi
tests/test_union_forms.py
{ "start": 192, "end": 250 }
class ____(BaseModel): name: str email: str
UserForm
python
chroma-core__chroma
chromadb/utils/embedding_functions/bm25_embedding_function.py
{ "start": 464, "end": 8321 }
class ____(SparseEmbeddingFunction[Documents]): def __init__( self, avg_len: Optional[float] = None, task: Optional[TaskType] = "document", cache_dir: Optional[str] = None, k: Optional[float] = None, b: Optional[float] = None, language: Optional[str] = None, ...
Bm25EmbeddingFunction
python
catalyst-team__catalyst
tests/catalyst/runners/test_reid.py
{ "start": 1863, "end": 5789 }
class ____(dl.SupervisedRunner): """ReidCustomRunner for reid case""" def handle_batch(self, batch: Dict[str, torch.Tensor]) -> None: """ Process batch Args: batch: batch data """ if self.is_train_loader: images, targets = batch["features"].float...
ReIDCustomRunner
python
pennersr__django-allauth
allauth/socialaccount/providers/twitch/views.py
{ "start": 280, "end": 1600 }
class ____(OAuth2Adapter): provider_id = "twitch" access_token_url = "https://id.twitch.tv/oauth2/token" # nosec authorize_url = "https://id.twitch.tv/oauth2/authorize" profile_url = "https://api.twitch.tv/helix/users" def complete_login(self, request, app, token, **kwargs): headers = { ...
TwitchOAuth2Adapter