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
sphinx-doc__sphinx
sphinx/util/logging.py
{ "start": 6390, "end": 6892 }
class ____(logging.StreamHandler['SafeEncodingWriter']): """StreamHandler which switches line terminator by record.nonl flag.""" def emit(self, record: logging.LogRecord) -> None: try: self.acquire() if getattr(record, 'nonl', False): # skip appending terminator ...
NewLineStreamHandler
python
keras-team__keras
keras/src/layers/attention/additive_attention_test.py
{ "start": 81, "end": 3030 }
class ____(testing.TestCase): def test_attention_basics(self): # No scale self.run_layer_test( layers.AdditiveAttention, init_kwargs={ "use_scale": True, "dropout": 0.5, }, input_shape=[(2, 3, 4), (2, 4, 4)], ...
AdditiveAttentionTest
python
django__django
tests/forms_tests/field_tests/test_datefield.py
{ "start": 320, "end": 8889 }
class ____(SimpleTestCase): def test_form_field(self): a = GetDate({"mydate_month": "4", "mydate_day": "1", "mydate_year": "2008"}) self.assertTrue(a.is_valid()) self.assertEqual(a.cleaned_data["mydate"], date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict...
DateFieldTest
python
kamyu104__LeetCode-Solutions
Python/unit-conversion-ii.py
{ "start": 64, "end": 967 }
class ____(object): def queryConversions(self, conversions, queries): """ :type conversions: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ MOD = 10**9+7 def divmod(a, b): return (a*pow(b, MOD-2, MOD))%MOD def unit():...
Solution
python
getsentry__sentry
tests/sentry/taskworker/test_client.py
{ "start": 1002, "end": 2046 }
class ____: """Stub for grpc service methods""" def __init__( self, path: str, responses: list[Any], request_serializer: Callable, response_deserializer: Callable, ): self.path = path self.request_serializer = request_serializer self.response_...
MockServiceMethod
python
kamyu104__LeetCode-Solutions
Python/longest-repeating-character-replacement.py
{ "start": 50, "end": 536 }
class ____(object): def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ result, max_count = 0, 0 count = collections.Counter() for i in xrange(len(s)): count[s[i]] += 1 max_count = max(max_count, ...
Solution
python
wandb__wandb
tests/system_tests/backend_fixtures.py
{ "start": 2692, "end": 2745 }
class ____: name: str @dataclass(frozen=True)
_Team
python
huggingface__transformers
src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py
{ "start": 798, "end": 3044 }
class ____(pl.LightningModule): def __init__(self, model): super().__init__() self.model = model self.num_labels = 2 self.qa_outputs = nn.Linear(self.model.config.hidden_size, self.num_labels) # implement only because lightning requires to do so def forward(self): pa...
LightningModel
python
huggingface__transformers
src/transformers/models/dpr/tokenization_dpr.py
{ "start": 6742, "end": 15041 }
class ____: def __call__( self, questions, titles: Optional[str] = None, texts: Optional[str] = None, padding: Union[bool, str] = False, truncation: Union[bool, str] = False, max_length: Optional[int] = None, return_tensors: Optional[Union[str, TensorT...
CustomDPRReaderTokenizerMixin
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 87156, "end": 95079 }
class ____(StrategyBase): __doc__ = StrategyBase.__doc__ def experimental_distribute_values_from_function(self, value_fn): """Generates `tf.distribute.DistributedValues` from `value_fn`. This function is to generate `tf.distribute.DistributedValues` to pass into `run`, `reduce`, or other methods that...
Strategy
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/auth_manager/cli/test_avp_commands.py
{ "start": 1326, "end": 5577 }
class ____: def setup_method(self): mock_boto3.reset_mock() @classmethod def setup_class(cls): with conf_vars( { ( "core", "auth_manager", ): "airflow.providers.amazon.aws.auth_manager.aws_auth_manager.AwsAu...
TestAvpCommands
python
FactoryBoy__factory_boy
tests/test_docs_internals.py
{ "start": 1836, "end": 2071 }
class ____: ACTIONS = ['create', 'update', 'disable'] def __init__(self, user, action, timestamp): self.user = user self.action = action self.timestamp = timestamp user.logs.append(self)
UserLog
python
plotly__plotly.py
plotly/graph_objs/histogram/marker/_colorbar.py
{ "start": 233, "end": 61680 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram.marker" _path_str = "histogram.marker.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "min...
ColorBar
python
huggingface__transformers
src/transformers/models/mbart/tokenization_mbart.py
{ "start": 1333, "end": 10252 }
class ____(TokenizersBackend): """ Construct an MBART tokenizer (backed by HuggingFace's *tokenizers* library). Based on [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This tokenizer inherits from [`TokenizersBackend`] which contains most of th...
MBartTokenizer
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/axislines.py
{ "start": 5072, "end": 5356 }
class ____(_AxisArtistHelperBase): def __init__(self, nth_coord, value): self._value = value super().__init__(nth_coord) def get_line(self, axes): raise RuntimeError("get_line method should be defined by the derived class")
_FloatingAxisArtistHelperBase
python
qdrant__qdrant-client
qdrant_client/local/payload_value_setter.py
{ "start": 987, "end": 2871 }
class ____: TYPE: Any SETTERS: dict[JsonPathItemType, Type["Setter"]] = {} @classmethod def add_setter(cls, item_type: JsonPathItemType, setter: Type["Setter"]) -> None: cls.SETTERS[item_type] = setter @classmethod def set( cls, data: Any, k_list: list[JsonPathI...
Setter
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 65435, "end": 65787 }
class ____(Locator): """ Place no ticks. """ def __call__(self): return self.tick_values(None, None) def tick_values(self, vmin, vmax): """ Return the locations of the ticks. .. note:: Because there are no ticks, *vmin* and *vmax* are not used. ...
NullLocator
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 50041, "end": 50267 }
class ____(_TestSubsets, __TestCase): left = set() right = set() name = "both empty" cases = "==", "<=", ">=" #------------------------------------------------------------------------------
TestSubsetEqualEmpty
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/packages.py
{ "start": 2969, "end": 3069 }
class ____(Exception): """Exception raised when package is suspended."""
PackageSuspendedException
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 136707, "end": 137092 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("type", "value") type = sgqlc.types.Field( sgqlc.types.non_null(SecurityAdvisoryIdentifierType), graphql_name="type" ) value = sgqlc.types.Field(sgqlc.types.non_n...
SecurityAdvisoryIdentifierFilter
python
ray-project__ray
python/ray/llm/_internal/serve/core/configs/openai_api_models.py
{ "start": 3829, "end": 3947 }
class ____(vLLMTranscriptionResponse): model_config = ConfigDict(arbitrary_types_allowed=True)
TranscriptionResponse
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context/op_execution_context.py
{ "start": 3388, "end": 53288 }
class ____(AbstractComputeExecutionContext): """The ``context`` object that can be made available as the first argument to the function used for computing an op or asset. This context object provides system information such as resources, config, and logging. To construct an execution context for testi...
OpExecutionContext
python
kamyu104__LeetCode-Solutions
Python/find-the-number-of-k-even-arrays.py
{ "start": 82, "end": 1412 }
class ____(object): def countOfArrays(self, n, m, k): """ :type n: int :type m: int :type k: int :rtype: int """ MOD = 10**9+7 fact, inv, inv_fact = [[1]*2 for _ in xrange(3)] def nCr(n, k): while len(inv) <= n: # lazy initializati...
Solution
python
numba__numba
numba/core/typing/arraydecl.py
{ "start": 22957, "end": 24042 }
class ____(AbstractTemplate): def generic(self, args, kws): # Resolution of members for records record, idx = args if isinstance(record, types.Record): if isinstance(idx, types.StringLiteral): if idx.literal_value not in record.fields: msg = (f...
StaticGetItemLiteralRecord
python
tensorflow__tensorflow
tensorflow/python/keras/saving/utils_v1/export_output.py
{ "start": 8127, "end": 13287 }
class ____(ExportOutput): """Represents the output of a supervised training or eval process.""" __metaclass__ = abc.ABCMeta LOSS_NAME = 'loss' PREDICTIONS_NAME = 'predictions' METRICS_NAME = 'metrics' METRIC_VALUE_SUFFIX = 'value' METRIC_UPDATE_SUFFIX = 'update_op' _loss = None _predictions = None ...
_SupervisedOutput
python
getsentry__sentry
src/sentry/api/endpoints/organization_releases.py
{ "start": 6859, "end": 10777 }
class ____(ReleaseWithVersionSerializer): projects = ListField() headCommits = ListField( child=ReleaseHeadCommitSerializerDeprecated(), required=False, allow_null=False ) refs = ListField(child=ReleaseHeadCommitSerializer(), required=False, allow_null=False) @sentry_sdk.trace def debounce_upd...
ReleaseSerializerWithProjects
python
pytorch__pytorch
torch/_numpy/_dtypes.py
{ "start": 1476, "end": 1574 }
class ____(signedinteger): name = "int16" typecode = "h" torch_dtype = torch.int16
int16
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 429, "end": 481 }
class ____: def abcd(self): pass
AbcdMixin
python
allegroai__clearml
clearml/backend_api/services/v2_23/workers.py
{ "start": 53854, "end": 60435 }
class ____(Response): """ Response of workers.get_all endpoint. :param workers: :type workers: Sequence[Worker] """ _service = "workers" _action = "get_all" _version = "2.23" _schema = { "definitions": { "current_task_entry": { "properties": { ...
GetAllResponse
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_with_default_factory.py
{ "start": 308, "end": 552 }
class ____: """A test dataclass with a field, that has a default_factory.""" test: list = field(default_factory=list) TEST = Test() TEST.test.append(1) print(TEST.test[0]) @dc.dataclass # Note the use of dc instead of dataclasses
Test
python
ray-project__ray
doc/source/serve/doc_code/getting_started/model_deployment_full.py
{ "start": 273, "end": 1147 }
class ____: def __init__(self): # Load model self.model = pipeline("translation_en_to_fr", model="t5-small") def translate(self, text: str) -> str: # Run inference model_output = self.model(text) # Post-process output to return only the translation text translat...
Translator
python
getsentry__sentry
src/sentry/hybridcloud/models/outbox.py
{ "start": 16531, "end": 17152 }
class ____(OutboxBase): def send_signal(self) -> None: process_region_outbox.send( sender=OutboxCategory(self.category), payload=self.payload, object_identifier=self.object_identifier, shard_identifier=self.shard_identifier, shard_scope=self.shard_...
RegionOutboxBase
python
pandas-dev__pandas
asv_bench/benchmarks/reshape.py
{ "start": 4040, "end": 4644 }
class ____: def setup(self): NUM_ROWS = 1000 self.df = DataFrame( { "A": np.random.randint(50, size=NUM_ROWS), "B": np.random.randint(50, size=NUM_ROWS), "C": np.random.randint(-10, 10, size=NUM_ROWS), "D": np.random.randint...
SparseIndex
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_type_check.py
{ "start": 1107, "end": 1892 }
class ____(TestCase): def test_basic(self): ai32 = np.array([[1, 2], [3, 4]], dtype=np.int32) af16 = np.array([[1, 2], [3, 4]], dtype=np.float16) af32 = np.array([[1, 2], [3, 4]], dtype=np.float32) af64 = np.array([[1, 2], [3, 4]], dtype=np.float64) acs = np.array([[1 + 5j, 2...
TestCommonType
python
spack__spack
lib/spack/spack/solver/requirements.py
{ "start": 1020, "end": 2632 }
class ____(NamedTuple): """Data class to collect information on a requirement""" pkg_name: str policy: str origin: RequirementOrigin requirements: Sequence[spack.spec.Spec] condition: spack.spec.Spec kind: RequirementKind message: Optional[str] def preference( pkg_name: str, c...
RequirementRule
python
numpy__numpy
numpy/distutils/npy_pkg_config.py
{ "start": 451, "end": 1857 }
class ____(OSError): """Exception raised when a package can not be located.""" def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def parse_flags(line): """ Parse a line from a config file containing compile flags. Parameters ---------- line : s...
PkgNotFound
python
walkccc__LeetCode
solutions/3068. Find the Maximum Sum of Node Values/3068.py
{ "start": 0, "end": 384 }
class ____: def maximumValueSum( self, nums: list[int], k: int, edges: list[list[int]], ) -> int: maxSum = sum(max(num, num ^ k) for num in nums) changedCount = sum((num ^ k) > num for num in nums) if changedCount % 2 == 0: return maxSum minChangeDiff = min(abs(num - (n...
Solution
python
numba__numba
numba/core/typing/templates.py
{ "start": 11182, "end": 12935 }
class ____(FunctionTemplate): """ Defines method ``generic(self, args, kws)`` which compute a possible signature base on input types. The signature does not have to match the input types. It is compared against the input types afterwards. """ def apply(self, args, kws): generic = getat...
AbstractTemplate
python
urllib3__urllib3
src/urllib3/poolmanager.py
{ "start": 5384, "end": 18453 }
class ____(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include wi...
PoolManager
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-integers-to-choose-from-a-range-i.py
{ "start": 1592, "end": 2049 }
class ____(object): def maxCount(self, banned, n, maxSum): """ :type banned: List[int] :type n: int :type maxSum: int :rtype: int """ lookup = set(banned) result = total = 0 for i in xrange(1, n+1): if i in lookup: c...
Solution3
python
doocs__leetcode
solution/2500-2599/2525.Categorize Box According to Criteria/Solution2.py
{ "start": 0, "end": 415 }
class ____: def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: v = length * width * height bulky = any(x >= 10000 for x in (length, width, height)) or v >= 10**9 heavy = mass >= 100 if bulky and heavy: return "Both" if bulky: ...
Solution
python
pytorch__pytorch
torch/multiprocessing/queue.py
{ "start": 769, "end": 1123 }
class ____(multiprocessing.queues.Queue): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._reader: ConnectionWrapper = ConnectionWrapper(self._reader) self._writer: ConnectionWrapper = ConnectionWrapper(self._writer) self._send = self._writer.send ...
Queue
python
pytorch__pytorch
torch/onnx/_internal/fx/passes/type_promotion.py
{ "start": 61425, "end": 64728 }
class ____(_pass.Transform): """Explicitly insert type promotion ops to the graph. Underneath, the main pass is driven by `_TypePromotionInterpreter`, which is a subclass of `torch.fx.Interpreter` to interpret the fx.Graph and perform the insertion of type promotion operations. By re-running the n...
InsertTypePromotion
python
google__jax
jax/_src/pallas/cost_estimate.py
{ "start": 1374, "end": 1854 }
class ____: flops: int transcendentals: int bytes_accessed: int def __add__(self, other: 'CostEstimate') -> 'CostEstimate': return CostEstimate( flops=self.flops + other.flops, transcendentals=self.transcendentals + other.transcendentals, bytes_accessed=self.bytes_accessed + other.b...
CostEstimate
python
getsentry__sentry
src/sentry/utils/session_store.py
{ "start": 178, "end": 3836 }
class ____: """ RedisSessionStore provides a convenience object, which when initialized will store attributes assigned to it into redis. The redis key is stored into the request session. Useful for storing data too large to be stored into the session cookie. The attributes to be backed by Redis...
RedisSessionStore
python
astropy__astropy
astropy/cosmology/_src/tests/test_realizations.py
{ "start": 817, "end": 3589 }
class ____: """Tests for :class:`~astropy.cosmology.realizations.default_cosmology`.""" # ----------------------------------------------------- # Get def test_get_current(self): """Test :meth:`astropy.cosmology.default_cosmology.get` current value.""" cosmo = default_cosmology.get() ...
Test_default_cosmology
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 15336, "end": 15504 }
class ____(models.Model): country = models.ForeignKey( Country, on_delete=models.CASCADE, db_column="countryCode" ) history = HistoricalRecords()
City
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeAlias4.py
{ "start": 1553, "end": 1890 }
class ____: my_type1: TA = int def func1(): # This should generate an error because type aliases are allowed # only in classes or modules. my_type1: TA = int _Obj = cast(type[object], object) # This should generate an error because _Obj is a variable, # which isn't allowed in a TypeAlias statement. ...
ClassB
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 129936, "end": 130199 }
class ____(BaseModel, extra="forbid"): """ Sparse vector structure """ indices: List[int] = Field(..., description="Indices must be unique") values: List[float] = Field(..., description="Values and indices must be the same length")
SparseVector
python
imageio__imageio
imageio/plugins/_swf.py
{ "start": 9840, "end": 10333 }
class ____(ControlTag): """Set the color in 0-255, or 0-1 (if floats given).""" def __init__(self, *rgb): self.tagtype = 9 if len(rgb) == 1: rgb = rgb[0] self.rgb = rgb def process_tag(self): bb = bytes() for i in range(3): clr = self.rgb[i] ...
SetBackgroundTag
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10979, "end": 20230 }
class ____(RoleBase): alias_permissions: List[AliasPermissionOutput] cluster_permissions: List[ClusterPermissionOutput] collections_permissions: List[CollectionsPermissionOutput] data_permissions: List[DataPermissionOutput] roles_permissions: List[RolesPermissionOutput] users_permissions: List[U...
Role
python
kamyu104__LeetCode-Solutions
Python/rotate-string.py
{ "start": 1146, "end": 2394 }
class ____(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ def strStr(haystack, needle): def KMP(text, pattern): prefix = getPrefix(pattern) j = -1 for i in xrange(len(te...
Solution2
python
apache__airflow
providers/google/tests/unit/google/common/hooks/test_base_google.py
{ "start": 42506, "end": 43804 }
class ____: """Test get_field function and _get_field method handle False and other falsy values correctly.""" def test_get_field_returns_false_not_none(self): """Test that get_field correctly returns False instead of None.""" extras = {"use_legacy_sql": False} result = hook.get_field(e...
TestGetFieldWithFalseValues
python
ethereum__web3.py
web3/_utils/module_testing/go_ethereum_admin_module.py
{ "start": 259, "end": 1958 }
class ____: def test_add_peer(self, w3: "Web3") -> None: result = w3.geth.admin.add_peer( EnodeURI( "enode://f1a6b0bdbf014355587c3018454d070ac57801f05d3b39fe85da574f002a32e929f683d72aa5a8318382e4d3c7a05c9b91687b0d997a39619fb8a6e7ad88e512@1.1.1.1:30303" # noqa: E501 )...
GoEthereumAdminModuleTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1022683, "end": 1044115 }
class ____( sgqlc.types.Type, Node, Actor, PackageOwner, ProjectOwner, ProjectNextOwner, ProjectV2Owner, ProjectV2Recent, RepositoryDiscussionAuthor, RepositoryDiscussionCommentAuthor, RepositoryOwner, UniformResourceLocatable, ProfileOwner, Sponsorable, ): ""...
User
python
plotly__plotly.py
plotly/graph_objs/bar/marker/colorbar/_title.py
{ "start": 233, "end": 3992 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "bar.marker.colorbar" _path_str = "bar.marker.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font t...
Title
python
ApeWorX__ape
src/ape/managers/project.py
{ "start": 20827, "end": 36029 }
class ____(BaseManager, ExtraAttributesMixin): """ A wrapper around a dependency. Users will not create this class directly but access them from ``project.dependencies``. """ def __init__(self, api: DependencyAPI, project: Optional["ProjectManager"] = None): self.api = api # Thi...
Dependency
python
django__django
tests/test_runner/tests.py
{ "start": 21649, "end": 23251 }
class ____(SimpleTestCase): @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") @mock.patch( "django.test.runner.ParallelTestSuite.initialize_suite", side_effect=Exception("initialize_suite() is called."), ) def test_no_initialize_suite_test_runner(self, *mocked...
NoInitializeSuiteTestRunnerTests
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 39930, "end": 40846 }
class ____(FlowRunStateChangeAction): """Changes the state of a flow run associated with the trigger""" type: Literal["change-flow-run-state"] = "change-flow-run-state" name: Optional[str] = Field( None, description="The name of the state to change the flow run to", ) state: StateT...
ChangeFlowRunState
python
tensorflow__tensorflow
tensorflow/python/debug/cli/command_parser_test.py
{ "start": 10861, "end": 12613 }
class ____(test_util.TensorFlowTestCase): INF_VALUE = sys.float_info.max def testParseEmptyRangeString(self): self.assertEqual([], command_parser.parse_ranges("")) self.assertEqual([], command_parser.parse_ranges(" ")) def testParseSingleRange(self): self.assertAllClose([[-0.1, 0.2]], ...
ParseRangesTest
python
viewflow__viewflow
viewflow/workflow/nodes/start.py
{ "start": 1368, "end": 1955 }
class ____(StartActivation): @Activation.status.transition( source=STATUS.DONE, target=STATUS.CANCELED, conditions=[leading_tasks_canceled], permission=has_manage_permission, ) def undo(self): # undo if self.flow_task._undo_func is not None: self.f...
StartHandleActivation
python
faif__python-patterns
tests/creational/test_prototype.py
{ "start": 92, "end": 949 }
class ____(unittest.TestCase): def setUp(self): self.prototype = Prototype() def test_cloning_propperty_innate_values(self): sample_object_1 = self.prototype.clone() sample_object_2 = self.prototype.clone() self.assertEqual(sample_object_1.value, sample_object_2.value) def ...
TestPrototypeFeatures
python
python__mypy
mypy/checker.py
{ "start": 377844, "end": 392623 }
class ____(TypeTraverserVisitor): """Collects the non-nested argument types in a set.""" def __init__(self) -> None: self.arg_types: set[TypeVarType] = set() def visit_type_var(self, t: TypeVarType) -> None: self.arg_types.add(t) @overload def conditional_types( current_type: Type, ...
CollectArgTypeVarTypes
python
mwaskom__seaborn
tests/test_distributions.py
{ "start": 10226, "end": 28160 }
class ____(SharedAxesLevelTests): func = staticmethod(kdeplot) def get_last_color(self, ax, fill=True): if fill: return ax.collections[-1].get_facecolor() else: return ax.lines[-1].get_color() @pytest.mark.parametrize("fill", [True, False]) def test_color(self...
TestKDEPlotUnivariate
python
django-guardian__django-guardian
example_project/posts/admin.py
{ "start": 133, "end": 374 }
class ____(GuardedModelAdmin): prepopulated_fields = {"slug": ("title",)} list_display = ("title", "slug", "created_at") search_fields = ("title", "content") ordering = ("-created_at",) date_hierarchy = "created_at"
PostAdmin
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_context_cache.py
{ "start": 5489, "end": 9330 }
class ____: """Test the integration of SecretCache with variable access.""" @staticmethod @conf_vars({("secrets", "use_cache"): "true"}) def setup_method(): SecretCache.reset() SecretCache.init() @staticmethod def teardown_method(): SecretCache.reset() @patch("airf...
TestVariableCacheIntegration
python
falconry__falcon
falcon/_typing.py
{ "start": 2538, "end": 2936 }
class ____(Protocol[_AReqT, _ARespT]): async def __call__( self, req: _AReqT, resp: _ARespT | None, error: Exception, params: dict[str, Any], *, ws: WebSocket | None = ..., ) -> None: ... # Error serializers ErrorSerializer = Callable[[_ReqT, _RespT, 'HT...
AsgiErrorHandler
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/markdown/base.py
{ "start": 315, "end": 5226 }
class ____(BaseReader): """ Markdown parser. Extract text from markdown files. Returns dictionary with keys as headers and values as the text between headers. """ def __init__( self, *args: Any, remove_hyperlinks: bool = True, remove_images: bool = True, ...
MarkdownReader
python
pyparsing__pyparsing
tests/test_unit.py
{ "start": 2734, "end": 4512 }
class ____(unittest.TestCase): @contextlib.contextmanager def assertRaises(self, expected_exception_type: Any, msg: Any = None): """ Simple wrapper to print out the exceptions raised after assertRaises """ with super().assertRaises(expected_exception_type, msg=msg) as ar: ...
TestCase
python
getsentry__sentry
src/sentry/notifications/notification_action/metric_alert_registry/handlers/slack_metric_alert_handler.py
{ "start": 989, "end": 2890 }
class ____(BaseMetricAlertHandler): @classmethod def send_alert( cls, notification_context: NotificationContext, alert_context: AlertContext, metric_issue_context: MetricIssueContext, open_period_context: OpenPeriodContext, trigger_status: TriggerStatus, n...
SlackMetricAlertHandler
python
google__pytype
pytype/overlays/typed_dict.py
{ "start": 13715, "end": 14346 }
class ____(abstract.PyTDFunction): """Implementation of typing.is_typeddict.""" def call(self, node, func, args, alias_map=None): self.match_args(node, args) if args.posargs: tp = args.posargs[0] elif "tp" in args.namedargs: tp = args.namedargs["tp"] else: return node, self.ctx.co...
IsTypedDict
python
pydata__xarray
xarray/tests/test_datatree.py
{ "start": 88081, "end": 93848 }
class ____: def test_chunksizes(self): ds1 = xr.Dataset({"a": ("x", np.arange(10))}) ds2 = xr.Dataset({"b": ("y", np.arange(5))}) ds3 = xr.Dataset({"c": ("z", np.arange(4))}) ds4 = xr.Dataset({"d": ("x", np.arange(-5, 5))}) groups = { "/": ds1.chunk({"x": 5}), ...
TestDask
python
pypa__warehouse
warehouse/accounts/interfaces.py
{ "start": 6837, "end": 7225 }
class ____(Interface): def dumps(data): """ Generates a unique token based on the data provided """ def loads(token): """ Gets the data corresponding to the token provided """ def unsafe_load_payload(token): """ Gets the data corresponding to...
ITokenService
python
huggingface__transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
{ "start": 22320, "end": 24617 }
class ____(SamHQPreTrainedModel): _can_record_outputs = { "hidden_states": SamHQVisionLayer, "attentions": SamHQVisionAttention, } def __init__(self, config: SamHQVisionConfig): super().__init__(config) self.config = config self.image_size = config.image_size ...
SamHQVisionEncoder
python
gevent__gevent
src/greentest/3.14/test_httpservers.py
{ "start": 12556, "end": 15093 }
class ____(BaseTestCase): CERTFILE = certdata_file("keycert.pem") ONLYCERT = certdata_file("ssl_cert.pem") ONLYKEY = certdata_file("ssl_key.pem") CERTFILE_PROTECTED = certdata_file("keycert.passwd.pem") ONLYKEY_PROTECTED = certdata_file("ssl_key.passwd.pem") EMPTYCERT = certdata_file("nullcert.p...
BaseHTTPSServerTestCase
python
doocs__leetcode
lcof2/剑指 Offer II 085. 生成匹配的括号/Solution.py
{ "start": 0, "end": 404 }
class ____: def generateParenthesis(self, n: int) -> List[str]: def dfs(left, right, t): if left == n and right == n: ans.append(t) return if left < n: dfs(left + 1, right, t + '(') if right < left: dfs(left,...
Solution
python
Netflix__metaflow
metaflow/exception.py
{ "start": 3291, "end": 3596 }
class ____(MetaflowException): headline = "Unknown user" def __init__(self): msg = ( "Metaflow could not determine your user name based on " "environment variables ($USERNAME etc.)" ) super(MetaflowUnknownUser, self).__init__(msg)
MetaflowUnknownUser
python
ansible__ansible
lib/ansible/module_utils/facts/virtual/netbsd.py
{ "start": 862, "end": 2791 }
class ____(Virtual, VirtualSysctlDetectionMixin): platform = 'NetBSD' def get_virtual_facts(self): virtual_facts = {} host_tech = set() guest_tech = set() # Set empty values as default virtual_facts['virtualization_type'] = '' virtual_facts['virtualization_role'...
NetBSDVirtual
python
nedbat__coveragepy
coverage/types.py
{ "start": 5011, "end": 5168 }
class ____(Protocol): """A callable warn() function.""" def __call__(self, msg: str, slug: str | None = None, once: bool = False) -> None: ...
TWarnFn
python
doocs__leetcode
solution/2000-2099/2076.Process Restricted Friend Requests/Solution.py
{ "start": 0, "end": 804 }
class ____: def friendRequests( self, n: int, restrictions: List[List[int]], requests: List[List[int]] ) -> List[bool]: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] p = list(range(n)) ans = [] for u, v in re...
Solution
python
sqlalchemy__sqlalchemy
test/orm/test_options.py
{ "start": 37167, "end": 41430 }
class ____(_Polymorphic): def test_missing_attr_wpoly_subclasss(self): s = fixture_session() wp = with_polymorphic(Person, [Manager], flat=True) assert_raises_message( sa.exc.ArgumentError, r"Mapped class Mapper\[Manager\(managers\)\] does not apply to " ...
OptionsNoPropTestInh
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
{ "start": 49541, "end": 50729 }
class ____(nn.Module): def __init__(self, config: Sam3TrackerVideoPromptEncoderConfig): super().__init__() self.scale = config.scale positional_embedding = self.scale * torch.randn((2, config.hidden_size // 2)) self.register_buffer("positional_embedding", positional_embedding) d...
Sam3TrackerVideoPositionalEmbedding
python
mlflow__mlflow
mlflow/tracing/export/uc_table.py
{ "start": 481, "end": 2670 }
class ____(MlflowV3SpanExporter): """ An exporter implementation that logs the traces to Databricks Unity Catalog table. """ def __init__(self, tracking_uri: str | None = None) -> None: super().__init__(tracking_uri) # Track if we've raised an error for span export to avoid raising it ...
DatabricksUCTableSpanExporter
python
pypa__pip
src/pip/_vendor/packaging/specifiers.py
{ "start": 1186, "end": 2871 }
class ____(metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """ @abc.abstractmethod def __hash__(self) -> int: """ ...
BaseSpecifier
python
automl__auto-sklearn
autosklearn/pipeline/components/classification/gaussian_nb.py
{ "start": 326, "end": 2034 }
class ____(AutoSklearnClassificationAlgorithm): def __init__(self, random_state=None, verbose=0): self.random_state = random_state self.verbose = int(verbose) self.estimator = None def fit(self, X, y): import sklearn.naive_bayes self.estimator = sklearn.naive_bayes.Gau...
GaussianNB
python
pypa__pipenv
pipenv/resolver.py
{ "start": 3217, "end": 3752 }
class ____: """Core package requirement information.""" name: str version: Optional[str] = None extras: Set[str] = field(default_factory=set) markers: Optional[str] = None hashes: Set[str] = field(default_factory=set) source: PackageSource = field(default_factory=PackageSource) def __p...
PackageRequirement
python
kamyu104__LeetCode-Solutions
Python/number-of-steps-to-reduce-a-number-to-zero.py
{ "start": 32, "end": 290 }
class ____(object): def numberOfSteps (self, num): """ :type num: int :rtype: int """ result = 0 while num: result += 2 if num%2 else 1 num //= 2 return max(result-1, 0)
Solution
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_to_sparse_op_test.py
{ "start": 1325, "end": 8600 }
class ____(test_util.TensorFlowTestCase): def testDocStringExample(self): rt = ragged_factory_ops.constant([[1, 2, 3], [4], [], [5, 6]]) st = self.evaluate(rt.to_sparse()) self.assertAllEqual(st.indices, [[0, 0], [0, 1], [0, 2], [1, 0], [3, 0], [3, 1]]) self.assertAllEqual(st....
RaggedTensorToSparseOpTest
python
numba__numba
numba/tests/test_parallel_backend.py
{ "start": 3405, "end": 4658 }
class ____(runnable): def __call__(self): sig = ['(f4, f4, f4[:])'] cfunc = guvectorize(sig, '(),()->()', **self._options)(gufunc_foo) a = b = np.random.random(10).astype(np.float32) expected = ufunc_foo(a, b) got = cfunc(a, b) np.testing.assert_allclose(expected, go...
guvectorize_runner
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 383253, "end": 383920 }
class ____(sgqlc.types.Interface): """Represents an announcement banner.""" __schema__ = github_schema __field_names__ = ("announcement", "announcement_expires_at", "announcement_user_dismissible") announcement = sgqlc.types.Field(String, graphql_name="announcement") """The text of the announcement...
AnnouncementBanner
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_management_commands.py
{ "start": 778, "end": 3751 }
class ____(WhooshTestCase): fixtures = ["bulk_data"] def setUp(self): super().setUp() self.old_ui = connections["whoosh"].get_unified_index() self.ui = UnifiedIndex() self.wmmi = WhooshMockSearchIndex() self.ui.build(indexes=[self.wmmi]) self.sb = connections["w...
ManagementCommandTestCase
python
dask__distributed
distributed/http/scheduler/api.py
{ "start": 302, "end": 1104 }
class ____(RequestHandler): async def post(self): self.set_header("Content-Type", "application/json") scheduler = self.server try: params = json.loads(self.request.body) n_workers = params.get("n", 0) if n_workers: workers = scheduler.worke...
RetireWorkersHandler
python
falconry__falcon
falcon/testing/client.py
{ "start": 94280, "end": 98705 }
class ____: def __init__( self, ws: helpers.ASGIWebSocketSimulator, task_req: asyncio.Task ) -> None: self._ws = ws self._task_req = task_req async def __aenter__(self) -> helpers.ASGIWebSocketSimulator: ready_waiter = asyncio.create_task(self._ws.wait_ready()) # NO...
_WSContextManager
python
ansible__ansible
test/lib/ansible_test/_util/controller/sanity/pylint/plugins/deprecated_comment.py
{ "start": 403, "end": 5226 }
class ____(pylint.checkers.BaseTokenChecker): """Checks for ``# deprecated:`` comments to ensure that the ``version`` has not passed or met the time for removal.""" name = 'deprecated-comment' msgs = { 'E9601': ( "Deprecated core version (%r) found: %s", "ansible-deprecated-...
AnsibleDeprecatedCommentChecker
python
numba__llvmlite
llvmlite/binding/newpassmanagers.py
{ "start": 19785, "end": 34496 }
class ____(ffi.ObjectRef): def __init__(self, tm, pto): super().__init__(ffi.lib.LLVMPY_CreatePassBuilder(tm, pto)) self._pto = pto self._tm = tm self._time_passes_handler = None def getModulePassManager(self): return ModulePassManager( ffi.lib.LLVMPY_buildP...
PassBuilder
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 733442, "end": 733789 }
class ____(sgqlc.types.Type, RepositoryNode): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("error", "pull_request") error = sgqlc.types.Field(DependabotUpdateError, graphql_name="error") pull_request = sgqlc.types.Field("PullRequest", graphql_name="p...
DependabotUpdate
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/button_multiline_label.py
{ "start": 80, "end": 299 }
class ____(App): def compose(self) -> ComposeResult: yield Button("Button\nwith\nmulti-line\nlabel") if __name__ == "__main__": app = ButtonWithMultilineLabelApp() app.run()
ButtonWithMultilineLabelApp
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess1.py
{ "start": 1080, "end": 1173 }
class ____: instance: Factory reveal_type(ClassC.instance, expected_text="ClassC")
ClassC
python
keras-team__keras
keras/src/ops/image.py
{ "start": 55173, "end": 58020 }
class ____(Operation): def __init__( self, kernel_size=(3, 3), sigma=(1.0, 1.0), data_format=None, *, name=None, ): super().__init__(name=name) self.kernel_size = kernel_size self.sigma = sigma self.data_format = backend.standardize...
GaussianBlur
python
scrapy__scrapy
tests/test_loader.py
{ "start": 19658, "end": 19754 }
class ____(ItemLoader): default_item_class = FunctionProcessorItem
FunctionProcessorItemLoader