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
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/pickleable.py
{ "start": 485, "end": 526 }
class ____(ComparableEntity): pass
User
python
chardet__chardet
chardet/universaldetector.py
{ "start": 1235, "end": 1962 }
class ____ user of ``chardet`` should use. :author: Mark Pilgrim (initial port to Python) :author: Shy Shalom (original C code) :author: Dan Blanchard (major refactoring for 3.0) :author: Ian Cordasco """ import codecs import logging import re from typing import List, Optional, Union from .charsetgroupprober import ...
a
python
PyCQA__pylint
tests/functional/u/unsupported/unsupported_binary_operation.py
{ "start": 1206, "end": 1339 }
class ____(Parent): def __add__(self, other): return NotImplemented Child() + Parent() # [unsupported-binary-operation]
Child
python
pytorch__pytorch
torch/serialization.py
{ "start": 9455, "end": 12595 }
class ____(_weights_only_unpickler._safe_globals): r"""Context-manager that adds certain globals as safe for ``weights_only`` load. Args: safe_globals: List of globals for weights_only load. Example: >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on t...
safe_globals
python
django__django
tests/one_to_one/models.py
{ "start": 2747, "end": 2876 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_temp=False)
DirectorManager
python
doocs__leetcode
lcci/17.11.Find Closest/Solution2.py
{ "start": 0, "end": 492 }
class ____: def findClosest(self, words: List[str], word1: str, word2: str) -> int: d = defaultdict(list) for i, w in enumerate(words): d[w].append(i) ans = inf idx1, idx2 = d[word1], d[word2] i, j, m, n = 0, 0, len(idx1), len(idx2) while i < m and j < n: ...
Solution
python
tiangolo__fastapi
docs_src/sql_databases/tutorial001_py310.py
{ "start": 130, "end": 1760 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) age: int | None = Field(default=None, index=True) secret_name: str sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": ...
Hero
python
pytorch__pytorch
torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cuda.py
{ "start": 104, "end": 162 }
class ____: def __init__(self, v): pass
CUstream
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_tz_convert.py
{ "start": 294, "end": 11704 }
class ____: def test_tz_convert_nat(self): # GH#5546 dates = [NaT] idx = DatetimeIndex(dates) idx = idx.tz_localize("US/Pacific") tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Pacific")) idx = idx.tz_convert("US/Eastern") tm.assert_index_equal(idx, Da...
TestTZConvert
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/retries.py
{ "start": 977, "end": 2014 }
class ____(Enum): ENABLED = "enabled" DISABLED = "disabled" # Designed for use of inner plan execution within "orchestrator" engine such as multiprocess, # up_for_retry steps are not directly re-enqueued, deferring that to the engine. DEFERRED = "deferred" @staticmethod def from_config(conf...
RetryMode
python
getsentry__sentry
tests/sentry/issues/endpoints/test_organization_group_search_view_details.py
{ "start": 3538, "end": 5514 }
class ____(BaseGSVTestCase): endpoint = "sentry-api-0-organization-group-search-view-details" method = "get" def setUp(self) -> None: self.login_as(user=self.user) self.base_data = self.create_base_data() # Get the first view's ID for testing self.view_id = str(self.base_da...
OrganizationGroupSearchViewsGetTest
python
kevin1024__vcrpy
vcr/patch.py
{ "start": 13756, "end": 17342 }
class ____: def __init__(self, connection_class): self._connection_class = connection_class self._connection_pool_to_connections = {} def add_connection_to_pool_entry(self, pool, connection): if isinstance(connection, self._connection_class): self._connection_pool_to_connect...
ConnectionRemover
python
keras-team__keras
keras/src/backend/common/variables_test.py
{ "start": 610, "end": 5426 }
class ____(test_case.TestCase): """Tests for Variable.__init__()""" def test_deferred_initialization(self): """Tests deferred initialization of variables.""" with backend.StatelessScope(): v = backend.Variable( initializer=initializers.RandomNormal(), shape=(2, 2) ...
VariableInitializationTest
python
jazzband__django-waffle
waffle/managers.py
{ "start": 955, "end": 1053 }
class ____(BaseManager['AbstractBaseSample']): KEY_SETTING = 'ALL_SAMPLES_CACHE_KEY'
SampleManager
python
kennethreitz__tablib
tests/test_tablib.py
{ "start": 44023, "end": 44238 }
class ____(unittest.TestCase): def test_rst_formatter_doctests(self): import tablib.formats._rst results = doctest.testmod(tablib.formats._rst) self.assertEqual(results.failed, 0)
DocTests
python
ray-project__ray
python/ray/serve/_private/benchmarks/locust_utils.py
{ "start": 897, "end": 8707 }
class ____: def __init__( self, host_url: str, token: str, data: Dict[str, Any] = None, ): from locust import FastHttpUser, constant, events, task from locust.contrib.fasthttp import FastResponse self.errors = [] self.stats_in_stages: List[Perform...
LocustClient
python
scikit-image__scikit-image
src/skimage/transform/_geometric.py
{ "start": 77415, "end": 92575 }
class ____(_GeometricTransform): """2D polynomial transformation. Has the following form:: X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) Parameters ---------- params : (2, N) array_like, optional Pol...
PolynomialTransform
python
optuna__optuna
tests/study_tests/test_study.py
{ "start": 1763, "end": 63106 }
class ____: def __init__(self, sleep_sec: float | None = None) -> None: self.n_calls = 0 self.sleep_sec = sleep_sec self.lock = threading.Lock() def __call__(self, trial: Trial) -> float: with self.lock: self.n_calls += 1 # Sleep for testing parallelism. ...
Func
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 33925, "end": 35008 }
class ____(TypeSystemDefinition): __slots__ = ('loc', 'name', 'arguments', 'locations') _fields = ('name', 'locations') def __init__(self, name, locations, arguments=None, loc=None): self.name = name self.locations = locations self.loc = loc self.arguments = arguments d...
DirectiveDefinition
python
numba__numba
numba/core/typing/builtins.py
{ "start": 8970, "end": 9046 }
class ____(BinOpPower): # TODO add 3 operand version pass
PowerBuiltin
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 22314, "end": 22481 }
class ____(VyperNode): __slots__ = ("args", "defaults", "default") _only_empty_fields = ("posonlyargs", "vararg", "kwonlyargs", "kwarg", "kw_defaults")
arguments
python
huggingface__transformers
tests/models/pix2struct/test_modeling_pix2struct.py
{ "start": 1599, "end": 4589 }
class ____: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=12, patch_embed_hidden_size=12, projection_dim=32, max_patches=64, num_hidden_layers=2, ...
Pix2StructVisionModelTester
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 682389, "end": 682787 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("IssueTimelineItem", graph...
IssueTimelineItemEdge
python
etianen__django-reversion
tests/test_app/admin.py
{ "start": 132, "end": 313 }
class ____(VersionAdmin): filter_horizontal = ("related",) admin.site.register(TestModel, TestModelAdmin) admin.site.register(TestModelRelated, admin.ModelAdmin)
TestModelAdmin
python
scipy__scipy
scipy/optimize/_shgo_lib/_vertex.py
{ "start": 118, "end": 1878 }
class ____(ABC): """ Base class for a vertex. """ def __init__(self, x, nn=None, index=None): """ Initiation of a vertex object. Parameters ---------- x : tuple or vector The geometric location (domain). nn : list, optional Nearest...
VertexBase
python
wandb__wandb
tests/system_tests/test_functional/metaflow/flow_foreach.py
{ "start": 582, "end": 2354 }
class ____(FlowSpec): seed = Parameter("seed", default=1337) test_size = Parameter("test_size", default=0.2) raw_data = Parameter( "raw_data", default=pathlib.Path(__file__).parent / "wine.csv", help="path to the raw data", ) @step def start(self): self.models = ...
WandbForeachFlow
python
spack__spack
lib/spack/spack/vendor/jinja2/meta.py
{ "start": 270, "end": 4422 }
class ____(CodeGenerator): """We abuse the code generator for introspection.""" def __init__(self, environment: "Environment") -> None: super().__init__(environment, "<introspection>", "<introspection>") self.undeclared_identifiers: t.Set[str] = set() def write(self, x: str) -> None: ...
TrackingCodeGenerator
python
walkccc__LeetCode
solutions/435. Non-overlapping Intervals/435.py
{ "start": 0, "end": 299 }
class ____: def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int: ans = 0 currentEnd = -math.inf for interval in sorted(intervals, key=lambda x: x[1]): if interval[0] >= currentEnd: currentEnd = interval[1] else: ans += 1 return ans
Solution
python
cython__cython
Cython/Plex/Machines.py
{ "start": 3410, "end": 7510 }
class ____: """ FastMachine is a deterministic machine represented in a way that allows fast scanning. """ def __init__(self): self.initial_states = {} # {state_name:state} self.states = [] # [state] where state = {event:state, 'else':state, 'action':Action} self.n...
FastMachine
python
huggingface__transformers
src/transformers/models/nemotron/modeling_nemotron.py
{ "start": 14210, "end": 20349 }
class ____(NemotronAttention): """ Nemotron flash attention module. This module inherits from `NemotronAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding t...
NemotronFlashAttention2
python
pytorch__pytorch
torch/testing/_internal/distributed/multi_threaded_pg.py
{ "start": 10018, "end": 11760 }
class ____: def __init__(self, world_size, collective, pg): self._world_size = world_size self._collective = collective self._start_cond = threading.Condition() self._done_cond = threading.Condition() self._data = [None] * world_size self._count = 0 self._do...
Collective
python
dagster-io__dagster
python_modules/dagster/dagster_tests/storage_tests/test_run_storage.py
{ "start": 2225, "end": 3030 }
class ____(TestRunStorage): __test__ = True def supports_backfill_tags_filtering_queries(self) -> bool: return True def supports_backfill_job_name_filtering_queries(self) -> bool: return True def supports_backfill_id_filtering_queries(self) -> bool: return True def suppor...
TestInMemoryRunStorage
python
getsentry__sentry
tests/snuba/api/endpoints/test_project_tags.py
{ "start": 162, "end": 4786 }
class ____(APITestCase, SnubaTestCase): endpoint = "sentry-api-0-project-tags" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def test_simple(self) -> None: self.store_event( data={ "tags": {"foo": "oof", "bar": "rab"}, ...
ProjectTagsTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE790.py
{ "start": 947, "end": 1580 }
class ____(Exception): pass try: foo() except NetworkError: pass def foo() -> None: pass def foo(): print("foo") pass def foo(): """A docstring.""" print("foo") pass for i in range(10): pass pass for i in range(10): pass pass for i in range(10): pass ...
Error
python
tensorflow__tensorflow
tensorflow/python/util/lazy_loader.py
{ "start": 862, "end": 3736 }
class ____(types.ModuleType): """Lazily import a module, mainly to avoid pulling in large dependencies. `contrib`, and `ffmpeg` are examples of modules that are large and not always needed, and this allows them to only be loaded when they are used. """ # The lint error here is incorrect. def __init__(self...
LazyLoader
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-google/llama_index/vector_stores/google/base.py
{ "start": 16986, "end": 18030 }
class ____(BaseModel): """Every node in nodes have the same source node.""" source_node: RelatedNodeInfo nodes: List[BaseNode] def _group_nodes_by_source(nodes: Sequence[BaseNode]) -> List[_NodeGroup]: """ Returns a list of lists of nodes where each list has all the nodes from the same docume...
_NodeGroup
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 41775, "end": 60067 }
class ____(Callback): """Callback to save the Keras model or model weights at some frequency. `ModelCheckpoint` callback is used in conjunction with training using `model.fit()` to save a model or weights (in a checkpoint file) at some interval, so the model or weights can be loaded later to continue the train...
ModelCheckpoint
python
chroma-core__chroma
chromadb/test/api/test_schema_e2e.py
{ "start": 94580, "end": 96761 }
class ____(SparseEmbeddingFunction[List[str]]): """Sparse embedding function for testing search API with string queries.""" def __init__(self, label: str = "test_sparse"): self._label = label def __call__(self, input: List[str]) -> List[SparseVector]: return [ SparseVector(indi...
TestSparseEmbeddingFunction
python
great-expectations__great_expectations
tests/integration/data_sources_and_expectations/test_expectation_conditions.py
{ "start": 19745, "end": 26845 }
class ____: """Simple tests to ensure that SQL properly utilizes row condition from each type of expectation (ColumnMapExpectation, ColumnPairMapExpectation, etc) """ @parameterize_batch_for_data_sources( data_source_configs=[ BigQueryDatasourceTestConfig( column_typ...
TestSQLConditionClassAcrossExpectationTypes
python
apache__airflow
providers/sqlite/src/airflow/providers/sqlite/hooks/sqlite.py
{ "start": 935, "end": 2361 }
class ____(DbApiHook): """Interact with SQLite.""" conn_name_attr = "sqlite_conn_id" default_conn_name = "sqlite_default" conn_type = "sqlite" hook_name = "Sqlite" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._placeholder: str = "?" def get_c...
SqliteHook
python
fluentpython__example-code
07-closure-deco/average_oo.py
{ "start": 83, "end": 296 }
class ____(): def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) total = sum(self.series) return total/len(self.series)
Averager
python
ray-project__ray
python/ray/exceptions.py
{ "start": 29904, "end": 30125 }
class ____(RayError): """Raised when an `ray.ObjectRef` is out of band serialized by `ray.cloudpickle`. It is an anti pattern. """ pass @PublicAPI(stability="alpha")
OufOfBandObjectRefSerializationException
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/tree/all_leaf_retriever.py
{ "start": 525, "end": 1907 }
class ____(BaseRetriever): """ GPT all leaf retriever. This class builds a query-specific tree from leaf nodes to return a response. Using this query mode means that the tree index doesn't need to be built when initialized, since we rebuild the tree for each query. Args: text_qa_templa...
TreeAllLeafRetriever
python
EpistasisLab__tpot
tpot/builtin_modules/imputer.py
{ "start": 1828, "end": 5408 }
class ____(TransformerMixin, BaseEstimator ): def __init__(self, columns="all", missing_values=np.nan, strategy="mean", fill_value=None, copy=True, add_indicator=False, ...
ColumnSimpleImputer
python
pypa__pipenv
pipenv/vendor/click/_compat.py
{ "start": 2000, "end": 14134 }
class ____: """The new io interface needs more from streams than streams traditionally implement. As such, this fix-up code is necessary in some circumstances. The forcing of readable and writable flags are there because some tools put badly patched objects on sys (one such offender are certain ve...
_FixupStream
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 18262, "end": 18474 }
class ____(_Constraint): """Constraint representing sparse matrices.""" def is_satisfied_by(self, val): return issparse(val) def __str__(self): return "a sparse matrix"
_SparseMatrices
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/report_file_recod_builder.py
{ "start": 156, "end": 354 }
class ____(RecordBuilder): @classmethod def report_file_record(cls): return cls(find_template("download_report_file", __file__)[0], FieldPath("campaignId"), None)
ReportFileRecordBuilder
python
huggingface__transformers
src/transformers/models/vit_mae/modeling_vit_mae.py
{ "start": 17028, "end": 17755 }
class ____(nn.Module): """ The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: ViTMAEConfig): super().__init__() self.dense = nn.Linear(config.hidden_size...
ViTMAESelfOutput
python
apache__airflow
providers/opsgenie/tests/unit/opsgenie/operators/test_opsgenie.py
{ "start": 1128, "end": 4559 }
class ____: _config = { "message": "An example alert message", "alias": "Life is too short for no alias", "description": "Every alert needs a description", "responders": [ {"id": "4513b7ea-3b91-438f-b7e4-e3e54af9147c", "type": "team"}, {"name": "NOC", "type": ...
TestOpsgenieCreateAlertOperator
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup_py314.py
{ "start": 602, "end": 1797 }
class ____: constant = 42 x: int # see https://docs.python.org/3/reference/datamodel.html#python-buffer-protocol # and https://peps.python.org/pep-0688/ def __buffer__(self, flags): return memoryview( self.constant.to_bytes() + self.x.to_bytes(length=32, signed=True) ) ...
A
python
huggingface__transformers
src/transformers/models/mamba2/modeling_mamba2.py
{ "start": 35072, "end": 35823 }
class ____(ModelOutput): r""" cache_params (`Mamba2Cache`): The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to avoid providing the old `input_ids`. Includes both the State space model state matrices after the selective scan, and th...
Mamba2Output
python
huggingface__transformers
tests/models/mluke/test_tokenization_mluke.py
{ "start": 5860, "end": 27499 }
class ____(unittest.TestCase): tokenizer_class = MLukeTokenizer from_pretrained_kwargs = {"cls_token": "<s>"} @classmethod def setUpClass(cls): cls.tokenizer = MLukeTokenizer.from_pretrained("studio-ousia/mluke-base", return_token_type_ids=True) cls.entity_classification_tokenizer = MLu...
MLukeTokenizerIntegrationTests
python
google__jax
jax/_src/pallas/mosaic_gpu/lowering.py
{ "start": 19648, "end": 19964 }
class ____(Protocol): shape: tuple[jax_core.DimSize, ...] dtype: jnp.dtype weak_type: bool @property def ndim(self) -> int: ... @property def size(self) -> int: ... def update(self, **kwargs: Any) -> Self: raise NotImplementedError @dataclasses.dataclass(frozen=True)
ShapedAbstractValue
python
django__django
tests/bulk_create/models.py
{ "start": 4418, "end": 4636 }
class ____(models.Model): name = models.CharField(max_length=10) created_at = models.DateTimeField(db_default=Now()) class Meta: required_db_features = {"supports_expression_defaults"}
DbDefaultModel
python
run-llama__llama_index
llama-index-instrumentation/src/llama_index_instrumentation/span/simple.py
{ "start": 122, "end": 444 }
class ____(BaseSpan): """Simple span class.""" start_time: datetime = Field(default_factory=lambda: datetime.now()) end_time: Optional[datetime] = Field(default=None) duration: float = Field(default=0.0, description="Duration of span in seconds.") metadata: Optional[Dict] = Field(default=None)
SimpleSpan
python
pytorch__pytorch
torch/distributed/pipelining/microbatch.py
{ "start": 1430, "end": 3190 }
class ____: """ Class used to specify chunking of inputs """ def __init__(self, split_dim): self.split_dim = split_dim split_dim: int def __repr__(self): return ( f"{self.__class__.__module__}.{self.__class__.__name__}({self.split_dim})" ) def __str__(...
TensorChunkSpec
python
openai__openai-python
src/openai/_base_client.py
{ "start": 45163, "end": 46702 }
class ____(httpx.AsyncClient): def __init__(self, **kwargs: Any) -> None: kwargs.setdefault("timeout", DEFAULT_TIMEOUT) kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) kwargs.setdefault("follow_redirects", True) super().__init__(**kwargs) try: import httpx_aiohttp except...
_DefaultAsyncHttpxClient
python
django__django
tests/utils_tests/test_json.py
{ "start": 203, "end": 1597 }
class ____(SimpleTestCase): def test_converts_json_types(self): for test_case, expected in [ (None, "null"), (True, "true"), (False, "false"), (2, "2"), (3.0, "3.0"), (1e23 + 1, "1e+23"), ("1", '"1"'), (b"hello",...
JSONNormalizeTestCase
python
donnemartin__interactive-coding-challenges
linked_lists/linked_list/linked_list.py
{ "start": 0, "end": 163 }
class ____(object): def __init__(self, data, next=None): self.next = next self.data = data def __str__(self): return self.data
Node
python
huggingface__transformers
src/transformers/modeling_flash_attention_utils.py
{ "start": 21557, "end": 31786 }
class ____(TypedDict, total=False): """ Keyword arguments for Flash Attention with Compile. Attributes: cu_seq_lens_q (`torch.LongTensor`, *optional*) Gets cumulative sequence length for query state. cu_seq_lens_k (`torch.LongTensor`, *optional*) Gets cumulative sequ...
FlashAttentionKwargs
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/buffer.py
{ "start": 1577, "end": 1759 }
class ____(enum.Enum): OBSERVATION = "obs" NEXT_OBSERVATION = "next_obs" GROUP_OBSERVATION = "group_obs" NEXT_GROUP_OBSERVATION = "next_group_obs"
ObservationKeyPrefix
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0026_ad-free-option.py
{ "start": 149, "end": 650 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0025_show-version-warning-existing-projects"), ] operations = [ migrations.AddField( model_name="project", name="ad_free", field=models.BooleanField( ...
Migration
python
spack__spack
lib/spack/spack/test/mirror.py
{ "start": 9564, "end": 15558 }
class ____: """Mock fetcher object which implements the necessary functionality for testing MirrorCache """ @staticmethod def archive(dst): with open(dst, "w", encoding="utf-8"): pass @pytest.mark.regression("14067") def test_mirror_layout_make_alias(tmp_path: pathlib.Path): ...
MockFetcher
python
agronholm__apscheduler
src/apscheduler/triggers/cron/expressions.py
{ "start": 5563, "end": 6195 }
class ____(RangeExpression): value_re: ClassVar[Pattern] = re.compile( r"(?P<first>[a-z]+)(?:-(?P<last>[a-z]+))?", re.IGNORECASE ) def __init__(self, first: str, last: str | None = None): first_num = get_weekday_index(first) last_num = get_weekday_index(last) if last else None ...
WeekdayRangeExpression
python
PrefectHQ__prefect
src/prefect/_experimental/plugins/spec.py
{ "start": 452, "end": 1000 }
class ____: """ Context provided to plugin hooks at startup. Attributes: prefect_version: The version of Prefect running api_url: The configured Prefect API URL, if any logger_factory: Factory function to create a stdlib logger for the plugin """ prefect_version: str ap...
HookContext
python
eth-brownie__brownie
brownie/_config.py
{ "start": 1441, "end": 4796 }
class ____: def __init__(self) -> None: base_config = _load_config(BROWNIE_FOLDER.joinpath("data/default-config.yaml")) if Path.home().joinpath("brownie-config.yaml").exists(): home_config = _load_config(Path.home().joinpath("brownie-config.yaml")) _recursive_update(base_conf...
ConfigContainer
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_wx.py
{ "start": 48118, "end": 48354 }
class ____(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2Wx.save_figure( self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(_FigureCanvasWxBase)
SaveFigureWx
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 11289, "end": 12184 }
class ____(BiffRecord): """ This record is part of the worksheet/workbook protection. It stores a 16-bit hash value, calculated from the worksheet or workbook protection password. """ _REC_ID = 0x0013 def passwd_hash(self, plaintext): """ Based on the algorithm provided by Da...
PasswordRecord
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 118089, "end": 118315 }
class ____(ServerAdapter): """ Untested. """ def run(self, handler): from rocket import Rocket server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler }) server.start()
RocketServer
python
getsentry__sentry-python
sentry_sdk/integrations/boto3.py
{ "start": 853, "end": 4411 }
class ____(Integration): identifier = "boto3" origin = f"auto.http.{identifier}" @staticmethod def setup_once(): # type: () -> None version = parse_version(BOTOCORE_VERSION) _check_minimum_version(Boto3Integration, version, "botocore") orig_init = BaseClient.__init__ ...
Boto3Integration
python
Textualize__textual
src/textual/messages.py
{ "start": 498, "end": 578 }
class ____(Message, verbose=True): """Exit the app.""" @rich.repr.auto
ExitApp
python
ipython__ipython
IPython/core/display.py
{ "start": 16126, "end": 17791 }
class ____(DisplayObject): """Progressbar supports displaying a progressbar like element """ def __init__(self, total): """Creates a new progressbar Parameters ---------- total : int maximum size of the progressbar """ self.total = total s...
ProgressBar
python
great-expectations__great_expectations
tests/core/test_expectation_validation_result.py
{ "start": 23043, "end": 25723 }
class ____: @pytest.mark.unit def test_hash_consistency_with_equality(self): config = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) evr = ExpectationValidationResult( success=True, expectation_config=conf...
TestExpectationSuiteValidationResultHash
python
pytoolz__toolz
toolz/tests/test_dicttoolz.py
{ "start": 6267, "end": 6649 }
class ____(TestDict): """Test defaultdict as input and factory Class attributes: D: callable that inputs a dict and creates or returns a MutableMapping kw: kwargs dict to specify "factory" keyword (if applicable) """ @staticmethod def D(dict_): return defaultdict(int, dict_)...
TestDefaultDict
python
ray-project__ray
doc/source/ray-overview/examples/e2e-timeseries/e2e_timeseries/data_loader.py
{ "start": 160, "end": 9421 }
class ____(Dataset): def __init__( self, flag="train", size=None, features="S", target="OT", scale=True, train_only=False, smoke_test=False, ): # sequence_lengths: A list containing [encoder_sequence_length, decoder_context_length, predicti...
Dataset_ETT_hour
python
scikit-image__scikit-image
tests/skimage/_shared/test_testing.py
{ "start": 3228, "end": 4196 }
class ____: def raise_warning(self, *args, **kwargs): warnings.warn(*args, **kwargs) def test_correct_stacklevel(self): # Should pass if stacklevel is set correctly with pytest.warns(UserWarning, match="passes") as record: self.raise_warning("passes", UserWarning, stacklevel...
Test_assert_stacklevel
python
scipy__scipy
scipy/interpolate/_fitpack2.py
{ "start": 80385, "end": 90341 }
class ____(SphereBivariateSpline): """ Bivariate spline approximation over a rectangular mesh on a sphere. Can be used for smoothing data. .. versionadded:: 0.11.0 Parameters ---------- u : array_like 1-D array of colatitude coordinates in strictly ascending order. Coordin...
RectSphereBivariateSpline
python
dask__dask
dask/tests/test_expr.py
{ "start": 2306, "end": 2346 }
class ____(SingletonExpr): ...
MySingleton
python
huggingface__transformers
src/transformers/models/ijepa/modular_ijepa.py
{ "start": 5541, "end": 7181 }
class ____(IJepaPreTrainedModel, ViTForImageClassification): def __init__(self, config: IJepaConfig): super().__init__(config) self.ijepa = IJepaModel(config, add_pooling_layer=False) self.post_init() def forward( self, pixel_values: Optional[torch.Tensor] = None, ...
IJepaForImageClassification
python
huggingface__transformers
src/transformers/models/convbert/modeling_convbert.py
{ "start": 18576, "end": 20804 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([ConvBertLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Ten...
ConvBertEncoder
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 8338, "end": 9100 }
class ____(ValueError): """ Exception that is raised by an error encountered in parsing file contents. This is a generic error raised for errors encountered when functions like `read_csv` or `read_html` are parsing contents of a file. See Also -------- read_csv : Read CSV (comma-separated)...
ParserError
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_matmul_op_test.py
{ "start": 1785, "end": 12555 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def eager_ragged_matmul(self, a, b, **kwargs): """Reference implementation for ragged matmul.""" if len(a.shape) > 2: return [ self.eager_ragged_matmul(a[i], b[i], **kwargs) for i in range(a.shape[0]) ] a = ...
RaggedMatmulOpTest
python
conda__conda
conda/plugins/reporter_backends/console.py
{ "start": 4579, "end": 8313 }
class ____(ReporterRendererBase): """ Default implementation for console reporting in conda """ def detail_view(self, data: dict[str, str | int | bool], **kwargs) -> str: table_parts = [""] longest_header = max(map(len, data.keys())) for header, value in data.items(): ...
ConsoleReporterRenderer
python
airbytehq__airbyte
airbyte-ci/connectors/live-tests/src/live_tests/commons/json_schema_helper.py
{ "start": 301, "end": 1895 }
class ____: """Field class to represent cursor/pk fields. It eases the read of values from records according to schema definition. """ def __init__(self, schema: Mapping[str, Any], path: List[str]): self.schema = schema self.path = path self.formats = self._detect_formats() ...
CatalogField
python
prabhupant__python-ds
data_structures/binary_trees/print_path_to_a_node.py
{ "start": 0, "end": 552 }
class ____: def __init__(self, val): self.val = val self.left = None self.right = None def has_path(root, stack, x): if not root: return False stack.append(root.val) if root.val == x: return True if has_path(root.left, stack, x) or has_path(root.right, s...
Node
python
Textualize__textual
docs/examples/guide/compound/byte01.py
{ "start": 675, "end": 1076 }
class ____(Widget): """A compound widget with 8 switches.""" DEFAULT_CSS = """ ByteInput { width: auto; height: auto; border: blank; layout: horizontal; } ByteInput:focus-within { border: heavy $secondary; } """ def compose(self) -> ComposeResult...
ByteInput
python
openai__openai-python
src/openai/types/realtime/call_accept_params.py
{ "start": 666, "end": 5171 }
class ____(TypedDict, total=False): type: Required[Literal["realtime"]] """The type of session to create. Always `realtime` for the Realtime API.""" audio: RealtimeAudioConfigParam """Configuration for input and output audio.""" include: List[Literal["item.input_audio_transcription.logprobs"]] ...
CallAcceptParams
python
tiangolo__fastapi
tests/test_security_api_key_query_description.py
{ "start": 244, "end": 2083 }
class ____(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_secu...
User
python
python-attrs__attrs
tests/test_make.py
{ "start": 46420, "end": 48877 }
class ____: """ Tests for `validate`. """ def test_success(self): """ If the validator succeeds, nothing gets raised. """ C = make_class( "C", {"x": attr.ib(validator=lambda *a: None), "y": attr.ib()} ) validate(C(1, 2)) def test_propagat...
TestValidate
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/complex.py
{ "start": 10690, "end": 11812 }
class ____(BaseComplex[np.dtypes.Complex64DType, np.complex64]): """ A Zarr data type for arrays containing 64 bit complex floats. Wraps the [`np.dtypes.Complex64DType`][numpy.dtypes.Complex64DType] data type. Scalars for this data type are instances of [`np.complex64`][numpy.complex64]. Attribute...
Complex64
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 4559, "end": 6507 }
class ____: def to_json_dict(self) -> dict[str, JSONValues]: """Returns a JSON-serializable dict representation of this RenderedContent. Returns: A JSON-serializable dict representation of this RenderedContent. """ return {} @override def __eq__(self, other): ...
RenderedContent
python
redis__redis-py
tests/test_asyncio/test_multidb/test_pipeline.py
{ "start": 707, "end": 10371 }
class ____: @pytest.mark.asyncio @pytest.mark.parametrize( "mock_multi_db_config,mock_db, mock_db1, mock_db2", [ ( {}, {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.CLOSED}}, ...
TestPipeline
python
getsentry__sentry
src/sentry/models/options/organization_option.py
{ "start": 477, "end": 3845 }
class ____(OptionManager["OrganizationOption"]): def get_value_bulk( self, instances: Sequence[Organization], key: str, default: Any = None ) -> Mapping[Organization, Any]: instance_map = {i.id: i for i in instances} queryset = self.filter(organization__in=instances, key=key) res...
OrganizationOptionManager
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/pagination_strategies/cursor_based_pagination_strategy.py
{ "start": 175, "end": 831 }
class ____(PaginationStrategy): def __init__(self, first_url: Optional[str] = None) -> None: self._first_url = first_url def update(self, response: Dict[str, Any]) -> None: """ Only allow for one page """ response["meta"]["has_more"] = True response["meta"]["afte...
CursorBasedPaginationStrategy
python
pydantic__pydantic
pydantic/_internal/_discriminated_union.py
{ "start": 2429, "end": 25478 }
class ____: """This class is used to convert an input schema containing a union schema into one where that union is replaced with a tagged-union, with all the associated debugging and performance benefits. This is done by: * Validating that the input schema is compatible with the provided discriminator...
_ApplyInferredDiscriminator
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 11692, "end": 11754 }
class ____(User): date_of_birth = models.DateField()
Profile
python
ray-project__ray
rllib/models/preprocessors.py
{ "start": 7757, "end": 9038 }
class ____(Preprocessor): """Preprocessor that turns a MultiBinary space into a Box. Note: Before RLModules were introduced, RLlib's ModelCatalogV2 would produce ComplexInputNetworks that treat MultiBinary spaces as Boxes. This preprocessor is needed to get rid of the ComplexInputNetworks and use RLMod...
MultiBinaryPreprocessor
python
django__django
tests/postgres_tests/test_array.py
{ "start": 29516, "end": 33155 }
class ____(PostgreSQLSimpleTestCase): def test_field_checks(self): class MyModel(PostgreSQLModel): field = ArrayField(models.CharField(max_length=-1)) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField has a non-positi...
TestChecks
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 83505, "end": 83580 }
class ____(PyStep): "Step-over Python code." stepinto = False
PyNext
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 16647, "end": 17791 }
class ____(nn.Module): def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=0): super().__init__() self.self = Swin2SRSelfAttention( config=config, dim=dim, num_heads=num_heads, window_size=window_size, pretrained_...
Swin2SRAttention