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
wandb__wandb
wandb/sdk/artifacts/_generated/fragments.py
{ "start": 6836, "end": 7055 }
class ____(GQLResult): total_count: int = Field(alias="totalCount") page_info: PageInfoFragment = Field(alias="pageInfo") edges: List[RunInputArtifactConnectionFragmentEdges]
RunInputArtifactConnectionFragment
python
pikepdf__pikepdf
src/pikepdf/objects.py
{ "start": 5883, "end": 6359 }
class ____(Object, metaclass=_ObjectMeta): """Construct a PDF String object.""" object_type = ObjectType.string def __new__(cls, s: str | bytes) -> String: """Construct a PDF String. Args: s: The string to use. String will be encoded for PDF, bytes will be cons...
String
python
ray-project__ray
python/ray/air/integrations/wandb.py
{ "start": 13605, "end": 17129 }
class ____: """ Wandb assumes that each trial's information should be logged from a separate process. We use Ray actors as forking multiprocessing processes is not supported by Ray and spawn processes run into pickling problems. We use a queue for the driver to communicate with the logging proc...
_WandbLoggingActor
python
keras-team__keras
keras/src/optimizers/rmsprop_test.py
{ "start": 157, "end": 2761 }
class ____(testing.TestCase): def test_config(self): optimizer = RMSprop( learning_rate=0.5, rho=0.8, momentum=0.05, epsilon=1e-6, centered=True, ) self.run_class_serialization_test(optimizer) def test_single_step(self): ...
RMSpropTest
python
django__django
tests/utils_tests/test_autoreload.py
{ "start": 23067, "end": 24457 }
class ____(SimpleTestCase): RELOADER_CLS = None def setUp(self): _tempdir = tempfile.TemporaryDirectory() self.tempdir = Path(_tempdir.name).resolve(strict=True).absolute() self.existing_file = self.ensure_file(self.tempdir / "test.py") self.nonexistent_file = (self.tempdir / "d...
ReloaderTests
python
psf__black
src/black/brackets.py
{ "start": 1080, "end": 1216 }
class ____(Exception): """Raised when an opening bracket is unable to be matched to a closing bracket.""" @dataclass
BracketMatchError
python
walkccc__LeetCode
solutions/678. Valid Parenthesis String/678.py
{ "start": 0, "end": 366 }
class ____: def checkValidString(self, s: str) -> bool: low = 0 high = 0 for c in s: if c == '(': low += 1 high += 1 elif c == ')': if low > 0: low -= 1 high -= 1 else: if low > 0: low -= 1 high += 1 if high < 0: ...
Solution
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 100785, "end": 102900 }
class ____(BasePostProgressGroupMixin): @patch("sentry.tasks.post_process.safe_execute") def test_process_similarity(self, mock_safe_execute: MagicMock) -> None: from sentry import similarity event = self.create_event(data={}, project_id=self.project.id) self.call_post_process_group( ...
ProcessSimilarityTestMixin
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_stateful.py
{ "start": 4115, "end": 4545 }
class ____(RuleBasedStateMachine): ratchet = 0 @rule(d=data()) def action(self, d): FlakyRatchettingMachine.ratchet += 1 n = FlakyRatchettingMachine.ratchet d.draw(lists(integers(), min_size=n, max_size=n)) raise AssertionError @Settings( stateful_step_count=10, ma...
FlakyRatchettingMachine
python
ansible__ansible
lib/ansible/_internal/_json/__init__.py
{ "start": 856, "end": 959 }
class ____(t.Protocol): """Utility protocol for mixin type safety.""" _current: t.Any
HasCurrent
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_check_health.py
{ "start": 644, "end": 9042 }
class ____(LoadableBy[AssetKey]): """Maintains a list of asset checks for the asset in each terminal state. If a check is in progress, it will not move to a new list until the execution is complete. """ passing_checks: set[AssetCheckKey] failing_checks: set[AssetCheckKey] warning_checks: set[As...
AssetCheckHealthState
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 208794, "end": 209581 }
class ____(SocketUDPLITETest): def testUDPLITETimeout(self): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.recv(1024) self.assertRaises(TimeoutError, raise_timeout, "Error generating a timeout exception (UDPLITE)") ...
UDPLITETimeoutTest
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_delayed_workflow.py
{ "start": 10439, "end": 11926 }
class ____(TestDelayedWorkflowBase): def test_fetch_project(self) -> None: assert fetch_project(self.project.id) == self.project assert fetch_project(1) is None def test_fetch_workflows_envs(self) -> None: self._push_base_events() event_data = EventRedisData.from_redis_data( ...
TestDelayedWorkflowHelpers
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_pretty.py
{ "start": 7747, "end": 8030 }
class ____: __module__ = 1 @property def __class__(self): raise ValueError("I am horrible") def __repr__(self): raise BadException def test_really_bad_repr(): with pytest.raises(BadException): pretty.pretty(ReallyBadRepr())
ReallyBadRepr
python
tensorflow__tensorflow
tensorflow/python/ops/boosted_trees_ops.py
{ "start": 7909, "end": 9741 }
class ____(saver.BaseSaverBuilder.SaveableObject): """SaveableObject implementation for TreeEnsemble.""" def __init__(self, resource_handle, create_op, name): """Creates a _TreeEnsembleSavable object. Args: resource_handle: handle to the decision tree ensemble variable. create_op: the op to in...
_TreeEnsembleSavable
python
run-llama__llama_index
llama-index-core/llama_index/core/base/response/schema.py
{ "start": 412, "end": 1285 }
class ____: """ Response object. Returned if streaming=False. Attributes: response: The response text. """ response: Optional[str] source_nodes: List[NodeWithScore] = field(default_factory=list) metadata: Optional[Dict[str, Any]] = None def __str__(self) -> str: ...
Response
python
keras-team__keras
keras/src/metrics/iou_metrics.py
{ "start": 261, "end": 5759 }
class ____(Metric): """Computes the confusion matrix for Intersection-Over-Union metrics. Formula: ```python iou = true_positives / (true_positives + false_positives + false_negatives) ``` Intersection-Over-Union is a common evaluation metric for semantic image segmentation. From IoUs...
_IoUBase
python
jazzband__django-simple-history
simple_history/tests/tests/test_commands.py
{ "start": 6689, "end": 16666 }
class ____(TestCase): command_name = "clean_duplicate_history" command_error = (management.CommandError, SystemExit) def test_no_args(self): out = StringIO() management.call_command(self.command_name, stdout=out, stderr=StringIO()) self.assertIn(clean_duplicate_history.Command.COMMA...
TestCleanDuplicateHistory
python
cython__cython
Cython/Plex/Regexps.py
{ "start": 7411, "end": 8728 }
class ____(RE): """Seq(re1, re2, re3...) is an RE which matches |re1| followed by |re2| followed by |re3|...""" def __init__(self, *re_list): nullable = 1 for i, re in enumerate(re_list): self.check_re(i, re) nullable = nullable and re.nullable self.re_list =...
Seq
python
getsentry__sentry
src/sentry/snuba/metrics/naming_layer/public.py
{ "start": 6053, "end": 6286 }
class ____(Enum): """Identifier for a transaction-related tag.""" TRANSACTION_STATUS = "transaction.status" TRANSACTION_SATISFACTION = "satisfaction" TRANSACTION_HTTP_STATUS_CODE = "http.status_code"
TransactionTagsKey
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 185642, "end": 186716 }
class ____(Response): """ Response of datasets.get_sources endpoint. :param sources: Mapping of source URL to first frame_id of the source :type sources: dict """ _service = "datasets" _action = "get_sources" _version = "2.23" _schema = { "definitions": {}, "proper...
GetSourcesResponse
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 47397, "end": 50708 }
class ____(VCSFetchStrategy): """ Fetch strategy that gets source code from a Mercurial repository. Use like this in a package:: version("name", hg="https://jay.grs.rwth-aachen.de/hg/lwm2") Optionally, you can provide a branch, or revision to check out, e.g.:: version("torus", hg="htt...
HgFetchStrategy
python
coleifer__peewee
tests/sqlite.py
{ "start": 3397, "end": 3515 }
class ____(FTS5Model): message = SearchField() class Meta: options = {'tokenize': 'porter'}
FTS5Document
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/cluster_coordinator.py
{ "start": 12382, "end": 22784 }
class ____(object): """Manage a queue of closures, inflight count and errors from execution. This class is thread-safe. """ def __init__(self): # `self._inflight_closure_count` only tracks the number of inflight closures # that are "in generation". Once an error occurs, error generation is # incre...
_CoordinatedClosureQueue
python
getsentry__sentry
tests/sentry/api/endpoints/test_builtin_symbol_sources.py
{ "start": 617, "end": 1222 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-builtin-symbol-sources" def setUp(self) -> None: super().setUp() self.organization = self.create_organization(owner=self.user) self.login_as(user=self.user) def test_with_slug(self) -> None: resp = self.get_resp...
BuiltinSymbolSourcesWithSlugTest
python
kamyu104__LeetCode-Solutions
Python/minimum-sum-after-divisible-sum-deletions.py
{ "start": 50, "end": 393 }
class ____(object): def minArraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dp = [float("inf")]*k dp[0] = result = 0 for x in nums: result += x dp[result%k] = result = min(result, dp[result%k]) ...
Solution
python
python__mypy
mypyc/test/test_exceptions.py
{ "start": 877, "end": 2133 }
class ____(MypycDataSuite): files = files base_path = test_temp_dir def run_case(self, testcase: DataDrivenTestCase) -> None: """Perform a runtime checking transformation test case.""" with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase): expect...
TestExceptionTransform
python
ray-project__ray
python/ray/data/_internal/execution/node_trackers/actor_location.py
{ "start": 191, "end": 1384 }
class ____: def __init__(self): self._actor_locations = {} self._actor_locations_lock = threading.Lock() def update_actor_location(self, logical_actor_id: str, node_id: str): with self._actor_locations_lock: self._actor_locations[logical_actor_id] = node_id def get_acto...
ActorLocationTracker
python
ipython__ipython
IPython/terminal/interactiveshell.py
{ "start": 6154, "end": 40095 }
class ____(InteractiveShell): mime_renderers = Dict().tag(config=True) min_elide = Integer( 30, help="minimum characters for filling with ellipsis in file completions" ).tag(config=True) space_for_menu = Integer( 6, help="Number of line at the bottom of the screen " "to ...
TerminalInteractiveShell
python
jazzband__tablib
src/tablib/formats/_latex.py
{ "start": 117, "end": 4148 }
class ____: title = 'latex' extensions = ('tex',) TABLE_TEMPLATE = """\ %% Note: add \\usepackage{booktabs} to your preamble %% \\begin{table}[!htbp] \\centering %(CAPTION)s \\begin{tabular}{%(COLSPEC)s} \\toprule %(HEADER)s %(MIDRULE)s %(BODY)s \\bottomrule \\end{tabular} \\end{table} ...
LATEXFormat
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py
{ "start": 170, "end": 1375 }
class ____(Benchmark): r""" Parsopoulos objective function. This class defines the Parsopoulos [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Parsopoulos}}(x) = \cos(x_1)^2 + \sin(x_2)^2 with :math:`x_i \in [-5, 5]...
Parsopoulos
python
PrefectHQ__prefect
tests/cli/test_api_command.py
{ "start": 13534, "end": 15355 }
class ____: """Test output formatting and verbosity.""" def test_json_output(self, respx_mock: MockRouter) -> None: """Test JSON is output correctly.""" respx_mock.get("http://localhost:4200/api/flows/123").mock( return_value=httpx.Response(200, json={"id": "123", "name": "test"}) ...
TestOutputFormatting
python
huggingface__transformers
src/transformers/models/glm4_moe/modeling_glm4_moe.py
{ "start": 21391, "end": 22403 }
class ____(PreTrainedModel): config: Glm4MoeConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Glm4MoeDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True...
Glm4MoePreTrainedModel
python
bokeh__bokeh
src/bokeh/models/nodes.py
{ "start": 1638, "end": 3366 }
class ____: """ Provider of box nodes for box-like models. """ def __init__(self, target: Model | ImplicitTargetType) -> None: self.target = target def _node(self, symbol: str) -> Node: return Node(target=self.target, symbol=symbol) @property def left(self) -> Node: return...
BoxNodes
python
encode__django-rest-framework
tests/test_pagination.py
{ "start": 12437, "end": 22912 }
class ____: """ Unit tests for `pagination.LimitOffsetPagination`. """ def setup_method(self): class ExamplePagination(pagination.LimitOffsetPagination): default_limit = 10 max_limit = 15 self.pagination = ExamplePagination() self.queryset = range(1, 101...
TestLimitOffset
python
ray-project__ray
release/llm_tests/benchmark/load_test.py
{ "start": 7562, "end": 9824 }
class ____(BaseProvider): def get_url(self): if self.parsed_options.chat: return "/v1/chat/completions" else: return "/v1/completions" def format_payload(self, prompt, max_tokens, images): data = { "model": self.model, "max_tokens": max_to...
OpenAIProvider
python
ansible__ansible
lib/ansible/module_utils/_internal/_messages.py
{ "start": 3605, "end": 4307 }
class ____(WarningSummary): """Deprecation summary with details (possibly derived from an exception __cause__ chain) and an optional traceback.""" deprecator: _t.Optional[PluginInfo] = None """ The identifier for the content which is being deprecated. """ date: _t.Optional[str] = None """ ...
DeprecationSummary
python
dagster-io__dagster
python_modules/libraries/dagster-snowflake/dagster_snowflake_tests/test_snowflake_io_manager.py
{ "start": 754, "end": 7553 }
class ____(SnowflakeIOManager): @classmethod def _is_dagster_maintained(cls) -> bool: return True def type_handlers(self): # pyright: ignore[reportIncompatibleMethodOverride] return [PassTypeHandler()] def test_get_select_statement(): assert ( SnowflakeDbClient.get_select_sta...
TestSnowflakeIOManager
python
huggingface__transformers
examples/modular-transformers/modeling_dummy_bert.py
{ "start": 15170, "end": 15743 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_f...
DummyBertIntermediate
python
bokeh__bokeh
tests/unit/bokeh/core/test_has_props.py
{ "start": 2632, "end": 10968 }
class ____(Child): aliased_int1 = Alias("int1") aliased_int2 = Alias("int2") def test_HasProps_getattr() -> None: p = Parent() assert getattr(p, "int1") == 10 assert p.int1 == 10 assert getattr(p, "foo_prop") == 110 assert p.foo_prop == 110 assert isinstance(getattr(p, "foo_func"), M...
AliasedChild
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 52499, "end": 54792 }
class ____(FunnelPreTrainedModel): def __init__(self, config: FunnelConfig) -> None: super().__init__(config) self.num_labels = config.num_labels self.funnel = FunnelModel(config) self.dropout = nn.Dropout(config.hidden_dropout) self.classifier = nn.Linear(config.hidden_size...
FunnelForTokenClassification
python
getsentry__sentry
src/sentry/integrations/aws_lambda/integration.py
{ "start": 14594, "end": 18326 }
class ____: def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase: if "finish_pipeline" in request.GET: return pipeline.finish_pipeline() assert pipeline.organization is not None organization = pipeline.organization account_number =...
AwsLambdaSetupLayerPipelineView
python
spack__spack
lib/spack/spack/database.py
{ "start": 5252, "end": 8286 }
class ____: """A record represents one installation in the DB. The record keeps track of the spec for the installation, its install path, AND whether or not it is installed. We need the installed flag in case a user either: 1. blew away a directory, or 2. used spack uninstall -f to get rid of...
InstallRecord
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 17328, "end": 17651 }
class ____(Constraint): """ Constrain to square matrices. """ event_dim = 2 def check(self, value): return torch.full( size=value.shape[:-2], fill_value=(value.shape[-2] == value.shape[-1]), dtype=torch.bool, device=value.device, )
_Square
python
django__django
django/contrib/postgres/validators.py
{ "start": 2330, "end": 2568 }
class ____(MaxValueValidator): def compare(self, a, b): return a.upper is None or a.upper > b message = _( "Ensure that the upper bound of the range is not greater than %(limit_value)s." )
RangeMaxValueValidator
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 129410, "end": 129589 }
class ____(str, Enum): """ Mutable RAM sparse index """ def __str__(self) -> str: return str(self.value) MUTABLERAM = "MutableRam"
SparseIndexTypeOneOf
python
pydantic__pydantic
pydantic/json_schema.py
{ "start": 116494, "end": 123938 }
class ____: """Add examples to a JSON schema. If the JSON Schema already contains examples, the provided examples will be appended. If `mode` is set this will only apply to that schema generation mode, allowing you to add different examples for validation and serialization. """ @overload ...
Examples
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_pclass.py
{ "start": 434, "end": 1301 }
class ____(type): def __new__(mcs, name, bases, dct): set_fields(dct, bases, name='_pclass_fields') store_invariants(dct, bases, '_pclass_invariants', '__invariant__') dct['__slots__'] = ('_pclass_frozen',) + tuple(key for key in dct['_pclass_fields']) # There must only be one __wea...
PClassMeta
python
keras-team__keras
keras/src/metrics/f_score_metrics.py
{ "start": 225, "end": 9225 }
class ____(Metric): """Computes F-Beta score. Formula: ```python b2 = beta ** 2 f_beta_score = (1 + b2) * (precision * recall) / (precision * b2 + recall) ``` This is the weighted harmonic mean of precision and recall. Its output range is `[0, 1]`. It works for both multi-class and...
FBetaScore
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 120717, "end": 121659 }
class ____(ColumnElement[_T]): """Wrap a column expression as it appears in a 'reference' context. This expression is any that includes an _order_by_label_element, which is a Label, or a DESC / ASC construct wrapping a Label. The production of _label_reference() should occur when an expression is ...
_label_reference
python
mkdocs__mkdocs
mkdocs/structure/pages.py
{ "start": 21104, "end": 21575 }
class ____(markdown.htmlparser.htmlparser.HTMLParser): # type: ignore[name-defined] def __init__(self) -> None: super().__init__() self.present_anchor_ids: set[str] = set() def handle_starttag(self, tag: str, attrs: Sequence[tuple[str, str]]) -> None: for k, v in attrs: if ...
_HTMLHandler
python
wandb__wandb
wandb/sdk/data_types/table.py
{ "start": 40541, "end": 40982 }
class ____: """Helper class for PartitionTable to track its parts.""" def __init__(self, entry, source_artifact): self.entry = entry self.source_artifact = source_artifact self._part = None def get_part(self): if self._part is None: self._part = self.source_arti...
_PartitionTablePartEntry
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_dtype.py
{ "start": 6915, "end": 10766 }
class ____(TestCase): """Test cases related to more complex DType promotions. Further promotion tests are defined in `test_numeric.py` """ @parametrize( "other, expected, expected_weak", [ (2**16 - 1, np.complex64, None), (2**32 - 1, np.complex128, np.complex64)...
TestPromotion
python
huggingface__transformers
src/transformers/models/glm4/modeling_glm4.py
{ "start": 2801, "end": 8805 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Glm4Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Glm4Attention(config=config, layer_idx=layer_idx) self.mlp = Glm4MLP(config) self.input_layernorm = Glm4R...
Glm4DecoderLayer
python
PrefectHQ__prefect
tests/server/models/test_flow_runs.py
{ "start": 46518, "end": 49030 }
class ____: async def test_read_task_run_dependencies(self, flow_run, session): task_run_1 = await models.task_runs.create_task_run( session=session, task_run=schemas.core.TaskRun( flow_run_id=flow_run.id, task_key="key-1", dynamic_key="0" ), ) ...
TestReadFlowRunTaskRunDependencies
python
pypa__hatch
src/hatch/template/files_default.py
{ "start": 541, "end": 2264 }
class ____(File): TEMPLATE = """\ # {project_name} [![PyPI - Version](https://img.shields.io/pypi/v/{project_name_normalized}.svg)](https://pypi.org/project/{project_name_normalized}) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/{project_name_normalized}.svg)](https://pypi.org/project/{project_...
Readme
python
ZoranPandovski__al-go-rithms
data_structures/B+tree/btree.py
{ "start": 708, "end": 4255 }
class ____(Node): def __init__(self): self.pt = 4 self.n = 3 self.root = Node(True) def get_leaf(self,val,node): if node.leaf == False: for ind, key in enumerate(node.keys): if ind == 0 and val<= key: return self.get_leaf(val,node.children[ind]) ...
Btree
python
scipy__scipy
scipy/sparse/linalg/_eigen/arpack/arpack.py
{ "start": 41655, "end": 69603 }
class ____(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres_loose, tol=0): self.A = A self.M = M self.sigma = sigma def mult_func(x): re...
IterOpInv
python
huggingface__transformers
src/transformers/models/florence2/modeling_florence2.py
{ "start": 12712, "end": 16114 }
class ____(nn.Module): def __init__(self, config: Florence2VisionConfig, stage_idx: int): super().__init__() self.config = config self.dim = config.embed_dim[stage_idx] self.window_size = config.window_size self.num_heads = config.num_heads[stage_idx] head_dim = self....
Florence2VisionWindowAttention
python
huggingface__transformers
src/transformers/models/instructblip/modeling_instructblip.py
{ "start": 16569, "end": 20905 }
class ____(nn.Module): def __init__(self, config, is_cross_attention=False): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( "The hidden size (%d) is not a...
InstructBlipQFormerMultiHeadAttention
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/compute.py
{ "start": 68250, "end": 73337 }
class ____(ComputeEngineBaseOperator): """ Permanently and irrevocably deletes an Instance Group Managers. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ComputeEngineDeleteInstanceGroupManagerOperator` :param resource_id: ...
ComputeEngineDeleteInstanceGroupManagerOperator
python
pytest-dev__pytest
src/_pytest/main.py
{ "start": 15879, "end": 16101 }
class ____(dict[Path, str]): __slots__ = ("path",) path: Path def __missing__(self, path: Path) -> str: r = bestrelpath(self.path, path) self[path] = r return r @final
_bestrelpath_cache
python
pydantic__pydantic
tests/mypy/modules/metaclass_args.py
{ "start": 186, "end": 325 }
class ____(BaseModel, validate_by_name=True): i: int = Field(alias='j') MetaclassArgumentsNoDefault(i=None)
MetaclassArgumentsNoDefault
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/fixtures/sql.py
{ "start": 802, "end": 6218 }
class ____(TestBase): # 'once', None run_setup_bind = "once" # 'once', 'each', None run_define_tables = "once" # 'once', 'each', None run_create_tables = "once" # 'once', 'each', None run_inserts = "each" # 'each', None run_deletes = "each" # 'once', None run_dispose...
TablesTest
python
getsentry__sentry
src/sentry/rules/conditions/event_frequency.py
{ "start": 31769, "end": 32678 }
class ____(EventFrequencyForm): intervals = PERCENT_INTERVALS_TO_DISPLAY interval = forms.ChoiceField( choices=[ (key, label) for key, (label, duration) in sorted( PERCENT_INTERVALS_TO_DISPLAY.items(), key=lambda key____label__duration: key____labe...
EventFrequencyPercentForm
python
django__django
tests/admin_views/test_history_view.py
{ "start": 377, "end": 1894 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_chan...
AdminHistoryViewTests
python
huggingface__transformers
tests/models/gemma2/test_modeling_gemma2.py
{ "start": 1907, "end": 20908 }
class ____(unittest.TestCase): input_text = ["Hello I am doing", "Hi today"] def setUp(self): cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @require_torch_large_accelerator @require_read_token def test_model_9b_bf16(self): ...
Gemma2IntegrationTest
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 8915, "end": 9507 }
class ____(Real): """A type that represents reals that are not instances of int. Behaves like float, but also works with values extracted from numpy arrays. isintance(1, RealNotInt) -> False isinstance(1.0, RealNotInt) -> True """ RealNotInt.register(float) def _type_name(t): """Convert typ...
RealNotInt
python
huggingface__transformers
.circleci/create_circleci_config.py
{ "start": 2322, "end": 3362 }
class ____: job_name = "empty" def to_dict(self): steps = [{"run": 'ls -la'}] if self.job_name == "collection_job": steps.extend( [ "checkout", {"run": "pip install requests || true"}, {"run": """while [[ $(...
EmptyJob
python
TheAlgorithms__Python
data_structures/queues/queue_by_two_stacks.py
{ "start": 84, "end": 2614 }
class ____[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: """ >>> QueueByTwoStacks() Queue(()) >>> QueueByTwoStacks([10, 20, 30]) Queue((10, 20, 30)) >>> QueueByTwoStacks((i**2 for i in range(1, 4))) Queue((1, 4, 9)) """ s...
QueueByTwoStacks
python
python-openxml__python-docx
src/docx/oxml/text/font.py
{ "start": 10702, "end": 10882 }
class ____(BaseOxmlElement): """`<w:vertAlign>` element, specifying subscript or superscript.""" val: str = RequiredAttribute("w:val", ST_VerticalAlignRun)
CT_VerticalAlignRun
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 2271, "end": 2387 }
class ____(Parent): @functools().cached_property def _protected(self): pass
ChildHidingAncestorAttribute
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 30908, "end": 31819 }
class ____(graphene.Mutation): """Log telemetry about the Dagster instance.""" Output = graphene.NonNull(GrapheneLogTelemetryMutationResult) class Arguments: action = graphene.Argument(graphene.NonNull(graphene.String)) clientTime = graphene.Argument(graphene.NonNull(graphene.String)) ...
GrapheneLogTelemetryMutation
python
kamyu104__LeetCode-Solutions
Python/find-indices-with-index-and-value-difference-i.py
{ "start": 42, "end": 1153 }
class ____(object): def findIndices(self, nums, indexDifference, valueDifference): """ :type nums: List[int] :type indexDifference: int :type valueDifference: int :rtype: List[int] """ mx_i = mn_i = 0 for i in xrange(len(nums)-indexDifference): ...
Solution
python
prabhupant__python-ds
data_structures/binary_trees/left_right_to_down_right.py
{ "start": 88, "end": 436 }
class ____: def __init__(self, val): self.val = val self.left = None self.rigt = None def convert(root): if root is None: return convert(root.left) convert(root.right) if root.left == None: root.left = root.right else: root.left.right = root.r...
Node
python
huggingface__transformers
tests/models/visual_bert/test_modeling_visual_bert.py
{ "start": 23578, "end": 29197 }
class ____(unittest.TestCase): @slow def test_inference_vqa_coco_pre(self): model = VisualBertForPreTraining.from_pretrained("uclanlp/visualbert-vqa-coco-pre") input_ids = torch.tensor([1, 2, 3, 4, 5, 6], dtype=torch.long).reshape(1, -1) token_type_ids = torch.tensor([0, 0, 0, 1, 1, 1],...
VisualBertModelIntegrationTest
python
ray-project__ray
release/llm_tests/serve/benchmark/firehose_utils.py
{ "start": 377, "end": 630 }
class ____(str, Enum): STARTUP_TEST = "service-startup-test" STARTUP_TEST_GCP = "service-startup-test-gcp" STARTUP_TEST_AWS = "service-startup-test-aws" RAYLLM_PERF_TEST = "rayllm-perf-test" VLLM_PERF_TEST = "vllm-perf-test"
RecordName
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 111651, "end": 131875 }
class ____(FuncDefNode): # C function definition. # # modifiers ['inline'] # visibility 'private' or 'public' or 'extern' # base_type CBaseTypeNode # declarator CDeclaratorNode # cfunc_declarator the CFuncDeclarator of this function # (this is also...
CFuncDefNode
python
airbytehq__airbyte
airbyte-integrations/bases/base-normalization/normalization/transform_catalog/table_name_registry.py
{ "start": 1533, "end": 2799 }
class ____(Dict[str, List[NormalizedNameMetadata]]): """ An intermediate registry used by TableNameRegistry to detect conflicts in table names per schema """ def __init__(self, name_transformer: DestinationNameTransformer): super(NormalizedTablesRegistry, self).__init__() self.name_tran...
NormalizedTablesRegistry
python
kubernetes-client__python
kubernetes/client/models/v1_validating_admission_policy_binding_spec.py
{ "start": 383, "end": 11243 }
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...
V1ValidatingAdmissionPolicyBindingSpec
python
django__django
django/test/runner.py
{ "start": 1060, "end": 1952 }
class ____(logging.Formatter): def format(self, record): if (alias := getattr(record, "alias", None)) in connections: format_sql = connections[alias].ops.format_debug_sql sql = None formatted_sql = None if args := record.args: if isinstance(ar...
QueryFormatter
python
django__django
tests/decorators/test_vary.py
{ "start": 1360, "end": 2409 }
class ____(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = vary_on_cookie(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coro...
VaryOnCookieTests
python
walkccc__LeetCode
solutions/3008. Find Beautiful Indices in the Given Array II/3008.py
{ "start": 0, "end": 1699 }
class ____: # Same as 3006. Find Beautiful Indices in the Given Array I def beautifulIndices(self, s: str, a: str, b: str, k: int) -> list[int]: ans = [] indicesA = self._kmp(s, a) indicesB = self._kmp(s, b) indicesBIndex = 0 # indicesB' index for i in indicesA: # The constraint is: |j -...
Solution
python
PyCQA__pylint
tests/functional/u/unexpected_special_method_signature.py
{ "start": 2008, "end": 2810 }
class ____: def __new__(cls, test, multiple, args): pass # pylint: disable-next=too-many-positional-arguments def __init__(self, this, can, have, multiple, args, as_well): pass def __call__(self, also, trv, for_this): pass def __round__(self, n): pass def __i...
Valid
python
facebook__pyre-check
tools/generate_taint_models/__init__.py
{ "start": 2459, "end": 2918 }
class ____(enum.IntEnum): SUCCESS = 0 # Unexpected internal error INTERNAL_ERROR = 1 # Error that originated from the user's code, not the model generator. # For instance, when importing modules or initializing things. USER_ERROR = 2 # Pyre start errors PYRE_INTERNAL_ERROR = 3 BUC...
ExitCode
python
django__django
tests/test_client_regress/tests.py
{ "start": 36965, "end": 42187 }
class ____(TestDataMixin, TestCase): def test_session(self): "The session isn't lost if a user logs in" # The session doesn't exist to start. response = self.client.get("/check_session/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"NO") ...
SessionTests
python
wandb__wandb
wandb/plot/custom_chart.py
{ "start": 120, "end": 2131 }
class ____: spec_name: str fields: dict[str, Any] string_fields: dict[str, Any] key: str = "" panel_type: str = "Vega2" split_table: bool = False @property def table_key(self) -> str: if not self.key: raise wandb.Error("Key for the custom chart spec is not set.") ...
CustomChartSpec
python
django__django
tests/admin_filters/tests.py
{ "start": 6840, "end": 7185 }
class ____(ModelAdmin): list_filter = ( "year", "is_best_seller", "date_registered", "no", ("author", RelatedOnlyFieldListFilter), ("contributors", RelatedOnlyFieldListFilter), ("employee__department", RelatedOnlyFieldListFilter), ) ordering = ("-id",)...
BookAdminRelatedOnlyFilter
python
django__django
tests/db_functions/text/test_strindex.py
{ "start": 190, "end": 2672 }
class ____(TestCase): def test_annotate_charfield(self): Author.objects.create(name="George. R. R. Martin") Author.objects.create(name="J. R. R. Tolkien") Author.objects.create(name="Terry Pratchett") authors = Author.objects.annotate(fullstop=StrIndex("name", Value("R."))) s...
StrIndexTests
python
pandas-dev__pandas
pandas/tests/reshape/concat/test_append_common.py
{ "start": 1433, "end": 25913 }
class ____: """ Test common dtype coercion rules between concat and append. """ def test_dtypes(self, item, index_or_series, using_infer_string): # to confirm test case covers intended dtypes typ, vals = item obj = index_or_series(vals) if typ == "object" and using_infer...
TestConcatAppendCommon
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol1.py
{ "start": 1565, "end": 1720 }
class ____(Protocol): def __call__(self) -> None: pass var3: TestClass3 = func1 var3 = func2 var3 = func3 var3 = func4 var3 = func5
TestClass3
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 148441, "end": 151384 }
class ____(torch.nn.Module): def __init__( self, channels, kernel_size=3, dilation=(1, 3, 5), ): super().__init__() self.convs1 = nn.ModuleList( [ nn.Conv1d( channels, channels, ...
AMPBlock
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0023_migrate-alias-slug.py
{ "start": 131, "end": 990 }
class ____(migrations.Migration): safe = Safe.after_deploy() def migrate_data(apps, schema_editor): # Keep things that slugify wouldn't normally accept, # so that we don't break a bunch of folks URL's. # They will have to change them on update. invalid_chars_re = re.compile("[^-...
Migration
python
ray-project__ray
python/ray/_private/runtime_env/plugin.py
{ "start": 3509, "end": 9423 }
class ____: """This manager is used to load plugins in runtime env agent.""" def __init__(self): self.plugins: Dict[str, PluginSetupContext] = {} plugin_config_str = os.environ.get(RAY_RUNTIME_ENV_PLUGINS_ENV_VAR) if plugin_config_str: plugin_configs = json.loads(plugin_conf...
RuntimeEnvPluginManager
python
PrefectHQ__prefect
src/prefect/exceptions.py
{ "start": 11341, "end": 11430 }
class ____(PrefectException): """Raised when a flow pause times out"""
FlowPauseTimeout
python
encode__django-rest-framework
tests/test_relations_slug.py
{ "start": 169, "end": 455 }
class ____(serializers.ModelSerializer): sources = serializers.SlugRelatedField( slug_field='name', queryset=ForeignKeySource.objects.all(), many=True ) class Meta: model = ForeignKeyTarget fields = '__all__'
ForeignKeyTargetSerializer
python
huggingface__transformers
src/transformers/models/granitemoe/modular_granitemoe.py
{ "start": 6371, "end": 9375 }
class ____(MixtralModel): def __init__(self, config: GraniteMoeConfig): super().__init__(config) self.layers = nn.ModuleList( [GraniteMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = GraniteMoeRMSNorm(config.hidden_size, e...
GraniteMoeModel
python
django__django
tests/file_storage/models.py
{ "start": 894, "end": 990 }
class ____(LazyObject): def _setup(self): self._wrapped = temp_storage
LazyTempStorage
python
numba__numba
numba/tests/gdb/test_break_on_symbol.py
{ "start": 307, "end": 976 }
class ____(TestCase): def test(self): foo(120) sz = types.intp.bitwidth driver = GdbMIDriver(__file__) driver.set_breakpoint(symbol="__main__::foo") driver.run() # will hit cpython symbol match driver.check_hit_breakpoint(number=1) driver.cont() # will hit nj...
Test
python
pytorch__pytorch
torch/onnx/errors.py
{ "start": 349, "end": 484 }
class ____(RuntimeError): """Errors raised by the ONNX exporter. This is the base class for all exporter errors."""
OnnxExporterError