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 | google__pytype | pytype/tools/analyze_project/pytype_runner_test.py | {
"start": 1501,
"end": 2080
} | class ____(unittest.TestCase):
"""Test resolved_file_to_module."""
def test_basic(self):
resolved_file = Local('foo/bar.py', 'bar.py', 'bar')
self.assertEqual(
pytype_runner.resolved_file_to_module(resolved_file),
Module('foo/', 'bar.py', 'bar', 'Local'),
)
def test_preserve_init(sel... | TestResolvedFileToModule |
python | numba__numba | versioneer.py | {
"start": 22130,
"end": 65126
} | class ____(Exception):
"""Exception raised if a method is not valid for the current scenario."""
LONG_VERSION_PY: Dict[str, str] = {}
HANDLERS: Dict[str, Dict[str, Callable]] = {}
def register_vcs_handler(vcs, method): # decorator
"""Create decorator to mark a method as the handler of a VCS."""
def dec... | NotThisMethod |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/asm.py | {
"start": 458,
"end": 703
} | class ____(c_preproc.c_parser):
def filter_comments(self, node):
code = node.read()
code = c_preproc.re_nl.sub('', code)
code = c_preproc.re_cpp.sub(c_preproc.repl, code)
return re_lines.findall(code)
| asm_parser |
python | PrefectHQ__prefect | src/prefect/filesystems.py | {
"start": 12099,
"end": 18280
} | class ____(WritableFileSystem, WritableDeploymentStorage):
"""
Store data as a file on a remote file system.
Supports any remote file system supported by `fsspec`. The file system is specified
using a protocol. For example, "s3://my-bucket/my-folder/" will use S3.
Example:
Load stored remo... | RemoteFileSystem |
python | getsentry__sentry | tests/acceptance/test_oauth_authorize.py | {
"start": 117,
"end": 566
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com", is_superuser=True)
self.login_as(self.user)
def test_simple(self) -> None:
self.browser.get("/debug/oauth/authorize/")
self.browser.wait_until_not(".l... | OAuthAuthorizeTest |
python | google__jax | jax/experimental/jax2tf/examples/keras_reuse_main_test.py | {
"start": 945,
"end": 1702
} | class ____(tf_test_util.JaxToTfTestCase):
def setUp(self):
super().setUp()
FLAGS.model_path = os.path.join(absltest.get_default_test_tmpdir(),
"saved_models")
FLAGS.num_epochs = 1
FLAGS.test_savedmodel = True
FLAGS.mock_data = True
FLAGS.show_images = False... | KerasReuseMainTest |
python | doocs__leetcode | solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution3.py | {
"start": 0,
"end": 307
} | class ____:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
cost = l = 0
for a, b in zip(s, t):
cost += abs(ord(a) - ord(b))
if cost > maxCost:
cost -= abs(ord(s[l]) - ord(t[l]))
l += 1
return len(s) - l
| Solution |
python | conda__conda | conda/base/constants.py | {
"start": 5028,
"end": 5181
} | class ____(Enum):
disabled = "disabled"
warn = "warn"
enabled = "enabled"
def __str__(self) -> str:
return self.value
| SafetyChecks |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 964,
"end": 1071
} | class ____(HTTPError):
"""Raised when SSL certificate fails in an HTTPS connection."""
pass
| SSLError |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/lexers/pygments.py | {
"start": 4517,
"end": 11928
} | class ____(Lexer):
"""
Lexer that calls a pygments lexer.
Example::
from pygments.lexers.html import HtmlLexer
lexer = PygmentsLexer(HtmlLexer)
Note: Don't forget to also load a Pygments compatible style. E.g.::
from prompt_toolkit.styles.from_pygments import style_from_pygme... | PygmentsLexer |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/api_connexion/exceptions.py | {
"start": 5252,
"end": 5783
} | class ____(ProblemException):
"""Returns a response body and status code for HTTP 500 exception."""
def __init__(
self,
title: str = "Internal Server Error",
detail: str | None = None,
headers: dict | None = None,
**kwargs: Any,
) -> None:
super().__init__(
... | Unknown |
python | Netflix__metaflow | test/unit/inheritance/flows/comprehensive_diamond_flow.py | {
"start": 461,
"end": 1796
} | class ____(BaseC):
"""
Comprehensive diamond inheritance flow.
Verifies:
- MRO correctly resolves diamond pattern
- Parameters from all branches accessible (param_a, param_b, param_c, final_param)
- Configs from all branches accessible (config_a, config_b, config_c)
- Steps from BaseA execu... | ComprehensiveDiamondFlow |
python | spack__spack | lib/spack/spack/operating_systems/_operating_system.py | {
"start": 199,
"end": 1434
} | class ____:
"""Base class for all the Operating Systems.
On a multiple architecture machine, the architecture spec field can be set to
build a package against any target and operating system that is present on the
platform. On Cray platforms or any other architecture that has different front
and ba... | OperatingSystem |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 28423,
"end": 29196
} | class ____(TableDropDDL):
"""'DROP VIEW' construct.
.. versionadded:: 2.1 the :class:`.DropView` construct became public
and was renamed from ``_DropView``.
"""
__visit_name__ = "drop_view"
materialized: bool
"""Boolean flag indicating if this is a materialized view."""
def __ini... | DropView |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/stateful_reward.py | {
"start": 412,
"end": 5121
} | class ____(
gym.Wrapper[ObsType, ActType, ObsType, ActType], gym.utils.RecordConstructorArgs
):
r"""Normalizes immediate rewards such that their exponential moving average has an approximately fixed variance.
The property `_update_running_mean` allows to freeze/continue the running mean calculation of the ... | NormalizeReward |
python | django__django | django/db/models/functions/datetime.py | {
"start": 1010,
"end": 4323
} | class ____(TimezoneMixin, Transform):
lookup_name = None
output_field = IntegerField()
def __init__(self, expression, lookup_name=None, tzinfo=None, **extra):
if self.lookup_name is None:
self.lookup_name = lookup_name
if self.lookup_name is None:
raise ValueError("l... | Extract |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/core/dbt_cli_invocation.py | {
"start": 1655,
"end": 2059
} | class ____(NamedTuple):
"""Relation metadata queried from a database."""
name: str
columns: list[BaseColumn]
def _get_relation_from_adapter(adapter: BaseAdapter, relation_key: RelationKey) -> BaseRelation:
return adapter.Relation.create(
database=relation_key.database,
schema=relation... | RelationData |
python | django__django | tests/admin_views/tests.py | {
"start": 220243,
"end": 235199
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.collector = Collector.objects.create(pk=1, name="John Fowles")
def setUp(self):
self.pos... | AdminInlineTests |
python | python-openxml__python-docx | tests/oxml/unitdata/section.py | {
"start": 344,
"end": 483
} | class ____(BaseBuilder):
__tag__ = "w:pgSz"
__nspfxs__ = ("w",)
__attrs__ = ("w:w", "w:h", "w:orient", "w:code")
| CT_PageSzBuilder |
python | getsentry__sentry | src/sentry/feedback/endpoints/project_user_reports.py | {
"start": 1069,
"end": 1230
} | class ____(serializers.ModelSerializer):
class Meta:
model = UserReport
fields = ("name", "email", "comments", "event_id")
| UserReportSerializer |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 48885,
"end": 49411
} | class ____(fixtures.MappedTest):
def test_config_errors(self):
sm = sessionmaker()
def go():
s = sm()
s._is_asyncio = True
return s
Session = scoped_session(go)
with expect_deprecated(
"Using `scoped_session` with asyncio is deprecat... | DeprecationScopedSessionTest |
python | jina-ai__jina | tests/integration/inspect_deployments_flow/test_inspect_deployments_flow.py | {
"start": 123,
"end": 437
} | class ____(Executor):
tag = 1
@requests(on=['/index'])
def craft(self, docs, *args, **kwargs):
tmp_dir = os.environ.get('TEST_EVAL_FLOW_TMPDIR')
with open(f'{tmp_dir}/{self.tag}.txt', 'a', encoding='utf-8') as fp:
fp.write(f'{docs[0].id}')
return None
| DummyEvaluator1 |
python | getsentry__sentry | src/sentry/sentry_metrics/configuration.py | {
"start": 668,
"end": 1221
} | class ____(Enum):
RELEASE_HEALTH = "release-health"
PERFORMANCE = "performance"
# Rate limiter namespaces, the postgres (PG)
# values are the same as UseCaseKey to keep
# backwards compatibility
RELEASE_HEALTH_PG_NAMESPACE = "releasehealth"
PERFORMANCE_PG_NAMESPACE = "performance"
RELEASE_HEALTH_SCHEMA_VALID... | UseCaseKey |
python | django-guardian__django-guardian | guardian/testapp/tests/test_admin.py | {
"start": 13146,
"end": 19732
} | class ____(TestCase):
def _get_gma(self, attrs=None, name=None, model=None):
"""
Returns ``GuardedModelAdmin`` instance.
"""
attrs = attrs or {}
name = str(name or "GMA")
model = model or User
GMA = type(name, (GuardedModelAdmin,), attrs)
gma = GMA(mod... | GuardedModelAdminTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 10218,
"end": 10435
} | class ____:
def f():
x = 1
def g():
return 1
return 2
def f():
class Baz:
x = 1
def g():
return 1
return 2
# end
| Bar |
python | lepture__authlib | authlib/oauth2/rfc9207/parameter.py | {
"start": 173,
"end": 1695
} | class ____:
def __call__(self, authorization_server):
if isinstance(authorization_server, BaseGrant):
deprecate(
"IssueParameter should be used as an authorization server extension with 'authorization_server.register_extension(IssueParameter())'.",
version="1.8",
... | IssuerParameter |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator.py | {
"start": 7251,
"end": 11564
} | class ____(object):
"""Hold a function to be scheduled and its arguments."""
def __init__(self, function, cancellation_mgr, args=None, kwargs=None):
if not callable(function):
raise ValueError("Function passed to `ClusterCoordinator.schedule` must "
"be a callable object.")
sel... | Closure |
python | bokeh__bokeh | src/bokeh/models/plots.py | {
"start": 35491,
"end": 37054
} | class ____(_list_attr_splat):
def __setattr__(self, attr, value):
if not len(self):
from ..util.warnings import warn
warn(_LEGEND_EMPTY_WARNING % attr)
return super().__setattr__(attr, value)
def _select_helper(args, kwargs):
""" Allow flexible selector syntax.
Ret... | _legend_attr_splat |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/recompose_on_mount.py | {
"start": 539,
"end": 768
} | class ____(Screen):
def compose(self) -> ComposeResult:
"""Create child widgets for the app."""
yield Header()
yield Static(" Profile ", id="title")
yield Profile()
yield Footer()
| Landing |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 6489,
"end": 6781
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
self.count = 3
def forward(self, x):
for _ in range(self.count):
x = torch.sigmoid(self.linear1(x))
return x
| ConstLoop |
python | davidhalter__jedi | jedi/inference/compiled/mixed.py | {
"start": 3497,
"end": 3640
} | class ____(CompiledContext, TreeContextMixin):
@property
def compiled_value(self):
return self._value.compiled_value
| MixedContext |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 232,
"end": 314
} | class ____(JoseError):
error = "unsupported_algorithm"
| UnsupportedAlgorithmError |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/pypy/pypy3.py | {
"start": 481,
"end": 2010
} | class ____(PyPy3, PosixSupports):
"""PyPy 3 on POSIX."""
@classmethod
def _shared_libs(cls, python_dir):
# glob for libpypy3-c.so, libpypy3-c.dylib, libpypy3.9-c.so ...
return python_dir.glob("libpypy3*.*")
def to_lib(self, src):
return self.dest / "lib" / src.name
@classm... | PyPy3Posix |
python | jazzband__tablib | src/tablib/exceptions.py | {
"start": 402,
"end": 540
} | class ____(TablibException, AttributeError):
"""Header parameter must be given when appending a column to this Dataset."""
| HeadersNeeded |
python | pydantic__pydantic | tests/typechecking/decorators.py | {
"start": 3833,
"end": 4932
} | class ____(BaseModel):
"""Same tests should apply to `mode='plain'`."""
@field_validator('foo', mode='before')
def no_classmethod(self, value: Any) -> Any:
"""TODO this shouldn't be valid, the decorator should only work on classmethods.
We might want to do the same type checking as wrap mo... | BeforeFieldValidator |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 3253,
"end": 4127
} | class ____(AnalysisResult):
module_t: "ModuleT"
alias: str
# import_node: vy_ast._ImportStmt # maybe could be useful
ownership: ModuleOwnership = ModuleOwnership.NO_OWNERSHIP
ownership_decl: Optional[vy_ast.VyperNode] = None
@property
def module_node(self):
return self.module_t._mod... | ModuleInfo |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 7531,
"end": 7676
} | class ____(TestPickleItemExporter):
item_class = MyDataClass
custom_field_item_class = CustomFieldDataclass
| TestPickleItemExporterDataclass |
python | tensorflow__tensorflow | tensorflow/python/distribute/shared_variable_creator_test.py | {
"start": 1630,
"end": 2454
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def testSharedVariable(self):
shared_variable_store = {}
num_devices = 3
creator_fns = []
for i in range(num_devices):
creator_fn = shared_variable_creator.make_fn(shared_variable_store, i)
creator_fns.append(creator_fn... | SharedVariableCreatorTest |
python | psf__requests | tests/test_requests.py | {
"start": 94623,
"end": 106562
} | class ____:
@pytest.mark.parametrize(
"url,expected",
(
("http://google.com", "http://google.com/"),
("http://ジェーピーニック.jp", "http://xn--hckqz9bzb1cyrb.jp/"),
("http://xn--n3h.net/", "http://xn--n3h.net/"),
("http://ジェーピーニック.jp".encode(), "http://xn--hc... | TestPreparingURLs |
python | python-poetry__poetry | src/poetry/utils/helpers.py | {
"start": 3185,
"end": 4514
} | class ____(Exception):
"""Raised when server unexpectedly supports byte ranges."""
def download_file(
url: str,
dest: Path,
*,
session: Authenticator | Session | None = None,
chunk_size: int = 1024,
raise_accepts_ranges: bool = False,
max_retries: int = 0,
) -> None:
from poetry.pu... | HTTPRangeRequestSupportedError |
python | lepture__authlib | authlib/jose/rfc7517/key_set.py | {
"start": 49,
"end": 1606
} | class ____:
"""This class represents a JSON Web Key Set."""
def __init__(self, keys):
self.keys = keys
def as_dict(self, is_private=False, **params):
"""Represent this key as a dict of the JSON Web Key Set."""
return {"keys": [k.as_dict(is_private, **params) for k in self.keys]}
... | KeySet |
python | pallets__jinja | tests/test_api.py | {
"start": 8986,
"end": 15601
} | class ____:
def test_stopiteration_is_undefined(self):
def test():
raise StopIteration()
t = Template("A{{ test() }}B")
assert t.render(test=test) == "AB"
t = Template("A{{ test().missingattribute }}B")
pytest.raises(UndefinedError, t.render, test=test)
def ... | TestUndefined |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/gather_nd_op_test.py | {
"start": 1795,
"end": 18043
} | class ____(test.TestCase):
def _testSimpleDtype(self, dtype, itype):
with self.cached_session():
params = constant_op.constant(np.array([8, 1, 2, 3, 7, 5], dtype=dtype))
indices = constant_op.constant([[4], [4], [0]], dtype=itype)
gather_nd_t = array_ops.gather_nd(params, indices)
gather_... | GatherNdTest |
python | mlflow__mlflow | tests/langgraph/sample_code/langgraph_chat_agent.py | {
"start": 3404,
"end": 4762
} | class ____(ChatAgent):
def __init__(self, agent: CompiledStateGraph):
self.agent = agent
def predict(
self,
messages: list[ChatAgentMessage],
context: ChatContext | None = None,
custom_inputs: dict[str, Any] | None = None,
) -> ChatAgentResponse:
request = {"... | LangGraphChatAgent |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 144001,
"end": 146003
} | class ____(Response):
"""
Response of events.get_task_single_value_metrics endpoint.
:param tasks: Single value metrics grouped by task
:type tasks: Sequence[dict]
"""
_service = "events"
_action = "get_task_single_value_metrics"
_version = "2.23"
_schema = {
"definitions":... | GetTaskSingleValueMetricsResponse |
python | walkccc__LeetCode | solutions/314. Binary Tree Vertical Order Traversal/314.py | {
"start": 0,
"end": 770
} | class ____:
def verticalOrder(self, root: TreeNode | None) -> list[list[int]]:
if not root:
return []
range_ = [0] * 2
def getRange(root: TreeNode | None, x: int) -> None:
if not root:
return
range_[0] = min(range_[0], x)
range_[1] = max(range_[1], x)
getRange(roo... | Solution |
python | marshmallow-code__marshmallow | tests/test_options.py | {
"start": 73,
"end": 343
} | class ____(Schema):
name = fields.String(allow_none=True)
email = fields.Email(allow_none=True)
age = fields.Integer()
created = fields.DateTime()
id = fields.Integer(allow_none=True)
homepage = fields.Url()
birthdate = fields.Date()
| UserSchema |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/biases/base.py | {
"start": 296,
"end": 554
} | class ____(ABC):
"""
Base class representing the generator of rules connected to a bias.
"""
@abstractmethod
def generate_rules(self, project: Project, base_sample_rate: float) -> list[PolymorphicRule]:
raise NotImplementedError
| Bias |
python | keras-team__keras | keras/src/layers/activations/relu_test.py | {
"start": 112,
"end": 2915
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_relu(self):
self.run_layer_test(
relu.ReLU,
init_kwargs={
"max_value": 10,
"negative_slope": 1,
"threshold": 0.5,
},
input_shape=... | ReLUTest |
python | RaRe-Technologies__gensim | gensim/test/test_scripts.py | {
"start": 767,
"end": 4208
} | class ____(unittest.TestCase):
def setUp(self):
self.fname = datapath('enwiki-latest-pages-articles1.xml-p000000010p000030302-shortened.bz2')
self.expected_title = 'Anarchism'
self.expected_section_titles = [
'Introduction',
'Etymology and terminology',
'... | TestSegmentWiki |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 109144,
"end": 110042
} | class ____(TestCase):
@skipIfNoDill
def test_spawn_lambdas_iter(self):
idp = dp.iter.IterableWrapper(range(3)).map(lambda x: x + 1).shuffle()
dl = DataLoader(
idp,
num_workers=2,
shuffle=True,
multiprocessing_context="spawn",
collate_fn... | TestSerialization |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 60261,
"end": 62117
} | class ____(TypedDict, total=False):
type: Required[Literal['set']]
items_schema: CoreSchema
min_length: int
max_length: int
fail_fast: bool
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def set_schema(
items_schema: CoreSchema | None = None,
*,
... | SetSchema |
python | nedbat__coveragepy | coverage/report.py | {
"start": 652,
"end": 10817
} | class ____:
"""A reporter for writing the summary report."""
def __init__(self, coverage: Coverage) -> None:
self.coverage = coverage
self.config = self.coverage.config
self.branches = coverage.get_data().has_arcs()
self.outfile: IO[str] | None = None
self.output_format ... | SummaryReporter |
python | huggingface__transformers | src/transformers/models/olmoe/modular_olmoe.py | {
"start": 1585,
"end": 1711
} | class ____(LlamaRMSNorm):
def __init__(self, hidden_size, eps=1e-5):
super().__init__(hidden_size, eps)
| OlmoeRMSNorm |
python | google__pytype | pytype/overlays/typing_overlay.py | {
"start": 22746,
"end": 26714
} | class ____(abstract.SimpleValue):
"""Minimal implementation of typing.dataclass_transform."""
def __init__(self, ctx):
super().__init__("<dataclass_transform>", ctx)
def call(self, node, func, args, alias_map=None):
del func, alias_map # unused
arg = args.posargs[0]
for d in arg.data:
if ... | DataclassTransform |
python | huggingface__transformers | tests/models/tvp/test_modeling_tvp.py | {
"start": 1466,
"end": 6404
} | class ____:
def __init__(
self,
parent,
batch_size=1,
seq_length=2,
alpha=1.0,
beta=0.1,
visual_prompter_type="framepad",
visual_prompter_apply="replace",
num_frames=2,
max_img_size=448,
visual_prompt_size=96,
vocab_size... | TVPModelTester |
python | django-compressor__django-compressor | compressor/filters/datauri.py | {
"start": 1638,
"end": 1825
} | class ____(DataUriFilter):
"""Filter for embedding media as data: URIs in CSS files.
See DataUriFilter.
"""
url_patterns = (re.compile(r"url\(([^\)]+)\)"),)
| CssDataUriFilter |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 12822,
"end": 12914
} | class ____(Super):
def __init__(self, a, *args):
super().__init__(a, *args)
| SubTwo |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image08.py | {
"start": 315,
"end": 898
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | numba__numba | numba/core/removerefctpass.py | {
"start": 174,
"end": 3398
} | class ____(CallVisitor):
"""
A pass to mark all NRT_incref and NRT_decref.
"""
def __init__(self):
self.marked = set()
def visit_Call(self, instr):
if getattr(instr.callee, 'name', '') in _accepted_nrtfns:
self.marked.add(instr)
def _rewrite_function(function):
# M... | _MarkNrtCallVisitor |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_connect.py | {
"start": 4495,
"end": 6749
} | class ____(ReadWriteTestMixin):
"""Test the classes CosmologyRead/Write."""
@pytest.fixture(scope="class", params=cosmo_instances)
def cosmo(self, request):
return getattr(cosmology.realizations, request.param)
@pytest.fixture(scope="class")
def cosmo_cls(self, cosmo):
return cosmo... | TestCosmologyReadWrite |
python | kamyu104__LeetCode-Solutions | Python/construct-the-lexicographically-largest-valid-sequence.py | {
"start": 30,
"end": 900
} | class ____(object):
def constructDistancedSequence(self, n):
"""
:type n: int
:rtype: List[int]
"""
def backtracking(n, i, result, lookup):
if i == len(result):
return True
if result[i]:
return backtracking(n, i+1, resul... | Solution |
python | python__mypy | mypy/build.py | {
"start": 120968,
"end": 148810
} | class ____:
"""Some info about a node in the graph of SCCs."""
def __init__(self, index: int, scc: list[str]) -> None:
self.node_id = "n%d" % index
self.scc = scc
self.sizes: dict[str, int] = {} # mod -> size in bytes
self.deps: dict[str, int] = {} # node_id -> pri
def du... | NodeInfo |
python | getsentry__sentry | src/sentry/issues/endpoints/grouping_configs.py | {
"start": 397,
"end": 869
} | class ____(Endpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = ()
def get(self, request: Request, **kwargs) -> Response:
return Response(
serialize(
[
config.as_dict()
... | GroupingConfigsEndpoint |
python | great-expectations__great_expectations | great_expectations/data_context/data_context_variables.py | {
"start": 1131,
"end": 2087
} | class ____(str, enum.Enum):
ALL_VARIABLES = "data_context_variables" # If retrieving/setting the entire config at once
CONFIG_VERSION = "config_version"
DATASOURCES = "datasources"
FLUENT_DATASOURCES = "fluent_datasources"
EXPECTATIONS_STORE_NAME = "expectations_store_name"
VALIDATIONS_STORE_NA... | DataContextVariableSchema |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes11.py | {
"start": 511,
"end": 564
} | class ____(Sequence[float], Mapping[float, int]): ...
| D |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 973933,
"end": 974716
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"email",
"invitee",
"inviter",
"permalink",
"permission",
"repository",
)
email = sgqlc.types.Field(String, graphql_name... | RepositoryInvitation |
python | django__django | django/contrib/postgres/operations.py | {
"start": 3707,
"end": 4058
} | class ____:
def _ensure_not_in_transaction(self, schema_editor):
if schema_editor.connection.in_atomic_block:
raise NotSupportedError(
"The %s operation cannot be executed inside a transaction "
"(set atomic = False on the migration)." % self.__class__.__name__
... | NotInTransactionMixin |
python | jina-ai__jina | jina/serve/instrumentation/__init__.py | {
"start": 5239,
"end": 6869
} | class ____:
"""
Helper dataclass that accepts optional Summary or Histogram recorders which are used to record the time take to execute
the decorated or context managed function
"""
def __init__(
self,
summary_metric: Optional['Summary'],
histogram: Optional['Histogram'],
... | MetricsTimer |
python | huggingface__transformers | tests/models/vits/test_modeling_vits.py | {
"start": 5560,
"end": 15058
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (VitsModel,) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": VitsModel, "text-to-audio": VitsModel} if is_torch_available() else {}
)
is_encoder_decoder = False
test_r... | VitsModelTest |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 1041,
"end": 1131
} | class ____(Enum):
ABOVE = 0
BELOW = 1
ABOVE_AND_BELOW = 2
| AlertRuleThresholdType |
python | jina-ai__jina | jina/excepts.py | {
"start": 2818,
"end": 4579
} | class ____(grpc.aio.AioRpcError, BaseJinaException):
"""
Raised when communication between microservices fails.
Needed to propagate information about the root cause event, such as request_id and dest_addr.
"""
def __init__(
self,
og_exception: grpc.aio.AioRpcError,
request_i... | InternalNetworkError |
python | numpy__numpy | numpy/_core/tests/test_defchararray.py | {
"start": 6190,
"end": 6412
} | class ____(TestComparisons):
"""Ticket #1276"""
def B(self):
return np.array(
[['efg', 'efg', '123 '],
['051', 'efgg', 'tuv']], np.str_).view(np.char.chararray)
| TestComparisonsMixed1 |
python | dask__distributed | distributed/tests/test_active_memory_manager.py | {
"start": 1353,
"end": 42132
} | class ____(ActiveMemoryManagerPolicy):
"""Drop or replicate a key n times"""
def __init__(
self,
action: Literal["drop", "replicate"],
key: str,
n: int,
candidates: list[int] | None,
):
self.action = action
self.key = key
self.n = n
se... | DemoPolicy |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 39160,
"end": 41628
} | class ____(nn.Module):
def __init__(self, config: Sam2VideoConfig):
super().__init__()
self.layers = nn.ModuleList(
[Sam2VideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)]
)
self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_s... | Sam2VideoMemoryAttention |
python | pydantic__pydantic | pydantic-core/tests/validators/test_dataclasses.py | {
"start": 6934,
"end": 8250
} | class ____:
a: str
b: bool
def test_dataclass():
schema = core_schema.dataclass_schema(
FooDataclass,
core_schema.dataclass_args_schema(
'FooDataclass',
[
core_schema.dataclass_field(name='a', schema=core_schema.str_schema()),
core_sc... | FooDataclass |
python | allegroai__clearml | clearml/utilities/enum.py | {
"start": 840,
"end": 1093
} | class ____(object):
"""Base class for an Options class which allow getting all class properties as a key/value mapping"""
@classmethod
def _all(cls) -> Dict[str, Any]:
return {k: v for k, v in vars(cls) if not k.startswith("_")}
| Options |
python | plotly__plotly.py | plotly/graph_objs/scattermapbox/_hoverlabel.py | {
"start": 233,
"end": 11283
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermapbox"
_path_str = "scattermapbox.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namele... | Hoverlabel |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/graph.py | {
"start": 3107,
"end": 3372
} | class ____(NamedTuple):
"""Branch in a graph."""
condition: Callable[..., str]
"""A callable that returns a string representation of the condition."""
ends: dict[str, str] | None
"""Optional dictionary of end node IDs for the branches. """
| Branch |
python | pallets__jinja | src/jinja2/loaders.py | {
"start": 16204,
"end": 17490
} | class ____(BaseLoader):
"""A loader that is passed a function which does the loading. The
function receives the name of the template and has to return either
a string with the template source, a tuple in the form ``(source,
filename, uptodatefunc)`` or `None` if the template does not exist.
>>> de... | FunctionLoader |
python | wandb__wandb | wandb/sdk/data_types/helper_types/image_mask.py | {
"start": 362,
"end": 8878
} | class ____(Media):
"""Format image masks or overlays for logging to W&B.
Args:
val: (dictionary)
One of these two keys to represent the image:
mask_data : (2D numpy array) The mask containing an integer class label
for each pixel in the image
... | ImageMask |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 2833,
"end": 3651
} | class ____(StrEnum):
"""
SentryAppIdentifier is an enum that represents the identifier for a Sentry app.
"""
SENTRY_APP_INSTALLATION_UUID = "sentry_app_installation_uuid"
SENTRY_APP_SLUG = "sentry_app_slug"
SENTRY_APP_ID = "sentry_app_id"
FIELDS_TO_DETECTOR_FIELDS = {
"name": "name",
... | SentryAppIdentifier |
python | django__django | tests/admin_widgets/tests.py | {
"start": 50784,
"end": 50879
} | class ____(DateTimePickerShortcutsSeleniumTests):
pass
| DateTimePickerAltTimezoneSeleniumTests |
python | django__django | tests/backends/base/test_operations.py | {
"start": 6984,
"end": 8327
} | class ____(TransactionTestCase):
available_apps = ["backends"]
def test_sql_flush_no_tables(self):
self.assertEqual(connection.ops.sql_flush(no_style(), []), [])
def test_execute_sql_flush_statements(self):
with transaction.atomic():
author = Author.objects.create(name="George ... | SqlFlushTests |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/resolution.py | {
"start": 732,
"end": 1336
} | class ____:
params = (
["D", "h", "m", "s", "us", "ns"],
_sizes,
_tzs,
)
param_names = ["unit", "size", "tz"]
def setup(self, unit, size, tz):
if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
... | TimeResolution |
python | python-openxml__python-docx | src/docx/text/paragraph.py | {
"start": 652,
"end": 6828
} | class ____(StoryChild):
"""Proxy object wrapping a `<w:p>` element."""
def __init__(self, p: CT_P, parent: t.ProvidesStoryPart):
super(Paragraph, self).__init__(parent)
self._p = self._element = p
def add_run(self, text: str | None = None, style: str | CharacterStyle | None = None) -> Run:... | Paragraph |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 32889,
"end": 33615
} | class ____(AnnotatedConstructorWithSignature):
__signature__ = signature(selfless_signature)
def really_takes_str(value: int) -> None:
"""By this example we show, that ``__signature__`` is the most important source."""
assert isinstance(value, str)
really_takes_str.__signature__ = signature(selfless_sig... | AnnotatedConstructorWithSelflessSignature |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 218231,
"end": 233476
} | class ____(TestCase):
def test_inout(self):
def kernel(ctx, src, inout, dst, smem):
val = memref.load(inout, [])
gpu.barrier()
new_val = arith.constant(ir.IntegerType.get_signless(32), 42)
memref.store(new_val, inout, [])
x = mgpu.FragmentedArray.load_strided(src, is_signed=True)
... | ApiTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor30.py | {
"start": 426,
"end": 665
} | class ____(Generic[P, T]):
def __init__(
self, _type: Callable[P, T], *args: P.args, **kwargs: P.kwargs
) -> None: ...
def func1(t: type[TA]) -> TA: ...
b = B(func1, A)
reveal_type(b, expected_text="B[(t: type[A]), A]")
| B |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_emr.py | {
"start": 10340,
"end": 11565
} | class ____(BaseAwsLinksTestCase):
link_class = EmrServerlessCloudWatchLogsLink
def test_extra_link(self, mock_supervisor_comms):
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=self.link_class.key,
va... | TestEmrServerlessCloudWatchLogsLink |
python | kamyu104__LeetCode-Solutions | Python/lowest-common-ancestor-of-deepest-leaves.py | {
"start": 191,
"end": 738
} | class ____(object):
def lcaDeepestLeaves(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def lcaDeepestLeavesHelper(root):
if not root:
return 0, None
d1, lca1 = lcaDeepestLeavesHelper(root.left)
d2, lca2 = lcaDee... | Solution |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_search_tool_regex_20251119_param.py | {
"start": 350,
"end": 1063
} | class ____(TypedDict, total=False):
name: Required[Literal["tool_search_tool_regex"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["tool_search_tool_regex_20251119", "tool_search_tool_regex"]]
allowed_callers: List[... | BetaToolSearchToolRegex20251119Param |
python | django__django | django/contrib/postgres/forms/ranges.py | {
"start": 3120,
"end": 3295
} | class ____(BaseRangeField):
default_error_messages = {"invalid": _("Enter two numbers.")}
base_field = forms.DecimalField
range_type = NumericRange
| DecimalRangeField |
python | mwaskom__seaborn | tests/_core/test_plot.py | {
"start": 75273,
"end": 77797
} | class ____:
@pytest.fixture(autouse=True)
def reset_config(self):
yield
Plot.config.display.update(PlotConfig().display)
def test_png_format(self):
Plot.config.display["format"] = "png"
assert Plot()._repr_svg_() is None
assert Plot().plot()._repr_svg_() is None
... | TestDisplayConfig |
python | numba__numba | numba/cuda/target.py | {
"start": 14511,
"end": 16837
} | class ____(BaseCallConv):
"""
Calling convention aimed at matching the CUDA C/C++ ABI. The implemented
function signature is:
<Python return type> (<Python arguments>)
Exceptions are unsupported in this convention.
"""
def _make_call_helper(self, builder):
# Call helpers are u... | CUDACABICallConv |
python | jina-ai__jina | jina/jaml/parsers/base.py | {
"start": 1612,
"end": 3169
} | class ____(VersionedYAMLParser, ABC):
"""
BaseLegacyParser for classes that need parameter injection and that will be managed inside a runtime
for instance, :class:`BaseExecutor` and :class:`BaseGateway`
"""
@staticmethod
def _get_all_arguments(class_):
"""
:param class_: targe... | BaseLegacyParser |
python | pypa__pipenv | pipenv/patched/pip/_internal/req/req_file.py | {
"start": 2851,
"end": 3287
} | class ____:
# TODO: replace this with slots=True when dropping Python 3.9 support.
__slots__ = (
"requirement",
"is_editable",
"comes_from",
"constraint",
"options",
"line_source",
)
requirement: str
is_editable: bool
comes_from: str
constrain... | ParsedRequirement |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vision.py | {
"start": 1695,
"end": 5869
} | class ____(GoogleCloudBaseOperator):
"""
Create a new ProductSet resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudVisionCreateProductSetOperator`
:param product_set: (Required) The ProductSet to create. If a di... | CloudVisionCreateProductSetOperator |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 9325,
"end": 9607
} | class ____:
test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "IDEA"),
["idea-cfb.txt"],
lambda key, **kwargs: IDEA(binascii.unhexlify(key)),
lambda iv, **kwargs: CFB(binascii.unhexlify(iv)),
)
| TestIDEAModeCFB |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarinherit.py | {
"start": 573,
"end": 680
} | class ____(np.float64, HasNew):
pass
@skip(reason="scalar repr: numpy plans to make it more explicit")
| B1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.