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
tests/sentry/utils/test_committers.py
{ "start": 8820, "end": 9835 }
class ____(TestCase): def test_simple(self) -> None: current_datetime = timezone.now() org = self.create_organization() project = self.create_project(organization=org, name="foo") release1 = Release.objects.create( organization=org, version="a" * 40, date_released=curre...
GetPreviousReleasesTestCase
python
django__django
tests/delete/models.py
{ "start": 4523, "end": 4810 }
class ____(models.Model): m2m = models.ManyToManyField(R, related_name="m_set") m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set") m2m_through_null = models.ManyToManyField( R, through="MRNull", related_name="m_through_null_set" )
M
python
streamlit__streamlit
lib/streamlit/runtime/caching/cache_utils.py
{ "start": 4412, "end": 5911 }
class ____(Generic[P, R]): # ty: ignore[invalid-argument-type] """Encapsulates data for a cached function instance. CachedFuncInfo instances are scoped to a single script run - they're not persistent. """ def __init__( self, func: Callable[P, R], hash_funcs: HashFuncsDict ...
CachedFuncInfo
python
python__mypy
mypy/test/teststubgen.py
{ "start": 57376, "end": 57949 }
class ____(unittest.TestCase): def test_repr(self) -> None: assert_equal( repr(ArgSig(name='asd"dsa')), "ArgSig(name='asd\"dsa', type=None, default=False)" ) assert_equal( repr(ArgSig(name="asd'dsa")), 'ArgSig(name="asd\'dsa", type=None, default=False)' ) ...
ArgSigSuite
python
tensorflow__tensorflow
tensorflow/python/data/ops/concatenate_op.py
{ "start": 1081, "end": 2499 }
class ____(dataset_ops.DatasetV2): """A `Dataset` that concatenates its input with given dataset.""" def __init__(self, input_dataset, dataset_to_concatenate, name=None): """See `Dataset.concatenate()` for details.""" self._input_dataset = input_dataset self._dataset_to_concatenate = dataset_to_concate...
_ConcatenateDataset
python
jackfrued__Python-100-Days
Day31-35/code/example17.py
{ "start": 151, "end": 216 }
class ____(): def say_hello(self): print('Hello, A')
A
python
getsentry__sentry
tests/sentry/search/test_utils.py
{ "start": 1879, "end": 2449 }
class ____(TestCase): def test_simple(self) -> None: assert parse_numeric_value("10", None) == 10 def test_k(self) -> None: assert parse_numeric_value("1", "k") == 1000.0 assert parse_numeric_value("1", "K") == 1000.0 def test_m(self) -> None: assert parse_numeric_value("1"...
TestParseNumericValue
python
doocs__leetcode
solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/Solution.py
{ "start": 0, "end": 396 }
class ____: def __init__(self, n): self.p = list(range(n)) self.n = n def union(self, a, b): if self.find(a) == self.find(b): return False self.p[self.find(a)] = self.find(b) self.n -= 1 return True def find(self, x): if self.p[x] != x: ...
UnionFind
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_all_reduce_strategy.py
{ "start": 12856, "end": 43571 }
class ____(mirrored_strategy.MirroredExtended): """Implementation of CollectiveAllReduceStrategy.""" # Whether to perdically check the health of the cluster. If any worker is not # reachable, collectives are aborted and the user program should get a # tf.errors.UnavailableError. It's required to restart in ord...
CollectiveAllReduceExtended
python
django__django
django/db/models/aggregates.py
{ "start": 9699, "end": 9775 }
class ____(Aggregate): function = "MAX" name = "Max" arity = 1
Max
python
optuna__optuna
optuna/terminator/median_erroreval.py
{ "start": 407, "end": 3534 }
class ____(BaseErrorEvaluator): """An error evaluator that returns the ratio to initial median. This error evaluator is introduced as a heuristics in the following paper: - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple regrets <https://proceedings.mlr.press/v2...
MedianErrorEvaluator
python
walkccc__LeetCode
solutions/1642. Furthest Building You Can Reach/1642.py
{ "start": 0, "end": 516 }
class ____: def furthestBuilding( self, heights: list[int], bricks: int, ladders: int, ) -> int: minHeap = [] for i, (a, b) in enumerate(itertools.pairwise(heights)): diff = b - a if diff <= 0: continue heapq.heappush(minHeap, diff) # If we run out of...
Solution
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_K.py
{ "start": 1648, "end": 2931 }
class ____(Benchmark): r""" Keane objective function. This class defines the Keane [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Keane}}(x) = \frac{\sin^2(x_1 - x_2)\sin^2(x_1 + x_2)} {\sqrt{x_1^2 + x_2^2}} ...
Keane
python
fluentpython__example-code-2e
16-op-overloading/bingoaddable.py
{ "start": 1245, "end": 1959 }
class ____(BingoCage): # <1> def __add__(self, other): if isinstance(other, Tombola): # <2> return AddableBingoCage(self.inspect() + other.inspect()) else: return NotImplemented def __iadd__(self, other): if isinstance(other, Tombola): other_iterab...
AddableBingoCage
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 23165, "end": 29680 }
class ____(abc.ABC): @abc.abstractmethod def bar(self): pass @fails_with(ResolutionFailed) @given(st.from_type(AbstractBar)) def test_cannot_resolve_abstract_class_with_no_concrete_subclass(instance): raise AssertionError("test body unreachable as strategy cannot resolve") @fails_with(Resolution...
AbstractBar
python
walkccc__LeetCode
solutions/3234. Count the Number of Substrings With Dominant Ones/3234.py
{ "start": 0, "end": 1147 }
class ____: def numberOfSubstrings(self, s: str) -> int: ans = 0 # z^2 + z = n. # => z^2 + z - n = 0. # => z = (-1 + sqrt(1 + 4n)) / 2. maxZero = (-1 + math.sqrt(1 + 4 * len(s))) // 2 # Iterate through all possible number of 0s. for zero in range(int(maxZero) + 1): lastInvalidPos...
Solution
python
getsentry__sentry
tests/sentry/rules/filters/test_assigned_to.py
{ "start": 247, "end": 2470 }
class ____(RuleTestCase): rule_cls = AssignedToFilter def test_assigned_to_member_passes(self) -> None: event = self.get_event() GroupAssignee.objects.create(user_id=self.user.id, group=event.group, project=self.project) data = { "targetType": "Member", "targetI...
AssignedToFilterTest
python
davidhalter__jedi
test/completion/django.py
{ "start": 595, "end": 4537 }
class ____(models.Model): attached_o2o = models.OneToOneField(AttachedData) category_fk = models.ForeignKey(Category) category_fk2 = models.ForeignKey('Category') category_fk3 = models.ForeignKey(1) category_fk4 = models.ForeignKey('models') category_fk5 = models.ForeignKey() integer_field...
BusinessModel
python
huggingface__transformers
src/transformers/quantizers/quantizer_gptq.py
{ "start": 1072, "end": 5584 }
class ____(HfQuantizer): """ Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through `auto_gptq` or `gptqmodel` package. Quantization is done under the hood for users if they load a non-prequantized model. """ requires_calibration = False required_packages...
GptqHfQuantizer
python
pytest-dev__pluggy
src/pluggy/_manager.py
{ "start": 2226, "end": 20285 }
class ____: """Core class which manages registration of plugin objects and 1:N hook calling. You can register new hooks by calling :meth:`add_hookspecs(module_or_class) <PluginManager.add_hookspecs>`. You can register plugin objects (which contain hook implementations) by calling :meth:`regist...
PluginManager
python
laurentluce__python-algorithms
algorithms/tests/test_a_star_path_finding.py
{ "start": 63, "end": 1108 }
class ____(unittest.TestCase): def setUp(self): pass def test_maze(self): a = pf.AStar() walls = ((0, 5), (1, 0), (1, 1), (1, 5), (2, 3), (3, 1), (3, 2), (3, 5), (4, 1), (4, 4), (5, 1)) a.init_grid(6, 6, walls, (0, 0), (5, 5)) path = a.solve() s...
Test
python
django__django
tests/fixtures_regress/models.py
{ "start": 3308, "end": 3471 }
class ____(models.Manager): def get_by_natural_key(self, name, author): return self.get(name=name, author__name=author)
NaturalKeyWithFKDependencyManager
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/__init__.py
{ "start": 293, "end": 812 }
class ____(Exception): """My custom exception.""" def f(self): """Exception method.""" def _funky_classmethod(name, b, c, d, docstring=None): """Generates a classmethod for a class from a template by filling out some arguments.""" def template(cls, a, b, c, d=4, e=5, f=6): return a, ...
CustomEx
python
pytorch__pytorch
torch/_inductor/runtime/triton_heuristics.py
{ "start": 69056, "end": 80602 }
class ____(CompileResult[CompiledKernel]): """ Upstream Triton CompileKernel can not be pickled. This is a wrapper to support serialization and generate the launcher function. """ @staticmethod @functools.lru_cache(32) def _kernel_metadata_cls(fields: tuple[str, ...]) -> Any: retur...
TritonCompileResult
python
wandb__wandb
wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py
{ "start": 396, "end": 569 }
class ____(GQLResult): artifact_collection: DeleteArtifactPortfolioResultArtifactCollection = Field( alias="artifactCollection" )
DeleteArtifactPortfolioResult
python
django__django
django/contrib/staticfiles/storage.py
{ "start": 1530, "end": 17993 }
class ____: default_template = """url("%(url)s")""" max_post_process_passes = 5 support_js_module_import_aggregation = False _js_module_import_aggregation_patterns = ( "*.js", ( ( ( r"""(?P<matched>import""" r"""(?s:(?P<...
HashedFilesMixin
python
getsentry__sentry
src/sentry/models/sentryshot.py
{ "start": 353, "end": 1081 }
class ____(Model): """ Represents metadata for a screenshot within Sentry product """ __relocation_scope__ = RelocationScope.Excluded # uuid represents the ID of the object for external use. We want something long and difficult to # guess since the API reading these will be a public API uu...
SentryShot
python
getsentry__sentry
src/sentry/sentry_metrics/querying/visitors/query_expression.py
{ "start": 9259, "end": 11235 }
class ____(QueryExpressionVisitor[set[str]]): """ Visitor that recursively computes all the groups of the `QueryExpression`. """ def __init__(self, mappers: list[Mapper] | None = None): self.mappers = mappers or [] def _visit_formula(self, formula: Formula) -> set[str]: group_bys: ...
UsedGroupBysVisitor
python
spack__spack
lib/spack/spack/spec.py
{ "start": 31306, "end": 35443 }
class ____(lang.HashableMap[str, List[CompilerFlag]]): __slots__ = ("spec",) def __init__(self, spec): super().__init__() self.spec = spec def satisfies(self, other): return all(f in self and set(self[f]) >= set(other[f]) for f in other) def intersects(self, other): re...
FlagMap
python
py-pdf__pypdf
pypdf/_utils.py
{ "start": 17217, "end": 17747 }
class ____: # noqa: N801 """ Decorator that converts a method with a single cls argument into a property that can be accessed directly from the class. """ def __init__(self, method=None) -> None: # type: ignore # noqa: ANN001 self.fget = method def __get__(self, instance, cls=None) ...
classproperty
python
mlflow__mlflow
tests/utils/test_async_artifacts_logging_queue.py
{ "start": 6334, "end": 8498 }
class ____: def __init__(self) -> None: self.filenames = [] self.artifact_paths = [] self.artifacts = [] def consume_queue_data(self, filename, artifact_path, artifact): time.sleep(0.5) self.filenames.append(filename) self.artifact_paths.append(artifact_path) ...
Consumer
python
encode__django-rest-framework
tests/test_request.py
{ "start": 1359, "end": 1710 }
class ____(BaseParser): media_type = 'text/plain' def parse(self, stream, media_type=None, parser_context=None): """ Returns a 2-tuple of `(data, files)`. `data` will simply be a string representing the body of the request. `files` will always be `None`. """ ret...
PlainTextParser
python
dask__distributed
distributed/client.py
{ "start": 24195, "end": 26825 }
class ____(Expr): func: Callable iterables: Iterable key: Key pure: bool annotations: dict kwargs: dict _cached_keys: Iterable[Key] | None _parameters = [ "func", "iterables", "key", "pure", "annotations", "kwargs", "_cached_keys", ...
_MapExpr
python
getsentry__sentry
src/sentry/api/endpoints/organization_unsubscribe.py
{ "start": 4307, "end": 5402 }
class ____(OrganizationUnsubscribeBase[Group]): object_type = "issue" def fetch_instance( self, request: Request, organization_id_or_slug: int | str, issue_id: int ) -> Group: try: issue = Group.objects.get_from_cache(id=issue_id) except Group.DoesNotExist: r...
OrganizationUnsubscribeIssue
python
OmkarPathak__pygorithm
pygorithm/data_structures/queue.py
{ "start": 74, "end": 1673 }
class ____(object): """Queue Queue implementation """ def __init__(self, limit=10): """ :param limit: Queue limit size, default @ 10 """ self.queue = [] self.front = None self.rear = None self.limit = limit self.size = 0 def __str__(se...
Queue
python
getsentry__sentry
tests/sentry/utils/test_auth.py
{ "start": 538, "end": 1903 }
class ____(TestCase): def setUp(self) -> None: self.user = User(username="foo", email="baz@example.com") self.user.set_password("bar") self.user.save() @property def backend(self): return EmailAuthBackend() def test_can_authenticate_with_username(self) -> None: ...
EmailAuthBackendTest
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup_py38.py
{ "start": 1821, "end": 2019 }
class ____(typing.TypedDict): a: int @given(from_type(A)) def test_simple_typeddict(value): assert type(value) == dict assert set(value) == {"a"} assert isinstance(value["a"], int)
A
python
kubernetes-client__python
kubernetes/client/models/v1_pod_anti_affinity.py
{ "start": 383, "end": 8293 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1PodAntiAffinity
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_data_test.py
{ "start": 4051, "end": 5649 }
class ____(test_util.TensorFlowTestCase): def testDebugDatum(self): dump_root = "/tmp/tfdbg_1" debug_dump_rel_path = ( debug_data.METADATA_FILE_PREFIX + debug_data.DEVICE_TAG + ",job_localhost,replica_0,task_0,cpu_0" + "/ns1/ns2/node_a_1_2_DebugIdentity_1472563253536385" )...
DebugTensorDatumTest
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 103628, "end": 105139 }
class ____(TestCase): def test_get_level_indicator(self): queryset = Category.objects.all() field = TreeNodeMultipleChoiceField(queryset=queryset) self.assertEqual(field._get_level_indicator(Category(level=0)), "") self.assertEqual(field._get_level_indicator(Category(level=1)), "---"...
FormTests
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1015824, "end": 1018407 }
class ____(sgqlc.types.Type, Node, Starrable): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("name", "related_topics", "repositories") name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") related_topics = sgqlc.types.Field( ...
Topic
python
openai__openai-python
src/openai/resources/audio/speech.py
{ "start": 9213, "end": 9424 }
class ____: def __init__(self, speech: Speech) -> None: self._speech = speech self.create = _legacy_response.to_raw_response_wrapper( speech.create, )
SpeechWithRawResponse
python
getsentry__sentry
tests/sentry/flags/endpoints/test_secrets.py
{ "start": 144, "end": 11493 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-flag-hooks-signing-secrets" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.obj = FlagWebHookSigningSecretModel.objects.create( created_by=self.user.id, organization=self.o...
OrganizationFlagsWebHookSigningSecretsEndpointTestCase
python
langchain-ai__langchain
libs/core/tests/unit_tests/fake/callbacks.py
{ "start": 3091, "end": 6421 }
class ____(BaseCallbackHandler, BaseFakeCallbackHandlerMixin): """Fake callback handler for testing.""" @property def ignore_llm(self) -> bool: """Whether to ignore LLM callbacks.""" return self.ignore_llm_ @property def ignore_chain(self) -> bool: """Whether to ignore chai...
FakeCallbackHandler
python
optuna__optuna
optuna/visualization/_slice.py
{ "start": 1330, "end": 9056 }
class ____(NamedTuple): x: list[Any] y: list[float] trial_numbers: list[int] def _get_slice_subplot_info( trials: list[FrozenTrial], param: str, target: Callable[[FrozenTrial], float] | None, log_scale: bool, numerical: bool, x_labels: tuple[CategoricalChoiceType, ...] | None, ) ->...
_PlotValues
python
bokeh__bokeh
tests/unit/bokeh/test___init__.py
{ "start": 3315, "end": 4559 }
class ____: @pytest.mark.parametrize('cat', (BokehDeprecationWarning, BokehUserWarning)) def test_bokeh_custom(self, cat) -> None: r = warnings.formatwarning("message", cat, "line", "lineno") assert r == f"{cat.__name__}: message\n" def test_general_default(self) -> None: r = warnin...
TestWarnings
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1586256, "end": 1586517 }
class ____(sgqlc.types.Union): """Represents either a issue the viewer can access or a restricted contribution. """ __schema__ = github_schema __types__ = (CreatedIssueContribution, RestrictedContribution)
CreatedIssueOrRestrictedContribution
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 3183, "end": 10981 }
class ____(TestCase): # check that non-array arguments to functions wrap them in arrays def test_choose(self): choices = [[0, 1, 2], [3, 4, 5], [5, 6, 7]] tgt = [5, 1, 5] a = [2, 0, 1] out = np.choose(a, choices) assert_equal(out, tgt) def test_clip(self): a...
TestNonarrayArgs
python
run-llama__llama_index
llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-azure/llama_index/storage/kvstore/azure/base.py
{ "start": 605, "end": 17766 }
class ____(BaseKVStore): """ Provides a key-value store interface for Azure Table Storage and Cosmos DB. This class supports both synchronous and asynchronous operations on Azure Table Storage and Cosmos DB. It supports connecting to the service using different credentials and manages table creation...
AzureKVStore
python
modin-project__modin
modin/pandas/series_utils.py
{ "start": 3135, "end": 5949 }
class ____(ClassLogger): _series: Series _query_compiler: BaseQueryCompiler def __init__(self, data: Series): self._series = data self._query_compiler = data._query_compiler @cached_property def _Series(self) -> Series: # noqa: GL08 # to avoid cyclic import from mo...
CategoryMethods
python
django__django
tests/fixtures/tests.py
{ "start": 52061, "end": 54194 }
class ____(DumpDataAssertMixin, TransactionTestCase): available_apps = [ "fixtures", "django.contrib.sites", ] @skipUnlessDBFeature("supports_forward_references") def test_format_discovery(self): # Load fixture 1 again, using format discovery management.call_command("loa...
FixtureTransactionTests
python
realpython__materials
python-namedtuple/namedtuple_dataclass_memory.py
{ "start": 169, "end": 534 }
class ____: x: int y: int z: int namedtuple_memory = asizeof.asizeof(PointNamedTuple(x=1, y=2, z=3)) dataclass_memory = asizeof.asizeof(PointDataClass(x=1, y=2, z=3)) gain = 100 - namedtuple_memory / dataclass_memory * 100 print(f"namedtuple: {namedtuple_memory} bytes ({gain:.2f}% smaller)") print(f"data...
PointDataClass
python
huggingface__transformers
src/transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py
{ "start": 14924, "end": 16802 }
class ____(GradientCheckpointingLayer): def __init__(self, config: HunYuanMoEV1Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = HunYuanMoEV1Attention(config=config, layer_idx=layer_idx) self.mlp = HunYuanMoEV1Moe(config, layer_idx=lay...
HunYuanMoEV1DecoderLayer
python
huggingface__transformers
tests/models/detr/test_image_processing_detr.py
{ "start": 4853, "end": 37758 }
class ____(AnnotationFormatTestMixin, ImageProcessingTestMixin, unittest.TestCase): image_processing_class = DetrImageProcessor if is_vision_available() else None fast_image_processing_class = DetrImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() se...
DetrImageProcessingTest
python
jina-ai__jina
jina/serve/networking/sse.py
{ "start": 3327, "end": 6554 }
class ____: """Class to manage Server-Sent Events""" def __init__( self, data: Optional[Any] = None, *, event: Optional[str] = None, id: Optional[int] = None, retry: Optional[int] = None, comment: Optional[str] = None, sep: Optional[str] = None, ...
ServerSentEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_requests/report_download_request_builder.py
{ "start": 118, "end": 742 }
class ____(AmazonAdsRequestBuilder): @classmethod def download_endpoint(cls, report_id: str) -> "ReportDownloadRequestBuilder": return cls(report_id) def __init__(self, report_id: str) -> None: self._report_id: str = report_id @property def url(self): return f"https://offli...
ReportDownloadRequestBuilder
python
buildout__buildout
src/zc/buildout/tests/test_all.py
{ "start": 1455, "end": 116780 }
class ____(unittest.TestCase): # The contents of a zipped egg, created by setuptools: # from setuptools import setup # setup( # name='TheProject', # version='3.3', # ) # # (we can't run setuptools at runtime, it may not be installed) EGG_DATA = ( b'PK\x03\x04\x14\x00\x...
TestEasyInstall
python
pytorch__pytorch
test/functorch/test_dims.py
{ "start": 1985, "end": 20030 }
class ____(TestCase): def setUp(self): super().setUp() gc.disable() gc.collect() self.interesting = set() for o in gc.get_objects(): if isinstance(o, (torch.Tensor, Dim, Tensor, DimList)): self.interesting.add(id(o)) if "cuda" in self._test...
TestMin
python
arrow-py__arrow
tests/test_locales.py
{ "start": 10450, "end": 17586 }
class ____: def test_singles_timeframe(self): # Second result = self.locale._format_timeframe("second", 1) assert result == "секунда" result = self.locale._format_timeframe("second", -1) assert result == "секунда" # Quarter result = self.locale._format_timef...
TestRussianLocale
python
fastai__fastai
fastai/losses.py
{ "start": 7721, "end": 9040 }
class ____(Module): y_int = True # y interpolation def __init__(self, eps:float=0.1, # The weight for the interpolation formula weight:Tensor=None, # Manual rescaling weight given to each class passed to `F.nll_loss` reduction:str='mean' # PyTorch reduction to apply to the output ):...
LabelSmoothingCrossEntropy
python
django__django
tests/model_fields/models.py
{ "start": 14839, "end": 14996 }
class ____(models.Model): m2m = models.ManyToManyField("self") ###############################################################################
ManyToMany
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-github/tests/test_github_app_auth.py
{ "start": 12463, "end": 15181 }
class ____: """Test GithubClient with GitHub App authentication.""" def test_init_with_pat(self): """Test initialization with PAT (backward compatibility).""" client = GithubClient(github_token="ghp_test_token") assert client._github_token == "ghp_test_token" assert not client....
TestGithubClientWithAppAuth
python
numpy__numpy
numpy/f2py/tests/test_callback.py
{ "start": 5689, "end": 6195 }
class ____(util.F2PyTest): """The reproduction of the reported issue requires specific input that extensions may break the issue conditions, so the reproducer is implemented as a separate test class. Do not extend this test with other tests! """ sources = [util.getpath("tests", "src", "callback"...
TestGH18335
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/libceed/package.py
{ "start": 216, "end": 617 }
class ____(Package): """Package that has a dependency imposing conditional requirements on platforms""" homepage = "https://github.com/CEED/libCEED" url = "http://www.fake.com/libceed.tgz" version("0.12.0", sha256="e491ccadebc5cdcd1fc08b5b4509a0aba4e2c096f53d7880062a66b82a0baf84") depends_on("c",...
Libceed
python
indygreg__python-build-standalone
pythonbuild/buildenv.py
{ "start": 4123, "end": 8229 }
class ____: def __init__(self, td): self.td = pathlib.Path(td) self.tools_path = str(self.td / "tools") @property def is_isolated(self): return False def copy_file(self, source: pathlib.Path, dest_path=None, dest_name=None): if dest_path: dest_dir = self.td...
TempdirContext
python
pyca__cryptography
tests/hazmat/primitives/test_block.py
{ "start": 4646, "end": 5819 }
class ____: def test_cbc(self, backend): with pytest.raises(ValueError): Cipher( algorithms.AES(b"\x00" * 16), modes.CBC(b"abc"), backend, ) def test_ofb(self, backend): with pytest.raises(ValueError): Cipher( ...
TestModeValidation
python
walkccc__LeetCode
solutions/3392. Count Subarrays of Length Three With a Condition/3392.py
{ "start": 0, "end": 161 }
class ____: def countSubarrays(self, nums: list[int]) -> int: return sum(b == (a + c) * 2 for a, b, c in zip(nums, nums[1:], nums[2:]))
Solution
python
doocs__leetcode
solution/0600-0699/0653.Two Sum IV - Input is a BST/Solution2.py
{ "start": 192, "end": 679 }
class ____: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: q = deque([root]) vis = set() while q: for _ in range(len(q)): node = q.popleft() if k - node.val in vis: return True vis.add(node.val) ...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-mysql/dagster_mysql_tests/test_schedule_storage.py
{ "start": 187, "end": 479 }
class ____(TestScheduleStorage): __test__ = True @pytest.fixture(scope="function", name="storage") def schedule_storage(self, conn_string): storage = MySQLScheduleStorage.create_clean_storage(conn_string) assert storage return storage
TestMySQLScheduleStorage
python
davidhalter__jedi
test/completion/classes.py
{ "start": 7640, "end": 8018 }
class ____(Super): #? super() def test(self): #? SuperCopy() super() #? ['a'] super().a if 1: #? SuperCopy() super() def a(): #? super() def return_sup(self): #? int() return super().return_s...
TestSuper
python
numba__numba
numba/core/types/npytypes.py
{ "start": 9442, "end": 13173 }
class ____(IteratorType): """ Type class for `np.nditer()` objects. The layout denotes in which order the logical shape is iterated on. "C" means logical order (corresponding to in-memory order in C arrays), "F" means reverse logical order (corresponding to in-memory order in F arrays). """...
NumpyNdIterType
python
fastai__fastai
fastai/vision/core.py
{ "start": 8730, "end": 9749 }
class ____(L): "Basic type for a list of bounding boxes in an image" def show(self, ctx=None, **kwargs): for b,l in zip(self.bbox, self.lbl): if l != '#na#': ctx = retain_type(b, self.bbox).show(ctx=ctx, text=l) return ctx bbox,lbl = add_props(lambda i,self: self[i]) # %% ../.....
LabeledBBox
python
bokeh__bokeh
src/bokeh/models/annotations/legends.py
{ "start": 9832, "end": 11872 }
class ____(Model): ''' ''' def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) if isinstance(self.label, str): # Allow convenience of setting label as a string self.label = value(self.label) label = NullStringSpec(help=""" A label ...
LegendItem
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_data_condition_group.py
{ "start": 18442, "end": 22633 }
class ____(unittest.TestCase): def test_any_all_untainted_true_returns_untainted_true(self) -> None: assert TriggerResult.any([FALSE, TRUE, FALSE]) == TRUE def test_any_one_untainted_true_returns_untainted_true(self) -> None: assert TriggerResult.any([TRUE, TRUE.with_error(ERR)]) == TRUE ...
TestTriggerResult
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/types.py
{ "start": 20788, "end": 21968 }
class ____(_StringType): """MySQL LONGTEXT type, for character storage encoded up to 2^32 bytes.""" __visit_name__ = "LONGTEXT" def __init__(self, **kwargs: Any): """Construct a LONGTEXT. :param charset: Optional, a column-level character set for this string value. Takes preced...
LONGTEXT
python
eventlet__eventlet
eventlet/green/http/cookiejar.py
{ "start": 66124, "end": 69155 }
class ____(CookieJar): """CookieJar that can be loaded from and saved to a file.""" def __init__(self, filename=None, delayload=False, policy=None): """ Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ CookieJar.__in...
FileCookieJar
python
Lightning-AI__lightning
examples/pytorch/domain_templates/reinforce_learn_ppo.py
{ "start": 4620, "end": 17067 }
class ____(LightningModule): """PyTorch Lightning implementation of PPO. Example: model = PPOLightning("CartPole-v0") Train: trainer = Trainer() trainer.fit(model) """ def __init__( self, env: str, gamma: float = 0.99, lam: float = 0.95, ...
PPOLightning
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/variables/dense_update_ops_no_tsan_test.py
{ "start": 1048, "end": 5623 }
class ____(test.TestCase): # NOTE(mrry): We exclude thess tests from the TSAN TAP target, because they # contain benign and deliberate data races when multiple threads update # the same parameters without a lock. def testParallelUpdateWithoutLocking(self): # We need each thread to keep its own device s...
AssignOpTest
python
spyder-ide__spyder
spyder/plugins/run/api.py
{ "start": 3468, "end": 3650 }
class ____(TypedDict): # Error code for the current error. code: Optional[int] # Human-readable message that describes the error. message: Optional[str]
RunResultError
python
getsentry__sentry
src/sentry/mail/adapter.py
{ "start": 1447, "end": 6790 }
class ____: """ This class contains generic logic for notifying users via Email. TODO(mgaeta): Make an explicit interface that is shared with NotificationPlugin. """ mail_option_key = "mail:subject_prefix" def rule_notify( self, event: Event | GroupEvent, futures: Seque...
MailAdapter
python
pytorch__pytorch
torchgen/dest/lazy_ir.py
{ "start": 26485, "end": 27564 }
class ____: """ Here we use the base name as the suffix of the signature to avoid generating for in-place variants. """ def __init__(self, kernel_name: str, f: NativeFunction, *, symint: bool) -> None: self.__schema = LazyIrSchema(f.func, symint=symint) self.__dispatch_args = ", ".join(...
ComputeShapeSignature
python
pytorch__pytorch
torch/_dynamo/variables/distributed.py
{ "start": 4924, "end": 6074 }
class ____(DistributedVariable): @staticmethod def is_placement_type(value: object) -> bool: # we can't rely on importing/accessing torch distributed, it is not always built. if not DistributedVariable.is_available(): return False from torch.distributed.tensor.placement_type...
PlacementClassVariable
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_scheduler.py
{ "start": 39169, "end": 41701 }
class ____: """Tests scheduler service.""" @pytest.mark.parametrize( ("executor", "creates_service"), [ ("LocalExecutor", True), ("CeleryExecutor", False), ("CeleryKubernetesExecutor", False), ("KubernetesExecutor", False), ("LocalKube...
TestSchedulerService
python
oauthlib__oauthlib
tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py
{ "start": 226, "end": 7718 }
class ____(TestCase): def setUp(self): self.validator = MagicMock(wraps=RequestValidator()) self.validator.client_authentication_required.return_value = True self.validator.authenticate_client.return_value = True self.validator.validate_bearer_token.return_value = True self....
IntrospectEndpointTest
python
weaviate__weaviate-python-client
weaviate/collections/batch/client.py
{ "start": 1004, "end": 4419 }
class ____(_BatchBase): def add_object( self, collection: str, properties: Optional[WeaviateProperties] = None, references: Optional[ReferenceInputs] = None, uuid: Optional[UUID] = None, vector: Optional[VECTORS] = None, tenant: Optional[Union[str, Tenant]] = ...
_BatchClient
python
neetcode-gh__leetcode
python/0323-number-of-connected-components-in-an-undirected-graph.py
{ "start": 289, "end": 517 }
class ____: def countComponents(self, n: int, edges: List[List[int]]) -> int: dsu = UnionFind() for a, b in edges: dsu.union(a, b) return len(set(dsu.findParent(x) for x in range(n)))
Solution
python
getsentry__sentry
src/sentry/integrations/cursor/integration.py
{ "start": 2297, "end": 2945 }
class ____: def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase: if request.method == "POST": form = CursorAgentConfigForm(request.POST) if form.is_valid(): pipeline.bind_state("config", form.cleaned_data) return...
CursorPipelineView
python
celery__celery
celery/utils/functional.py
{ "start": 5142, "end": 12017 }
class ____(UserList, list): # must be subclass of list so that json can encode. def __init__(self, it): # pylint: disable=super-init-not-called # UserList creates a new list and sets .data, so we don't # want to call init here. self.__it = it self.__consumed = [] ...
_regen
python
kamyu104__LeetCode-Solutions
Python/total-characters-in-string-after-transformations-i.py
{ "start": 1057, "end": 2207 }
class ____(object): def lengthAfterTransformations(self, s, t): """ :type s: str :type t: int :type nums: List[int] :rtype: int """ MOD = 10**9+7 def matrix_mult(A, B): ZB = zip(*B) return [[sum(a*b % MOD for a, b in itertools.i...
Solution3
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-frogs-croaking.py
{ "start": 29, "end": 538 }
class ____(object): def minNumberOfFrogs(self, croakOfFrogs): """ :type croakOfFrogs: str :rtype: int """ S = "croak" lookup = [0]*len(S) result = 0 for c in croakOfFrogs: i = S.find(c) lookup[i] += 1 if lookup[i-1]:...
Solution
python
huggingface__transformers
src/transformers/models/flava/modeling_flava.py
{ "start": 25730, "end": 26410 }
class ____(nn.Module): """ The residual connection is defined in FlavaLayer (same as ViTLayer) instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: FlavaPossibleConfigs) -> None: super().__init__() self.de...
FlavaSelfOutput
python
Lightning-AI__lightning
src/lightning/fabric/connector.py
{ "start": 2543, "end": 28432 }
class ____: """The Connector parses several Fabric arguments and instantiates the Strategy including its owned components. A. accelerator flag could be: 1. accelerator class 2. accelerator str 3. accelerator auto B. strategy flag could be: 1. strateg...
_Connector
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol4.py
{ "start": 695, "end": 904 }
class ____: def __init__(self): self.x: int = 0 # This should generate an error because x is an instance-only variable # and doesn't satisfy the ClassVar annotation in the protocol. c: ProtoC = C()
C
python
langchain-ai__langchain
libs/partners/mistralai/tests/unit_tests/test_standard.py
{ "start": 284, "end": 429 }
class ____(ChatModelUnitTests): @property def chat_model_class(self) -> type[BaseChatModel]: return ChatMistralAI
TestMistralStandard
python
dateutil__dateutil
tests/test_tz.py
{ "start": 87023, "end": 87149 }
class ____(TzPickleTest): """ Run all the TzPickleTest tests, using a temporary file """ _asfile = True
TzPickleFileTest
python
ansible__ansible
lib/ansible/_internal/_errors/_task_timeout.py
{ "start": 278, "end": 923 }
class ____(AnsibleTimeoutError, ContributesToTaskResult): """ A task-specific timeout. This exception provides a result dictionary via the ContributesToTaskResult mixin. """ @property def result_contribution(self) -> _c.Mapping[str, object]: help_text = "Configure `DISPLAY_TRACEBACK` t...
TaskTimeoutError
python
kamyu104__LeetCode-Solutions
Python/array-with-elements-not-equal-to-average-of-neighbors.py
{ "start": 2182, "end": 2455 }
class ____(object): def rearrangeArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.sort() mid = (len(nums)-1)//2 nums[::2], nums[1::2] = nums[mid::-1], nums[:mid:-1] return nums
Solution2
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/summary_ops/summary_v1_audio_op_test.py
{ "start": 933, "end": 2422 }
class ____(test.TestCase): def _AsSummary(self, s): summ = summary_pb2.Summary() summ.ParseFromString(s) return summ def _CheckProto(self, audio_summ, sample_rate, num_channels, length_frames): """Verify that the non-audio parts of the audio_summ proto match shape.""" # Only the first 3 sounds...
SummaryV1AudioOpTest
python
django__django
django/template/loaders/app_directories.py
{ "start": 206, "end": 312 }
class ____(FilesystemLoader): def get_dirs(self): return get_app_template_dirs("templates")
Loader
python
huggingface__transformers
src/transformers/models/time_series_transformer/modeling_time_series_transformer.py
{ "start": 7146, "end": 9845 }
class ____(nn.Module): """ Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data. """ def __init__(self, config: TimeSeriesTransformerConfig): super().__init__() self.dim = config.scaling_dim if hasattr(config, "scaling_dim") e...
TimeSeriesNOPScaler