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
gevent__gevent
src/greentest/3.14/test_urllib2.py
{ "start": 14231, "end": 17172 }
class ____: # useful for testing handler machinery # see add_ordered_mock_handlers() docstring handler_order = 500 def __init__(self, methods): self._define_methods(methods) def _define_methods(self, methods): for spec in methods: if len(spec) == 2: name...
MockHandler
python
ray-project__ray
rllib/examples/_old_api_stack/models/autoregressive_action_dist.py
{ "start": 2632, "end": 4994 }
class ____(TorchDistributionWrapper): """Action distribution P(a1, a2) = P(a1) * P(a2 | a1)""" def deterministic_sample(self): # First, sample a1. a1_dist = self._a1_distribution() a1 = a1_dist.deterministic_sample() # Sample a2 conditioned on a1. a2_dist = self._a2_dis...
TorchBinaryAutoregressiveDistribution
python
bokeh__bokeh
src/bokeh/models/callbacks.py
{ "start": 6958, "end": 8108 }
class ____(Callback): """ Allows to update a property of an object. """ # explicit __init__ to support Init signatures def __init__(self, obj: Init[HasProps] = Intrinsic, attr: Init[str] = Intrinsic, value: Init[Any] = Intrinsic, **kwargs: Any) -> None: super().__init__(obj=obj, attr=attr, value=va...
SetValue
python
pypa__pip
src/pip/_vendor/urllib3/packages/six.py
{ "start": 17738, "end": 18519 }
class ____(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), ...
Module_six_moves_urllib_response
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 20711, "end": 20921 }
class ____(sympy.Function): is_integer = True @classmethod def eval(cls, base, shift): if shift < 0: raise ValueError("negative shift count") return base * 2**shift
LShift
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault5.py
{ "start": 227, "end": 355 }
class ____[T: ClassA = ClassA]: owner: T def post_comment[T: ClassA](owner: T) -> ClassB[T]: return ClassB(owner)
ClassB
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/properties.py
{ "start": 806, "end": 1049 }
class ____(Class): def uses_property(self): self.tainted = _test_source() return self.my_property def uses_property_but_no_tito_taint(self): self.untainted = _test_source() return self.my_property
Derived
python
ray-project__ray
python/ray/tests/test_autoscaling_policy.py
{ "start": 15875, "end": 21431 }
class ____(unittest.TestCase): def setUp(self): _NODE_PROVIDERS["mock"] = lambda config: self.create_provider self.provider = None self.tmpdir = tempfile.mkdtemp() logging.disable(level=logging.CRITICAL) # This seems to be the only way of turning the cli logger off. The ...
AutoscalingPolicyTest
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/GraphicsView.py
{ "start": 394, "end": 15472 }
class ____(QtWidgets.QGraphicsView): """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the viewed coordinate range. Also automatically creates a GraphicsScene and a central QGraphicsWidget that is automatically scaled to the full view geometry. This wi...
GraphicsView
python
anthropics__anthropic-sdk-python
src/anthropic/types/thinking_block_param.py
{ "start": 218, "end": 367 }
class ____(TypedDict, total=False): signature: Required[str] thinking: Required[str] type: Required[Literal["thinking"]]
ThinkingBlockParam
python
TheAlgorithms__Python
data_structures/binary_tree/non_recursive_segment_tree.py
{ "start": 1131, "end": 4746 }
class ____[T]: def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: """ Segment Tree constructor, it works just with commutative combiner. :param arr: list of elements for the segment tree :param fnc: commutative function for combine two elements >>> SegmentTr...
SegmentTree
python
celery__celery
t/unit/app/test_amqp.py
{ "start": 657, "end": 1755 }
class ____: def test_setup_nolimit(self, app): app.conf.broker_pool_limit = None try: delattr(app, '_pool') except AttributeError: pass app.amqp._producer_pool = None pool = app.amqp.producer_pool assert pool.limit == app.pool.limit as...
test_ProducerPool
python
openai__openai-python
src/openai/types/conversations/message.py
{ "start": 1340, "end": 2033 }
class ____(BaseModel): id: str """The unique ID of the message.""" content: List[Content] """The content of the message""" role: Literal["unknown", "user", "assistant", "system", "critic", "discriminator", "developer", "tool"] """The role of the message. One of `unknown`, `user`, `assista...
Message
python
ansible__ansible
lib/ansible/plugins/cache/__init__.py
{ "start": 2296, "end": 10347 }
class ____(BaseCacheModule): """ A caching module backed by file based storage. """ def __init__(self, *args, **kwargs): try: super(BaseFileCacheModule, self).__init__(*args, **kwargs) self._cache_dir = self._get_cache_connection(self.get_option('_uri')) self...
BaseFileCacheModule
python
python-openxml__python-docx
tests/image/test_tiff.py
{ "start": 574, "end": 2052 }
class ____: def it_can_construct_from_a_tiff_stream(self, stream_, _TiffParser_, tiff_parser_, Tiff__init_): px_width, px_height = 111, 222 horz_dpi, vert_dpi = 333, 444 tiff_parser_.px_width = px_width tiff_parser_.px_height = px_height tiff_parser_.horz_dpi = horz_dpi ...
DescribeTiff
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 608910, "end": 609809 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "organizations") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") organizations = sgqlc.types.Field( OrganizationC...
RevokeEnterpriseOrganizationsMigratorRolePayload
python
kamyu104__LeetCode-Solutions
Python/select-k-disjoint-special-substrings.py
{ "start": 64, "end": 1358 }
class ____(object): def maxSubstringLength(self, s, k): """ :type s: str :type k: int :rtype: bool """ def erase_overlap_intervals(intervals): intervals.sort(key=lambda interval: interval[1]) result, right = 0, float("-inf") for l, ...
Solution
python
pytorch__pytorch
torch/utils/data/datapipes/dataframe/dataframes.py
{ "start": 1667, "end": 6102 }
class ____: # TODO: All operations are shared across entire InitialCapture, need to figure out what if we join two captures def __init__(self, schema_df=None) -> None: self.ctx = {"operations": [], "variables": [], "schema_df": schema_df} def __str__(self) -> str: return self._ops_str() ...
Capture
python
pytorch__pytorch
torch/nn/modules/_functions.py
{ "start": 11832, "end": 12143 }
class ____(torch.autograd.Function): @staticmethod # pyrefly: ignore [bad-override] def forward(ctx, *args): ctx.mark_non_differentiable(*[arg for arg in args if not arg.requires_grad]) return args @staticmethod def backward(ctx, *args): return args
BackwardHookFunction
python
doocs__leetcode
solution/1500-1599/1590.Make Sum Divisible by P/Solution.py
{ "start": 0, "end": 465 }
class ____: def minSubarray(self, nums: List[int], p: int) -> int: k = sum(nums) % p if k == 0: return 0 last = {0: -1} cur = 0 ans = len(nums) for i, x in enumerate(nums): cur = (cur + x) % p target = (cur - k + p) % p ...
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_9/projects.py
{ "start": 15048, "end": 22509 }
class ____(NonStrictDataModel): """ :param id: Project id :type id: str :param name: Project name :type name: str :param description: Project description :type description: str :param user: Associated user id :type user: str :param company: Company id :type company: str :...
ProjectsGetAllResponseSingle
python
davidhalter__parso
parso/python/tree.py
{ "start": 5404, "end": 5635 }
class ____(_LeafWithoutNewlines): __slots__ = () type = 'endmarker' def __repr__(self): return "<%s: prefix=%s end_pos=%s>" % ( type(self).__name__, repr(self.prefix), self.end_pos )
EndMarker
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/cli/commands.py
{ "start": 9095, "end": 40914 }
class ____(ShellOperation): """ A block representing a dbt operation, containing multiple dbt and shell commands. For long-lasting operations, use the trigger method and utilize the block as a context manager for automatic closure of processes when context is exited. If not, manually call the close...
DbtCoreOperation
python
walkccc__LeetCode
solutions/1274. Number of Ships in a Rectangle/1274.py
{ "start": 306, "end": 1256 }
class ____(object): def countShips( self, sea: 'Sea', topRight: 'Point', bottomLeft: 'Point', ) -> int: if topRight.x < bottomLeft.x or topRight.y < bottomLeft.y: return 0 if not sea.hasShips(topRight, bottomLeft): return 0 # sea.hashShips(topRight, bottomLeft) == Tr...
Solution
python
kamyu104__LeetCode-Solutions
Python/count-prefixes-of-a-given-string.py
{ "start": 61, "end": 276 }
class ____(object): def countPrefixes(self, words, s): """ :type words: List[str] :type s: str :rtype: int """ return sum(itertools.imap(s.startswith, words))
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox12.py
{ "start": 315, "end": 866 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox12.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workb...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_daemon_cursor.py
{ "start": 1233, "end": 2092 }
class ____(FieldSerializer): def pack( self, mapping: Mapping[str, float], whitelist_map: WhitelistMap, descent_path: str, ) -> JsonSerializableValue: return pack_value(SerializableNonScalarKeyMapping(mapping), whitelist_map, descent_path) def unpack( # pyright: ign...
ObserveRequestTimestampSerializer
python
encode__django-rest-framework
rest_framework/permissions.py
{ "start": 585, "end": 895 }
class ____(OperationHolderMixin): def __init__(self, operator_class, op1_class): self.operator_class = operator_class self.op1_class = op1_class def __call__(self, *args, **kwargs): op1 = self.op1_class(*args, **kwargs) return self.operator_class(op1)
SingleOperandHolder
python
pytorch__pytorch
functorch/einops/_parsing.py
{ "start": 2053, "end": 12309 }
class ____: """Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)').""" def __init__( self, expression: str, *, allow_underscore: bool = False, allow_duplicates: bool = False, ) -> None: """Parse the expression and s...
ParsedExpression
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 61995, "end": 62594 }
class ____(BaseDataset): def test_write_list(self): ds = self.f.create_dataset(make_name(), (1,), dtype="3int8") ds[0] = [1, 2, 3] np.testing.assert_array_equal(ds[:], [[1, 2, 3]]) ds[:] = [[4, 5, 6]] np.testing.assert_array_equal(ds[:], [[4, 5, 6]]) def test_write_arra...
TestSubarray
python
scrapy__scrapy
scrapy/utils/sitemap.py
{ "start": 368, "end": 1839 }
class ____: """Class to parse Sitemap (type=urlset) and Sitemap Index (type=sitemapindex) files""" def __init__(self, xmltext: str | bytes): xmlp = lxml.etree.XMLParser( recover=True, remove_comments=True, resolve_entities=False ) self._root = lxml.etree.fromstring(xmlte...
Sitemap
python
pytorch__pytorch
test/inductor/test_benchmarking.py
{ "start": 549, "end": 4128 }
class ____(TestCase): def setUp(self): super().setUp() torch.manual_seed(12345) counters.clear() @staticmethod def get_counter_value(benchmarker_cls, fn_name): return counters["inductor"][ f"benchmarking.{benchmarker_cls.__name__}.{fn_name}" ] @stati...
TestBenchmarker
python
mlflow__mlflow
dev/clint/src/clint/rules/nested_mock_patch.py
{ "start": 84, "end": 1963 }
class ____(Rule): def _message(self) -> str: return ( "Do not nest `unittest.mock.patch` context managers. " "Use multiple context managers in a single `with` statement instead: " "`with mock.patch(...), mock.patch(...): ...`" ) @staticmethod def check(no...
NestedMockPatch
python
sqlalchemy__sqlalchemy
test/orm/test_cache_key.py
{ "start": 2276, "end": 21404 }
class ____(fixtures.CacheKeyFixture, _fixtures.FixtureTest): run_setup_mappers = "once" run_inserts = None run_deletes = None @classmethod def setup_mappers(cls): cls._setup_stock_mapping() def test_mapper_and_aliased(self): User, Address, Keyword = self.classes("User", "Addres...
CacheKeyTest
python
pola-rs__polars
py-polars/tests/unit/functions/test_col.py
{ "start": 1460, "end": 3595 }
class ____: def __init__(self): self._selected = df.select(pl.col.__foo) def foo(self): return df.select(pl.col.__foo) @classmethod def misc(cls): def _nested(): return df.select(pl.col.__foo) return _nested() @staticmethod def indirect(): r...
Mangler
python
RaRe-Technologies__gensim
gensim/models/bm25model.py
{ "start": 13387, "end": 17130 }
class ____(BM25ABC): """The scoring function of Trotman et al. [5]_. Examples -------- .. sourcecode:: pycon >>> from gensim.corpora import Dictionary >>> from gensim.models import AtireBM25Model >>> from gensim.test.utils import common_texts >>> >>> dictionary ...
AtireBM25Model
python
PyCQA__flake8
src/flake8/checker.py
{ "start": 2442, "end": 8673 }
class ____: """Manage the parallelism and checker instances for each plugin and file. This class will be responsible for the following: - Determining the parallelism of Flake8, e.g.: * Do we use :mod:`multiprocessing` or is it unavailable? * Do we automatically decide on the number of jobs t...
Manager
python
getsentry__sentry
src/sentry/relocation/models/relocationtransfer.py
{ "start": 1405, "end": 1759 }
class ____(BaseRelocationTransfer): __relocation_scope__ = RelocationScope.Excluded # The public key of the region that is requesting # the relocation. public_key = models.BinaryField(null=True) class Meta: app_label = "sentry" db_table = "sentry_controlrelocationtransfer" @regio...
ControlRelocationTransfer
python
keras-team__keras
keras/src/metrics/iou_metrics_test.py
{ "start": 221, "end": 3883 }
class ____(testing.TestCase): def test_config(self): obj = metrics.IoU( num_classes=2, target_class_ids=[1, 0], name="iou_class_1_0" ) self.assertEqual(obj.name, "iou_class_1_0") self.assertEqual(obj.num_classes, 2) self.assertEqual(obj.target_class_ids, [1, 0]) ...
IoUTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/transfers/test_s3_to_dynamodb.py
{ "start": 3570, "end": 9556 }
class ____: @mock.patch.object(DynamoDBHook, "get_waiter") @mock.patch("botocore.client.BaseClient._make_api_call") def test_s3_to_dynamodb_new_table_wait_for_completion(self, mock_make_api_call, mock_wait, new_table_op): mock_make_api_call.return_value = SUCCESS_S3_RESPONSE res = new_table...
TestS3ToDynamoDBOperator
python
aio-libs__aiohttp
examples/combined_middleware.py
{ "start": 917, "end": 1604 }
class ____: """Middleware that logs request timing and response status.""" async def __call__( self, request: ClientRequest, handler: ClientHandlerType, ) -> ClientResponse: start_time = time.monotonic() # Log request _LOGGER.info("[REQUEST] %s %s", request....
LoggingMiddleware
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 195625, "end": 195964 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "topic") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") topic = sgqlc.types.Field("Topic", graphql_name="topic")
AcceptTopicSuggestionPayload
python
tiangolo__fastapi
fastapi/_compat/v1.py
{ "start": 5230, "end": 5280 }
class ____: ref_template: str
GenerateJsonSchema
python
walkccc__LeetCode
solutions/290. Word Pattern/290.py
{ "start": 0, "end": 157 }
class ____: def wordPattern(self, pattern: str, str: str) -> bool: t = str.split() return [*map(pattern.index, pattern)] == [*map(t.index, t)]
Solution
python
pytorch__pytorch
torch/testing/_internal/custom_tensor.py
{ "start": 333, "end": 2647 }
class ____(torch.Tensor): @staticmethod def __new__(cls, elem): shape = elem.shape kwargs = {} kwargs["strides"] = elem.stride() kwargs["storage_offset"] = elem.storage_offset() kwargs["device"] = elem.device kwargs["layout"] = elem.layout kwargs["requires...
ConstantExtraMetadataTensor
python
readthedocs__readthedocs.org
readthedocs/organizations/filters.py
{ "start": 569, "end": 1470 }
class ____(ModelFilterSet): """ Organization base filter set. Adds some methods that are used for organization related queries and common base querysets for filter fields. Note, the querysets here are also found in the organization base views and mixin classes. These are redefined here instead...
OrganizationFilterSet
python
PrefectHQ__prefect
src/prefect/server/database/query_components.py
{ "start": 28106, "end": 28606 }
class ____(sa.TypeDecorator[list[UUID]]): """Map a JSON list of strings back to a list of UUIDs at the result loading stage""" impl: Union[TypeEngine[Any], type[TypeEngine[Any]]] = sa.JSON() cache_ok: Optional[bool] = True def process_result_value( self, value: Optional[list[Union[str, UUID]]]...
UUIDList
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context/hook.py
{ "start": 2064, "end": 7580 }
class ____: """The ``context`` object available to a hook function on an DagsterEvent.""" def __init__( self, step_execution_context: StepExecutionContext, hook_def: HookDefinition, ): self._step_execution_context = step_execution_context self._hook_def = check.inst_...
HookContext
python
google__jax
tests/pallas/tpu_splash_attention_kernel_test.py
{ "start": 2061, "end": 2314 }
class ____: def get_mask(self) -> mask_lib.Mask: raise NotImplementedError() def full_mask_strategy( q_seq_len: int, kv_seq_len: int ) -> hps.SearchStrategy[Mask]: return hps.just(FullMask(q_seq_len, kv_seq_len)) @dataclasses.dataclass
Mask
python
huggingface__transformers
src/transformers/models/vitpose/modeling_vitpose.py
{ "start": 1351, "end": 2488 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Loss is not supported at this moment. See https://github.com/ViTAE-Transformer/ViTPose/tree/main/mmpose/models/losses for further detail. heatmaps (`torch.FloatTensor` of shape `...
VitPoseEstimatorOutput
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 33636, "end": 34189 }
class ____(EvalContextModifier): """Modifies the eval context and reverts it later. Works exactly like :class:`EvalContextModifier` but will only modify the :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`. """ fields = ("body",) body: list[Node] # make sure nobody creates cu...
ScopedEvalContextModifier
python
pandas-dev__pandas
pandas/tests/arrays/masked/test_indexing.py
{ "start": 110, "end": 3198 }
class ____: def _check_setitem_invalid(self, arr, invalid): msg = f"Invalid value '{invalid!s}' for dtype '{arr.dtype}'" msg = re.escape(msg) with pytest.raises(TypeError, match=msg): arr[0] = invalid with pytest.raises(TypeError, match=msg): arr[:] = invalid...
TestSetitemValidation
python
pypa__pip
tests/unit/test_utils.py
{ "start": 10333, "end": 11452 }
class ____: def __init__(self, duration: int = 1) -> None: self.succeed_after = time.time() + duration def call(self, *args: Any, **kw: Any) -> None: """Fail with OSError self.max_fails times""" if time.time() < self.succeed_after: raise OSError("Failed") def test_rmtree_r...
Failer
python
great-expectations__great_expectations
great_expectations/metrics/column/values_non_null.py
{ "start": 213, "end": 283 }
class ____(MetricResult[ConditionValues]): ...
ColumnValuesNonNullResult
python
ray-project__ray
python/ray/tune/error.py
{ "start": 146, "end": 259 }
class ____(TuneError): """Error that indicates a trial should not be retried.""" pass
_AbortTrialExecution
python
ray-project__ray
python/ray/data/_internal/datasource/numpy_datasource.py
{ "start": 283, "end": 1251 }
class ____(FileBasedDatasource): """Numpy datasource, for reading and writing Numpy files.""" _COLUMN_NAME = "data" _FILE_EXTENSIONS = ["npy"] def __init__( self, paths: Union[str, List[str]], numpy_load_args: Optional[Dict[str, Any]] = None, **file_based_datasource_kwa...
NumpyDatasource
python
spyder-ide__spyder
spyder/widgets/github/backend.py
{ "start": 3126, "end": 10214 }
class ____(BaseBackend): """ This backend sends the crash report on a github issue tracker:: https://github.com/gh_owner/gh_repo Usage:: github_backend = spyder.widgets.github.backend.GithubBackend( 'spyder-ide', 'spyder') """ def __init__(self, gh_owner, gh_repo, for...
GithubBackend
python
realpython__materials
build-a-blog-from-scratch-django/django-blog/blog/migrations/0001_initial.py
{ "start": 125, "end": 1606 }
class ____(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('...
Migration
python
boto__boto3
boto3/docs/docstring.py
{ "start": 2213, "end": 2360 }
class ____(LazyLoadedDocstring): def _write_docstring(self, *args, **kwargs): document_batch_action(*args, **kwargs)
BatchActionDocstring
python
huggingface__transformers
src/transformers/models/diffllama/modular_diffllama.py
{ "start": 19678, "end": 19971 }
class ____(LlamaForTokenClassification): pass __all__ = [ "DiffLlamaPreTrainedModel", "DiffLlamaModel", "DiffLlamaForCausalLM", "DiffLlamaForSequenceClassification", "DiffLlamaForQuestionAnswering", "DiffLlamaForTokenClassification", ]
DiffLlamaForTokenClassification
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/type_api.py
{ "start": 2618, "end": 2713 }
class ____(Protocol[_T_co]): def __call__(self, value: Any) -> str: ...
_LiteralProcessorType
python
kamyu104__LeetCode-Solutions
Python/largest-component-size-by-common-factor.py
{ "start": 700, "end": 1889 }
class ____(object): def largestComponentSize(self, A): """ :type A: List[int] :rtype: int """ def prime_factors(i): # prime factor decomposition result = [] d = 2 if i%d == 0: while i%d == 0: i //= d ...
Solution
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 16747, "end": 19042 }
class ____(MaskedArraySetup): def test_broadcast_to(self): shape = self.ma.shape ba = np.broadcast_to(self.mb, shape, subok=True) assert ba.shape == shape assert ba.mask.shape == shape expected = Masked( np.broadcast_to(self.mb.unmasked, shape, subok=True), ...
TestMaskedArrayBroadcast
python
prabhupant__python-ds
data_structures/graphs/shortest_path_unweighted_graph.py
{ "start": 529, "end": 1619 }
class ____: def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) def bfs(self, s): parent = [-1] * self.vertices visited = [False] * self.vertic...
Graph
python
django__django
tests/prefetch_related/models.py
{ "start": 6418, "end": 6607 }
class ____(models.Model): name = models.CharField(max_length=50) house = models.ForeignKey(House, models.CASCADE, related_name="rooms") class Meta: ordering = ["id"]
Room
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/unit_tests/test_components.py
{ "start": 8689, "end": 20377 }
class ____: @dataclass class _FakeResponse: chunks: List[bytes] status: int = 200 def iter_content(self, chunk_size=1): # Ignore chunk_size; we already control chunking via self.chunks for c in self.chunks: yield c def raise_for_status(se...
TestGoogleAdsStreamingDecoder
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 89049, "end": 89262 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING _AutoModelForVision2Seq = auto_class_update(_AutoModelForVision2Seq, head_doc="vision-to-text modeling")
_AutoModelForVision2Seq
python
huggingface__transformers
src/transformers/models/emu3/modeling_emu3.py
{ "start": 14468, "end": 15305 }
class ____(nn.Module): def __init__( self, in_channel: int, out_channel: int, kernel_size: tuple[int], stride: tuple[int], ): super().__init__() padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])] ...
Emu3VQVAEConv3d
python
tiangolo__fastapi
docs_src/dependencies/tutorial011_an.py
{ "start": 96, "end": 554 }
class ____: def __init__(self, fixed_content: str): self.fixed_content = fixed_content def __call__(self, q: str = ""): if q: return self.fixed_content in q return False checker = FixedContentQueryChecker("bar") @app.get("/query-checker/") async def read_query_check(fixe...
FixedContentQueryChecker
python
pdm-project__pdm
src/pdm/models/venv.py
{ "start": 877, "end": 2642 }
class ____: root: Path is_conda: bool interpreter: Path @classmethod def get(cls, root: Path) -> VirtualEnv | None: path = get_venv_python(root) if not path.exists(): return None return cls(root, is_conda_venv(root), path) @classmethod def from_interpret...
VirtualEnv
python
pypa__warehouse
dev/flake8/checkers.py
{ "start": 6513, "end": 9160 }
class ____: def __init__(self, tree: ast.AST, filename: str) -> None: self.tree = tree self.filename = filename def run(self) -> Generator[tuple[int, int, str, type[Any]]]: visitor = WarehouseVisitor(self.filename) visitor.visit(self.tree) for e in visitor.errors: ...
WarehouseCheck
python
pytorch__pytorch
torch/_inductor/codegen/cpp_wrapper_gpu.py
{ "start": 1458, "end": 16865 }
class ____: """ When using cpp wrapper, GPU kernel load and launch needs to wait for Triton kernels to be tuned and stored as cubin files, so use a deferred generating the final wrapper around the triton kernel until right before the prefix is written. """ wrapper_name: str kernel_name: str...
DeferredTritonCallWrapper
python
getsentry__sentry
tests/sentry/uptime/consumers/test_eap_converter.py
{ "start": 13484, "end": 18503 }
class ____(SentryTestCase): def _create_base_result(self, **overrides): """Create a base CheckResult for testing.""" base = { "guid": "test-guid-123", "subscription_id": "sub-456", "status": "success", "status_reason": None, "trace_id": "t...
TestFullDenormalizedConversion
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/group_by_window_test.py
{ "start": 14695, "end": 15733 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def _build_dataset(self, components): dataset = dataset_ops.Dataset.from_tensor_slices(components).repeat(-1) dataset = dataset.group_by_window( key_func=lambda x: x % 3, reduce_func...
GroupByWindowCheckpointTest
python
doocs__leetcode
solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/Solution.py
{ "start": 0, "end": 130 }
class ____: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: return sorted(target) == sorted(arr)
Solution
python
walkccc__LeetCode
solutions/1373. Maximum Sum BST in Binary Tree/1373.py
{ "start": 161, "end": 808 }
class ____: def maxSumBST(self, root: TreeNode | None) -> int: self.ans = 0 def traverse(root: TreeNode | None) -> T: if not root: return T(True, -math.inf, math.inf, 0) left: T = traverse(root.left) right: T = traverse(root.right) if not left.isBST or not right.isBST: ...
Solution
python
doocs__leetcode
solution/0100-0199/0128.Longest Consecutive Sequence/Solution2.py
{ "start": 0, "end": 303 }
class ____: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) ans = 0 for x in s: if x - 1 not in s: y = x + 1 while y in s: y += 1 ans = max(ans, y - x) return ans
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 73413, "end": 73514 }
class ____(BaseModel, extra="forbid"): neg: "Expression" = Field(..., description="")
NegExpression
python
PyCQA__pylint
tests/functional/u/useless/useless_parent_delegation.py
{ "start": 8586, "end": 11926 }
class ____(Base): def equivalent_params(self): # [useless-parent-delegation] return super(UselessSuper, self).equivalent_params() def equivalent_params_1(self, first): # [useless-parent-delegation] return super(UselessSuper, self).equivalent_params_1(first) def equivalent_params_2(self, ...
UselessSuper
python
bokeh__bokeh
src/bokeh/models/dom.py
{ "start": 2909, "end": 3087 }
class ____(DOMElement): # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
Span
python
graphql-python__graphene
examples/starwars_relay/schema.py
{ "start": 1816, "end": 1955 }
class ____(graphene.ObjectType): introduce_ship = IntroduceShip.Field() schema = graphene.Schema(query=Query, mutation=Mutation)
Mutation
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/system/utils/test_helpers.py
{ "start": 1665, "end": 4845 }
class ____: FETCH_VARIABLE_TEST_CASES = [ # Format is: # (Environment Variable value, Fetched SSM value, Provided Default value, Expected Result) (ENV_VALUE, SSM_VALUE, DEFAULT_VALUE, ENV_VALUE), (ENV_VALUE, SSM_VALUE, None, ENV_VALUE), (ENV_VALUE, None, DEFAULT_VALUE, ENV_VA...
TestAmazonSystemTestHelpers
python
kamyu104__LeetCode-Solutions
Python/sum-of-remoteness-of-all-cells.py
{ "start": 57, "end": 1105 }
class ____(object): def sumRemoteness(self, grid): """ :type grid: List[List[int]] :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) def bfs(i, j): total, cnt = grid[i][j], 1 grid[i][j] = -1 q = [(i, j)] wh...
Solution
python
django__django
tests/model_fields/test_decimalfield.py
{ "start": 260, "end": 5768 }
class ____(TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal("3")) self.assertEqual(f.to_python("3.14"), Decimal("3.14")) # to_python() converts floats and honors max_digits. self.assertEqual(...
DecimalFieldTests
python
astropy__astropy
astropy/extern/configobj/validate.py
{ "start": 12525, "end": 12926 }
class ____(ValidateError): """The value supplied was of the correct type, but was not an allowed value.""" def __init__(self, value): """ >>> raise VdtValueError('jedi') Traceback (most recent call last): VdtValueError: the value "jedi" is unacceptable. """ Valid...
VdtValueError
python
pytorch__pytorch
test/dynamo/cpython/3_13/typinganndata/ann_module2.py
{ "start": 264, "end": 402 }
class ____: def __init__(self, x: int) -> None: self.x = x c = C(5) c.new_attr: int = 10 __annotations__ = {} @no_type_check
C
python
astropy__astropy
astropy/coordinates/tests/test_representation_arithmetic.py
{ "start": 31767, "end": 36984 }
class ____: def _setup(self, omit_coslat): if omit_coslat: self.USD_cls = UnitSphericalCosLatDifferential else: self.USD_cls = UnitSphericalDifferential s = UnitSphericalRepresentation( lon=[0.0, 6.0, 21.0] * u.hourangle, lat=[0.0, -30.0, 85.0] * u.deg ...
TestUnitSphericalDifferential
python
numpy__numpy
numpy/polynomial/tests/test_printing.py
{ "start": 289, "end": 3778 }
class ____: @pytest.fixture(scope='class', autouse=True) def use_unicode(self): poly.set_default_printstyle('unicode') @pytest.mark.parametrize(('inp', 'tgt'), ( ([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"), ([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"), (arange(12), ("0.0 + 1....
TestStrUnicodeSuperSubscripts
python
pytest-dev__pytest-asyncio
tests/markers/test_class_scope.py
{ "start": 164, "end": 9888 }
class ____: pytestmark = pytest.mark.asyncio async def test_is_asyncio(self, sample_fixture): assert asyncio.get_event_loop() counter = 1 async def inc(): nonlocal counter counter += 1 await asyncio.sleep(0) await asyncio.ensure_future(inc()...
TestPyTestMark
python
ray-project__ray
python/ray/_private/runtime_env/nsight.py
{ "start": 1263, "end": 5263 }
class ____(RuntimeEnvPlugin): name = "_nsight" def __init__(self, resources_dir: str): self.nsight_cmd = [] # replace this with better way to get logs dir session_dir, runtime_dir = os.path.split(resources_dir) self._nsight_dir = Path(session_dir) / "logs" / "nsight" tr...
NsightPlugin
python
neetcode-gh__leetcode
python/0068-text-justification.py
{ "start": 0, "end": 1144 }
class ____: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: res = [] line = [] # Words in current line length = 0 # Current line length i = 0 while i < len(words): if length + len(line) + len(words[i]) > maxWidth: # Line comp...
Solution
python
walkccc__LeetCode
solutions/1835. Find XOR Sum of All Pairs Bitwise AND/1835.py
{ "start": 0, "end": 185 }
class ____: def getXORSum(self, arr1: list[int], arr2: list[int]) -> int: return functools.reduce( operator.xor, arr1) & functools.reduce( operator.xor, arr2)
Solution
python
pytorch__pytorch
torch/storage.py
{ "start": 14637, "end": 22007 }
class ____(torch._C.StorageBase, _StorageBase): def __getitem__(self, *args, **kwargs): if self.device.type == "meta": raise NotImplementedError("Not available for 'meta' device type") return super().__getitem__(*args, **kwargs) @property def is_cuda(self): return self.d...
UntypedStorage
python
scikit-learn__scikit-learn
sklearn/linear_model/_quantile.py
{ "start": 611, "end": 10527 }
class ____(LinearModel, RegressorMixin, BaseEstimator): """Linear regression model that predicts conditional quantiles. The linear :class:`QuantileRegressor` optimizes the pinball loss for a desired `quantile` and is robust to outliers. This model uses an L1 regularization like :class:`~sklearn.li...
QuantileRegressor
python
Netflix__metaflow
metaflow/plugins/azure/azure_tail.py
{ "start": 332, "end": 3375 }
class ____(object): def __init__(self, blob_full_uri): """Location should be something like <container_name>/blob""" container_name, blob_name = parse_azure_full_path(blob_full_uri) if not blob_name: raise MetaflowException( msg="Failed to parse blob_full_uri into...
AzureTail
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 1469, "end": 1517 }
class ____(Class5[Sequence[T]]): ...
Class5_Child3
python
walkccc__LeetCode
solutions/1814. Count Nice Pairs in an Array/1814.py
{ "start": 0, "end": 222 }
class ____: def countNicePairs(self, nums: list[int]) -> int: freqs = collections.Counter(num - int(str(num)[::-1]) for num in nums) return sum(freq * (freq - 1) // 2 for freq in freqs.values()) % 1000000007
Solution
python
mwaskom__seaborn
tests/_stats/test_order.py
{ "start": 556, "end": 2648 }
class ____(Fixtures): def test_int_k(self, df): ori = "x" gb = self.get_groupby(df, ori) res = Perc(3)(df, gb, ori, {}) percentiles = [0, 50, 100] assert_array_equal(res["percentile"], percentiles) assert_array_equal(res["y"], np.percentile(df["y"], percentiles)) ...
TestPerc
python
getsentry__sentry
src/sentry/replays/usecases/query/conditions/selector.py
{ "start": 7322, "end": 7720 }
class ____(ComputedBase): """Streaming click selector composite condition class.""" @staticmethod def visit_eq(value: list[QueryType]) -> Condition: return contains(ClickSelectorComposite.visit_eq(value)) @staticmethod def visit_neq(value: list[QueryType]) -> Condition: return does...
SumOfClickSelectorComposite
python
PyCQA__pylint
tests/functional/r/regression/regression_no_member_1078.py
{ "start": 205, "end": 325 }
class ____: def test(self): "a" test.__doc__ += "b" print(Cls().test.__doc__) print(Cls.test.__doc__)
Cls