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
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 10509, "end": 10854 }
class ____(PrefectBaseModel): """Filter by `TaskRun.flow_run_id`.""" any_: Optional[List[UUID]] = Field( default=None, description="A list of flow run ids to include" ) is_null_: bool = Field( default=False, description="If true, only include task runs without a flow run id", ...
TaskRunFilterFlowRunId
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_fixtures/test_public_class.py
{ "start": 1688, "end": 2123 }
class ____: """A non-public class - none of its methods should be validated even if marked @public.""" @public def public_method_on_non_public_class(self): """This should NOT be validated because the class is not @public.""" return "should_not_validate" def regular_method_on_non_public...
NonPublicClass
python
encode__starlette
starlette/authentication.py
{ "start": 4570, "end": 4750 }
class ____(BaseUser): @property def is_authenticated(self) -> bool: return False @property def display_name(self) -> str: return ""
UnauthenticatedUser
python
walkccc__LeetCode
solutions/1049. Last Stone Weight II/1049.py
{ "start": 0, "end": 339 }
class ____: def lastStoneWeightII(self, stones: list[int]) -> int: summ = sum(stones) s = 0 dp = [True] + [False] * summ for stone in stones: for w in range(summ // 2 + 1)[::-1]: if w >= stone: dp[w] = dp[w] or dp[w - stone] if dp[w]: s = max(s, w) retur...
Solution
python
ray-project__ray
doc/source/serve/doc_code/tutorial_batch.py
{ "start": 238, "end": 921 }
class ____: def __init__(self, pipeline_key: str, model_key: str): self.model = pipeline(pipeline_key, model_key) @serve.batch(max_batch_size=4) async def handle_batch(self, inputs: List[str]) -> List[str]: print("Our input array has length:", len(inputs)) results = self.model(inpu...
BatchTextGenerator
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0069_rename_error_detectors.py
{ "start": 684, "end": 2028 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
pytorch__pytorch
torch/_inductor/codegen/cpp_micro_gemm.py
{ "start": 8548, "end": 13108 }
class ____(CppMicroGemm): """ A reference implementation of the CppMicroGemm class with naive C++ code. It is used for correctness debugging. """ TEMPLATE_ENTRY = r""" {{declare_kernel}} { for (int64_t m = 0; m < M; ++m) { for (int64_t n = 0; n < N; ++n) { {{compute_t}} resu...
CppMicroGemmRef
python
openai__gym
gym/error.py
{ "start": 1887, "end": 2021 }
class ____(Error): """Raised when the user performs an action not contained within the action space.""" # API errors
InvalidAction
python
PrefectHQ__prefect
tests/experimental/test_bundles.py
{ "start": 664, "end": 11003 }
class ____: @pytest.fixture(autouse=True) def mock_subprocess_check_call(self, monkeypatch: pytest.MonkeyPatch): mock_subprocess_check_call = MagicMock() monkeypatch.setattr(subprocess, "check_call", mock_subprocess_check_call) return mock_subprocess_check_call @pytest.fixture(autou...
TestExecuteBundleInSubprocess
python
plotly__plotly.py
plotly/graph_objs/scattergeo/marker/colorbar/_tickfont.py
{ "start": 233, "end": 9969 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergeo.marker.colorbar" _path_str = "scattergeo.marker.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", ...
Tickfont
python
django__django
django/db/models/functions/text.py
{ "start": 9105, "end": 9147 }
class ____(LPad): function = "RPAD"
RPad
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 95745, "end": 99184 }
class ____( roles.InElementRole, roles.OrderByRole, roles.ColumnsClauseRole, roles.DMLColumnRole, DQLDMLClauseElement, ): """Describe a list of clauses, separated by an operator. By default, is comma-separated, such as a column listing. """ __visit_name__ = "clauselist" # Use...
ClauseList
python
spack__spack
lib/spack/spack/url_buildcache.py
{ "start": 29515, "end": 53807 }
class ____(URLBuildcacheEntry): """This class exists to provide read-only support for reading older buildcache layouts in a way that is transparent to binary_distribution code responsible for downloading and extracting binary packages. Since support for layout v2 is read-only, and since v2 did not have...
URLBuildcacheEntryV2
python
celery__celery
celery/platforms.py
{ "start": 3599, "end": 8818 }
class ____: """Pidfile. This is the type returned by :func:`create_pidlock`. See Also: Best practice is to not use this directly but rather use the :func:`create_pidlock` function instead: more convenient and also removes stale pidfiles (when the process holding the lock is...
Pidfile
python
numpy__numpy
numpy/lib/_datasource.py
{ "start": 2198, "end": 5780 }
class ____: """ Container for different methods to open (un-)compressed files. `_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that ...
_FileOpeners
python
huggingface__transformers
src/transformers/models/wav2vec2/tokenization_wav2vec2.py
{ "start": 29076, "end": 41263 }
class ____(PreTrainedTokenizer): """ Constructs a Wav2Vec2 tokenizer. This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to the superclass for more information regarding such methods. Args: vocab_file (`str`): File c...
Wav2Vec2Tokenizer
python
django__django
tests/admin_views/models.py
{ "start": 7089, "end": 7374 }
class ____(models.Model): """ A simple persona associated with accounts, to test inlining of related accounts which inherit from a common accounts class. """ name = models.CharField(blank=False, max_length=80) def __str__(self): return self.name
Persona
python
apache__airflow
providers/weaviate/tests/unit/weaviate/operators/test_weaviate.py
{ "start": 3268, "end": 5552 }
class ____: @pytest.fixture def operator(self): return WeaviateDocumentIngestOperator( task_id="weaviate_task", conn_id="weaviate_conn", input_data=[{"data": "sample_data"}], collection_name="my_collection", document_column="docLink", ...
TestWeaviateDocumentIngestOperator
python
ansible__ansible
test/units/module_utils/urls/test_fetch_url.py
{ "start": 620, "end": 849 }
class ____(AnsibleModuleExit): pass @pytest.fixture def open_url_mock(mocker): return mocker.patch('ansible.module_utils.urls.open_url') @pytest.fixture def fake_ansible_module(): return FakeAnsibleModule()
FailJson
python
django__django
tests/generic_views/views.py
{ "start": 5690, "end": 5759 }
class ____(BookConfig, generic.DayArchiveView): pass
BookDayArchive
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py
{ "start": 17048, "end": 19369 }
class ____(AwsBaseOperator[EmrContainerHook]): """ An operator that creates EMR on EKS virtual clusters. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:EmrEksCreateClusterOperator` :param virtual_cluster_name: The name of t...
EmrEksCreateClusterOperator
python
django__django
tests/swappable_models/tests.py
{ "start": 227, "end": 1895 }
class ____(TestCase): # Limit memory usage when calling 'migrate'. available_apps = [ "swappable_models", "django.contrib.auth", "django.contrib.contenttypes", ] @override_settings(TEST_ARTICLE_MODEL="swappable_models.AlternateArticle") def test_generated_data(self): ...
SwappableModelTests
python
pypa__virtualenv
src/virtualenv/discovery/cached_py_info.py
{ "start": 6538, "end": 6984 }
class ____: def __init__(self, cmd, env=None) -> None: self.cmd = cmd self.env = env def __repr__(self) -> str: cmd_repr = " ".join(quote(str(c)) for c in self.cmd) if self.env is not None: cmd_repr = f"{cmd_repr} env of {self.env!r}" return cmd_repr def cl...
LogCmd
python
getsentry__sentry
src/sentry/issues/endpoints/bases/group.py
{ "start": 5128, "end": 6217 }
class ____(GroupPermission): scope_map = { "GET": ["event:read", "event:write", "event:admin"], "POST": ["event:write", "event:admin"], "PUT": ["event:write", "event:admin"], "DELETE": ["event:admin"], } # We want to allow POST requests in order to showcase AI features in de...
GroupAiPermission
python
pdm-project__pdm
src/pdm/cli/utils.py
{ "start": 7049, "end": 27985 }
class ____: """An internal class for the convenience of dependency graph building.""" name: str = dc.field(hash=True, compare=True) version: str | None = dc.field(compare=False) requirements: dict[str, Requirement] = dc.field(compare=False) def __repr__(self) -> str: return f"<Package {sel...
PackageNode
python
django__django
tests/defer_regress/models.py
{ "start": 1749, "end": 1848 }
class ____(models.Model): profile1 = models.CharField(max_length=255, default="profile1")
Profile
python
numba__numba
numba/core/typeconv/castgraph.py
{ "start": 1828, "end": 4075 }
class ____(object): """A graph that maintains the casting relationship of all types. This simplifies the definition of casting rules by automatically propagating the rules. """ def __init__(self, callback=None): """ Args ---- - callback: callable or None ...
TypeGraph
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 216241, "end": 216606 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "sponsors_tier") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") sponsors_tier = sgqlc.types.Field("SponsorsTier", graphq...
CancelSponsorshipPayload
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 284017, "end": 287170 }
class ____(Request): """ Request to stop a running task :param force: If not true, call fails if the task status is not 'in_progress' :type force: bool :param task: Task ID :type task: str :param status_reason: Reason for status change :type status_reason: str :param status_message:...
StopRequest
python
python-poetry__poetry
src/poetry/console/commands/version.py
{ "start": 522, "end": 4259 }
class ____(Command): name = "version" description = ( "Shows the version of the project or bumps it when a valid " "bump rule is provided." ) arguments: ClassVar[list[Argument]] = [ argument( "version", "The version number or the rule to update the versio...
VersionCommand
python
airbytehq__airbyte
airbyte-ci/connectors/live-tests/src/live_tests/commons/models.py
{ "start": 4682, "end": 4759 }
class ____(Enum): TARGET = "target" CONTROL = "control"
TargetOrControl
python
python-jsonschema__jsonschema
jsonschema/_types.py
{ "start": 1601, "end": 5456 }
class ____: """ A :kw:`type` property checker. A `TypeChecker` performs type checking for a `Validator`, converting between the defined JSON Schema types and some associated Python types or objects. Modifying the behavior just mentioned by redefining which Python objects are considered to ...
TypeChecker
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 22739, "end": 22858 }
class ____(Hostname): platform = 'Linux' distribution = 'Redhat' strategy_class = RedHatStrategy
RHELHostname
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/definition/cacheable_assets_definition.py
{ "start": 14771, "end": 15440 }
class ____(WrappedCacheableAssetsDefinition): """Represents a CacheableAssetsDefinition that has been wrapped with resources.""" def __init__( self, wrapped: CacheableAssetsDefinition, resource_defs: Mapping[str, ResourceDefinition], ): self._resource_defs = resource_defs ...
ResourceWrappedCacheableAssetsDefinition
python
python-poetry__poetry
tests/helpers.py
{ "start": 4802, "end": 5341 }
class ____(Application): def __init__(self, poetry: Poetry) -> None: super().__init__() self._poetry = poetry def reset_poetry(self) -> None: assert self._poetry is not None poetry = self._poetry self._poetry = Factory().create_poetry(self._poetry.file.path.parent) ...
PoetryTestApplication
python
django__django
django/contrib/admin/widgets.py
{ "start": 14277, "end": 14374 }
class ____(AdminIntegerFieldWidget): class_name = "vBigIntegerField"
AdminBigIntegerFieldWidget
python
PrefectHQ__prefect
tests/server/api/test_saved_searches.py
{ "start": 3091, "end": 3960 }
class ____: async def test_read_saved_search(self, client): # first create a saved_search to read data = SavedSearchCreate( name="My SavedSearch", ).model_dump(mode="json") response = await client.put("/saved_searches/", json=data) saved_search_id = response.json(...
TestReadSavedSearch
python
django__django
tests/model_inheritance/models.py
{ "start": 1406, "end": 1484 }
class ____(Attachment): is_spam = models.BooleanField(default=False)
Comment
python
hynek__structlog
tests/test_tracebacks.py
{ "start": 463, "end": 27347 }
class ____(str): # noqa: SLOT000 """ Secrets representation as used in Typed Settings or Pydantic. """ def __repr__(self) -> str: return "*******" @pytest.fixture(autouse=True) def _unimport_rich(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(tracebacks, "rich", None) de...
SecretStr
python
great-expectations__great_expectations
great_expectations/render/renderer/content_block/exception_list_content_block.py
{ "start": 515, "end": 3617 }
class ____(ContentBlockRenderer): """Render a bullet list of exception messages raised for provided EVRs""" _rendered_component_type = RenderedBulletListContent _content_block_type = "bullet_list" _default_header = 'Failed expectations <span class="mr-3 triangle"></span>' _default_content_block_s...
ExceptionListContentBlockRenderer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 36406, "end": 37833 }
class ____(_DropBase["Constraint"]): """Represent an ALTER TABLE DROP CONSTRAINT statement.""" __visit_name__ = "drop_constraint" def __init__( self, element: Constraint, *, cascade: bool = False, if_exists: bool = False, isolate_from_table: bool = True, ...
DropConstraint
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 17127, "end": 17409 }
class ____(HTTPException): """*418* `I'm a teapot` The server should return this if it is a teapot and someone attempted to brew coffee with it. .. versionadded:: 0.7 """ code = 418 description = "This server is a teapot, not a coffee machine"
ImATeapot
python
walkccc__LeetCode
solutions/1638. Count Substrings That Differ by One Character/1638.py
{ "start": 0, "end": 830 }
class ____: def countSubstrings(self, s: str, t: str) -> int: ans = 0 for i in range(len(s)): ans += self._count(s, t, i, 0) for j in range(1, len(t)): ans += self._count(s, t, 0, j) return ans def _count(self, s: str, t: str, i: int, j: int) -> int: """Returns the number of subs...
Solution
python
getsentry__sentry
tests/snuba/api/endpoints/test_discover_saved_query_detail.py
{ "start": 385, "end": 21871 }
class ____(APITestCase, SnubaTestCase): feature_name = "organizations:discover" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.create_organization(owner=self.user) self.org_without_access = self.create_organization() self.project_i...
DiscoverSavedQueryDetailTest
python
streamlit__streamlit
lib/tests/streamlit/elements/lib/color_util_test.py
{ "start": 1444, "end": 6736 }
class ____(unittest.TestCase): def test_to_int_color_tuple(self): """Test to_int_color_tuple with good inputs""" test_combinations = [ # Hex-3, 4, 6, 8 ("#0f0", (0, 255, 0, 255)), ("#0f08", (0, 255, 0, 136)), ("#00ff00", (0, 255, 0, 255)), ...
ColorUtilTest
python
pypa__warehouse
tests/unit/legacy/api/xmlrpc/test_xmlrpc.py
{ "start": 3635, "end": 13843 }
class ____: @pytest.mark.parametrize("domain", [None, "example.com"]) def test_error(self, pyramid_request, metrics, monkeypatch, domain): registry_settings = {} if domain: registry_settings["warehouse.domain"] = domain monkeypatch.setattr(pyramid_request.registry, "settings"...
TestSearch
python
django__django
tests/lookup/models.py
{ "start": 550, "end": 925 }
class ____(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) slug = models.SlugField(unique=True, blank=True, null=True) class Meta: ordering = ("-pub_date", "headline") ...
Article
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_bash_code_execution_output_block.py
{ "start": 209, "end": 326 }
class ____(BaseModel): file_id: str type: Literal["bash_code_execution_output"]
BetaBashCodeExecutionOutputBlock
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
{ "start": 15286, "end": 16307 }
class ____(Mask): """Lazy full mask, allows all tokens to attend to all other tokens.""" # TODO(amagni): Transform FullMask into a _ComputableMask. _shape: tuple[int, int] def __post_init__(self): if not isinstance(self.shape, tuple): raise ValueError(f'Unsupported shape type: {type(self.shape)}') ...
FullMask
python
walkccc__LeetCode
solutions/1085. Sum of Digits in the Minimum Number/1085.py
{ "start": 0, "end": 120 }
class ____: def sumOfDigits(self, nums: list[int]) -> int: return sum(int(d) for d in str(min(nums))) & 1 ^ 1
Solution
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 63697, "end": 66448 }
class ____(BaseField): """A GridFS storage field.""" proxy_class = GridFSProxy def __init__( self, db_alias=DEFAULT_CONNECTION_NAME, collection_name="fs", **kwargs ): super().__init__(**kwargs) self.collection_name = collection_name self.db_alias = db_alias def __g...
FileField
python
kamyu104__LeetCode-Solutions
Python/number-of-zigzag-arrays-ii.py
{ "start": 100, "end": 1008 }
class ____(object): def zigZagArrays(self, n, l, r): """ :type n: int :type l: int :type r: int :rtype: int """ MOD = 10**9+7 def matrix_mult(A, B): ZB = zip(*B) return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD...
Solution
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 20742, "end": 21435 }
class ____: def __init__(self, privilege_group: str, privileges: List[milvus_types.PrivilegeEntity]): self._privilege_group = privilege_group privielges = [] for privilege in privileges: if isinstance(privilege, milvus_types.PrivilegeEntity): privielges.append(pri...
PrivilegeGroupItem
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 86882, "end": 87036 }
class ____(BaseModel, extra="forbid"): base: "Expression" = Field(..., description="") exponent: "Expression" = Field(..., description="")
PowParams
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/iterators.py
{ "start": 1459, "end": 1739 }
class ____: def __getitem__(self, i: int) -> str: return _test_source() def __len__(self) -> int: return 10 def test_custom_getitem(): # TODO(T137627339): False negative with custom `__getitem__` _test_sink(next(iter(CustomGetItem())))
CustomGetItem
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 69606, "end": 74321 }
class ____(PatchTSMixerPreTrainedModel): r""" `PatchTSMixer` for classification application. Args: config (`PatchTSMixerConfig`): Configuration. Returns: `None`. """ def __init__(self, config: PatchTSMixerConfig): super().__init__(config) self.mode...
PatchTSMixerForTimeSeriesClassification
python
doocs__leetcode
lcci/04.01.Route Between Nodes/Solution2.py
{ "start": 0, "end": 515 }
class ____: def findWhetherExistsPath( self, n: int, graph: List[List[int]], start: int, target: int ) -> bool: g = [[] for _ in range(n)] for a, b in graph: g[a].append(b) vis = {start} q = deque([start]) while q: i = q.popleft() ...
Solution
python
PrefectHQ__prefect
tests/server/models/test_orm.py
{ "start": 21436, "end": 26539 }
class ____: async def test_flow_run_lateness_when_scheduled(self, session, flow, db): lateness = datetime.timedelta(seconds=60) dt = now("UTC") - lateness fr = await models.flow_runs.create_flow_run( session=session, flow_run=schemas.core.FlowRun( flo...
TestExpectedStartTimeDelta
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 25280, "end": 26299 }
class ____(BaseModel, extra="forbid"): shard_key: "ShardKey" = Field(..., description="") shards_number: Optional[int] = Field( default=None, description="How many shards to create for this key If not specified, will use the default value from config", ) replication_factor: Optional[int]...
CreateShardingKey
python
pytorch__pytorch
torch/fx/passes/net_min_base.py
{ "start": 867, "end": 1034 }
class ____(Exception): """ Raised if error occurs during run_a or run_b functions """ @compatibility(is_backward_compatible=False)
FxNetMinimizerRunFuncError
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_validation__property.py
{ "start": 11283, "end": 17379 }
class ____: # test_Any unnecessary (no validation) # TODO (bev) test_Image def test_Angle(self, detail) -> None: p = Angle() with pytest.raises(ValueError) as e: p.validate("junk", detail) assert (str(e.value) == "") == (not detail) def test_Bool(self, detail) -> No...
TestValidateDetailExplicit
python
huggingface__transformers
src/transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py
{ "start": 21267, "end": 24436 }
class ____(HunYuanMoEV1PreTrainedModel): def __init__(self, config: HunYuanMoEV1Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) ...
HunYuanMoEV1Model
python
gevent__gevent
src/gevent/tests/test__server.py
{ "start": 17632, "end": 18221 }
class ____(TestCase): def get_spawn(self): return None def test_invalid_callback(self): self._test_invalid_callback() @greentest.skipOnAppVeyor("Sometimes doesn't get the error.") def test_assertion_in_blocking_func(self): def sleep(*_args): gevent.sleep(SMALLEST_R...
TestNoneSpawn
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_use_orig_params.py
{ "start": 55608, "end": 56597 }
class ____(TestCase): def test_multi_tensor_apply_size0_tensors_cpu(self): size0_tensors = [torch.empty(0, device="cpu") for _ in range(NUM_SIZE0_TENSORS)] # Check that this does not segfault torch._foreach_mul_(size0_tensors, 0.1) @unittest.skipIf(not TEST_CUDA and not TEST_XPU, "no cu...
TestMultiTensorApply
python
pydata__xarray
xarray/tests/test_coordinates.py
{ "start": 490, "end": 10999 }
class ____: def test_init_noindex(self) -> None: coords = Coordinates(coords={"foo": ("x", [0, 1, 2])}) expected = Dataset(coords={"foo": ("x", [0, 1, 2])}) assert_identical(coords.to_dataset(), expected) def test_init_default_index(self) -> None: coords = Coordinates(coords={"x...
TestCoordinates
python
pandas-dev__pandas
pandas/tests/tools/test_to_datetime.py
{ "start": 103815, "end": 107931 }
class ____: @pytest.mark.parametrize( "test_format", ["%m-%d-%Y", "%m/%d/%Y %H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S.%f"] ) def test_to_datetime_infer_datetime_format_consistent_format( self, cache, test_format ): ser = Series(date_range("20000101", periods=50, freq="h")) s_as_d...
TestToDatetimeInferFormat
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder6.py
{ "start": 473, "end": 925 }
class ____(Generic[_T]): ... def func1(future: Future[_T]) -> Future[_T]: ... def func2( __fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs ) -> Future[_T]: ... def func3() -> int: ... def func4(a: int, b: int) -> str: ... reveal_type(func1(func2(func3)), expected_text="Future[int]") reveal_type(...
Future
python
walkccc__LeetCode
solutions/28. Implement strStr()/28.py
{ "start": 0, "end": 215 }
class ____: def strStr(self, haystack: str, needle: str) -> int: m = len(haystack) n = len(needle) for i in range(m - n + 1): if haystack[i:i + n] == needle: return i return -1
Solution
python
fastapi__sqlmodel
docs_src/tutorial/update/tutorial001.py
{ "start": 100, "end": 1788 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_u...
Hero
python
facelessuser__pymdown-extensions
pymdownx/saneheaders.py
{ "start": 356, "end": 541 }
class ____(HashHeaderProcessor): """Process hash headers syntax.""" RE = re.compile(r'(?:^|\n)(?P<level>#{1,6})(?=[ ])(?P<header>(?:\\.|[^\\])*?)#*(?:\n|$)')
SaneHeadersProcessor
python
skorch-dev__skorch
skorch/tests/test_hf.py
{ "start": 41728, "end": 42583 }
class ____: """Mock of huggingface_hub.HfAPI""" def __init__(self, return_url='some-url'): self.return_url = return_url self.calls = [] self.saved = None self._call_count = 0 def _sanity_check(self, path_or_fileobj): # must be either BytesIO (memory) or str (disk) ...
MockHfApi
python
pytorch__pytorch
torch/fx/passes/operator_support.py
{ "start": 1119, "end": 6111 }
class ____(OperatorSupportBase): """ `_support_dict` maps node.target typename to supported inputs dtypes. node.target typename is retrieved using helper function `get_node_target()` If supported inputs dtypes is None, it means any dtype is supported, else we should see a tuple like (([dtypes], .....
OperatorSupport
python
plotly__plotly.py
plotly/graph_objs/waterfall/_insidetextfont.py
{ "start": 233, "end": 17194 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "waterfall" _path_str = "waterfall.insidetextfont" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", ...
Insidetextfont
python
sympy__sympy
sympy/polys/polyerrors.py
{ "start": 3512, "end": 3571 }
class ____(GeneratorsError): pass @public
GeneratorsNeeded
python
kubernetes-client__python
kubernetes/client/models/v1_secret.py
{ "start": 383, "end": 10414 }
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...
V1Secret
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 8418, "end": 8709 }
class ____(String): """A variably sized string type. In SQL, usually corresponds to CLOB or TEXT. In general, TEXT objects do not have a length; while some databases will accept a length argument here, it will be rejected by others. """ __visit_name__ = "text"
Text
python
fluentpython__example-code-2e
05-data-classes/typing_namedtuple/coordinates2.py
{ "start": 277, "end": 414 }
class ____(NamedTuple): lat: float # <1> lon: float reference: str = 'WGS84' # <2> # end::COORDINATE[]
Coordinate
python
google__pytype
pytype/config.py
{ "start": 962, "end": 4693 }
class ____: """Encapsulation of the configuration options.""" _HAS_DYNAMIC_ATTRIBUTES = True @overload def __init__(self, argv_or_options: list[str], command_line: Literal[True]): ... @overload def __init__( self, argv_or_options: argparse.Namespace, command_line: Literal[False] = ....
Options
python
ansible__ansible
test/lib/ansible_test/_internal/executor.py
{ "start": 2038, "end": 2260 }
class ____(ApplicationWarning): """Exception when changes detected, but no tests trigger as a result.""" def __init__(self) -> None: super().__init__('No tests found for detected changes.')
NoTestsForChanges
python
networkx__networkx
networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py
{ "start": 287, "end": 3314 }
class ____: def test_K4_normalized(self): """Betweenness centrality: K4""" G = nx.complete_graph(4) b = nx.current_flow_betweenness_centrality_subset( G, list(G), list(G), normalized=True ) b_answer = nx.current_flow_betweenness_centrality(G, normalized=True) ...
TestFlowBetweennessCentrality
python
sqlalchemy__sqlalchemy
test/orm/test_selectin_relations.py
{ "start": 70779, "end": 73906 }
class ____(fixtures.DeclarativeMappedTest): __requires__ = ("tuple_in",) @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(ComparableEntity, Base): __tablename__ = "a" id1 = Column(Integer, primary_key=True) id2 = Column(Integer, p...
TupleTest
python
gabrielfalcao__HTTPretty
httpretty/core.py
{ "start": 1961, "end": 5666 }
class ____: thread_timeout = 0.1 # https://github.com/gabrielfalcao/HTTPretty/issues/430 temp_files = [] threads = [] @classmethod def cleanup_sockets(cls): cls.cleanup_temp_files() cls.cleanup_threads() @classmethod def cleanup_threads(cls): for t in cls.threads: ...
__internals__
python
gevent__gevent
src/gevent/tests/known_failures.py
{ "start": 1058, "end": 1209 }
class ____(AbstractBinaryCondition): __slots__ = () OP = '&' def __bool__(self): return bool(self.lhs) and bool(self.rhs)
AndCondition
python
readthedocs__readthedocs.org
readthedocs/core/views/__init__.py
{ "start": 626, "end": 1041 }
class ____(CDNCacheControlMixin, View): # Never cache this view, we always want to get the live response from the server. # In production we should configure the health check to hit the LB directly, # but it's useful to be careful here in case of a misconfiguration. cache_response = False def get(s...
HealthCheckView
python
django-crispy-forms__django-crispy-forms
crispy_forms/helper.py
{ "start": 3660, "end": 12772 }
class ____(DynamicLayoutHandler): """ This class controls the form rendering behavior of the form passed to the `{% crispy %}` tag. For doing so you will need to set its attributes and pass the corresponding helper object to the tag:: {% crispy form form.helper %} Let's see what attributes...
FormHelper
python
python-attrs__attrs
tests/test_next_gen.py
{ "start": 364, "end": 10065 }
class ____: def test_simple(self): """ Instantiation works. """ C("1", 2) def test_field_type(self): """ Make class with attrs.field and type parameter. """ classFields = {"testint": attrs.field(type=int)} A = attrs.make_class("A", classF...
TestNextGen
python
ethereum__web3.py
web3/types.py
{ "start": 8110, "end": 8281 }
class ____(TypedDict, total=False): error_formatters: Formatters | None request_formatters: Formatters | None result_formatters: Formatters | None
FormattersDict
python
coleifer__peewee
tests/keys.py
{ "start": 1042, "end": 1143 }
class ____(TestModel): user = ForeignKeyField(User, backref='notes') content = TextField()
Note
python
django__django
tests/raw_query/models.py
{ "start": 990, "end": 1159 }
class ____(models.Model): brand = models.CharField(max_length=255, db_column="name") price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
Coffee
python
viewflow__viewflow
viewflow/fsm/viewset.py
{ "start": 3089, "end": 5496 }
class ____(metaclass=ViewsetMeta): flow_state = None transition_view_class = ModelTransitionView def get_flow_state(self, request) -> State: if self.flow_state is None: raise ValueError("flow_state attribute is not defined.") return self.flow_state def get_object_flow(self,...
FlowViewsMixin
python
pydantic__pydantic
pydantic/v1/types.py
{ "start": 6681, "end": 9187 }
class ____(float, metaclass=ConstrainedNumberMeta): strict: bool = False gt: OptionalIntFloat = None ge: OptionalIntFloat = None lt: OptionalIntFloat = None le: OptionalIntFloat = None multiple_of: OptionalIntFloat = None allow_inf_nan: Optional[bool] = None @classmethod def __modif...
ConstrainedFloat
python
ipython__ipython
IPython/core/builtin_trap.py
{ "start": 378, "end": 442 }
class ____: pass HideBuiltin = __HideBuiltin()
__HideBuiltin
python
encode__httpx
httpx/_transports/default.py
{ "start": 3494, "end": 3944 }
class ____(SyncByteStream): def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None: self._httpcore_stream = httpcore_stream def __iter__(self) -> typing.Iterator[bytes]: with map_httpcore_exceptions(): for part in self._httpcore_stream: yield part d...
ResponseStream
python
zarr-developers__zarr-python
src/zarr/codecs/_v2.py
{ "start": 475, "end": 3649 }
class ____(ArrayBytesCodec): filters: tuple[Numcodec, ...] | None compressor: Numcodec | None is_fixed_size = False async def _decode_single( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: cdata = chunk_bytes.as_array_like() # decompress ...
V2Codec
python
pydantic__pydantic
pydantic/errors.py
{ "start": 2452, "end": 3055 }
class ____: """A mixin class for common functionality shared by all Pydantic-specific errors. Attributes: message: A message describing the error. code: An optional error code from PydanticErrorCodes enum. """ def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None...
PydanticErrorMixin
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_testing.py
{ "start": 7769, "end": 8105 }
class ____: def f_missing(self, X, y): pass def f_bad_sections(self, X, y): """Function f Parameter --------- a : int Parameter a b : float Parameter b Results ------- c : list Parameter c """ ...
Klass
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_merge_range01.py
{ "start": 437, "end": 5004 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test merged cell range""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) worksheet.str_tabl...
TestAssembleWorksheet
python
great-expectations__great_expectations
great_expectations/core/batch_spec.py
{ "start": 1825, "end": 2037 }
class ____(Protocol): @property def reader_method(self) -> str: ... @property def reader_options(self) -> dict: ... def to_json_dict(self) -> dict[str, JSONValues]: ...
PandasBatchSpecProtocol
python
has2k1__plotnine
plotnine/themes/seaborn_rcmod.py
{ "start": 613, "end": 14750 }
class ____: """ No Op """ __version__ = _mpl.__version__ rcParams = {} mpl = dummy() _style_keys = [ "axes.facecolor", "axes.edgecolor", "axes.grid", "axes.axisbelow", "axes.labelcolor", "figure.facecolor", "grid.color", "grid.linestyle", "text.color", "x...
dummy
python
scipy__scipy
scipy/optimize/tests/test_minimize_constrained.py
{ "start": 5555, "end": 6893 }
class ____: """Rosenbrock function. The following optimization problem: minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0) """ def __init__(self, n=2, random_state=0): rng = np.random.RandomState(random_state) self.x0 = rng.uniform(-1, 1, n) self.x_opt =...
Rosenbrock