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 | redis__redis-py | tests/test_cache.py | {
"start": 1127,
"end": 14271
} | class ____:
@pytest.mark.parametrize(
"r",
[
{
"cache": DefaultCache(CacheConfig(max_size=5)),
"single_connection_client": True,
},
{
"cache": DefaultCache(CacheConfig(max_size=5)),
"single_connection... | TestCache |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 35169,
"end": 36089
} | class ____(ASTExpression):
def __init__(self, typ: ASTType) -> None:
self.typ = typ
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTSizeofType):
return NotImplemented
return self.typ == other.typ
def __hash__(self) -> int:
return hash(self.t... | ASTSizeofType |
python | getsentry__sentry | tests/sentry/replays/usecases/test_summarize.py | {
"start": 34264,
"end": 55630
} | class ____(
TransactionTestCase,
SnubaTestCase,
):
def setUp(self) -> None:
super().setUp()
self.replay_id = uuid.uuid4().hex
def store_replay(self, dt: datetime | None = None, **kwargs: Any) -> None:
replay = mock_replay(
dt or datetime.now(UTC) - timedelta(minutes=... | RpcGetReplaySummaryLogsTestCase |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofworkv2.py | {
"start": 73902,
"end": 75329
} | class ____(fixtures.MappedTest):
"""test [ticket:3167].
See also RefreshFlushInReturningTest in test/orm/test_events.py which
tests the positive case for the refresh_flush event, added in
[ticket:3427].
"""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata... | NoAttrEventInFlushTest |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/python.py | {
"start": 10449,
"end": 14888
} | class ____(PythonOperator, SkipMixin):
"""
Allows a pipeline to continue based on the result of a ``python_callable``.
The ShortCircuitOperator is derived from the PythonOperator and evaluates the result of a
``python_callable``. If the returned result is False or a falsy value, the pipeline will be
... | ShortCircuitOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes4.py | {
"start": 185,
"end": 365
} | class ____:
bar: str = "hi"
def __init__(self, val: str) -> None:
self.str = val
@classmethod
def method1(cls, val: str) -> None:
cls.str = val
| ClassA |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/hooks/databricks.py | {
"start": 8856,
"end": 29754
} | class ____(BaseDatabricksHook):
"""
Interact with Databricks.
:param databricks_conn_id: Reference to the :ref:`Databricks connection <howto/connection:databricks>`.
:param timeout_seconds: The amount of time in seconds the requests library
will wait before timing-out.
:param retry_limit: T... | DatabricksHook |
python | apache__airflow | devel-common/src/sphinx_exts/docs_build/docs_builder.py | {
"start": 1427,
"end": 14233
} | class ____:
"""Documentation builder for Airflow."""
def __init__(self, package_name: str) -> None:
self.package_name = package_name
self.is_provider = False
self.is_airflow = False
self.is_chart = False
self.is_docker_stack = False
self.is_task_sdk = False
... | AirflowDocsBuilder |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/types.py | {
"start": 2002,
"end": 2931
} | class ____(
NamedTuple(
"_DaemonStatus",
[
("daemon_type", str),
("required", bool),
("healthy", Optional[bool]),
("last_heartbeat", Optional[DaemonHeartbeat]),
],
)
):
"""Daemon statuses are derived from daemon heartbeats and instance ... | DaemonStatus |
python | huggingface__transformers | src/transformers/models/doge/modular_doge.py | {
"start": 30270,
"end": 34129
} | class ____(MixtralForCausalLM):
def __init__(self, config):
super().__init__(config)
self.model = DogeModel(config)
self.num_experts = config.num_experts
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = Non... | DogeForCausalLM |
python | gevent__gevent | src/gevent/_socketcommon.py | {
"start": 14114,
"end": 26066
} | class ____(object):
# pylint:disable=too-many-public-methods
__slots__ = (
'hub',
'timeout',
'_read_event',
'_write_event',
'_sock',
'__weakref__',
)
def __init__(self):
# Writing:
# (self.a, self.b) = (None,) * 2
# generates th... | SocketMixin |
python | tensorflow__tensorflow | tensorflow/compiler/tests/fake_quant_ops_test.py | {
"start": 17388,
"end": 21207
} | class ____(xla_test.XLATestCase):
"""Test cases for FakeQuantWithMinMaxVarsPerChannel operation."""
# 8 bits, wide range.
def testOp_with8Bits(self):
self._TestOp(
[0.0, 0.5, -128.0, -0.1],
[255.0, 128.0, -0.5, 127.4],
8,
False,
[0.0, 0.0, -127.5, 0.0],
[255.0,... | FakeQuantWithMinMaxVarsPerChannelTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox14.py | {
"start": 315,
"end": 868
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 246694,
"end": 249853
} | class ____(Operation):
def __init__(self, indices_or_sections, axis=0, *, name=None):
super().__init__(name=name)
self.indices_or_sections = indices_or_sections
self.axis = axis
def call(self, x):
return backend.numpy.array_split(
x,
indices_or_sections=... | ArraySplit |
python | tensorflow__tensorflow | tensorflow/python/saved_model/fingerprinting_test.py | {
"start": 1686,
"end": 8805
} | class ____(test.TestCase):
def _create_saved_model(self):
root = autotrackable.AutoTrackable()
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
save.save(root, save_dir)
self.addCleanup(shutil.rmtree, save_dir)
return save_dir
def _create_model_with_function(self):
root = autotr... | FingerprintingTest |
python | sympy__sympy | sympy/core/tests/test_operations.py | {
"start": 412,
"end": 2859
} | class ____(LatticeOp):
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert join(join(2, 3), 4) == join(2, join(3, 4))
assert join(2, 3) == join(3, 2)
assert join(0, 2) == 0
assert join(1, 2) == 2
assert join(2, 2) == 2
assert join(join(2, 3), 4) == join(2, 3, 4)
... | join |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 13970,
"end": 16827
} | class ____(nn.Module):
def __init__(self, config, stage):
super().__init__()
self.config = config
self.stage = stage
if self.config.cls_token[self.stage]:
self.cls_token = nn.Parameter(torch.randn(1, 1, self.config.embed_dim[-1]))
self.embedding = CvtEmbeddings(
... | CvtStage |
python | PyCQA__pylint | pylint/extensions/comparison_placement.py | {
"start": 680,
"end": 2362
} | class ____(BaseChecker):
"""Checks the placement of constants in comparisons."""
# configuration section name
name = "comparison-placement"
msgs = {
"C2201": (
"Comparison should be %s",
"misplaced-comparison-constant",
"Used when the constant is placed on th... | MisplacedComparisonConstantChecker |
python | great-expectations__great_expectations | great_expectations/render/renderer/page_renderer.py | {
"start": 1183,
"end": 24105
} | class ____(Renderer):
def __init__(
self,
column_section_renderer=None,
run_info_at_end: bool = False,
data_context=None,
) -> None:
"""
Args:
column_section_renderer:
run_info_at_end: Move the run info (Info, Batch Markers, Batch Kwargs) t... | ValidationResultsPageRenderer |
python | pypa__warehouse | warehouse/macaroons/caveats/_core.py | {
"start": 502,
"end": 596
} | class ____(CaveatError):
pass
@dataclass(frozen=True, slots=True)
| CaveatDeserializationError |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 30479,
"end": 34851
} | class ____(GPTJPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
def __init__(self, config):
super().__init__(config)
self.transformer = GPTJModel(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
# Initialize ... | GPTJForCausalLM |
python | python-markdown__markdown | tests/test_legacy.py | {
"start": 1327,
"end": 2792
} | class ____(LegacyTestCase):
"""
Notes on "excluded" tests:
Quotes in attributes: attributes get output in different order
Inline HTML (Span): Backtick in raw HTML attribute TODO: fix me
Backslash escapes: Weird whitespace issue in output
`Ins` & `del`: Our behavior follows `markdown.pl`. I t... | TestPhp |
python | tensorflow__tensorflow | tensorflow/python/summary/summary_iterator.py | {
"start": 917,
"end": 3085
} | class ____(object):
"""Yields `Event` protocol buffers from a given path."""
def __init__(self, path):
self._tf_record_iterator = tf_record.tf_record_iterator(path)
def __iter__(self):
return self
def __next__(self):
r = next(self._tf_record_iterator)
return event_pb2.Event.FromString(r)
n... | _SummaryIterator |
python | sphinx-doc__sphinx | sphinx/transforms/i18n.py | {
"start": 3151,
"end": 3507
} | class ____(SphinxTransform):
"""Preserve original translatable messages before translation"""
default_priority = 10 # this MUST be invoked before Locale transform
def apply(self, **kwargs: Any) -> None:
for node in self.document.findall(addnodes.translatable):
node.preserve_original_m... | PreserveTranslatableMessages |
python | django__django | tests/utils_tests/test_text.py | {
"start": 372,
"end": 19777
} | class ____(SimpleTestCase):
def test_get_text_list(self):
self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d")
self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c")
self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b")
self.asse... | TestUtilsText |
python | huggingface__transformers | src/transformers/models/smollm3/modeling_smollm3.py | {
"start": 15263,
"end": 15814
} | class ____(PreTrainedModel):
config: SmolLM3Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["SmolLM3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True... | SmolLM3PreTrainedModel |
python | allegroai__clearml | clearml/backend_api/services/v2_13/workers.py | {
"start": 60197,
"end": 66588
} | class ____(Request):
"""
Returns statistics for the selected workers and time range aggregated by date intervals.
:param worker_ids: List of worker ids to collect metrics for. If not provided
or empty then all the company workers metrics are analyzed.
:type worker_ids: Sequence[str]
:param ... | GetStatsRequest |
python | PrefectHQ__prefect | src/prefect/server/orchestration/core_policy.py | {
"start": 42349,
"end": 43324
} | class ____(
BaseOrchestrationRule[orm_models.Run, Union[core.TaskRunPolicy, core.FlowRunPolicy]]
):
"""
Ensures scheduled time is copied from scheduled states to pending states.
If a new scheduled time has been proposed on the pending state, the scheduled time
on the scheduled state will be ignored... | CopyScheduledTime |
python | marshmallow-code__marshmallow | src/marshmallow/types.py | {
"start": 594,
"end": 897
} | class ____(typing.Protocol):
def __call__(
self,
output: typing.Any,
original_data: typing.Any = ...,
*,
partial: bool | StrSequenceOrSet | None = None,
unknown: UnknownOption | None = None,
many: bool = False,
) -> None: ...
| SchemaValidator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams1.py | {
"start": 1360,
"end": 1397
} | class ____[T]:
pass
| ForwardRefClass |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 22280,
"end": 25806
} | class ____(Mean):
"""Wraps a stateless metric function with the Mean metric.
You could use this class to quickly build a mean metric from a function. The
function needs to have the signature `fn(y_true, y_pred)` and return a
per-sample loss array. `MeanMetricWrapper.result()` will return
the average metric v... | MeanMetricWrapper |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 58652,
"end": 63084
} | class ____(RoCBertPreTrainedModel):
# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->RoCBert,bert->roc_bert
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.ro... | RoCBertForSequenceClassification |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/watchdog.py | {
"start": 844,
"end": 2409
} | class ____(object):
"""A class to dump stack traces if no activity happens in ClusterCoordinator."""
def __init__(self, timeout=-1, traceback_file=sys.stdout, on_triggered=None):
if os.environ.get("TF_CLUSTER_COORDINATOR_WATCH_DOG_TIMEOUT",
"").isnumeric():
timeout = int(os.environ[... | WatchDog |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/grant_types/implicit.py | {
"start": 217,
"end": 16810
} | class ____(GrantTypeBase):
"""`Implicit Grant`_
The implicit grant type is used to obtain access tokens (it does not
support the issuance of refresh tokens) and is optimized for public
clients known to operate a particular redirection URI. These clients
are typically implemented in a browser usin... | ImplicitGrant |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 6695,
"end": 8497
} | class ____(ast.NodeVisitor):
"""Get nonlocal variables accessed."""
def __init__(self) -> None:
"""Create a NonLocals visitor."""
self.loads: set[str] = set()
self.stores: set[str] = set()
@override
def visit_Name(self, node: ast.Name) -> None:
"""Visit a name node.
... | NonLocals |
python | joke2k__faker | faker/providers/date_time/tl_PH/__init__.py | {
"start": 49,
"end": 155
} | class ____(FilPhProvider):
"""No difference from DateTime Provider for fil_PH locale"""
pass
| Provider |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 10196,
"end": 11290
} | class ____:
"""Make sure alignment works regardless of when it was set"""
def test_aligned_ascii(
self, aligned_before_table: PrettyTable, aligned_after_table: PrettyTable
) -> None:
assert aligned_before_table.get_string() == aligned_after_table.get_string()
def test_aligned_html(
... | TestAlignment |
python | django__django | tests/backends/sqlite/tests.py | {
"start": 10221,
"end": 10343
} | class ____(EscapingChecks):
pass
@unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests")
| EscapingChecksDebug |
python | optuna__optuna | optuna/samplers/_tpe/probability_distributions.py | {
"start": 797,
"end": 2485
} | class ____(NamedTuple):
mu: np.ndarray
sigma: np.ndarray
low: float # Currently, low, high and step do not change per trial.
high: float
step: float
_BatchedDistributions = Union[
_BatchedCategoricalDistributions,
_BatchedTruncNormDistributions,
_BatchedTruncLogNormDistributions,
... | _BatchedDiscreteTruncLogNormDistributions |
python | langchain-ai__langchain | libs/partners/ollama/tests/unit_tests/test_auth.py | {
"start": 6852,
"end": 7870
} | class ____:
"""Test URL authentication integration with OllamaEmbeddings."""
@patch("langchain_ollama.embeddings.Client")
@patch("langchain_ollama.embeddings.AsyncClient")
def test_ollama_embeddings_url_auth_integration(
self, mock_async_client: MagicMock, mock_client: MagicMock
) -> None:
... | TestOllamaEmbeddingsUrlAuth |
python | huggingface__transformers | src/transformers/models/phimoe/modular_phimoe.py | {
"start": 13172,
"end": 14958
} | class ____(MixtralForCausalLM):
def __init__(self, config):
super().__init__(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=self.config.lm_head_bias)
# Copied from transformers.models.phi3.modeling_phi3.Phi3ForCausalLM.prepare_inputs_for_generation
def prepare_... | PhimoeForCausalLM |
python | django__django | tests/test_utils/test_transactiontestcase.py | {
"start": 1797,
"end": 2361
} | class ____(TransactionTestCase):
available_apps = ["test_utils"]
def test_disallowed_database_queries(self):
message = (
"Database queries to 'other' are not allowed in this test. "
"Add 'other' to test_utils.test_transactiontestcase."
"DisallowedDatabaseQueriesTests... | DisallowedDatabaseQueriesTests |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/utils.py | {
"start": 929,
"end": 1748
} | class ____:
def __init__(self, target):
self.target = target
def __str__(self):
name = self.target.__module__ + '.' if hasattr(self.target, '__module__') else ''
name += self.target.__name__ if hasattr(self.target, '__name__') else repr(self.target)
return name
def __repr__... | NameWrapper |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v2.4.0.a.py | {
"start": 1439,
"end": 1672
} | class ____(BaseModel):
__tablename__ = "trials"
trial_id = Column(Integer, primary_key=True)
number = Column(Integer)
study_id = Column(Integer, ForeignKey("studies.study_id"))
value = sa.Column(sa.Float)
| TrialModel |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 1470,
"end": 1522
} | class ____(TypedDict):
users: str
| PermissionsUsers |
python | python__mypy | mypyc/ir/rtypes.py | {
"start": 21574,
"end": 22931
} | class ____(RTypeVisitor[str]):
"""Produce a tuple name based on the concrete representations of types."""
def visit_rinstance(self, t: RInstance) -> str:
return "O"
def visit_runion(self, t: RUnion) -> str:
return "O"
def visit_rprimitive(self, t: RPrimitive) -> str:
if t._cty... | TupleNameVisitor |
python | sphinx-doc__sphinx | sphinx/directives/admonitions.py | {
"start": 1690,
"end": 1750
} | class ____(SphinxAdmonition):
node_class = nodes.note
| Note |
python | ray-project__ray | python/ray/tests/test_runtime_env_complicated.py | {
"start": 3722,
"end": 34795
} | class ____:
def get_emoji_version(self):
import emoji # noqa: E811
return emoji.__version__
check_remote_client_conda = """
import ray
context = (ray.client("localhost:24001")
.env({{"conda" : "package-{package_version}"}})
.connect())
@ray.remote
def get_package_vers... | VersionActor |
python | pypa__setuptools | setuptools/_vendor/autocommand/automain.py | {
"start": 777,
"end": 2076
} | class ____(AutocommandError, TypeError):
pass
def automain(module, *, args=(), kwargs=None):
'''
This decorator automatically invokes a function if the module is being run
as the "__main__" module. Optionally, provide args or kwargs with which to
call the function. If `module` is "__main__", the f... | AutomainRequiresModuleError |
python | ipython__ipython | IPython/core/history.py | {
"start": 19436,
"end": 19613
} | class ____:
output_type: typing.Literal[
"out_stream", "err_stream", "display_data", "execute_result"
]
bundle: typing.Dict[str, str | list[str]]
| HistoryOutput |
python | doocs__leetcode | solution/0300-0399/0342.Power of Four/Solution.py | {
"start": 0,
"end": 131
} | class ____:
def isPowerOfFour(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0
| Solution |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 19508,
"end": 20125
} | class ____(TestCase):
def test_init(self):
try:
foo = FacetIntegerField(model_attr="foo")
foo_exact = FacetIntegerField(facet_for="bar")
except:
self.fail()
self.assertEqual(foo.facet_for, None)
self.assertEqual(foo_exact.null, True)
self.... | FacetIntegerFieldTestCase |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 36628,
"end": 37728
} | class ____(_MagiclinkReferencePattern):
"""Convert #1, !1, and commit_hash."""
ANCESTOR_EXCLUDES = ('a',)
def handleMatch(self, m, data):
"""Handle email link patterns."""
# We don't have a valid provider, user, and repo, reject
if not self.user or not self.repo:
retur... | MagiclinkInternalRefsPattern |
python | yaml__pyyaml | lib/yaml/constructor.py | {
"start": 314,
"end": 6501
} | class ____:
yaml_constructors = {}
yaml_multi_constructors = {}
def __init__(self):
self.constructed_objects = {}
self.recursive_objects = {}
self.state_generators = []
self.deep_construct = False
def check_data(self):
# If there are more documents available?
... | BaseConstructor |
python | walkccc__LeetCode | solutions/748. Shortest Completing Word/748.py | {
"start": 0,
"end": 527
} | class ____:
def shortestCompletingWord(self, licensePlate: str, words: list[str]) -> str:
def isMatch(word: str) -> bool:
wordCount = collections.Counter(word)
return False if any(
wordCount[i] < count[i] for i in string.ascii_letters) else True
ans = '*' * 16
count = collections.de... | Solution |
python | huggingface__transformers | src/transformers/models/pegasus_x/modeling_pegasus_x.py | {
"start": 27933,
"end": 32986
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: PegasusXConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = PegasusXAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_he... | PegasusXDecoderLayer |
python | vyperlang__vyper | vyper/venom/analysis/cfg.py | {
"start": 212,
"end": 4501
} | class ____(IRAnalysis):
"""
Compute control flow graph information for each basic block in the function.
"""
_dfs: OrderedSet[IRBasicBlock]
_cfg_in: MutableMapping[IRBasicBlock, OrderedSet[IRBasicBlock]]
_cfg_out: MutableMapping[IRBasicBlock, OrderedSet[IRBasicBlock]]
_reachable: MutableMap... | CFGAnalysis |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 46036,
"end": 50478
} | class ____(Colormap):
"""
Colormap object generated from a list of colors.
This may be most useful when indexing directly into a colormap,
but it can also be used to generate special colormaps for ordinary
mapping.
Parameters
----------
colors : list of :mpltype:`color` or array
... | ListedColormap |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_stateful.py | {
"start": 9226,
"end": 10256
} | class ____(RuleBasedStateMachine):
values = Bundle("values")
def __init__(self):
super().__init__()
self.called = False
@rule(target=values, value=st.just([]) | st.lists(values))
def f(self, value):
assert not self.called
# ensure we get two calls to f before failing. I... | SourceSameAsTargetUnclearOrigin |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 75917,
"end": 81527
} | class ____(Request):
"""
Creates a new dataset with an initial (empty) version
:param name: Dataset name. Unique within the company.
:type name: str
:param comment: Dataset comment
:type comment: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: S... | CreateRequest |
python | great-expectations__great_expectations | tests/expectations/test_expectation.py | {
"start": 1504,
"end": 1607
} | class ____(MulticolumnMapExpectation):
map_metric = "fake_multicol_metric"
| FakeMulticolumnExpectation |
python | eth-brownie__brownie | brownie/project/main.py | {
"start": 24750,
"end": 43486
} | class ____(_ProjectBase):
"""Simplified Project class used to hold temporary contracts that are
compiled via project.compile_source"""
def __init__(self, name: str, contract_sources: Dict, compiler_config: CompilerConfig) -> None:
self._path = None
self._build_path = None
self._name... | TempProject |
python | walkccc__LeetCode | solutions/2050. Parallel Courses III/2050.py | {
"start": 0,
"end": 665
} | class ____:
def minimumTime(
self,
n: int,
relations: list[list[int]],
time: list[int],
) -> int:
graph = [[] for _ in range(n)]
inDegrees = [0] * n
dist = time.copy()
# Build the graph.
for a, b in relations:
u = a - 1
v = b - 1
graph[u].append(v)
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 14206,
"end": 15038
} | class ____(Metafield):
"""
{
orders(query: "updated_at:>='2023-02-07T00:00:00+00:00' AND updated_at:<='2023-12-04T00:00:00+00:00'", sortKey: UPDATED_AT) {
edges {
node {
id
metafields {
edges {
... | MetafieldOrder |
python | cython__cython | Cython/Build/Tests/TestCythonizeArgsParser.py | {
"start": 313,
"end": 18614
} | class ____(TestCase):
def setUp(self):
TestCase.setUp(self)
self.parse_args = lambda x, parser=create_args_parser() : parse_args_raw(parser, x)
def are_default(self, options, skip):
# empty containers
empty_containers = ['directives', 'compile_time_env', 'options', 'excludes']... | TestCythonizeArgsParser |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 35337,
"end": 36508
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"keywords": 9000, "dynamic": ["keywords"]}})
with pytest.raises(
ValueError,
match="Metadata field `keywords` cannot be both statically defined and listed in field `p... | TestKeywords |
python | tiangolo__fastapi | tests/test_duplicate_models_openapi.py | {
"start": 195,
"end": 2159
} | class ____(BaseModel):
c: Model
d: Model2
@app.get("/", response_model=Model3)
def f():
return {"c": {}, "d": {"a": {}}}
client = TestClient(app)
def test_get_api_route():
response = client.get("/")
assert response.status_code == 200, response.text
assert response.json() == {"c": {}, "d": ... | Model3 |
python | getsentry__sentry | tests/sentry/uptime/endpoints/test_organization_uptime_alert_index.py | {
"start": 377,
"end": 3905
} | class ____(OrganizationUptimeAlertIndexBaseEndpointTest):
method = "get"
def check_valid_response(self, response, expected_detectors):
assert [
serialize(uptime_alert, serializer=UptimeDetectorSerializer())
for uptime_alert in expected_detectors
] == response.data
d... | OrganizationUptimeAlertIndexEndpointTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_1.py | {
"start": 367,
"end": 409
} | class ____(BaseModel):
x: pathlib.Path
| C |
python | plotly__plotly.py | plotly/graph_objs/funnel/_insidetextfont.py | {
"start": 233,
"end": 17179
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnel"
_path_str = "funnel.insidetextfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
... | Insidetextfont |
python | pytorch__pytorch | torch/_inductor/codegen/cpp.py | {
"start": 184179,
"end": 221606
} | class ____(BaseScheduling):
# Subclass CppKernelProxy to customize codegen without copying codegen_node().
# Use kernel_proxy_cls to inject custom proxies in CppScheduling subclasses.
# Avoid duplicating codegen_node() just to swap in a custom kernel proxy class.
kernel_proxy_cls: type[CppKernelProxy] =... | CppScheduling |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 8162,
"end": 10374
} | class ____(LossFunctionWrapper):
"""Computes the cosine similarity between `y_true` & `y_pred`.
Note that it is a number between -1 and 1. When it is a negative number
between -1 and 0, 0 indicates orthogonality and values closer to -1
indicate greater similarity. This makes it usable as a loss functio... | CosineSimilarity |
python | joke2k__faker | faker/providers/job/sk_SK/__init__.py | {
"start": 41,
"end": 16519
} | class ____(JobProvider):
"""Translated from Super class"""
jobs = (
"Administrátor, umenie",
"Administrátor, štátna služba",
"Advokát",
"Advokát pre ochranné známky",
"Akademický knihovník",
"Akupunkturista",
"Analytický chemik",
"Analytik finančn... | Provider |
python | eventlet__eventlet | tests/isolated/wsgi_connection_timeout.py | {
"start": 998,
"end": 1149
} | class ____:
@staticmethod
def write(s):
output_buffer.append(s.rstrip())
return len(s)
# This test might make you wince
| BufferLog |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton_addmm.py | {
"start": 231,
"end": 1085
} | class ____(TemplateConfigHeuristics):
"""
Simple mixin to handle scalars for addmm like operators (addmm, baddbmm)
"""
def get_extra_kwargs(
self,
kernel_inputs: KernelInputs,
op_name: str,
) -> dict[str, Any]:
kwargs = super().get_extra_kwargs(kernel_inputs, op_name... | AddMMConfigMixin |
python | mwaskom__seaborn | seaborn/_core/properties.py | {
"start": 20183,
"end": 26959
} | class ____(Property):
"""Color, as RGB(A), scalable with nominal palettes or continuous gradients."""
legend = True
normed = True
def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple:
# Return color with alpha channel only if the input spec has it
# This is so that RGBA colors ... | Color |
python | great-expectations__great_expectations | scripts/cleanup/cleanup_big_query.py | {
"start": 299,
"end": 2224
} | class ____(BaseSettings):
"""Environment variables for BigQuery connection.
These are injected in via CI, but when running locally, you may use your own credentials.
GOOGLE_APPLICATION_CREDENTIALS must be kept secret
"""
GE_TEST_GCP_PROJECT: str
GE_TEST_BIGQUERY_DATASET: str
GOOGLE_APPLICAT... | BigQueryConnectionConfig |
python | apache__airflow | dev/breeze/tests/test_release_date_validation.py | {
"start": 910,
"end": 2676
} | class ____:
"""Test validation of planned release date format YYYY_MM_DD[_NN]."""
@pytest.mark.parametrize(
"date_value",
[
"2025-11-16",
"2025-11-16_01",
"2025-11-16_99",
"2025-01-01",
"2024-02-29", # Leap year
"2025-12-3... | TestPlannedReleaseDateValidation |
python | py-pdf__pypdf | pypdf/_crypt_providers/_base.py | {
"start": 1480,
"end": 1670
} | class ____:
def encrypt(self, data: bytes) -> bytes: # pragma: no cover
return data
def decrypt(self, data: bytes) -> bytes: # pragma: no cover
return data
| CryptBase |
python | python-markdown__markdown | scripts/griffe_extensions.py | {
"start": 1656,
"end": 4122
} | class ____(Extension):
""" Griffe extension to insert a table of processor priority in specified functions. """
def __init__(self, paths: list[str] | None = None) -> None:
super().__init__()
self.paths = paths
def linked_obj(self, value: str, path: str) -> str:
""" Wrap object name... | PriorityTableExtension |
python | viewflow__viewflow | viewflow/workflow/migrations/0002_fsmchange.py | {
"start": 565,
"end": 935
} | class ____(migrations.Migration):
dependencies = [
("viewflow", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="task",
name="comments",
field=models.TextField(blank=True, null=True),
preserve_default=True,
),
... | Migration |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 19562,
"end": 19634
} | class ____(Sam2VideoPromptEncoder):
pass
| Sam3TrackerVideoPromptEncoder |
python | doocs__leetcode | solution/2500-2599/2568.Minimum Impossible OR/Solution.py | {
"start": 0,
"end": 159
} | class ____:
def minImpossibleOR(self, nums: List[int]) -> int:
s = set(nums)
return next(1 << i for i in range(32) if 1 << i not in s)
| Solution |
python | getsentry__sentry | src/sentry/seer/endpoints/organization_seer_explorer_update.py | {
"start": 838,
"end": 2602
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
permission_classes = (OrganizationSeerExplorerUpdatePermission,)
def post(self, request: Request, organization: Organization, run_id: int) -> Response:
"""
Se... | OrganizationSeerExplorerUpdateEndpoint |
python | django__django | django/core/exceptions.py | {
"start": 109,
"end": 208
} | class ____(Exception):
"""The requested model field does not exist"""
pass
| FieldDoesNotExist |
python | django__django | tests/model_formsets_regress/tests.py | {
"start": 12563,
"end": 12803
} | class ____(forms.ModelForm):
class Meta:
model = UserSite
fields = "__all__"
widgets = {
"id": CustomWidget,
"data": CustomWidget,
}
localized_fields = ("data",)
| UserSiteForm |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 15377,
"end": 28815
} | class ____(ValueError):
"""
Exception raised by _rewrite_gamma. Mainly for internal use.
"""
pass
def _rewrite_gamma(f, s, a, b):
"""
Try to rewrite the product f(s) as a product of gamma functions,
so that the inverse Mellin transform of f can be expressed as a meijer
G function.
... | MellinTransformStripError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 72382,
"end": 77026
} | class ____(SchemaType, Emulated, TypeEngine[bool]):
"""A bool datatype.
:class:`.Boolean` typically uses BOOLEAN or SMALLINT on the DDL side,
and on the Python side deals in ``True`` or ``False``.
The :class:`.Boolean` datatype currently has two levels of assertion
that the values persisted are si... | Boolean |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-postgres/llama_index/storage/kvstore/postgres/base.py | {
"start": 1827,
"end": 14932
} | class ____(BaseKVStore):
"""
Postgres Key-Value store.
Args:
connection_string (str): psycopg2 connection string
async_connection_string (str): asyncpg connection string
table_name (str): table name
schema_name (Optional[str]): schema name
perform_setup (Optional[boo... | PostgresKVStore |
python | django-debug-toolbar__django-debug-toolbar | tests/test_utils.py | {
"start": 1852,
"end": 3916
} | class ____(unittest.TestCase):
@override_settings(DEBUG_TOOLBAR_CONFIG={"HIDE_IN_STACKTRACES": []})
def test_get_stack_trace_skip(self):
stack_trace = get_stack_trace(skip=-1)
self.assertTrue(len(stack_trace) > 2)
self.assertEqual(stack_trace[-1][0], debug_toolbar.utils.__file__)
... | StackTraceTestCase |
python | pypa__pip | src/pip/_vendor/rich/color.py | {
"start": 6436,
"end": 18209
} | class ____(NamedTuple):
"""Terminal color definition."""
name: str
"""The name of the color (typically the input to Color.parse)."""
type: ColorType
"""The type of the color."""
number: Optional[int] = None
"""The color number, if a standard color, or None."""
triplet: Optional[ColorTri... | Color |
python | matplotlib__matplotlib | lib/matplotlib/lines.py | {
"start": 49680,
"end": 55210
} | class ____(Line2D):
"""
A helper class that implements `~.Axes.axline`, by recomputing the artist
transform at draw time.
"""
def __init__(self, xy1, xy2, slope, **kwargs):
"""
Parameters
----------
xy1 : (float, float)
The first set of (x, y) coordinates... | AxLine |
python | scikit-image__scikit-image | src/skimage/feature/_fisher_vector.py | {
"start": 1201,
"end": 10511
} | class ____(FisherVectorException):
pass
def learn_gmm(descriptors, *, n_modes=32, gm_args=None):
"""Estimate a Gaussian mixture model (GMM) given a set of descriptors and
number of modes (i.e. Gaussians). This function is essentially a wrapper
around the scikit-learn implementation of GMM, namely the
... | DescriptorException |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/relu_op_test.py | {
"start": 1482,
"end": 7493
} | class ____(test.TestCase):
def _npRelu(self, np_features):
return np.maximum(np_features, np.zeros(np_features.shape))
def testNpRelu(self):
self.assertAllClose(
np.array([[0.0, 0.7, 0.0, 0.3, 0.0], [0.1, 0.0, 0.5, 0.0, 0.9]]),
self._npRelu(
np.array([[-0.9, 0.7, -0.5, 0.3, -0.... | ReluTest |
python | facebook__pyre-check | client/command_arguments.py | {
"start": 8791,
"end": 8915
} | class ____:
output: Optional[Path] = None
server_log_count: Optional[int] = None
@dataclass(frozen=True)
| RageArguments |
python | realpython__materials | python-double-underscore/mangling.py | {
"start": 126,
"end": 661
} | class ____(A):
def __init__(self):
super().__init__()
self.__attr = 1 # Doesn't override A.__attr
def __method(self): # Doesn't override A.__method()
print("B.__attr = ", self.__attr)
if __name__ == "__main__":
a = A()
b = B()
# Call the mangled methods
print(f"{a._... | B |
python | docker__docker-py | docker/transport/sshconn.py | {
"start": 3181,
"end": 4545
} | class ____(urllib3.connectionpool.HTTPConnectionPool):
scheme = 'ssh'
def __init__(self, ssh_client=None, timeout=60, maxsize=10, host=None):
super().__init__(
'localhost', timeout=timeout, maxsize=maxsize
)
self.ssh_transport = None
self.timeout = timeout
if... | SSHConnectionPool |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 167177,
"end": 168071
} | class ____:
def test_cache_policy_init_to_none_when_not_persisting_results(self):
@task(persist_result=False)
def my_task():
pass
assert my_task.cache_policy is NO_CACHE
def test_cache_policy_init_to_default_when_persisting_results(self):
@task(persist_result=True)
... | TestCachePolicies |
python | ray-project__ray | rllib/algorithms/tests/test_algorithm.py | {
"start": 1006,
"end": 23627
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
register_env("multi_cart", lambda cfg: MultiAgentCartPole(cfg))
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_add_module_and_remove_module(self):
config = (
ppo.PP... | TestAlgorithm |
python | mwaskom__seaborn | tests/_core/test_properties.py | {
"start": 19162,
"end": 19366
} | class ____(IntervalBase):
prop = LineWidth
def test_rcparam_default(self):
with mpl.rc_context({"lines.linewidth": 2}):
assert self.prop().default_range == (1, 4)
| TestLineWidth |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.