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
pallets__markupsafe
src/markupsafe/__init__.py
{ "start": 264, "end": 332 }
class ____(t.Protocol): def __html__(self, /) -> str: ...
_HasHTML
python
huggingface__transformers
src/transformers/models/dpt/modeling_dpt.py
{ "start": 20320, "end": 25609 }
class ____(nn.Module): """ This class reassembles the hidden states of the backbone into image-like feature representations at various resolutions. This happens in 3 stages: 1. Map the N + 1 tokens to a set of N tokens, by taking into account the readout ([CLS]) token according to `config.re...
DPTReassembleStage
python
coleifer__peewee
peewee.py
{ "start": 152328, "end": 152914 }
class ____(object): def __init__(self, cursor_wrapper): self.cursor_wrapper = cursor_wrapper self.index = 0 def __iter__(self): return self def next(self): if self.index < self.cursor_wrapper.count: obj = self.cursor_wrapper.row_cache[self.index] elif no...
ResultIterator
python
dagster-io__dagster
python_modules/libraries/dagster-tableau/dagster_tableau/resources.py
{ "start": 36799, "end": 37485 }
class ____(BaseTableauWorkspace): """Represents a workspace in Tableau Server and provides utilities to interact with Tableau APIs. """ server_name: str = Field(..., description="The server name of the Tableau Server workspace.") def build_client(self) -> None: self._client = TableauServer...
TableauServerWorkspace
python
fluentpython__example-code-2e
21-async/domains/asyncio/domainlib.py
{ "start": 123, "end": 835 }
class ____(NamedTuple): # <1> domain: str found: bool OptionalLoop = Optional[asyncio.AbstractEventLoop] # <2> async def probe(domain: str, loop: OptionalLoop = None) -> Result: # <3> if loop is None: loop = asyncio.get_running_loop() try: await loop.getaddrinfo(domain, None) ...
Result
python
Netflix__metaflow
metaflow/plugins/azure/azure_exceptions.py
{ "start": 267, "end": 433 }
class ____(MetaflowException): headline = "Missing required packages 'azure-identity' and 'azure-storage-blob' and 'azure-keyvault-secrets'"
MetaflowAzurePackageError
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 21790, "end": 23992 }
class ____(Dinov2WithRegistersPreTrainedModel): def __init__(self, config: Dinov2WithRegistersConfig) -> None: super().__init__(config) self.num_labels = config.num_labels self.dinov2_with_registers = Dinov2WithRegistersModel(config) # Classifier head self.classifier = ( ...
Dinov2WithRegistersForImageClassification
python
getsentry__sentry
src/sentry/models/organizationslugreservationreplica.py
{ "start": 446, "end": 1496 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded organization_slug_reservation_id = HybridCloudForeignKey( "sentry.organizationslugreservation", on_delete="CASCADE", unique=True, ) slug = models.SlugField(unique=True, db_index=True) organization_id = Bounde...
OrganizationSlugReservationReplica
python
facebookresearch__faiss
tests/test_fast_scan.py
{ "start": 10935, "end": 11778 }
class ____(TestImplems): def build_fast_scan_index(self, index, params): qbs, bbs = params index2 = faiss.IndexPQFastScan(index, bbs) index2.qbs = qbs index2.implem = 14 return index2 def test_1_32(self): self.do_with_params(32, (1, 32)) def test_1_64(self)...
TestImplem14
python
getsentry__sentry
src/sentry/incidents/subscription_processor.py
{ "start": 1787, "end": 1988 }
class ____(TypedDict): """ Schema for Metric Issue Detector.config. """ comparison_delta: int | None detection_type: Literal["static", "percent", "dynamic"]
MetricIssueDetectorConfig
python
getsentry__sentry
src/sentry_plugins/gitlab/plugin.py
{ "start": 417, "end": 7182 }
class ____(CorePluginMixin, IssuePlugin2): description = "Integrate GitLab issues by linking a repository to a project" slug = "gitlab" title = "GitLab" conf_title = title conf_key = "gitlab" required_field = "gitlab_url" feature_descriptions = [ FeatureDescription( """ ...
GitLabPlugin
python
apache__airflow
airflow-core/tests/unit/models/test_deadline.py
{ "start": 18687, "end": 22236 }
class ____: """DeadlineReference lives in definitions/deadlines.py but properly testing them requires DB access.""" DEFAULT_INTERVAL = timedelta(hours=1) DEFAULT_ARGS = {"interval": DEFAULT_INTERVAL} @pytest.mark.parametrize("reference", REFERENCE_TYPES) @pytest.mark.db_test def test_deadline_...
TestDeadlineReference
python
mlflow__mlflow
mlflow/pyspark/optuna/study.py
{ "start": 638, "end": 4354 }
class ____: is_resumed: bool study_name: str | None = None existing_trials: int | None = None completed_trials: int | None = None best_value: float | None = None best_params: dict[str, Any] | None = None def is_spark_connect_mode() -> bool: """Check if the current Spark session is running ...
ResumeInfo
python
automl__auto-sklearn
test/test_metalearning/pyMetaLearn/test_optimizer_base.py
{ "start": 119, "end": 1518 }
class ____(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): self.hyperparameters = OrderedDict() self.hyperparameters["x"] = [-5, 0, 5, 10] self.hyperparameters["y"] = [0, 5, 10, 15] def test_parse_hyperopt_string(self): hyperparameter_string = "x {-5, 0...
OptimizerBaseTest
python
pytorch__pytorch
torch/_dynamo/utils.py
{ "start": 42636, "end": 61120 }
class ____: compile_id: Optional[str] = None frame_key: Optional[str] = None co_name: Optional[str] = None co_filename: Optional[str] = None co_firstlineno: Optional[int] = None cache_size: Optional[int] = None accumulated_cache_size: Optional[int] = None guard_count: Optional[int] = Non...
CompilationMetrics
python
readthedocs__readthedocs.org
readthedocs/integrations/models.py
{ "start": 5205, "end": 7262 }
class ____(models.Model): """HTTP request/response exchange.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() related_object = GenericForeignKey("content_...
HttpExchange
python
doocs__leetcode
solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/Solution.py
{ "start": 0, "end": 208 }
class ____: def greatestLetter(self, s: str) -> str: ss = set(s) for c in ascii_uppercase[::-1]: if c in ss and c.lower() in ss: return c return ''
Solution
python
scipy__scipy
scipy/stats/tests/test_correlation.py
{ "start": 293, "end": 4387 }
class ____: @pytest.mark.parametrize('case', [ dict(y_cont=True, statistic=-0.303030303030303, pvalue=0.9351329808526656), dict(y_cont=False, statistic=0.07407407407407396, pvalue=0.3709859367123997)]) @pytest.mark.parametrize('dtype', ['float32', 'float64', None]) def test_against_R_XICOR(s...
TestChatterjeeXi
python
anthropics__anthropic-sdk-python
src/anthropic/_client.py
{ "start": 21875, "end": 23030 }
class ____: _client: AsyncAnthropic def __init__(self, client: AsyncAnthropic) -> None: self._client = client @cached_property def completions(self) -> completions.AsyncCompletionsWithStreamingResponse: from .resources.completions import AsyncCompletionsWithStreamingResponse r...
AsyncAnthropicWithStreamedResponse
python
apache__airflow
task-sdk/tests/task_sdk/bases/test_operator.py
{ "start": 3162, "end": 3361 }
class ____(BaseOperator): def __init__(self, **kwargs): warnings.warn("This operator is deprecated.", DeprecationWarning, stacklevel=2) super().__init__(**kwargs)
DeprecatedOperator
python
langchain-ai__langchain
libs/partners/ollama/langchain_ollama/llms.py
{ "start": 615, "end": 19875 }
class ____(BaseLLM): """Ollama large language models. Setup: Install `langchain-ollama` and install/run the Ollama server locally: ```bash pip install -U langchain-ollama # Visit https://ollama.com/download to download and install Ollama # (Linux users): start the serve...
OllamaLLM
python
joke2k__faker
faker/providers/date_time/ro_RO/__init__.py
{ "start": 46, "end": 781 }
class ____(DateTimeProvider): DAY_NAMES = { "0": "duminica", "1": "luni", "2": "marti", "3": "miercuri", "4": "joi", "5": "vineri", "6": "sambata", } MONTH_NAMES = { "01": "ianuarie", "02": "februarie", "03": "martie", ...
Provider
python
kubernetes-client__python
kubernetes/client/models/v1_service_cidr.py
{ "start": 383, "end": 7226 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ServiceCIDR
python
mwaskom__seaborn
seaborn/_statistics.py
{ "start": 20817, "end": 24946 }
class ____: def __init__(self, k_depth, outlier_prop, trust_alpha): """ Compute percentiles of a distribution using various tail stopping rules. Parameters ---------- k_depth: "tukey", "proportion", "trustworthy", or "full" Stopping rule for choosing tail percen...
LetterValues
python
pytorch__pytorch
torch/_dynamo/testing.py
{ "start": 9277, "end": 10216 }
class ____: def __init__(self) -> None: self.graphs: list[torch.fx.GraphModule] = [] self.fw_graphs: list[torch.fx.GraphModule] = [] self.bw_graphs: list[torch.fx.GraphModule] = [] def __call__( self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] ) -> Callable...
AotEagerAndRecordGraphs
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_zip9.py
{ "start": 629, "end": 1610 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_zip9" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, ...
ColumnValuesToBeValidZip9
python
squidfunk__mkdocs-material
material/extensions/preview.py
{ "start": 5611, "end": 8283 }
class ____(Extension): """ A Markdown extension to enable instant previews on links. This extensions allows to automatically add the `data-preview` attribute to internal links matching specific criteria, so Material for MkDocs renders a nice preview on hover as part of a tooltip. It is the recommen...
PreviewExtension
python
kamyu104__LeetCode-Solutions
Python/choose-k-elements-with-maximum-sum.py
{ "start": 83, "end": 805 }
class ____(object): def findMaxSum(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ result = [0]*len(nums1) min_heap = [] idxs = range(len(nums1)) idxs.sort(key=lambda x: nums1...
Solution
python
keras-team__keras
keras/src/metrics/confusion_metrics_test.py
{ "start": 6520, "end": 9549 }
class ____(testing.TestCase): def test_config(self): tn_obj = metrics.TrueNegatives(name="my_tn", thresholds=[0.4, 0.9]) self.assertEqual(tn_obj.name, "my_tn") self.assertLen(tn_obj.variables, 1) self.assertEqual(tn_obj.thresholds, [0.4, 0.9]) # Check save and restore config...
TrueNegativesTest
python
bokeh__bokeh
src/bokeh/models/tickers.py
{ "start": 4896, "end": 5648 }
class ____(Ticker): ''' A base class for non-categorical ticker types. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) num_minor_ticks = Int(5, help=""" The number of minor tick positions to ge...
ContinuousTicker
python
astropy__astropy
astropy/units/errors.py
{ "start": 418, "end": 607 }
class ____(UnitsError, ValueError): """ Used specifically for errors related to converting between units or interpreting units in terms of other units. """
UnitConversionError
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_optimize05.py
{ "start": 315, "end": 1426 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("optimize05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook( ...
TestCompareXLSXFiles
python
skorch-dev__skorch
skorch/tests/test_dataset.py
{ "start": 12581, "end": 14982 }
class ____: """Huggingface tokenizers should work without special adjustments""" @pytest.fixture(scope='session') def tokenizer(self): transformers = pytest.importorskip('transformers') tokenizer = transformers.AutoTokenizer.from_pretrained('bert-base-uncased') return tokenizer ...
TestNetWithTokenizers
python
doocs__leetcode
solution/2400-2499/2465.Number of Distinct Averages/Solution2.py
{ "start": 0, "end": 307 }
class ____: def distinctAverages(self, nums: List[int]) -> int: nums.sort() ans = 0 cnt = Counter() for i in range(len(nums) >> 1): x = nums[i] + nums[-i - 1] cnt[x] += 1 if cnt[x] == 1: ans += 1 return ans
Solution
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-google/llama_index/embeddings/google/palm.py
{ "start": 587, "end": 2727 }
class ____(BaseEmbedding): """ Class for Google PaLM embeddings. Args: model_name (str): Model for embedding. Defaults to "models/embedding-gecko-001". api_key (Optional[str]): API key to access the model. Defaults to None. """ _model: Any = PrivateAttr() def __i...
GooglePaLMEmbedding
python
pytorch__pytorch
test/ao/sparsity/test_scheduler.py
{ "start": 2792, "end": 7248 }
class ____(TestCase): def setUp(self): super().setUp() self.model_sparse_config = [ {"tensor_fqn": "0.weight", "sparsity_level": 0.8}, {"tensor_fqn": "2.weight", "sparsity_level": 0.4}, ] self.sorted_sparse_levels = [ conf["sparsity_level"] for con...
TestCubicScheduler
python
facelessuser__soupsieve
soupsieve/css_match.py
{ "start": 1625, "end": 2087 }
class ____: """ Fake parent class. When we have a fragment with no `BeautifulSoup` document object, we can't evaluate `nth` selectors properly. Create a temporary fake parent so we can traverse the root element as a child. """ def __init__(self, element: bs4.Tag) -> None: """Initi...
_FakeParent
python
django__django
tests/contenttypes_tests/test_models.py
{ "start": 12789, "end": 13256 }
class ____(TestCase): databases = {"default", "other"} def test_multidb(self): """ When using multiple databases, ContentType.objects.get_for_model() uses db_for_read(). """ ContentType.objects.clear_cache() with ( self.assertNumQueries(0, using="defa...
ContentTypesMultidbTests
python
ray-project__ray
python/ray/tests/test_autoscaler.py
{ "start": 11367, "end": 146911 }
class ____(unittest.TestCase): def setUp(self): _NODE_PROVIDERS["mock"] = lambda config: self.create_provider _DEFAULT_CONFIGS["mock"] = _DEFAULT_CONFIGS["aws"] self.provider = None self.tmpdir = tempfile.mkdtemp() def tearDown(self): self.provider = None del _NO...
AutoscalingTest
python
kamyu104__LeetCode-Solutions
Python/longest-substring-with-at-most-two-distinct-characters.py
{ "start": 29, "end": 724 }
class ____(object): # @param s, a string # @return an integer def lengthOfLongestSubstringTwoDistinct(self, s): longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)] for i, char in enumerate(s): if visited[ord(char)] == 0: distinct_count += 1...
Solution
python
getsentry__sentry
fixtures/page_objects/transaction_summary.py
{ "start": 29, "end": 252 }
class ____(BasePage): def wait_until_loaded(self): self.browser.wait_until_not('[data-test-id="loading-indicator"]') self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
TransactionSummaryPage
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/json.py
{ "start": 541, "end": 1250 }
class ____(sqltypes.JSON): """MySQL JSON type. MySQL supports JSON as of version 5.7. MariaDB supports JSON (as an alias for LONGTEXT) as of version 10.2. :class:`_mysql.JSON` is used automatically whenever the base :class:`_types.JSON` datatype is used against a MySQL or MariaDB backend. .. ...
JSON
python
tensorflow__tensorflow
tensorflow/python/framework/convert_to_constants_test.py
{ "start": 19419, "end": 33710 }
class ____(test.TestCase): def _freezeModel(self, func): """Freezes the function. Args: func: Function. Returns: root: AutoTrackable object with original ConcreteFunction. output_func: frozen ConcreteFunction. """ root = autotrackable.AutoTrackable() root.f = func inpu...
ConvertVariablesToConstantsV2SessionTest
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 98993, "end": 100632 }
class ____(IndexFetcher): """Fetcher for index.json, using ETags headers as cache invalidation strategy""" def __init__(self, url, etag, urlopen=web_util.urlopen): self.url = url self.etag = etag self.urlopen = urlopen def conditional_fetch(self) -> FetchIndexResult: # Just...
EtagIndexFetcherV2
python
openai__openai-python
src/openai/_models.py
{ "start": 24308, "end": 30717 }
class ____: field_name: str """The name of the discriminator field in the variant class, e.g. ```py class Foo(BaseModel): type: Literal['foo'] ``` Will result in field_name='type' """ field_alias_from: str | None """The name of the discriminator field in the API response, ...
DiscriminatorDetails
python
pallets__werkzeug
src/werkzeug/routing/rules.py
{ "start": 5719, "end": 6563 }
class ____(RuleFactory): """Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications:: url_map = Map([ Rule('/', endpoint='index'), EndpointPrefix('blog/', [Submount('/blog', [ Rule('/', endpoint...
EndpointPrefix
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/utils/utils.py
{ "start": 33214, "end": 40234 }
class ____(InfoJsonEncodable): """Defines encoding TaskGroup object to JSON.""" renames = { "_group_id": "group_id", } includes = [ "downstream_group_ids", "downstream_task_ids", "prefix_group_id", "tooltip", "upstream_group_ids", "upstream_task_i...
TaskGroupInfo
python
pytorch__pytorch
test/distributed/tensor/test_dtensor_compile.py
{ "start": 1874, "end": 3144 }
class ____: """ Tuple-like values that are treated as leaves of a PyTree. """ def __init__(self, *values): self._values = tuple(values) def __repr__(self): pr = repr(self._values)[1:-1] return f"{type(self).__name__}({pr})" def __getitem__(self, i): return self...
PytreeTuple
python
django__django
tests/migrations/models.py
{ "start": 205, "end": 561 }
class ____(models.Model): title = models.CharField("ÚÑÍ¢ÓÐÉ", max_length=20, default="“Ðjáñgó”") class Meta: # Disable auto loading of this model as we load it on our own apps = Apps() verbose_name = "úñí©óðé µóðéø" verbose_name_plural = "úñí©óðé µóðéøß" def __str__(self): ...
UnicodeModel
python
getsentry__sentry
tests/sentry/sentry_apps/test_webhooks.py
{ "start": 335, "end": 23159 }
class ____(TestCase): def setUp(self) -> None: self.organization = self.create_organization() self.project = self.create_project(organization=self.organization) # Create sentry apps with different event subscriptions self.sentry_app_1 = self.create_sentry_app( name="App1...
BroadcastWebhooksForOrganizationTest
python
readthedocs__readthedocs.org
readthedocs/notifications/tests/test_querysets.py
{ "start": 401, "end": 4722 }
class ____: def test_add(self): user = fixture.get( User, ) # There is any notification attached to this user assert ( Notification.objects.filter( attached_to_content_type=ContentType.objects.get_for_model(User), attached_to_i...
TestNotificationQuerySet
python
coleifer__peewee
playhouse/dataset.py
{ "start": 10523, "end": 10674 }
class ____(object): def __init__(self, query): self.query = query def export(self, file_obj): raise NotImplementedError
Exporter
python
kamyu104__LeetCode-Solutions
Python/semi-ordered-permutation.py
{ "start": 38, "end": 278 }
class ____(object): def semiOrderedPermutation(self, nums): """ :type nums: List[int] :rtype: int """ i, j = nums.index(1), nums.index(len(nums)) return i+((len(nums)-1)-j)-int(i > j)
Solution
python
python-attrs__attrs
tests/test_functional.py
{ "start": 1038, "end": 1118 }
class ____(BaseSlots): y = attr.ib() @attr.s(frozen=True, slots=True)
SubSlots
python
facebook__pyre-check
tools/upgrade/tests/ast_test.py
{ "start": 233, "end": 1498 }
class ____(unittest.TestCase): def test_check_stable(self) -> None: ast.check_stable("def foo(): pass", "def foo():\n pass") with self.assertRaises(ast.UnstableAST): ast.check_stable("def foo(): pass", "def bar(): pass") with self.assertRaises(SyntaxError): ast.chec...
ErrorsTest
python
django__django
tests/forms_tests/models.py
{ "start": 713, "end": 1469 }
class ____(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" CHOICES = [ ("", "No Preference"), ("f", "Foo"), ("b", "Bar"), ] INTEGER_CHOICES = [ (None, "No Preference"), (1, "Foo"), (2, "Bar"), ] STRING_CHOICES_WITH_...
ChoiceModel
python
keon__algorithms
algorithms/compression/huffman_coding.py
{ "start": 3329, "end": 5477 }
class ____: def __init__(self, file): self.file = file self.buffer = "" self.saved_bits = 0 def write_char(self, char): self.write_int(ord(char)) def write_int(self, num): bin_int = "{0:08b}".format(num) self.write_bits(bin_int) def write_bits(self, bit...
HuffmanWriter
python
pdm-project__pdm
src/pdm/resolver/providers.py
{ "start": 21820, "end": 22456 }
class ____(ReusePinProvider): """A provider that reuses installed packages if possible.""" @cached_property def installed(self) -> WorkingSet: return self.repository.environment.get_working_set() def iter_reuse_candidates(self, identifier: str, requirement: Requirement | None) -> Iterable[Cand...
ReuseInstalledProvider
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 9153, "end": 9338 }
class ____(BaseModel): """ Response for task states with run_id, task and state. """ task_states: Annotated[dict[str, Any], Field(title="Task States")]
TaskStatesResponse
python
django__django
tests/forms_tests/field_tests/test_multivaluefield.py
{ "start": 1754, "end": 1841 }
class ____(Form): field1 = ComplexField(widget=ComplexMultiWidget())
ComplexFieldForm
python
huggingface__transformers
tests/models/timm_wrapper/test_modeling_timm_wrapper.py
{ "start": 1446, "end": 2579 }
class ____: def __init__( self, parent, batch_size=3, image_size=32, num_channels=3, is_training=True, ): self.parent = parent self.architecture = "resnet26" # We need this to make the model smaller self.model_args = {"channels": (1...
TimmWrapperModelTester
python
google__jax
jax/_src/pallas/mosaic_gpu/core.py
{ "start": 19450, "end": 21632 }
class ____(GPUMemoryRef): """A sequence of trees of refs that are allowed to reuse the same memory. One should not make assumptions as to how each ref will map to the underlying memory region, since arbitrary padding may be applied in between different refs. As such, ref unions are only safe to use when the...
RefUnion
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_notification_defaults.py
{ "start": 156, "end": 1436 }
class ____(APITestCase): endpoint = "sentry-api-0-notification-defaults" def test_basic(self) -> None: response = self.get_success_response() assert response.data == { "providerDefaults": ["email", "slack"], "typeDefaults": { "alerts": "always", ...
NotificationDefaultTest
python
kamyu104__LeetCode-Solutions
Python/maximum-distance-in-arrays.py
{ "start": 29, "end": 545 }
class ____(object): def maxDistance(self, arrays): """ :type arrays: List[List[int]] :rtype: int """ result, min_val, max_val = 0, arrays[0][0], arrays[0][-1] for i in xrange(1, len(arrays)): result = max(result, \ max(max_val - a...
Solution
python
google__pytype
pytype/imports/typeshed.py
{ "start": 15506, "end": 16485 }
class ____(base.BuiltinLoader): """Load modules from typeshed.""" def __init__(self, options, missing_modules): self.options = options self.typeshed = _get_typeshed(missing_modules) # TODO(mdemello): Inject options.open_function into self.typeshed def load_module(self, namespace, module_name): "...
TypeshedLoader
python
huggingface__transformers
src/transformers/models/vits/modeling_vits.py
{ "start": 52194, "end": 54073 }
class ____(PreTrainedModel): config: VitsConfig base_model_prefix = "vits" main_input_name = "input_ids" supports_gradient_checkpointing = True @torch.no_grad() def _init_weights(self, module: nn.Module): """Initialize the weights""" std = self.config.initializer_range i...
VitsPreTrainedModel
python
keras-team__keras
keras/src/ops/linalg_test.py
{ "start": 11379, "end": 21097 }
class ____(testing.TestCase): def test_cholesky(self): x_non_psd = np.random.rand(4, 3, 3).astype("float32") with self.assertRaises(ValueError): linalg.cholesky(x_non_psd) x = np.random.rand(4, 3, 3).astype("float32") x_psd = np.matmul(x, x.transpose((0, 2, 1))) + 1e-5 *...
LinalgOpsCorrectnessTest
python
numpy__numpy
numpy/linalg/tests/test_linalg.py
{ "start": 11245, "end": 11935 }
class ____: TEST_CASES = CASES def check_cases(self, require=set(), exclude=set()): """ Run func on each of the cases with all of the tags in require, and none of the tags in exclude """ for case in self.TEST_CASES: # filter by require and exclude ...
LinalgTestCase
python
doocs__leetcode
solution/2200-2299/2206.Divide Array Into Equal Pairs/Solution.py
{ "start": 0, "end": 149 }
class ____: def divideArray(self, nums: List[int]) -> bool: cnt = Counter(nums) return all(v % 2 == 0 for v in cnt.values())
Solution
python
pytorch__pytorch
torch/_inductor/template_heuristics/contiguous_mm.py
{ "start": 1149, "end": 2232 }
class ____(GemmMaxAutotuneTemplateConfigHeuristics): def _get_template_configs_impl( self, kernel_inputs: KernelInputs, op_name: str, ) -> Generator[dict[str, Any], None, None]: """ Get all the valid k_splits for the given m, n, k. """ assert isinstance(ke...
ContiguousMMHeuristics
python
python__mypy
mypyc/irbuild/nonlocalcontrol.py
{ "start": 1988, "end": 2667 }
class ____(NonlocalControl): """Nonlocal control within a loop.""" def __init__( self, outer: NonlocalControl, continue_block: BasicBlock, break_block: BasicBlock ) -> None: self.outer = outer self.continue_block = continue_block self.break_block = break_block def gen_b...
LoopNonlocalControl
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI029.py
{ "start": 656, "end": 822 }
class ____: @abstractmethod def __str__(self) -> builtins.str: ... @abstractmethod def __repr__(self) -> str: ...
MatchingArgsButAbstract
python
google__jax
jax/_src/prng.py
{ "start": 16535, "end": 47153 }
class ____(dtypes.ExtendedDType): _impl: PRNGImpl # TODO(mattjj,frostig): protocol really _rules = KeyTyRules type = dtypes.prng_key def __init__(self, impl): self._impl = impl @property def name(self) -> str: return f'key<{self._impl.tag}>' @property def itemsize(self) -> int: return ma...
KeyTy
python
apache__airflow
airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py
{ "start": 1687, "end": 1825 }
class ____: """Represents the details of a pool.""" name: str | None = None team_name: str | None = None @dataclass
PoolDetails
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/assignment10.py
{ "start": 425, "end": 2038 }
class ____(Generic[T]): ... def func1(v1: list[Any | None], v2: list[int | str]): x1: list[int | None] = v1 reveal_type(x1, expected_text="list[int | None]") x2: list[Any] = v2 reveal_type(x2, expected_text="list[Any]") x3: list[Any | str] = v2 reveal_type(x3, expected_text="list[Any | str]"...
B
python
neetcode-gh__leetcode
python/0055-jump-game.py
{ "start": 0, "end": 227 }
class ____: def canJump(self, nums: List[int]) -> bool: goal = len(nums) - 1 for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= goal: goal = i return goal == 0
Solution
python
kubernetes-client__python
kubernetes/client/models/v1_endpoint_address.py
{ "start": 383, "end": 6257 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1EndpointAddress
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_requests/sponsored_brands_report_v3_request_builder.py
{ "start": 280, "end": 3617 }
class ____(AmazonAdsBaseRequestBuilder): @classmethod def _init_report_endpoint( cls, client_id: str, client_access_token: str, profile_id: str, report_type: str, metrics: List[str], report_date: Optional[str] = None, ) -> "SponsoredBrandsV3ReportReque...
SponsoredBrandsV3ReportRequestBuilder
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/watchdog_test.py
{ "start": 883, "end": 2028 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters(True, False) def testWatchDogTimeout(self, use_env_var): tmp_file = self.create_tempfile() f = open(tmp_file, "w+") triggerred_count = [0] def on_triggered_fn(): triggerred_count[0] += 1 timeout = 3 if use...
WatchDogTest
python
ray-project__ray
rllib/connectors/connector.py
{ "start": 567, "end": 2618 }
class ____: """Data bits that may be needed for running connectors. Note(jungong) : we need to be really careful with the data fields here. E.g., everything needs to be serializable, in case we need to fetch them in a remote setting. """ # TODO(jungong) : figure out how to fetch these in a rem...
ConnectorContext
python
ray-project__ray
python/ray/dashboard/head.py
{ "start": 1460, "end": 18787 }
class ____: def __init__( self, http_host: str, http_port: int, http_port_retries: int, gcs_address: str, cluster_id_hex: str, node_ip_address: str, log_dir: str, logging_level: int, logging_format: str, logging_filename: str, ...
DashboardHead
python
walkccc__LeetCode
solutions/2294. Partition Array Such That Maximum Difference Is K/2294.py
{ "start": 0, "end": 238 }
class ____: def partitionArray(self, nums: list[int], k: int) -> int: nums.sort() ans = 1 mn = nums[0] for i in range(1, len(nums)): if mn + k < nums[i]: ans += 1 mn = nums[i] return ans
Solution
python
google__pytype
pytype/block_environment_test.py
{ "start": 279, "end": 669 }
class ____: def __init__(self): self.blocks = {} def add_edge(self, v1: int, v2: int): b1 = self.blocks.setdefault(v1, FakeBlock(v1)) b2 = self.blocks.setdefault(v2, FakeBlock(v2)) b2.incoming.add(b1) @classmethod def make(cls, edges): ret = cls() for v1, v2 in edges: ret.add_ed...
BlockGraph
python
encode__django-rest-framework
tests/test_serializer.py
{ "start": 15615, "end": 16711 }
class ____: def test_not_required_output_for_dict(self): """ 'required=False' should allow a dictionary key to be missing in output. """ class ExampleSerializer(serializers.Serializer): omitted = serializers.CharField(required=False) included = serializers.Cha...
TestNotRequiredOutput
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/patch_inheritance/package.py
{ "start": 199, "end": 309 }
class ____(Patch): def install(self, spec, prefix): Patch.install(self, spec, prefix)
PatchInheritance
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_dict.py
{ "start": 58795, "end": 58884 }
class ____(mapping_tests.BasicTestMappingProtocol): type2test = dict
GeneralMappingTests
python
getsentry__sentry
src/sentry/sentry_apps/services/app/model.py
{ "start": 4753, "end": 5130 }
class ____(Protocol): """ Protocol making RpcSentryAppEvents capable of consuming from various sources, keeping only the minimum required properties. """ @property def id(self) -> str: ... @property def label(self) -> str: ... @property def actionType(self) -> str: ... de...
SentryAppEventDataInterface
python
walkccc__LeetCode
solutions/236. Lowest Common Ancestor of a Binary Tree/236.py
{ "start": 0, "end": 378 }
class ____: def lowestCommonAncestor( self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode', ) -> 'TreeNode': if not root or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left ...
Solution
python
PyCQA__pylint
tests/checkers/unittest_spelling.py
{ "start": 749, "end": 21531 }
class ____(CheckerTestCase): # pylint:disable=too-many-public-methods # This is a test case class, not sure why it would be relevant to have # this pylint rule enforced for test case classes. CHECKER_CLASS = spelling.SpellingChecker skip_on_missing_package_or_dict = pytest.mark.skipif( spell...
TestSpellingChecker
python
tensorflow__tensorflow
tensorflow/python/keras/layers/convolutional.py
{ "start": 131584, "end": 140598 }
class ____(Layer): """Cropping layer for 3D data (e.g. spatial or spatio-temporal). Examples: >>> input_shape = (2, 28, 28, 10, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x) >>> print(y.shape) (2, 24, 20, 6, 3) Args: cr...
Cropping3D
python
django__django
tests/admin_inlines/admin.py
{ "start": 3404, "end": 3548 }
class ____(admin.StackedInline): model = Inner can_delete = False readonly_fields = ("readonly",) # For bug #13174 tests.
InnerInline
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 299002, "end": 303644 }
class ____(IRNode): """ TensorBox / StorageBox allow in-place mutation of Tensors """ data: IRNode def has_exceeded_max_reads(self) -> bool: return self.data.has_exceeded_max_reads() def get_device(self) -> Optional[torch.device]: return self.data.get_device() def make_lo...
MutableBox
python
apache__airflow
providers/standard/src/airflow/providers/standard/sensors/date_time.py
{ "start": 4219, "end": 6355 }
class ____(DateTimeSensor): """ Wait until the specified datetime occurs. Deferring itself to avoid taking up a worker slot while it is waiting. It is a drop-in replacement for DateTimeSensor. :param target_time: datetime after which the job succeeds. (templated) :param start_from_trigger: Sta...
DateTimeSensorAsync
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/shrinking/choicetree.py
{ "start": 1543, "end": 3850 }
class ____: """A source of nondeterminism for use in shrink passes.""" def __init__( self, tree: "ChoiceTree", selection_order: Callable[[int, int], Iterable[int]], ): self.__selection_order = selection_order self.__node_trail = [tree.root] self.__choices: li...
Chooser
python
getsentry__sentry
src/sentry/api/exceptions.py
{ "start": 2860, "end": 3042 }
class ____(SentryAPIException): status_code = status.HTTP_403_FORBIDDEN code = "superuser-required" message = "You need to re-authenticate for superuser."
SuperuserRequired
python
django__django
tests/generic_inline_admin/tests.py
{ "start": 899, "end": 3640 }
class ____(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) e = Episode.objects.create(name="This Week in Django") self.episode_pk = e.pk m = Media(content_object=e, url="http://example.com/podcast.mp3") m.save() self.mp3_media_pk = ...
GenericAdminViewTest
python
openai__openai-python
src/openai/types/realtime/realtime_audio_formats_param.py
{ "start": 492, "end": 616 }
class ____(TypedDict, total=False): type: Literal["audio/pcmu"] """The audio format. Always `audio/pcmu`."""
AudioPCMU
python
catalyst-team__catalyst
catalyst/loggers/mlflow.py
{ "start": 2172, "end": 7061 }
class ____(ILogger): """Mlflow logger for parameters, metrics, images and other artifacts. Mlflow documentation: https://mlflow.org/docs/latest/index.html. Args: experiment: Name of the experiment in MLflow to log to. run: Name of the run in Mlflow to log to. tracking_uri: URI of t...
MLflowLogger
python
huggingface__transformers
examples/pytorch/text-classification/run_glue.py
{ "start": 2417, "end": 6129 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ task_name: Optional[str] = field( default=None, ...
DataTrainingArguments
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 14098, "end": 14509 }
class ____(GroupType): type_id = 1910 slug = "performance_n_plus_one_api_calls_experimental" description = "N+1 API Call (Experimental)" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.HTTP_CLIENT.value noise_config = NoiseConfig() default_priority = PriorityLevel.LOW ...
PerformanceNPlusOneAPICallsExperimentalGroupType