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
getsentry__sentry
src/sentry/integrations/github/issues.py
{ "start": 1188, "end": 13469 }
class ____(SourceCodeIssueIntegration): def raise_error(self, exc: Exception, identity: Identity | None = None) -> NoReturn: if isinstance(exc, ApiError): if exc.code == 422: invalid_fields = {} if exc.json is not None: for e in exc.json.get("e...
GitHubIssuesSpec
python
mamba-org__mamba
micromamba/test-server/reposerver.py
{ "start": 1502, "end": 9817 }
class ____: keys = { "root": [], "key_mgr": [ { "private": "c9c2060d7e0d93616c2654840b4983d00221d8b6b69c850107da74b42168f937", "public": "013ddd714962866d12ba5bae273f14d48c89cf0773dee2dbf6d4561e521c83f7", }, ], "pkg_mgr": [ ...
RepoSigner
python
getsentry__sentry
tests/sentry/runner/commands/test_createflag.py
{ "start": 272, "end": 3664 }
class ____(CliTestCase): command = createflag def convert_output_to_feature(self, output: str) -> Feature: split_output = output.split("=== GENERATED YAML ===\n") assert len(split_output) == 2 return Feature.from_bulk_yaml(split_output[1])[0] def test_blank_options_only(self) -> No...
TestCreateFlag
python
pydata__xarray
xarray/tests/test_conventions.py
{ "start": 24457, "end": 27105 }
class ____: def test_decode_cf_variable_with_array_units(self) -> None: v = Variable(["t"], [1, 2, 3], {"units": np.array(["foobar"], dtype=object)}) v_decoded = conventions.decode_cf_variable("test2", v) assert_identical(v, v_decoded) def test_decode_cf_variable_timedelta64(): variabl...
TestDecodeCFVariableWithArrayUnits
python
spack__spack
lib/spack/spack/util/package_hash.py
{ "start": 14597, "end": 14713 }
class ____(spack.error.SpackError): """Raised for all errors encountered during package hashing."""
PackageHashError
python
walkccc__LeetCode
solutions/3241. Time Taken to Mark All Nodes/3241.py
{ "start": 176, "end": 537 }
class ____: def __init__(self, top1: Node = Node(), top2: Node = Node()): # the direct child node, where the time taken to mark the entire subtree # rooted at the node is the maximum self.top1 = top1 # the direct child node, where the time taken to mark the entire subtree # rooted at the node is t...
Top2
python
numba__numba
numba/core/typeinfer.py
{ "start": 10640, "end": 13964 }
class ____(object): def __init__(self, target, items, special_value, value_indexes, loc): self.target = target self.items = items self.special_value = special_value self.value_indexes = value_indexes self.loc = loc def __call__(self, typeinfer): with new_error_...
BuildMapConstraint
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/some_virtual_preferred/package.py
{ "start": 217, "end": 518 }
class ____(Package): """Package providing a virtual dependency with a preference in packages.yaml""" homepage = "http://www.example.com" url = "http://www.example.com/foo-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") provides("somevirtual")
SomeVirtualPreferred
python
django__django
tests/admin_views/models.py
{ "start": 9139, "end": 9474 }
class ____(models.Model): """ Used to check autocomplete to_field resolution when ForeignKey is PK. """ parent = models.ForeignKey(Parent, models.CASCADE, primary_key=True) name = models.CharField(max_length=128) class Meta: ordering = ["parent"] def __str__(self): return ...
PKChild
python
kamyu104__LeetCode-Solutions
Python/toeplitz-matrix.py
{ "start": 345, "end": 800 }
class ____(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ for row_index, row in enumerate(matrix): for digit_index, digit in enumerate(row): if not row_index or not digit_index: c...
Solution2
python
PyCQA__pylint
tests/functional/u/used/used_before_assignment_typing.py
{ "start": 3422, "end": 3781 }
class ____: """Class to test self referential variable typing within conditionals. This regressed, reported in: https://github.com/pylint-dev/pylint/issues/5499 """ def function(self, var: int) -> None: if var < 0.5: _x: MyThirdClass = self def other_function(self) -> None: ...
MyThirdClass
python
astropy__astropy
astropy/table/tests/test_subclass.py
{ "start": 1293, "end": 1901 }
class ____(table.Row): """ Row class that allows access to an arbitrary dict of parameters stored as a dict object in the ``params`` column. """ def __getitem__(self, item): if item not in self.colnames: return super().__getitem__("params")[item] else: return...
ParamsRow
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type.py
{ "start": 30532, "end": 40574 }
class ____(ExtensionType): """An ExtensionType that can be batched and unbatched. `BatchableExtensionType`s can be used with APIs that require batching or unbatching, including `Keras`, `tf.data.Dataset`, and `tf.map_fn`. E.g.: >>> class Vehicle(tf.experimental.BatchableExtensionType): ... top_speed: tf....
BatchableExtensionType
python
viewflow__viewflow
tests/workflow/test_fields__token.py
{ "start": 869, "end": 998 }
class ____(forms.ModelForm): # noqa: D101 class Meta: model = TokenTestModel fields = ('token', )
TokenTestForm
python
run-llama__llama_index
llama-index-finetuning/llama_index/finetuning/azure_openai/base.py
{ "start": 444, "end": 4470 }
class ____(OpenAIFinetuneEngine): """AzureOpenAI Finetuning Engine.""" def __init__( self, base_model: str, data_path: str, verbose: bool = False, start_job_id: Optional[str] = None, validate_json: bool = True, ) -> None: """Init params.""" se...
AzureOpenAIFinetuneEngine
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vision.py
{ "start": 3996, "end": 4869 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook") def test_minimal_green_path(self, mock_hook): mock_hook.return_value.update_product_set.return_value = {} op = CloudVisionUpdateProductSetOperator( location=LOCATION_TEST, product_set=PRODUCTSE...
TestCloudVisionProductSetUpdate
python
getsentry__sentry
src/sentry/api/endpoints/project_profiling_profile.py
{ "start": 2435, "end": 2993 }
class ____(ProjectProfilingBaseEndpoint): def get(self, request: Request, project: Project, profile_id: str) -> HttpResponse: if not features.has("organizations:profiling", project.organization, actor=request.user): return Response(status=404) kwargs: dict[str, Any] = { "meth...
ProjectProfilingRawProfileEndpoint
python
networkx__networkx
networkx/algorithms/centrality/tests/test_group.py
{ "start": 6839, "end": 8685 }
class ____: def test_group_degree_centrality_single_node(self): """ Group degree centrality for a single node group """ G = nx.path_graph(4) d = nx.group_degree_centrality(G, [1]) d_answer = nx.degree_centrality(G)[1] assert d == d_answer def test_group_d...
TestGroupDegreeCentrality
python
sympy__sympy
sympy/series/sequences.py
{ "start": 1025, "end": 11521 }
class ____(Basic): """Base class for sequences""" is_commutative = True _op_priority = 15 @staticmethod def _start_key(expr): """Return start (if possible) else S.Infinity. adapted from Set._infimum_key """ try: start = expr.start except NotImpl...
SeqBase
python
scipy__scipy
scipy/special/tests/test_ndtr.py
{ "start": 475, "end": 2680 }
class ____: # The expected values in these tests were computed with mpmath: # # def log_ndtr_mp(x): # return mpmath.log(mpmath.ncdf(x)) # def test_log_ndtr_moderate_le8(self): x = np.array([-0.75, -0.25, 0, 0.5, 1.5, 2.5, 3, 4, 5, 7, 8]) expected = np.array([-1.48444822...
TestLogNdtr
python
EpistasisLab__tpot
tpot/search_spaces/pipelines/dynamic_linear.py
{ "start": 1738, "end": 6307 }
class ____(SklearnIndividual): # takes in a single search space. # will produce a pipeline of variable length. Each step in the pipeline will be pulled from the search space provided. def __init__(self, search_space : SearchSpace, max_length: int , rng=None) -> None: super().__init__() rng...
DynamicLinearPipelineIndividual
python
apache__thrift
test/py/TestClient.py
{ "start": 19638, "end": 22668 }
class ____(unittest.TestProgram): def parseArgs(self, argv): if args: self.testNames = args else: self.testNames = ([self.defaultTest]) self.createTests() if __name__ == "__main__": parser = OptionParser() parser.add_option('--libpydir', type='string', dest=...
OwnArgsTestProgram
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/GradientLegend.py
{ "start": 136, "end": 4925 }
class ____(UIGraphicsItem): """ Draws a color gradient rectangle along with text labels denoting the value at specific points along the gradient. """ def __init__(self, size, offset): self.size = size self.offset = offset UIGraphicsItem.__init__(self) self.setAcc...
GradientLegend
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external_data.py
{ "start": 12444, "end": 13209 }
class ____: """Stores sensor metadata which is available in the Dagster UI. This is an unfortunate legacy class that is out of line with our preferred pattern of storing standard `Mapping[str, MetadataValue]` under the metadata field. Because this class already existed when adding this standard metadat...
SensorMetadataSnap
python
pytorch__pytorch
test/complex_tensor/test_complex_tensor.py
{ "start": 8126, "end": 9731 }
class ____(TestGradients): _default_dtype_check_enabled = True @ops( implemented_op_db, dtypes=OpDTypes.supported_backward, allowed_dtypes=[torch.complex128], ) def test_fn_grad(self, device: str, dtype: torch.dtype, op: OpInfo) -> None: test_info = Descriptor( ...
TestComplexBwdGradients
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 3658, "end": 3801 }
class ____(permissions.BasePermission): def has_permission(self, request, view): return request.method != 'POST'
POSTDeniedPermission
python
numpy__numpy
numpy/distutils/ccompiler_opt.py
{ "start": 23216, "end": 29727 }
class ____: """A helper class that provides a collection of fundamental methods implemented in a top of Python and NumPy Distutils. The idea behind this class is to gather all methods that it may need to override in case of reuse 'CCompilerOpt' in environment different than of what NumPy has. ...
_Distutils
python
instagram__MonkeyType
demo/models.py
{ "start": 1609, "end": 1980 }
class ____(InboxEvent): type = EventType.LIKED def __init__( self, id: InboxEventId, user_id: UserId, published: datetime, feedentry_id: FeedEntryId, liker_id: UserId, ) -> None: super().__init__(id, user_id, published) self.feedentry_id = fee...
LikedEvent
python
falconry__falcon
tests/_wsgi_test_app.py
{ "start": 739, "end": 1379 }
class ____: def on_get(self, req, resp): resp.set_header('X-Falcon', 'peregrine') resp.content_type = falcon.MEDIA_TEXT resp.text = 'Hello, World!\n' def on_get_deprecated(self, req, resp): resp.set_header('X-Falcon', 'deprecated') resp.content_type = falcon.MEDIA_TEXT...
Hello
python
arrow-py__arrow
arrow/locales.py
{ "start": 60038, "end": 60670 }
class ____(ArabicLocale): names = ["ar-iq", "ar-jo", "ar-lb", "ar-ps", "ar-sy"] month_names = [ "", "كانون الثاني", "شباط", "آذار", "نيسان", "أيار", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", ...
LevantArabicLocale
python
django__django
tests/requests_tests/test_data_upload_settings.py
{ "start": 562, "end": 1481 }
class ____(SimpleTestCase): def setUp(self): payload = FakePayload("a=1&a=2&a=3\r\n") self.request = WSGIRequest( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), ...
DataUploadMaxMemorySizeFormPostTests
python
pytorch__pytorch
torch/futures/__init__.py
{ "start": 300, "end": 14435 }
class ____(torch._C.Future, Generic[T]): r""" Wrapper around a ``torch._C.Future`` which encapsulates an asynchronous execution of a callable, e.g. :meth:`~torch.distributed.rpc.rpc_async`. It also exposes a set of APIs to add callback functions and set results. .. warning:: GPU support is a beta f...
Future
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_test.py
{ "start": 27417, "end": 37303 }
class ____(test.TestCase): def test_defaults(self): a = fc._categorical_column_with_hash_bucket('aaa', 10) self.assertEqual('aaa', a.name) self.assertEqual('aaa', a._var_scope_name) self.assertEqual('aaa', a.key) self.assertEqual(10, a.hash_bucket_size) self.assertEqual(dtypes.string, a.dtype...
HashedCategoricalColumnTest
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 12510, "end": 20909 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): __dialect__ = "default" @testing.combinations(True, False, argnames="reverse") @testing.combinations(True, False, argnames="negate") def test_associatives_mismatched_type(self, reverse, negate): """test we get two separate exprs if the ...
MultiElementExprTest
python
getsentry__sentry
src/sentry/hybridcloud/rpc/caching/service.py
{ "start": 6198, "end": 12470 }
class ____(Generic[_R]): """ Get a multiple records from cache or wrapped function. When cache read returns no or partial data, the wrapped function will be invoked with keys missing data. The result of the wrapped function will then be stored in cache. Ideal for 'get many by id' style methods. ...
SiloCacheManyBackedCallable
python
ray-project__ray
doc/source/serve/doc_code/test_service_pb2_grpc.py
{ "start": 2738, "end": 4450 }
class ____(object): """Missing associated documentation comment in .proto file.""" @staticmethod def Ping( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, ...
TestService
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 16094, "end": 20140 }
class ____(nn.Module): """Construct a SeamlessM4Tv2ConformerSelfAttention object. Can be enhanced with relative position embeddings. """ def __init__(self, config, use_position_embeddings=True): super().__init__() self.head_size = config.hidden_size // config.speech_encoder_attention_h...
SeamlessM4Tv2ConformerSelfAttention
python
pennersr__django-allauth
allauth/socialaccount/providers/wahoo/views.py
{ "start": 181, "end": 971 }
class ____(OAuth2Adapter): provider_id = "wahoo" access_token_url = "https://api.wahooligan.com/oauth/token" # nosec authorize_url = "https://api.wahooligan.com/oauth/authorize" profile_url = "https://api.wahooligan.com/v1/user" def complete_login(self, request, app, token, **kwargs): head...
WahooOAuth2Adapter
python
pytorch__pytorch
torch/onnx/_internal/fx/_pass.py
{ "start": 5493, "end": 8638 }
class ____(abc.ABC): """Base class for FX graph transformations to be used by FX-ONNX exporter. Similar to `FX Interpreter <https://pytorch.org/docs/stable/fx.html#torch.fx.Interpreter>`_, specializations of this class execute the FX graph Node-by-Node. Methods in the `Transform` class can be overridde...
Transform
python
keras-team__keras
keras/src/backend/numpy/export.py
{ "start": 0, "end": 351 }
class ____: def track(self, resource): raise NotImplementedError( "`track` is not implemented in the numpy backend." ) def add_endpoint(self, name, fn, input_signature=None, **kwargs): raise NotImplementedError( "`add_endpoint` is not implemented in the numpy bac...
NumpyExportArchive
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 14003, "end": 14717 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forwa...
AltRobertaOutput
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 38862, "end": 39285 }
class ____(_TestBasicOps, __TestCase): def setUp(self): self.case = "bytes set" self.values = [b"a", b"b", b"c"] self.set = set(self.values) self.dup = set(self.values) self.length = 3 super().setUp() def test_repr(self): self.check_repr_against_v...
TestBasicOpsBytes
python
streamlit__streamlit
lib/streamlit/navigation/page.py
{ "start": 5347, "end": 11649 }
class ____: """A page within a multipage Streamlit app. Use ``st.Page`` to initialize a ``StreamlitPage`` object. Attributes ---------- icon : str The icon of the page. If no icon was declared in ``st.Page``, this property returns ``""``. title : str The title of the ...
StreamlitPage
python
python-pillow__Pillow
src/PIL/GdImageFile.py
{ "start": 873, "end": 2788 }
class ____(ImageFile.ImageFile): """ Image plugin for the GD uncompressed format. Note that this format is not supported by the standard :py:func:`PIL.Image.open()` function. To use this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and use the :py:func:`PIL.GdImageFile.open()` f...
GdImageFile
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 17765, "end": 18127 }
class ____(_RerankerProvider): reranker: Union[Rerankers, _EnumLikeStr] = Field( default=Rerankers.CONTEXTUALAI, frozen=True, exclude=True ) model: Optional[Union[RerankerContextualAIModel, str]] = Field(default=None) instruction: Optional[str] = Field(default=None) topN: Optional[int] = Fie...
_RerankerContextualAIConfig
python
pytorch__pytorch
benchmarks/instruction_counts/definitions/setup.py
{ "start": 1500, "end": 1636 }
class ____(enum.Enum): TRIVIAL_2D = _TRIVIAL_2D TRIVIAL_3D = _TRIVIAL_3D TRIVIAL_4D = _TRIVIAL_4D TRAINING = _TRAINING
Setup
python
kamyu104__LeetCode-Solutions
Python/most-stones-removed-with-same-row-or-column.py
{ "start": 487, "end": 848 }
class ____(object): def removeStones(self, stones): """ :type stones: List[List[int]] :rtype: int """ MAX_ROW = 10000 union_find = UnionFind(2*MAX_ROW) for r, c in stones: union_find.union_set(r, c+MAX_ROW) return len(stones) - len({union_f...
Solution
python
huggingface__transformers
src/transformers/integrations/executorch.py
{ "start": 17536, "end": 26543 }
class ____(torch.nn.Module): """ A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`, specifically for decoder-only LM to `StaticCache`. This module ensures that the exported model is compatible with further lowering and execution in `ExecuTorch`. Note: This ...
TorchExportableModuleWithStaticCache
python
lazyprogrammer__machine_learning_examples
rl3/a2c/atari_wrappers.py
{ "start": 5160, "end": 6104 }
class ____(gym.ObservationWrapper): def __init__(self, env, width=84, height=84, grayscale=True): """Warp frames to 84x84 as done in the Nature paper and later work.""" gym.ObservationWrapper.__init__(self, env) self.width = width self.height = height self.grayscale = graysca...
WarpFrame
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-milvus/llama_index/vector_stores/milvus/utils.py
{ "start": 2673, "end": 6370 }
class ____(BaseModel): # scalar metadata filters for advanced vector filtering # https://docs.zilliz.com/docs/use-array-fields#advanced-scalar-filtering filters: List[ScalarMetadataFilter] # and/or such conditions for combining different filters condition: Optional[FilterCondition] = FilterCondition...
ScalarMetadataFilters
python
mlflow__mlflow
dev/tests/test_set_matrix.py
{ "start": 193, "end": 4883 }
class ____: def __init__(self, data): self.data = data def json(self): return self.data def raise_for_status(self): pass @classmethod def from_versions(cls, versions): return cls( { "releases": { v: [ ...
MockResponse
python
huggingface__transformers
src/transformers/models/arcee/modular_arcee.py
{ "start": 8410, "end": 8539 }
class ____(LlamaForSequenceClassification): pass @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
ArceeForSequenceClassification
python
weaviate__weaviate-python-client
weaviate/collections/classes/aggregate.py
{ "start": 2683, "end": 2823 }
class ____: """The aggregation results for a collection grouped by a property.""" groups: List[AggregateGroup]
AggregateGroupByReturn
python
django__django
django/forms/utils.py
{ "start": 1923, "end": 2587 }
class ____(RenderableMixin): def as_field_group(self): return self.render() def as_hidden(self): raise NotImplementedError( "Subclasses of RenderableFieldMixin must provide an as_hidden() method." ) def as_widget(self): raise NotImplementedError( "Su...
RenderableFieldMixin
python
django__django
tests/model_fields/models.py
{ "start": 4340, "end": 4463 }
class ____(models.Model): d = models.DateField() dt = models.DateTimeField() t = models.TimeField()
DateTimeModel
python
spyder-ide__spyder
spyder/plugins/updatemanager/widgets/update.py
{ "start": 21248, "end": 21492 }
class ____(QMessageBox): def __init__(self, icon=None, text=None, parent=None): super().__init__(icon=icon, text=text, parent=parent) self.setWindowModality(Qt.NonModal) self.setTextFormat(Qt.RichText)
UpdateMessageBox
python
ray-project__ray
release/nightly_tests/decision_tree/cart_with_tree.py
{ "start": 272, "end": 3439 }
class ____: """A decision tree node.""" def __init__(self, gini, num_samples, num_samples_per_class, predicted_class): self.gini = gini self.num_samples = num_samples self.num_samples_per_class = num_samples_per_class self.predicted_class = predicted_class self.feature_i...
Node
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_workflow_index.py
{ "start": 3307, "end": 3851 }
class ____(OrganizationEndpoint): permission_classes = (OrganizationWorkflowPermission,) def convert_args(self, request: Request, workflow_id, *args, **kwargs): args, kwargs = super().convert_args(request, *args, **kwargs) try: kwargs["workflow"] = Workflow.objects.get( ...
OrganizationWorkflowEndpoint
python
PrefectHQ__prefect
tests/utilities/test_pydantic.py
{ "start": 1323, "end": 2184 }
class ____: @pytest.fixture(autouse=True) def check_for_model_decoration_exception(self): if REDUCTION_MODELS_EXC: raise RuntimeError("Failed to create test model.") from REDUCTION_MODELS_EXC def test_add_cloudpickle_reduction(self): model = CythonFieldModel(x="./foo.txt") ...
TestCloudpickleReduction
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 4589, "end": 5029 }
class ____(BaseSafeMigrationTest): app = "bad_flow_rename_table_app" migrate_from = "0001_initial" migrate_to = "0002_rename_table" def test(self) -> None: with pytest.raises( UnsafeOperationException, match="Renaming table for model NewTable from bad_flow_rename_table_a...
RenameTableTest
python
sqlalchemy__sqlalchemy
test/orm/test_hasparent.py
{ "start": 593, "end": 6494 }
class ____(fixtures.MappedTest): """Test that the 'hasparent' flag gets flipped to False only if we're sure this object is the real parent. In ambiguous cases a stale data exception is raised. """ run_inserts = None # trying to push GC to do a better job run_setup_classes = "each" ...
ParentRemovalTest
python
huggingface__transformers
src/transformers/models/got_ocr2/modeling_got_ocr2.py
{ "start": 2427, "end": 8312 }
class ____(nn.Module): """Multi-head Attention block with relative position embeddings.""" def __init__(self, config, window_size): super().__init__() input_size = ( (config.image_size // config.patch_size, config.image_size // config.patch_size) if window_size == 0 ...
GotOcr2VisionAttention
python
PyCQA__pylint
pylint/checkers/refactoring/refactoring_checker.py
{ "start": 8145, "end": 101282 }
class ____(checkers.BaseTokenChecker): """Looks for code which can be refactored. This checker also mixes the astroid and the token approaches in order to create knowledge about whether an "else if" node is a true "else if" node, or an "elif" node. """ name = "refactoring" msgs = { ...
RefactoringChecker
python
getsentry__sentry
tests/sentry/integrations/github/test_client.py
{ "start": 34193, "end": 36702 }
class ____(TestCase): @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") def setUp(self, get_jwt): integration = self.create_integration( organization=self.organization, provider="github", name="Github Test Org", external_...
GitHubClientFileBlameBase
python
ansible__ansible
test/units/modules/test_service_facts.py
{ "start": 4790, "end": 5915 }
class ____(unittest.TestCase): def setUp(self): self.mock1 = patch.object(basic.AnsibleModule, 'get_bin_path', return_value='/usr/sbin/lssrc') self.mock1.start() self.addCleanup(self.mock1.stop) self.mock2 = patch.object(basic.AnsibleModule, 'run_command', return_value=(0, LSSRC_OUT...
TestAIXScanService
python
dask__distributed
distributed/tests/test_client.py
{ "start": 108788, "end": 136666 }
class ____(Exception): pass @contextmanager def catch_unhandled_exceptions() -> Generator[None]: loop = asyncio.get_running_loop() ctxs: list[dict[str, Any]] = [] old_handler = loop.get_exception_handler() @loop.set_exception_handler def _(loop: object, context: dict[str, Any]) -> None: ...
UnhandledExceptions
python
getsentry__sentry
src/sentry/shared_integrations/exceptions/__init__.py
{ "start": 4721, "end": 5057 }
class ____(IntegrationError): """ Error when external API access is blocked due to configuration issues like permissions, visibility changes, or invalid project settings. This is not a product error, but rather an integration setup issue that requires user intervention. """ pass
IntegrationConfigurationError
python
neetcode-gh__leetcode
python/0918-maximum-sum-circular-subarray.py
{ "start": 0, "end": 479 }
class ____: def maxSubarraySumCircular(self, nums: List[int]) -> int: globMax, globMin = nums[0], nums[0] curMax, curMin = 0, 0 total = 0 for i, n in enumerate(nums): curMax = max(curMax + n, n) curMin = min(curMin + n, n) total += n ...
Solution
python
sympy__sympy
sympy/functions/elementary/exponential.py
{ "start": 6519, "end": 19814 }
class ____(ExpBase, metaclass=ExpMeta): """ The exponential function, :math:`e^x`. Examples ======== >>> from sympy import exp, I, pi >>> from sympy.abc import x >>> exp(x) exp(x) >>> exp(x).diff(x) exp(x) >>> exp(I*pi) -1 Parameters ========== arg : Expr ...
exp
python
davidhalter__jedi
jedi/inference/value/dynamic_arrays.py
{ "start": 7312, "end": 7527 }
class ____(_Modification): def py__iter__(self, contextualized_node=None): yield from self._wrapped_value.py__iter__(contextualized_node) yield LazyKnownValues(self._assigned_values)
ListModification
python
airbytehq__airbyte
airbyte-integrations/connectors/source-tiktok-marketing/unit_tests/integration/test_creative_assets_portfolios.py
{ "start": 534, "end": 1479 }
class ____(TestCase): stream_name = "creative_assets_portfolios" advertiser_id = "872746382648" def catalog(self, sync_mode: SyncMode = SyncMode.full_refresh): return CatalogBuilder().with_stream(name=self.stream_name, sync_mode=sync_mode).build() def config(self): return ConfigBuilder...
TestCreativeAssetsPortfolios
python
catalyst-team__catalyst
catalyst/data/loader.py
{ "start": 193, "end": 1380 }
class ____(DataLoader): """Loader wrapper interface. Args: loader: torch dataloader. """ def __init__(self, loader: DataLoader): """Init""" self.origin = loader def __getattr__(self, key): """ Gets attribute by ``key``. Firstly, looks at the ``origi...
ILoaderWrapper
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_line01.py
{ "start": 315, "end": 1343 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_line01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
pypa__pip
src/pip/_internal/cli/index_command.py
{ "start": 1419, "end": 4592 }
class ____(CommandContextMixIn): """ A class mixin for command classes needing _build_session(). """ def __init__(self) -> None: super().__init__() self._session: PipSession | None = None @classmethod def _get_index_urls(cls, options: Values) -> list[str] | None: """Ret...
SessionCommandMixin
python
joke2k__faker
faker/providers/company/en_PH/__init__.py
{ "start": 82, "end": 3694 }
class ____(CompanyProvider): """ Provider for company names for en_PH locale Company naming scheme and probabilities are inspired by and/or based on existing companies in the Philippines. Sources: - https://en.wikipedia.org/wiki/List_of_companies_of_the_Philippines - https://www.pse.com.ph/sto...
Provider
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_top_left_cell02.py
{ "start": 315, "end": 813 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("top_left_cell02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.g...
TestCompareXLSXFiles
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-convex/destination_convex/client.py
{ "start": 171, "end": 2501 }
class ____: def __init__(self, config: ConvexConfig, table_metadata: Mapping[str, Any]): self.deployment_url = config["deployment_url"] self.access_key = config["access_key"] self.table_metadata = table_metadata def batch_write(self, records: List[Mapping[str, Any]]) -> requests.Respons...
ConvexClient
python
dask__dask
dask/array/_array_expr/_creation.py
{ "start": 2375, "end": 3617 }
class ____(Arange): _parameters = ["start", "stop", "num", "endpoint", "chunks", "dtype"] _defaults = {"num": 50, "endpoint": True, "chunks": "auto", "dtype": None} like = None @functools.cached_property def num_rows(self): return self.operand("num") @functools.cached_property def ...
Linspace
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 13261, "end": 13372 }
class ____(_GenerativeOpenAIConfigBase): resourceName: str deploymentId: str
_GenerativeAzureOpenAIConfig
python
astropy__astropy
astropy/modeling/spline.py
{ "start": 19820, "end": 21928 }
class ____(_SplineFitter): """ Fit a smoothing spline. """ def __call__(self, model, x, y, **kwargs): """ Fit a smoothing spline to data. Parameters ---------- model : `Spline1D` The spline model to fit. x : array-like The x data ...
SplineSmoothingFitter
python
dagster-io__dagster
python_modules/dagster/dagster/_config/stack.py
{ "start": 1813, "end": 3056 }
class ____(EvaluationStackEntry): parent: Optional["EvaluationStackEntry"] = None def iter_entries(self): yield from [] def get_friendly_path_msg(stack: EvaluationStackEntry) -> str: return get_friendly_path_info(stack)[0] def get_friendly_path_info(stack: EvaluationStackEntry) -> tuple[str, st...
EvaluationStackRoot
python
openai__openai-python
src/openai/types/fine_tuning/alpha/grader_run_response.py
{ "start": 1094, "end": 1323 }
class ____(BaseModel): errors: MetadataErrors execution_time: float name: str sampled_model_name: Optional[str] = None scores: Dict[str, object] token_usage: Optional[int] = None type: str
Metadata
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/savedsearch.py
{ "start": 614, "end": 1154 }
class ____(BaseOrganizationSearchSerializer): """ Organization admins/owners may create organization wide saved searches """ # TODO(epurkhiser): Once the frontend is deployed we should change this to # default to OWNER since that is a more sane default than organization # visibile. visibili...
OrganizationSearchAdminSerializer
python
huggingface__transformers
src/transformers/models/vilt/modeling_vilt.py
{ "start": 18791, "end": 20360 }
class ____(GradientCheckpointingLayer): """This corresponds to the Block class in the timm implementation.""" def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = ViltAttention(config) ...
ViltLayer
python
prabhupant__python-ds
data_structures/graphs/cycle_in_undirected_graph.py
{ "start": 38, "end": 773 }
class ____: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def is_cyclic_util(self, v, visited, parent): visited[v] = True for i in self.graph[v]: if visited[i] == Fals...
Graph
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/validators/test_base_data_condition.py
{ "start": 4484, "end": 4966 }
class ____(AbstractDataConditionValidator[int, bool]): def validate_comparison(self, value: Any) -> int: if isinstance(value, int): return value else: raise ValidationError("Comparison must be an integer") def validate_condition_result(self, value: Any) -> bool: ...
ExampleConditionValidator
python
spack__spack
lib/spack/spack/llnl/util/lock.py
{ "start": 25326, "end": 27982 }
class ____: """Simple nested transaction context manager that uses a file lock. Arguments: lock (Lock): underlying lock for this transaction to be acquired on enter and released on exit acquire (typing.Callable or contextlib.contextmanager): function to be called after l...
LockTransaction
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/qa_with_sources/vector_db.py
{ "start": 559, "end": 3013 }
class ____(BaseQAWithSourcesChain): """Question-answering with sources over a vector database.""" vectorstore: VectorStore = Field(exclude=True) """Vector Database to connect to.""" k: int = 4 """Number of results to return from store""" reduce_k_below_max_tokens: bool = False """Reduce the...
VectorDBQAWithSourcesChain
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 35286, "end": 38695 }
class ____(NonStrictDataModel): """ :param scroll_id: Scroll ID to pass to the next calls to get_debug_image_sample or next_debug_image_sample :type scroll_id: str :param event: Debug image event :type event: dict :param min_iteration: minimal valid iteration for the variant :type mi...
DebugImageSampleResponse
python
doocs__leetcode
solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution.py
{ "start": 0, "end": 165 }
class ____: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: arr = sorted(nums) return [bisect_left(arr, x) for x in nums]
Solution
python
getsentry__sentry
tests/sentry/api/test_base.py
{ "start": 3112, "end": 3827 }
class ____(Endpoint): permission_classes = () def get(self, request): values = [x for x in range(0, 100)] def data_fn(offset, limit): page_offset = offset * limit return values[page_offset : page_offset + limit] return self.paginate( request=request...
DummyPaginationStreamingEndpoint
python
kamyu104__LeetCode-Solutions
Python/count-collisions-of-monkeys-on-a-polygon.py
{ "start": 69, "end": 247 }
class ____(object): def monkeyMove(self, n): """ :type n: int :rtype: int """ MOD = 10**9+7 return (pow(2, n, MOD)-2)%MOD
Solution
python
tensorflow__tensorflow
tensorflow/python/client/events_writer_test.py
{ "start": 1303, "end": 2780 }
class ____(test_util.TensorFlowTestCase): def testWriteEvents(self): file_prefix = os.path.join(self.get_temp_dir(), "events") writer = _pywrap_events_writer.EventsWriter(compat.as_bytes(file_prefix)) filename = compat.as_text(writer.FileName()) event_written = event_pb2.Event( wall_time=123....
PywrapeventsWriterTest
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/adls.py
{ "start": 1216, "end": 3328 }
class ____(BaseOperator): """ Creates a new object from passed data to Azure Data Lake on specified file. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ADLSCreateObjectOperator` :param file_system_name: Name of the file sy...
ADLSCreateObjectOperator
python
django-haystack__django-haystack
test_haystack/test_fields.py
{ "start": 16609, "end": 18586 }
class ____(TestCase): def test_init(self): try: foo = CharField(use_template=True) except: self.fail() try: foo = CharField(use_template=True, template_name="foo.txt") except: self.fail() foo = CharField(use_template=True, tem...
CharFieldWithTemplateTestCase
python
ray-project__ray
python/ray/dag/collective_node.py
{ "start": 566, "end": 10115 }
class ____: """ Represent metadata for a collective communicator collective operation. Args: inputs: A list of lists of DAGNode. Each nested list inside of inputs should contain exactly one object per actor. If multiple nested lists are provided, then the order of ...
_CollectiveOperation
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 13624, "end": 13809 }
class ____(ArffException): '''Error raised when and invalid numerical value is used in some data instance.''' message = 'Invalid numerical value, at line %d.'
BadNumericalValue
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 27674, "end": 42423 }
class ____(Pop2PianoPreTrainedModel): # Copied from transformers.models.t5.modeling_t5.T5Stack.__init__ with T5->Pop2Piano,t5->pop2piano def __init__(self, config): super().__init__(config) self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model) self.is_decoder = config.is_d...
Pop2PianoStack
python
getsentry__sentry
src/sentry/api/paginator.py
{ "start": 19959, "end": 20736 }
class ____: is_empty = False def __init__(self, queryset, order_by): assert isinstance(order_by, list), "order_by must be a list of keys/field names" self.queryset = queryset self.order_by = order_by try: instance = queryset[:1].get() self.instance_type =...
CombinedQuerysetIntermediary
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py
{ "start": 11208, "end": 12298 }
class ____(TypedDict): registry: Optional[str] directory: Optional[str] def merge_build_configs( workspace_build_config: Optional[DgRawBuildConfig], project_build_config: Optional[DgRawBuildConfig], ) -> DgRawBuildConfig: project_dict = remove_none_recursively(project_build_config or {}) works...
DgRawBuildConfig