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/sentry_apps/api/endpoints/test_organization_sentry_apps.py
{ "start": 1213, "end": 4275 }
class ____(OrganizationSentryAppsTest): def test_gets_all_apps_in_own_org(self) -> None: self.login_as(user=self.user) response = self.client.get(self.url, format="json") assert response.status_code == 200 assert_response_json( response, [ { ...
GetOrganizationSentryAppsTest
python
walkccc__LeetCode
solutions/109. Convert Sorted List to Binary Search Tree/109-2.py
{ "start": 0, "end": 476 }
class ____: def sortedListToBST(self, head: ListNode | None) -> TreeNode | None: arr = [] # Construct the array. curr = head while curr: arr.append(curr.val) curr = curr.next def helper(l: int, r: int) -> TreeNode | None: if l > r: return None m = (l + r) // 2 ...
Solution
python
facebookresearch__faiss
benchs/bench_fw/benchmark.py
{ "start": 35153, "end": 42711 }
class ____: num_threads: int training_vectors: Optional[DatasetDescriptor] = None database_vectors: Optional[DatasetDescriptor] = None query_vectors: Optional[DatasetDescriptor] = None index_descs: Optional[List[IndexDescriptorClassic]] = None range_ref_index_desc: Optional[str] = None k: in...
Benchmark
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_stateful.py
{ "start": 1496, "end": 1704 }
class ____(RuleBasedStateMachine): def myfunc(self, data): print(data) rule1 = rule(data=just("rule1data"))(myfunc) rule2 = rule(data=just("rule2data"))(myfunc)
MultipleRulesSameFuncMachine
python
graphql-python__graphene
graphene/types/inputobjecttype.py
{ "start": 1956, "end": 2330 }
class ____(dict, BaseType): # type: ignore class Meta: abstract = True def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) for key in self._meta.fields: setattr(self, key, self.get(key, _INPUT_OBJECT_TYPE_DEFAULT_VALUE)) def __init_subclass__(cls,...
InputObjectTypeContainer
python
pytorch__pytorch
test/test_multiprocessing_spawn.py
{ "start": 7730, "end": 7880 }
class ____(TestCase, _TestMultiProcessing): start_method = 'fork' @unittest.skipIf( IS_WINDOWS, "Fork is only available on Unix", )
ForkTest
python
django__django
django/contrib/flatpages/middleware.py
{ "start": 172, "end": 784 }
class ____(MiddlewareMixin): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a flatpage for non-404 responses. try: return flatpage(request, request.path_info) # Return the original response if any...
FlatpageFallbackMiddleware
python
numba__numba
numba/cuda/args.py
{ "start": 193, "end": 771 }
class ____(metaclass=abc.ABCMeta): def __init__(self, value): self.value = value @abc.abstractmethod def to_device(self, retr, stream=0): """ :param stream: a stream to use when copying data :param retr: a list of clean-up work to do after the kernel's been run. ...
ArgHint
python
sphinx-doc__sphinx
sphinx/util/_io.py
{ "start": 275, "end": 884 }
class ____: """File-like object writing to two streams.""" def __init__( self, stream_term: SupportsWrite, stream_file: SupportsWrite, ) -> None: self.stream_term = stream_term self.stream_file = stream_file def write(self, text: str, /) -> None: self.st...
TeeStripANSI
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/functionAnnotation1.py
{ "start": 747, "end": 1061 }
class ____: pass def func1g(*args, **kwargs): # type: (*int, **float) -> int return sum(args) + sum(round(kwarg) for kwarg in kwargs.values()) def func1h( a, # type: _Literal["{", "}"] b, # type: Union[_Literal["%"], _Literal["{"], _Literal["$"]] ): # type: (...) -> str return ""
Foo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hardcoded-records/source_hardcoded_records/streams.py
{ "start": 557, "end": 834 }
class ____(HardcodedStream): sample_record = { "id": 1, "make": "Mazda", "model": "MX-5", "year": 2008, "price": 2869, "created_at": "2022-02-01T17:02:19+00:00", "updated_at": "2022-11-01T17:02:19+00:00", }
Products
python
walkccc__LeetCode
solutions/324. Wiggle Sort II/324.py
{ "start": 0, "end": 1302 }
class ____: def wiggleSort(self, nums: list[int]) -> None: n = len(nums) median = self._findKthLargest(nums, (n + 1) // 2) def A(i: int): return (1 + 2 * i) % (n | 1) i = 0 j = 0 k = n - 1 while i <= k: if nums[A(i)] > median: nums[A(i)], nums[A(j)] = nums[A(j)], num...
Solution
python
ansible__ansible
lib/ansible/module_utils/_internal/_ansiballz/_extensions/_debugpy.py
{ "start": 1745, "end": 3150 }
class ____: """Debugger options for debugpy.""" host: str = 'localhost' """The host to connect to for remote debugging.""" port: int = 5678 """The port to connect to for remote debugging.""" connect: dict[str, object] = dataclasses.field(default_factory=dict) """The options to pass to the `...
Options
python
networkx__networkx
networkx/classes/tests/test_special.py
{ "start": 2464, "end": 3739 }
class ____(BaseDiGraphTester): def setup_method(self): all_edge_dict = {"weight": 1} class MyGraph(nx.DiGraph): def edge_attr_dict_factory(self): return all_edge_dict self.Graph = MyGraph # build dict-of-dict-of-dict K3 ed1, ed2, ed3 = (all_edge_...
TestThinDiGraph
python
ansible__ansible
test/units/module_utils/facts/test_ansible_collector.py
{ "start": 19266, "end": 19996 }
class ____(TestPkgMgrFacts): def test_is_openbsd_pkg(self): self.assertIn('pkg_mgr', self.facts) self.assertEqual(self.facts['pkg_mgr'], 'openbsd_pkg') def setUp(self): self.patcher = patch('platform.system') mock_platform = self.patcher.start() mock_platform.return_valu...
TestOpenBSDPkgMgrFacts
python
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 1966, "end": 2047 }
class ____: @staticmethod def func(data): return data
Staticmethod
python
facebookresearch__faiss
benchs/bench_fw/utils.py
{ "start": 3741, "end": 3874 }
class ____(Enum): DISABLE = 1 # no Pareto filtering INDEX = 2 # index-local optima GLOBAL = 3 # global optima
ParetoMode
python
pytorch__pytorch
torch/_numpy/_dtypes.py
{ "start": 1672, "end": 1792 }
class ____(signedinteger): name = "int64" typecode = "l" torch_dtype = torch.int64 # unsigned integers
int64
python
plotly__plotly.py
plotly/graph_objs/scattergl/legendgrouptitle/_font.py
{ "start": 233, "end": 9937 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergl.legendgrouptitle" _path_str = "scattergl.legendgrouptitle.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "we...
Font
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_ops.py
{ "start": 163, "end": 530 }
class ____: def test_infer_freq(self, freq_sample): # GH 11018 idx = date_range("2011-01-01 09:00:00", freq=freq_sample, periods=10, unit="ns") result = DatetimeIndex(idx.asi8, freq="infer") tm.assert_index_equal(idx, result) assert result.freq == freq_sample @pytest.mark.p...
TestDatetimeIndexOps
python
pandas-dev__pandas
pandas/tests/series/methods/test_isna.py
{ "start": 147, "end": 941 }
class ____: def test_isna_period_dtype(self): # GH#13737 ser = Series([Period("2011-01", freq="M"), Period("NaT", freq="M")]) expected = Series([False, True]) result = ser.isna() tm.assert_series_equal(result, expected) result = ser.notna() tm.assert_series...
TestIsna
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 44490, "end": 47397 }
class ____(VCSFetchStrategy): """Fetch strategy that gets source code from a subversion repository. Use like this in a package:: version("name", svn="http://www.example.com/svn/trunk") Optionally, you can provide a revision for the URL:: version("name", svn="http://www.example.com/svn/tru...
SvnFetchStrategy
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/traversals.py
{ "start": 6358, "end": 7577 }
class ____(HasTraverseInternals): __slots__ = () def _clone(self, **kw): raise NotImplementedError() def _copy_internals( self, *, omit_attrs: Iterable[str] = (), **kw: Any ) -> None: """Reassign internal elements to be clones of themselves. Called during a copy-and-tr...
HasCopyInternals
python
django-import-export__django-import-export
tests/core/migrations/0002_book_published_time.py
{ "start": 43, "end": 395 }
class ____(migrations.Migration): dependencies = [ ("core", "0001_initial"), ] operations = [ migrations.AddField( model_name="book", name="published_time", field=models.TimeField( blank=True, null=True, verbose_name="Time published" ...
Migration
python
donnemartin__interactive-coding-challenges
linked_lists/partition/test_partition.py
{ "start": 18, "end": 1463 }
class ____(unittest.TestCase): def test_partition(self): print('Test: Empty list') linked_list = MyLinkedList(None) linked_list.partition(10) self.assertEqual(linked_list.get_all_data(), []) print('Test: One element list, left list empty') linked_list = MyLinkedList...
TestPartition
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/class_as_data_structure.py
{ "start": 960, "end": 1115 }
class ____: def __init__(self, foo:int, bar:list): self.foo = foo self.bar = bar def other_function(self): ...
NoWarningsMoreMethods
python
Lightning-AI__lightning
src/lightning/fabric/_graveyard/tpu.py
{ "start": 2413, "end": 2823 }
class ____(XLAPrecision): """Legacy class. Use :class:`~lightning.fabric.plugins.precision.xla.XLAPrecision` instead. """ def __init__(self, *args: Any, **kwargs: Any) -> None: rank_zero_deprecation( "The `TPUPrecision` class is deprecated. Use `lightning.fabric.plugins.precision....
TPUPrecision
python
kamyu104__LeetCode-Solutions
Python/find-palindrome-with-fixed-length.py
{ "start": 40, "end": 659 }
class ____(object): def kthPalindrome(self, queries, intLength): """ :type queries: List[int] :type intLength: int :rtype: List[int] """ def reverse(x): result = 0 while x: result = result*10+x%10 x //= 10 ...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 154076, "end": 154937 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, auth_token: str, counter_id: str, start_date: str, end_date: str): """Airbyte Source for Yandex Metrica. Args: name (str): The name of the destination. auth_token (str): Your Yandex Metrica API acc...
YandexMetricaSource
python
getsentry__sentry
src/sentry/api/serializers/models/group.py
{ "start": 35201, "end": 43663 }
class ____(GroupSerializerBase): skip_snuba_fields = { *SKIP_SNUBA_FIELDS, "last_seen", "times_seen", "date", "timestamp", # We merge this with start/end, so don't want to include it as its own # condition # We don't need to filter by release stage again here...
GroupSerializerSnuba
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 56835, "end": 57364 }
class ____(sgqlc.types.Enum): """Represents items that can be pinned to a profile page or dashboard. Enumeration Choices: * `GIST`: A gist. * `ISSUE`: An issue. * `ORGANIZATION`: An organization. * `PROJECT`: A project. * `PULL_REQUEST`: A pull request. * `REPOSITORY`: A repository...
PinnableItemType
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 45579, "end": 46193 }
class ____(CoercionTest): @pytest.fixture def obj(self): return Series([1.1, 2.2, 3.3, 4.4], dtype=np.float32) def test_slice_key(self, obj, key, expected, raises, val, indexer_sli, is_inplace): super().test_slice_key(obj, key, expected, raises, val, indexer_sli, is_inplace) if isi...
TestCoercionFloat32
python
google__jax
jax/_src/interpreters/batching.py
{ "start": 2050, "end": 2378 }
class ____: idx: core.Var lengths: Array | core.Var | Tracer def __repr__(self) -> str: return f'{self.lengths}.Var{id(self.idx)}' replace = dataclasses.replace # Jumble(aval=a:3 => f32[[3 1 4].a], # data=Array([0., 1., 2., 0., 0., 1., 2., 3.], dtype=float32)) @dataclasses.dataclass(frozen=True)
IndexedAxisSize
python
pytorch__pytorch
torch/_dynamo/guards.py
{ "start": 6942, "end": 7290 }
class ____(IndentedBuffer): def prefix(self) -> str: return "| " * (self._indent * self.tabwidth) def writeline(self, line: str, skip_prefix: bool = False) -> None: # type: ignore[override] if skip_prefix: super().writeline(line) else: super().writeline("+- " + ...
IndentedBufferWithPrefix
python
kamyu104__LeetCode-Solutions
Python/permutation-difference-between-two-strings.py
{ "start": 48, "end": 379 }
class ____(object): def findPermutationDifference(self, s, t): """ :type s: str :type t: str :rtype: int """ lookup = [-1]*26 for i, x in enumerate(s): lookup[ord(x)-ord('a')] = i return sum(abs(lookup[ord(x)-ord('a')]-i)for i, x in enumera...
Solution
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 39499, "end": 45507 }
class ____(WavLMPreTrainedModel): def __init__(self, config: WavLMConfig): super().__init__(config) self.config = config self.feature_extractor = WavLMFeatureEncoder(config) self.feature_projection = WavLMFeatureProjection(config) # model only needs masking vector if mask pr...
WavLMModel
python
cython__cython
tests/run/test_templatelib.py
{ "start": 8641, "end": 9728 }
class ____(unittest.TestCase): def test_abc(self): self.assertIsInstance(iter(t''), Iterable) self.assertIsInstance(iter(t''), Iterator) def test_final(self): TemplateIter = type(iter(t'')) with self.assertRaisesRegex(TypeError, 'is not an acceptable base type'): cla...
TemplateIterTests
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/vertex_ai.py
{ "start": 5256, "end": 6064 }
class ____(BaseVertexAIJobTrigger): """CreateBatchPredictionJobTrigger run on the trigger worker to perform create operation.""" job_type_verbose_name = "Batch Prediction Job" job_serializer_class = BatchPredictionJob @cached_property def async_hook(self) -> BatchPredictionJobAsyncHook: re...
CreateBatchPredictionJobTrigger
python
psf__black
tests/test_black.py
{ "start": 4027, "end": 85333 }
class ____(BlackBaseTestCase): invokeBlack = staticmethod(invokeBlack) def test_empty_ff(self) -> None: expected = "" tmp_file = Path(black.dump_to_file()) try: self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES)) actual = tmp_file.read_text(encoding="u...
BlackTestCase
python
walkccc__LeetCode
solutions/3085. Minimum Deletions to Make String K-Special/3085.py
{ "start": 0, "end": 388 }
class ____: def minimumDeletions(self, word: str, k: int) -> int: ans = math.inf count = collections.Counter(word) for minFreq in count.values(): deletions = 0 for freq in count.values(): if freq < minFreq: deletions += freq else: deletions += max(0, freq -...
Solution
python
pypa__warehouse
tests/unit/test_views.py
{ "start": 17028, "end": 28411 }
class ____: @pytest.mark.parametrize("page", [None, 1, 5]) def test_with_a_query( self, monkeypatch, pyramid_services, db_request, metrics, page ): params = MultiDict({"q": "foo bar"}) if page is not None: params["page"] = page db_request.params = params ...
TestSearch
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_container_instances.py
{ "start": 26434, "end": 26711 }
class ____: def __init__(self) -> None: self.values: MutableMapping[str, Any | None] = {} def xcom_push(self, key: str, value: Any | None) -> None: self.values[key] = value def xcom_pull(self, key: str) -> Any: return self.values[key]
XcomMock
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-sarvam/llama_index/llms/sarvam/base.py
{ "start": 472, "end": 2772 }
class ____(OpenAILike): """ Sarvam LLM. To instantiate the `Sarvam` class, you will need to provide an API key. You can set the API key either as an environment variable `SARVAM_API_KEY` or directly in the class constructor. If setting it in the class constructor, it would look like this: If you h...
Sarvam
python
zarr-developers__zarr-python
src/zarr/core/chunk_key_encodings.py
{ "start": 2145, "end": 2796 }
class ____(ChunkKeyEncoding): name: ClassVar[Literal["default"]] = "default" separator: SeparatorLiteral = "/" def __post_init__(self) -> None: separator_parsed = parse_separator(self.separator) object.__setattr__(self, "separator", separator_parsed) def decode_chunk_key(self, chunk_ke...
DefaultChunkKeyEncoding
python
pola-rs__polars
py-polars/src/polars/exceptions.py
{ "start": 5039, "end": 5500 }
class ____(PolarsWarning): """ Warning issued when a chrono format string contains dubious patterns. Polars uses Rust's chrono crate to convert between string data and temporal data. The patterns used by chrono differ slightly from Python's built-in datetime module. Refer to the `chrono strftime do...
ChronoFormatWarning
python
gevent__gevent
src/gevent/queue.py
{ "start": 23379, "end": 23899 }
class ____(Queue): """ A subclass of :class:`JoinableQueue` that retrieves most recently added entries first. .. versionchanged:: 24.10.1 Now extends :class:`JoinableQueue` instead of just :class:`Queue`. """ __slots__ = () def _create_queue(self, items=()): return list(items) ...
LifoQueue
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/branching/branching_io_manager.py
{ "start": 1224, "end": 5400 }
class ____(ConfigurableIOManager): """A branching I/O manager composes two I/O managers. 1) The parent I/O manager, typically your production environment. 2) The branch I/O manager, typically a development or branched environment. The objective of this to allow a developer to safely read from a produc...
BranchingIOManager
python
mahmoud__boltons
boltons/dictutils.py
{ "start": 35525, "end": 37642 }
class ____(dict): """An immutable dict subtype that is hashable and can itself be used as a :class:`dict` key or :class:`set` entry. What :class:`frozenset` is to :class:`set`, FrozenDict is to :class:`dict`. There was once an attempt to introduce such a type to the standard library, but it was...
FrozenDict
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 25033, "end": 25387 }
class ____(RequestHandler): def get(self): try: self.set_header("X-Foo", "foo\r\nX-Bar: baz") raise Exception("Didn't get expected exception") except ValueError as e: if "Unsafe header value" in str(e): self.finish(b"ok") else: ...
HeaderInjectionHandler
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 8396, "end": 8643 }
class ____(SerializationInfo[ContextT], Protocol): """Extra data used during field serialization.""" @property def field_name(self) -> str: """The name of the current field being serialized.""" ...
FieldSerializationInfo
python
getsentry__sentry
src/sentry/preprod/api/endpoints/size_analysis/project_preprod_size_analysis_compare_download.py
{ "start": 746, "end": 4586 }
class ____(ProjectEndpoint): owner = ApiOwner.EMERGE_TOOLS publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } def get( self, request: Request, project: Project, head_size_metric_id: int, base_size_metric_id: int ) -> HttpResponseBase: """ Download size analys...
ProjectPreprodArtifactSizeAnalysisCompareDownloadEndpoint
python
plotly__plotly.py
plotly/figure_factory/_streamline.py
{ "start": 4332, "end": 14499 }
class ____(object): """ Refer to FigureFactory.create_streamline() for docstring """ def __init__(self, x, y, u, v, density, angle, arrow_scale, **kwargs): self.x = np.array(x) self.y = np.array(y) self.u = np.array(u) self.v = np.array(v) self.angle = angle ...
_Streamline
python
django__django
django/contrib/admin/tests.py
{ "start": 711, "end": 9398 }
class ____(SeleniumTestCase, StaticLiveServerTestCase): available_apps = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", ] def tearDown(self): # Ensure that no CSP violations w...
AdminSeleniumTestCase
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_base.py
{ "start": 1056, "end": 1352 }
class ____(GoogleCloudBaseOperator): def __init__( self, retry: Retry | _MethodDefault = DEFAULT, config: dict | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.retry = retry self.config = config
GoogleSampleOperator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 218912, "end": 219224 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("column", "line") column = sgqlc.types.Field(Int, graphql_name="column") line = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="line")
CheckAnnotationPosition
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 15309, "end": 16481 }
class ____(SimpleElement): """ A base class for simple elements, such as FIELD, PARAM and INFO that don't require any special parsing or outputting machinery. """ def __init__(self): SimpleElement.__init__(self) self._content = None def parse(self, iterator, config): f...
SimpleElementWithContent
python
apache__airflow
providers/apache/beam/src/airflow/providers/apache/beam/operators/beam.py
{ "start": 2781, "end": 6948 }
class ____(metaclass=ABCMeta): """ Helper class to store common, Dataflow specific logic for both. :class:`~airflow.providers.apache.beam.operators.beam.BeamRunPythonPipelineOperator`, :class:`~airflow.providers.apache.beam.operators.beam.BeamRunJavaPipelineOperator` and :class:`~airflow.providers....
BeamDataflowMixin
python
numba__numba
numba/cuda/tests/cudadrv/test_nvvm_driver.py
{ "start": 5857, "end": 7252 }
class ____(unittest.TestCase): def test_libdevice_load(self): # Test that constructing LibDevice gives a bitcode file libdevice = LibDevice() self.assertEqual(libdevice.bc[:4], b'BC\xc0\xde') nvvmir_generic = '''\ target triple="nvptx64-nvidia-cuda" target datalayout = "{data_layout}" def...
TestLibDevice
python
ray-project__ray
python/ray/train/v2/_internal/state/schema.py
{ "start": 2521, "end": 3691 }
class ____(BaseModel): """Metadata about a Ray Train worker.""" world_rank: int = Field( description="The global rank of the worker in the training cluster." ) local_rank: int = Field(description="The local rank of the worker on its node.") node_rank: int = Field(description="The rank of th...
TrainWorker
python
aio-libs__aiohttp
aiohttp/web_urldispatcher.py
{ "start": 7187, "end": 8282 }
class ____(UrlMappingMatchInfo): __slots__ = ("_exception",) def __init__(self, http_exception: HTTPException) -> None: self._exception = http_exception super().__init__({}, SystemRoute(self._exception)) @property def http_exception(self) -> HTTPException: return self._excepti...
MatchInfoError
python
matplotlib__matplotlib
galleries/examples/event_handling/poly_editor.py
{ "start": 1032, "end": 6597 }
class ____: """ A polygon editor. Key-bindings 't' toggle vertex markers on and off. When vertex markers are on, you can move them, delete them 'd' delete the vertex under point 'i' insert a vertex at point. You must be within epsilon of the line connecting two ex...
PolygonInteractor
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/mro4.py
{ "start": 424, "end": 479 }
class ____(Generic[T1, T2], Foo1[T1], Foo2[T2]): ...
Bar1
python
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 667, "end": 835 }
class ____(Classmethod): @staticmethod def func(): # [arguments-differ] pass @classmethod def func1(cls): return cls()
ClassmethodChild
python
django__django
django/db/models/fields/__init__.py
{ "start": 69874, "end": 72278 }
class ____(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive =...
FilePathField
python
doocs__leetcode
solution/2400-2499/2496.Maximum Value of a String in an Array/Solution2.py
{ "start": 0, "end": 314 }
class ____: def maximumValue(self, strs: List[str]) -> int: def f(s: str) -> int: x = 0 for c in s: if c.isalpha(): return len(s) x = x * 10 + ord(c) - ord("0") return x return max(f(s) for s in strs)
Solution
python
langchain-ai__langchain
libs/core/langchain_core/runnables/graph_png.py
{ "start": 321, "end": 6473 }
class ____: """Helper class to draw a state graph into a PNG file. It requires `graphviz` and `pygraphviz` to be installed. Example: ```python drawer = PngDrawer() drawer.draw(state_graph, "graph.png") ``` """ def __init__( self, fontname: str | None = None...
PngDrawer
python
viewflow__viewflow
tests/test_this_object.py
{ "start": 710, "end": 1464 }
class ____(TestCase): def test_this_refs_data(self): self.assertEqual(this.some_name.name, 'some_name') self.assertEqual(this.another_some_name.name, 'another_some_name') def test_this_ref_resolve(self): review = Review() approve = this.approve.resolve(review) self.asse...
Test
python
hynek__structlog
src/structlog/twisted.py
{ "start": 8500, "end": 10118 }
class ____: """ Adapt an ``event_dict`` to Twisted logging system. Particularly, make a wrapped `twisted.python.log.err <https://docs.twisted.org/en/stable/api/twisted.python.log.html#err>`_ behave as expected. Args: dictRenderer: Renderer that is used for the actual log me...
EventAdapter
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 224447, "end": 243403 }
class ____: """Test tofile, fromfile, tobytes, and fromstring""" def _create_data(self): shape = (2, 4, 3) rand = np.random.random x = rand(shape) + rand(shape).astype(complex) * 1j x[0, :, 1] = [np.nan, np.inf, -np.inf, np.nan] return x @pytest.fixture(params=["str...
TestIO
python
PrefectHQ__prefect
src/prefect/server/utilities/messaging/__init__.py
{ "start": 2020, "end": 3071 }
class ____(Publisher): messages: list[CapturedMessage] = [] deduplicate_by: Optional[str] def __init__( self, topic: str, cache: Optional[Cache] = None, deduplicate_by: Optional[str] = None, ) -> None: self.topic = topic self.cache: Cache = cache or creat...
CapturingPublisher
python
catalyst-team__catalyst
catalyst/contrib/datasets/imagewoof.py
{ "start": 928, "end": 1446 }
class ____(ImageClassificationDataset): """ `Imagewoof <https://github.com/fastai/imagenette#imagewoof>`_ Dataset with images resized so that the shortest size is 320 px. .. note:: catalyst[cv] required for this dataset. """ name = "imagewoof2-320" resources = [ ( ...
Imagewoof320
python
pytorch__pytorch
test/distributed/test_c10d_spawn.py
{ "start": 806, "end": 3033 }
class ____: world_size = 2 def _test_multiprocess(self, f, shared_tensors, init_pg, n_output): ws = self.world_size # file store will delete the test file on destruction file = tempfile.NamedTemporaryFile(delete=False) ctx = mp.get_context("spawn") c2p = ctx.Queue(2) ...
AbstractProcessGroupShareTensorTest
python
huggingface__transformers
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
{ "start": 38032, "end": 39017 }
class ____(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None ...
XLMRobertaClassificationHead
python
pytorch__pytorch
test/profiler/test_profiler_tree.py
{ "start": 8565, "end": 48935 }
class ____(TestCase): def assertTreesMatch(self, actual: str, expected: str, allow_failure: bool = False): # Warning: Here be dragons # Different platforms will have subtly different behavior for Python # tracing. Observed differences include: # 1) Windows symbolicates names ...
TestProfilerTree
python
huggingface__transformers
src/transformers/models/pegasus/modeling_pegasus.py
{ "start": 55347, "end": 55800 }
class ____(PegasusPreTrainedModel): """ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is used in combination with the [`EncoderDecoderModel`] framework. """ def __init__(self, config): super().__init__(config) self.decod...
PegasusDecoderWrapper
python
ray-project__ray
python/ray/train/v2/_internal/execution/controller/state.py
{ "start": 4673, "end": 4920 }
class ____(TrainControllerState): def __init__( self, scaling_decision: ScalingDecision, ): super().__init__(state_type=TrainControllerStateType.RESIZING) self.scaling_decision = scaling_decision
ResizingState
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/ecs/launcher.py
{ "start": 2338, "end": 39234 }
class ____(RunLauncher[T_DagsterInstance], ConfigurableClass): """RunLauncher that starts a task in ECS for each Dagster job run. Args: inst_data (Optional[ConfigurableClassData]): If not provided, defaults to None. task_definition: If not provided, defaults to None. container_name (str...
EcsRunLauncher
python
instagram__MonkeyType
monkeytype/tracing.py
{ "start": 2510, "end": 6380 }
class ____(metaclass=ABCMeta): """Log and store/print records collected by a CallTracer.""" @abstractmethod def log(self, trace: CallTrace) -> None: """Log a single call trace.""" pass def flush(self) -> None: """Flush all logged traces to output / database. Not an abs...
CallTraceLogger
python
pyparsing__pyparsing
pyparsing/diagram/__init__.py
{ "start": 3224, "end": 9077 }
class ____(Generic[T]): """ Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been constructed. """ # We need this here because the railroad constructors actually transform the data, so can't be called until the # entire tree is assembled ...
EditablePartial
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 136292, "end": 139227 }
class ____(Request): """ Get the image for the next variant for the same iteration or for the next iteration :param task: Task ID :type task: str :param scroll_id: Scroll ID from the previous call to get_debug_image_sample :type scroll_id: str :param navigate_earlier: If set then get the ei...
NextDebugImageSampleRequest
python
pyca__cryptography
tests/hazmat/primitives/test_pkcs7.py
{ "start": 51646, "end": 54433 }
class ____: @pytest.mark.parametrize( ("encoding", "loader"), [ (serialization.Encoding.PEM, pkcs7.load_pem_pkcs7_certificates), (serialization.Encoding.DER, pkcs7.load_der_pkcs7_certificates), ], ) def test_roundtrip(self, encoding, loader, backend): ...
TestPKCS7SerializeCerts
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 921373, "end": 939538 }
class ____(PolarDef): r""" PositionFieldDefBase schema wrapper. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, and type aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp...
PositionFieldDefBase
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0061_add_imported_file_ignore.py
{ "start": 149, "end": 570 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0060_make_rank_not_null"), ] operations = [ migrations.AddField( model_name="importedfile", name="ignore", field=models.BooleanField( null=True...
Migration
python
eventlet__eventlet
tests/zmq_test.py
{ "start": 15400, "end": 17224 }
class ____(tests.LimitedTestCase): @tests.skip_unless(zmq_supported) def test_queue_lock_order(self): q = zmq._QueueLock() s = eventlet.Semaphore(0) results = [] def lock(x): with q: results.append(x) s.release() q.acquire() ...
TestQueueLock
python
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 46324, "end": 47775 }
class ____: def __init__(self, param, bins=50, start=0, end=1): # All tensors are of shape ..., bins. self.logits = param bins = torch.linspace(start, end, bins + 1, device=self.logits.device, dtype=self.logits.dtype) self.v_bins = (bins[:-1] + bins[1:]) / 2 def log_prob(self, t...
EsmCategoricalMixture
python
dagster-io__dagster
examples/assets_pandas_type_metadata/assets_pandas_type_metadata/resources/csv_io_manager.py
{ "start": 298, "end": 3123 }
class ____(ConfigurableIOManager): """Translates between Pandas DataFrames and CSVs on the local filesystem.""" base_dir: Optional[str] = Field(default=None) @property @cached_method def resolved_base_dir(self) -> str: if self.base_dir: return self.base_dir resource_con...
LocalCsvIOManager
python
dask__distributed
distributed/deploy/cluster.py
{ "start": 862, "end": 21279 }
class ____(SyncMethodMixin): """Superclass for cluster objects This class contains common functionality for Dask Cluster manager classes. To implement this class, you must provide 1. A ``scheduler_comm`` attribute, which is a connection to the scheduler following the ``distributed.core.rpc``...
Cluster
python
getsentry__sentry
tests/sentry/tasks/test_auth.py
{ "start": 3557, "end": 5906 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user(email="bar@example.com") self.organization = self.create_organization(name="Test") with assume_test_silo_mode(SiloMode.CONTROL): self.provider = AuthProvider.objects.create( ...
EmailUnlinkNotificationsTest
python
doocs__leetcode
solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/Solution2.py
{ "start": 0, "end": 580 }
class ____: def connectTwoGroups(self, cost: List[List[int]]) -> int: m, n = len(cost), len(cost[0]) f = [inf] * (1 << n) f[0] = 0 g = f[:] for i in range(1, m + 1): for j in range(1 << n): g[j] = inf for k in range(n): ...
Solution
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 4485, "end": 5924 }
class ____: """Test es_ES automotive provider methods""" new_format_pattern: Pattern = re.compile(r"\d{4}\s[A-Z]{3}") old_format_pattern: Pattern = re.compile(r"(?P<province_prefix>[A-Z]{1,2})\s\d{4}\s[A-Z]{2}") def test_plate_new_format(self, faker, num_samples): for _ in range(num_samples): ...
TestEsEs
python
matplotlib__matplotlib
galleries/examples/misc/multiprocess_sgskip.py
{ "start": 1710, "end": 2416 }
class ____: def __init__(self): self.plot_pipe, plotter_pipe = mp.Pipe() self.plotter = ProcessPlotter() self.plot_process = mp.Process( target=self.plotter, args=(plotter_pipe,), daemon=True) self.plot_process.start() def plot(self, finished=False): send = s...
NBPlot
python
yaml__pyyaml
packaging/_pyyaml_pep517.py
{ "start": 388, "end": 1149 }
class ____: _current = {} def __init__(self, config_settings): self._config = config_settings def __enter__(self): type(self)._current = self._config def __exit__(self, exc_type, exc_val, exc_tb): type(self)._current = {} @classmethod def current(cls): return ...
ActiveConfigSettings
python
tensorflow__tensorflow
tensorflow/python/ops/sparse_bincount_ops_test.py
{ "start": 1626, "end": 24240 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": ...
TestSparseCount
python
tiangolo__fastapi
scripts/notify_translations.py
{ "start": 2327, "end": 2401 }
class ____(BaseModel): discussion: CommentsDiscussion
CommentsRepository
python
ray-project__ray
python/ray/data/_internal/block_batching/interfaces.py
{ "start": 399, "end": 600 }
class ____: """A batch of data. Attributes: metadata: Metadata associated with this batch. data: The batch of data. """ metadata: BatchMetadata data: DataBatch
Batch
python
huggingface__transformers
src/transformers/models/arcee/modular_arcee.py
{ "start": 8539, "end": 8658 }
class ____(LlamaForQuestionAnswering): pass @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
ArceeForQuestionAnswering
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_python_ast_rule.py
{ "start": 9733, "end": 13828 }
class ____: """Test the validate_python_code_blocks function.""" def test_valid_code_blocks(self): """Test validation with valid Python code blocks.""" docstring = """ Function with valid examples. .. code-block:: python def example(): ...
TestValidatePythonCodeBlocks
python
pandas-dev__pandas
pandas/tests/api/test_api.py
{ "start": 11539, "end": 14655 }
class ____(Base): funcs = [ "assert_frame_equal", "assert_series_equal", "assert_index_equal", "assert_extension_array_equal", ] def test_testing(self): from pandas import testing self.check(testing, self.funcs) def test_util_in_top_level(self): ...
TestTesting
python
donnemartin__interactive-coding-challenges
math_probability/generate_primes/test_generate_primes.py
{ "start": 18, "end": 991 }
class ____(unittest.TestCase): def test_generate_primes(self): prime_generator = PrimeGenerator() self.assertRaises(TypeError, prime_generator.generate_primes, None) self.assertRaises(TypeError, prime_generator.generate_primes, 98.6) self.assertEqual(prime_generator.generate_primes(...
TestMath
python
networkx__networkx
networkx/algorithms/tests/test_vitality.py
{ "start": 24, "end": 1380 }
class ____: def test_unweighted(self): G = nx.cycle_graph(3) vitality = nx.closeness_vitality(G) assert vitality == {0: 2, 1: 2, 2: 2} def test_weighted(self): G = nx.Graph() nx.add_cycle(G, [0, 1, 2], weight=2) vitality = nx.closeness_vitality(G, weight="weight"...
TestClosenessVitality