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
django__django
tests/template_tests/test_response.py
{ "start": 8789, "end": 13242 }
class ____(SimpleTestCase): factory = RequestFactory() def _response(self, template="foo", *args, **kwargs): self._request = self.factory.get("/") template = engines["django"].from_string(template) return TemplateResponse(self._request, template, *args, **kwargs) def test_render(se...
TemplateResponseTest
python
django__django
tests/admin_views/tests.py
{ "start": 3807, "end": 4889 }
class ____: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for fi...
AdminFieldExtractionMixin
python
streamlit__streamlit
lib/tests/streamlit/components_test.py
{ "start": 10306, "end": 13465 }
class ____(unittest.TestCase): """Test component registration.""" def setUp(self) -> None: config = RuntimeConfig( script_path="mock/script/path.py", command_line=None, component_registry=LocalComponentRegistry(), media_file_storage=MemoryMediaFileStorage...
ComponentRegistryTest
python
pytest-dev__pytest-xdist
testing/test_newhooks.py
{ "start": 16, "end": 2553 }
class ____: @pytest.fixture(autouse=True) def create_test_file(self, pytester: pytest.Pytester) -> None: pytester.makepyfile( """ import os def test_a(): pass def test_b(): pass def test_c(): pass """ ) def test_runtest_log...
TestHooks
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-make-columns-strictly-increasing.py
{ "start": 42, "end": 483 }
class ____(object): def minimumOperations(self, grid): """ :type grid: List[List[int]] :rtype: int """ result = 0 for i in xrange(len(grid)-1): for j in xrange(len(grid[0])): if grid[i][j]+1 <= grid[i+1][j]: continue ...
Solution
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-weather/llama_index/readers/weather/base.py
{ "start": 195, "end": 2910 }
class ____(BaseReader): """ Weather Reader. Reads the forecast & current weather of any location using OpenWeatherMap's free API. Check 'https://openweathermap.org/appid' \ on how to generate a free OpenWeatherMap API, It's free. Args: token (str): bearer_token that you get from O...
WeatherReader
python
viewflow__viewflow
tests/test_templates.py
{ "start": 1694, "end": 2053 }
class ____(IndexViewMixin, AppMenuMixin, Viewset): title = 'Test Viewset' page_path = path('test/', TemplateView.as_view(template_name='viewflow/base_page.html'), name="page") urlpatterns = [ path('', Site(viewsets=[ Application( title='Test Application', viewsets=[TestView...
TestViewset
python
openai__openai-python
src/openai/types/model.py
{ "start": 181, "end": 532 }
class ____(BaseModel): id: str """The model identifier, which can be referenced in the API endpoints.""" created: int """The Unix timestamp (in seconds) when the model was created.""" object: Literal["model"] """The object type, which is always "model".""" owned_by: str """The organiz...
Model
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/side_channel/stats_side_channel.py
{ "start": 736, "end": 1876 }
class ____(SideChannel): """ Side channel that receives (string, float) pairs from the environment, so that they can eventually be passed to a StatsReporter. """ def __init__(self) -> None: # >>> uuid.uuid5(uuid.NAMESPACE_URL, "com.unity.ml-agents/StatsSideChannel") # UUID('a1d8f7b7...
StatsSideChannel
python
django__django
tests/middleware_exceptions/middleware.py
{ "start": 2952, "end": 3109 }
class ____(BaseMiddleware): def process_template_response(self, request, response): return None @async_only_middleware
NoTemplateResponseMiddleware
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 124320, "end": 131700 }
class ____(test.TestCase): def setUp(self): ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.mean_squared_error( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables( self, ('mean_squared_error/count:0', 'mean...
MeanSquaredErrorTest
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 14417, "end": 15193 }
class ____: def setup(self): self.df = DataFrame(np.random.randn(1000, 100)) self.s = Series(np.arange(1028.0)) self.df2 = DataFrame(dict.fromkeys(range(1028), self.s)) self.df3 = DataFrame(np.random.randn(1000, 3), columns=list("ABC")) def time_apply_user_func(self): s...
Apply
python
Pylons__pyramid
tests/test_security.py
{ "start": 18097, "end": 19474 }
class ____: def __init__(self, result): self.result = result def permits(self, context, principals, permission): return self.result def principals_allowed_by_permission(self, context, permission): return self.result def _registerSecurityPolicy(reg, result): from pyramid.inter...
DummyAuthorizationPolicy
python
scikit-learn__scikit-learn
sklearn/linear_model/_coordinate_descent.py
{ "start": 69338, "end": 79029 }
class ____(RegressorMixin, LinearModelCV): """Lasso linear model with iterative fitting along a regularization path. See glossary entry for :term:`cross-validation estimator`. The best model is selected by cross-validation. The optimization objective for Lasso is:: (1 / (2 * n_samples)) * ||...
LassoCV
python
cython__cython
Cython/Plex/Actions.py
{ "start": 2209, "end": 2524 }
class ____(Action): """ IGNORE is a Plex action which causes its associated token to be ignored. See the docstring of Plex.Lexicon for more information. """ def perform(self, token_stream, text): return None def __repr__(self): return "IGNORE" IGNORE = Ignore()
Ignore
python
getsentry__sentry
src/sentry/models/distribution.py
{ "start": 268, "end": 743 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded organization_id = BoundedBigIntegerField(db_index=True) release = FlexibleForeignKey("sentry.Release") name = models.CharField(max_length=64) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label...
Distribution
python
plotly__plotly.py
plotly/graph_objs/scattermapbox/_cluster.py
{ "start": 233, "end": 9697 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattermapbox" _path_str = "scattermapbox.cluster" _valid_props = { "color", "colorsrc", "enabled", "maxzoom", "opacity", "opacitysrc", "size", "sizesrc", "step", "stepsrc...
Cluster
python
pytorch__pytorch
torch/distributed/_local_tensor/__init__.py
{ "start": 15021, "end": 19835 }
class ____: """ Like a LocalTensor, but for an int. We can't use a 0D tensor to represent this because often only a SymInt is accepted where we wish to use this. """ def __new__(cls, local_ints: dict[int, int]) -> "ConstantIntNode | LocalIntNode": # type: ignore[misc] if len(set(local_int...
LocalIntNode
python
openai__openai-python
src/openai/resources/audio/translations.py
{ "start": 13974, "end": 14237 }
class ____: def __init__(self, translations: AsyncTranslations) -> None: self._translations = translations self.create = _legacy_response.async_to_raw_response_wrapper( translations.create, )
AsyncTranslationsWithRawResponse
python
great-expectations__great_expectations
tests/execution_engine/test_sparkdf_execution_engine.py
{ "start": 42037, "end": 52661 }
class ____: @pytest.mark.parametrize( "condition,expected_output", [ pytest.param( ComparisonCondition(column=Column("age"), operator=Operator.EQUAL, parameter=5), "age == 5", id="equal", ), pytest.param( ...
TestConditionToFilterClause
python
huggingface__transformers
tests/sagemaker/test_multi_node_data_parallel.py
{ "start": 1120, "end": 3850 }
class ____(unittest.TestCase): def setUp(self): subprocess.run( f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), encoding="utf-8", check=True, ) assert hasattr(self, "env") def create_estimator(self, i...
MultiNodeTest
python
pytest-dev__pytest
testing/example_scripts/fixtures/custom_item/conftest.py
{ "start": 148, "end": 375 }
class ____(pytest.File): def collect(self): yield CustomItem.from_parent(name="foo", parent=self) def pytest_collect_file(file_path, parent): return CustomFile.from_parent(path=file_path, parent=parent)
CustomFile
python
huggingface__transformers
src/transformers/models/clipseg/modeling_clipseg.py
{ "start": 30974, "end": 33178 }
class ____(nn.Module): # Copied from transformers.models.altclip.modeling_altclip.AltCLIPVisionTransformer.__init__ with AltCLIP->CLIPSeg def __init__(self, config: CLIPSegVisionConfig): super().__init__() self.config = config embed_dim = config.hidden_size self.embeddings = CLI...
CLIPSegVisionTransformer
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 30615, "end": 31188 }
class ____(Expr): """An internal name in the compiler. You cannot create these nodes yourself but the parser provides a :meth:`~spack.vendor.jinja2.parser.Parser.free_identifier` method that creates a new identifier for you. This identifier is not available from the template and is not treated spe...
InternalName
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/observability.py
{ "start": 7898, "end": 8045 }
class ____(BaseObservation): type: InfoObservationType title: str content: str | dict @dataclass(slots=True, frozen=True)
InfoObservation
python
streamlit__streamlit
lib/streamlit/elements/widgets/button_group.py
{ "start": 3891, "end": 5240 }
class ____(Generic[T]): """Only meant to be used internally for the button_group element. Uses the ButtonGroup's _MultiSelectSerde under-the-hood, but accepts a single index value and deserializes to a single index value. This is because button_group can be single and multi select, but we use the same ...
_SingleSelectSerde
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_checks.py
{ "start": 3722, "end": 4990 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.String) runId = graphene.NonNull(graphene.String) status = graphene.NonNull(GrapheneAssetCheckExecutionResolvedStatus) evaluation = graphene.Field(GrapheneAssetCheckEvaluation) timestamp = graphene.Field( graphene.NonNull(graphe...
GrapheneAssetCheckExecution
python
pandas-dev__pandas
pandas/core/interchange/dataframe_protocol.py
{ "start": 4678, "end": 12805 }
class ____(ABC): """ A column object, with only the methods and properties required by the interchange protocol defined. A column can contain one or more chunks. Each chunk can contain up to three buffers - a data buffer, a mask buffer (depending on null representation), and an offsets buffer (...
Column
python
huggingface__transformers
tests/models/xlm_roberta/test_tokenization_xlm_roberta.py
{ "start": 882, "end": 2626 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "FacebookAI/xlm-roberta-base" tokenizer_class = XLMRobertaTokenizer integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fals', 'é', '.', ...
XLMRobertaTokenizationTest
python
sympy__sympy
sympy/integrals/risch.py
{ "start": 32428, "end": 60298 }
class ____(Exception): """ Exception used by subroutines within the Risch algorithm to indicate to one another that the function being integrated does not have an elementary integral in the given differential field. """ # TODO: Rewrite algorithms below to use this (?) # TODO: Pass through i...
NonElementaryIntegralException
python
numba__numba
numba/core/typing/enumdecl.py
{ "start": 356, "end": 498 }
class ____(AttributeTemplate): key = types.EnumMember def resolve_value(self, ty): return ty.dtype @infer_getattr
EnumAttribute
python
psf__black
scripts/release.py
{ "start": 2205, "end": 7567 }
class ____: def __init__(self, black_repo_dir: Path): # File path fun all pathlib to be platform agnostic self.black_repo_path = black_repo_dir self.changes_path = self.black_repo_path / "CHANGES.md" self.docs_path = self.black_repo_path / "docs" self.version_doc_paths = ( ...
SourceFiles
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_with_skeleton.py
{ "start": 15976, "end": 18426 }
class ____ {{ {double_forward_slash} {CodeHierarchyNodeParser._get_comment_text(chunks[1])} }} """ ) def test_skeletonize_with_repeated_function() -> None: """Test case for code splitting using python.""" if "CI" in os.environ: return code_splitter = CodeHierarchyNodeParser( langu...
Example
python
getsentry__sentry
src/sentry/monitors/processing_errors/errors.py
{ "start": 2541, "end": 2708 }
class ____(TypedDict): """ Monitor was disabled for a non-billing related reason """ type: Literal[ProcessingErrorType.MONITOR_DISABLED]
MonitorDisabled
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 5100, "end": 5509 }
class ____( typing.Iterator[int] ): # Y022 Use "collections.abc.Iterator[T]" instead of "typing.Iterator[T]" (PEP 585 syntax) def __iter__(self) -> collections.abc.Iterator[int]: ... # Y034 "__iter__" methods in classes like "BadIterator3" usually return "self" at runtime. Consider using "typing_exten...
BadIterator3
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 18895, "end": 19326 }
class ____(BaseModel): """ Pool serializer for patch bodies. """ model_config = ConfigDict( extra="forbid", ) pool: Annotated[str | None, Field(title="Pool")] = None slots: Annotated[int | None, Field(title="Slots")] = None description: Annotated[str | None, Field(title="Descrip...
PoolPatchBody
python
kamyu104__LeetCode-Solutions
Python/jump-game-ix.py
{ "start": 581, "end": 1166 }
class ____(object): def maxValue(self, nums): """ :type nums: List[int] :rtype: List[int] """ suffix = [float("inf")]*(len(nums)+1) for i in reversed(xrange(len(nums))): suffix[i] = min(suffix[i+1], nums[i]) result = [0]*len(nums) mx = left...
Solution2
python
django__django
django/core/files/images.py
{ "start": 151, "end": 2643 }
class ____(File): """ A mixin for use alongside django.core.files.base.File, which provides additional features for dealing with images. """ @property def width(self): return self._get_image_dimensions()[0] @property def height(self): return self._get_image_dimensions()...
ImageFile
python
wandb__wandb
tests/unit_tests/test_step_upload.py
{ "start": 7192, "end": 16455 }
class ____: def test_upload(self, tmp_path: Path): api = make_api() cmd = make_request_upload(make_tmp_file(tmp_path)) run_step_upload([cmd], api=api) api.upload_file_retry.assert_called_once() assert api.upload_file_retry.call_args[0][0] == get_upload_url(cmd.save_name) ...
TestUpload
python
viewflow__viewflow
viewflow/views/list.py
{ "start": 10795, "end": 11168 }
class ____(object): bulk_actions = None def get_bulk_actions(self, *actions): if self.viewset is not None and hasattr(self.viewset, "get_list_bulk_actions"): actions = self.viewset.get_list_bulk_actions(self.request) + actions if self.bulk_actions: actions = self.bulk_ac...
BulkActionsMixin
python
rushter__MLAlgorithms
mla/ensemble/gbm.py
{ "start": 2008, "end": 4058 }
class ____(BaseEstimator): """Gradient boosting trees with Taylor's expansion approximation (as in xgboost).""" def __init__( self, n_estimators, learning_rate=0.1, max_features=10, max_depth=2, min_samples_split=10, ): self.min_samples_split = min_sa...
GradientBoosting
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 32125, "end": 33747 }
class ____(GeneratedAirbyteSource): class OAuth20: @public def __init__( self, client_id: str, client_secret: str, refresh_token: str, auth_method: Optional[str] = None, ): self.auth_method = check.opt_str_param(auth_met...
LinkedinPagesSource
python
getsentry__sentry
src/sentry/analytics/events/sentryapp_issue_webhooks.py
{ "start": 582, "end": 697 }
class ____(SentryAppIssueEvent): pass @analytics.eventclass("sentry_app.issue.unresolved")
SentryAppIssueResolved
python
huggingface__transformers
src/transformers/models/florence2/modeling_florence2.py
{ "start": 10390, "end": 12712 }
class ____(nn.Module): def __init__( self, config: Florence2VisionConfig, stage_idx: int, drop_path_rate: float, ): super().__init__() self.config = config dim_in = config.embed_dim[stage_idx] self.conv1 = nn.Conv2d( dim_in, ...
Florence2VisionChannelBlock
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_boolean_trap/FBT.py
{ "start": 1951, "end": 2807 }
class ____: def __init__(self) -> None: self._switches = [False] * len(Switch) # FBT001: Boolean positional arg in function definition def __setitem__(self, switch: Switch, value: bool) -> None: self._switches[switch.value] = value @foo.setter def foo(self, value: bool) -> None: ...
Registry
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 11897, "end": 12490 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = OpenBSDPkgMgrFactCollector def test_collect(self): module = self._mock_module() fact_collector = self.collector_class() ...
TestOpenBSDPkgMgrFacts
python
paramiko__paramiko
paramiko/proxy.py
{ "start": 1240, "end": 4648 }
class ____(ClosingContextManager): """ Wraps a subprocess running ProxyCommand-driven programs. This class implements a the socket-like interface needed by the `.Transport` and `.Packetizer` classes. Using this class instead of a regular socket makes it possible to talk with a Popen'd command that ...
ProxyCommand
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/multi_mesh_test.py
{ "start": 2600, "end": 28241 }
class ____(test_util.DTensorBaseTest): def setUp(self): super(MultiMeshTest, self).setUp() self.first_mesh = _ONE_D_CPU_MESH if test_util.is_tpu_present(): self.second_mesh = _ONE_D_TPU_MESH elif test_util.is_gpu_present(): self.second_mesh = _ONE_D_GPU_MESH else: self.second_me...
MultiMeshTest
python
pola-rs__polars
py-polars/src/polars/dataframe/group_by.py
{ "start": 27435, "end": 33201 }
class ____: """ A rolling grouper. This has an `.agg` method which will allow you to run all polars expressions in a group by context. """ def __init__( self, df: DataFrame, index_column: IntoExpr, *, period: str | timedelta, offset: str | timede...
RollingGroupBy
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/dagster/dagster_pipes/dagster_pipes_details_and_customization/custom_context_injector.py
{ "start": 280, "end": 1049 }
class ____(PipesContextInjector): # Note that `PipesContextData` corresponds to what this document # calls the "context payload"-- a JSON-serializable dictionary with context info. @contextmanager def inject_context(self, context_data: "PipesContextData") -> Iterator[PipesParams]: key = "".join(...
MyCustomCloudServiceContextInjector
python
jina-ai__jina
tests/integration/docarray_v2/test_streaming.py
{ "start": 6049, "end": 7265 }
class ____(Executor): @requests(on='/non_generator') def non_generator(self, docs: DocList[BaseDoc], **kwargs): return docs @requests(on='/generator') def generator(self, doc: MyDocument, **kwargs): yield MyDocument(text='new document') @pytest.mark.asyncio @pytest.mark.parametrize( ...
Executor3
python
getsentry__sentry
src/sentry/api/endpoints/email_capture.py
{ "start": 697, "end": 1604 }
class ____(Endpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } owner = ApiOwner.TELEMETRY_EXPERIENCE # Disable authentication and permission requirements. permission_classes = (IsAuthenticated,) def post(self, request: Request) -> Response: if not is_demo_mode_enab...
EmailCaptureEndpoint
python
anthropics__anthropic-sdk-python
src/anthropic/types/completion_create_params.py
{ "start": 3662, "end": 3936 }
class ____(CompletionCreateParamsBase, total=False): stream: Literal[False] """Whether to incrementally stream the response using server-sent events. See [streaming](https://docs.claude.com/en/api/streaming) for details. """
CompletionCreateParamsNonStreaming
python
doocs__leetcode
solution/1500-1599/1562.Find Latest Group of Size M/Solution2.py
{ "start": 0, "end": 404 }
class ____: def findLatestStep(self, arr: List[int], m: int) -> int: n = len(arr) if m == n: return n cnt = [0] * (n + 2) ans = -1 for i, v in enumerate(arr): v -= 1 l, r = cnt[v - 1], cnt[v + 1] if l == m or r == m: ...
Solution
python
pypa__pip
src/pip/_internal/models/direct_url.py
{ "start": 467, "end": 1829 }
class ____(Exception): pass def _get( d: dict[str, Any], expected_type: type[T], key: str, default: T | None = None ) -> T | None: """Get value from dictionary and verify expected type.""" if key not in d: return default value = d[key] if not isinstance(value, expected_type): r...
DirectUrlValidationError
python
kubernetes-client__python
kubernetes/client/rest.py
{ "start": 1154, "end": 13121 }
class ____(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github....
RESTClientObject
python
tornadoweb__tornado
tornado/test/httpserver_test.py
{ "start": 26261, "end": 26997 }
class ____(AsyncHTTPSTestCase, HandlerBaseTestCase): def get_app(self): return Application([("/", XHeaderTest.Handler)]) def get_httpserver_options(self): output = super().get_httpserver_options() output["xheaders"] = True return output def test_request_without_xprotocol(se...
SSLXHeaderTest
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_output_config_param.py
{ "start": 239, "end": 385 }
class ____(TypedDict, total=False): effort: Optional[Literal["low", "medium", "high"]] """All possible effort levels."""
BetaOutputConfigParam
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 89295, "end": 91251 }
class ____(AwsBaseOperator[SageMakerHook]): """ Start a notebook instance. .. seealso: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:SageMakerStartNotebookOperator` :param instance_name: The name of the notebook instance to start. ...
SageMakerStartNoteBookOperator
python
ipython__ipython
IPython/core/magics/extension.py
{ "start": 925, "end": 2477 }
class ____(Magics): """Magics to manage the IPython extensions system.""" @line_magic def load_ext(self, module_str): """Load an IPython extension by its module name.""" if not module_str: raise UsageError('Missing module name.') res = self.shell.extension_manager.load_e...
ExtensionMagics
python
pytorch__pytorch
torch/distributed/checkpoint/_experimental/checkpoint_reader.py
{ "start": 476, "end": 8695 }
class ____: """ Handles reading state dictionaries from storage. This class is responsible for reading model state dictionaries from storage according to the specified checkpoint layout. It supports synchronization barriers to ensure all ranks in a distributed setting complete their checkpoint oper...
CheckpointReader
python
readthedocs__readthedocs.org
readthedocs/oauth/services/base.py
{ "start": 5087, "end": 12510 }
class ____(Service): """ Subclass of Service that interacts with a VCS provider using the user's OAuth token. :param user: User to use in token lookup and session creation :param account: :py:class:`SocialAccount` instance for user """ def __init__(self, user, account): self.user = use...
UserService
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_massachusetts_zip.py
{ "start": 1791, "end": 4174 }
class ____(ColumnMapExpectation): """Expect values in this column to be valid Massachusetts zipcodes. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples...
ExpectColumnValuesToBeValidMassachusettsZip
python
getsentry__sentry
tests/sentry/issues/endpoints/test_organization_group_suspect_flags.py
{ "start": 197, "end": 4099 }
class ____(APITestCase, SnubaTestCase): endpoint = "sentry-api-0-organization-group-suspect-flags" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) @property def features(self) -> dict[str, bool]: return {"organizations:feature-flag-suspect-flags": True} ...
OrganizationGroupSuspectFlagsTestCase
python
fluentpython__example-code-2e
24-class-metaprog/persistent/persistlib.py
{ "start": 1304, "end": 1800 }
class ____: def __init__(self, name: str, py_type: type) -> None: self.name = name self.type = py_type def __set__(self, instance: 'Persistent', value: Any) -> None: try: value = self.type(value) except (TypeError, ValueError) as e: type_name = self.type....
Field
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 52572, "end": 53003 }
class ____(TestOnlySetsInBinaryOps, TestCase): def setUp(self): super().setUp() def gen(): for i in range(0, 10, 2): # noqa: UP028 yield i self.OrderedSet = OrderedSet((1, 2, 3)) self.other = gen() self.otherIsIterable = True del TestOnlySetsI...
TestOnlySetsGenerator
python
bokeh__bokeh
src/bokeh/core/property/instance.py
{ "start": 4156, "end": 4579 }
class ____(Object[S]): """ Accept values that are instances of serializable types (e.g. |HasProps|). """ @staticmethod def _assert_type(instance_type: type[Any]) -> None: if not (isinstance(instance_type, type) and issubclass(instance_type, Serializable)): raise ValueError(f"expected a ...
Instance
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/tf_record_writer_test.py
{ "start": 1448, "end": 5778 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def setUp(self): super(TFRecordWriterTest, self).setUp() self._num_records = 8 def writer_fn(self, filename, compression_type=""): input_dataset = readers.TFRecordDataset([filename], compression_type) return writers.TFRecordWriter(self...
TFRecordWriterTest
python
gevent__gevent
src/gevent/_fileobjectcommon.py
{ "start": 3045, "end": 3111 }
class ____(WriteIsWriteallMixin, io.FileIO): pass
WriteallFileIO
python
pallets__flask
src/flask/templating.py
{ "start": 846, "end": 1333 }
class ____(BaseEnvironment): """Works like a regular Jinja environment but has some additional knowledge of how Flask's blueprint works so that it can prepend the name of the blueprint to referenced templates if necessary. """ def __init__(self, app: App, **options: t.Any) -> None: if "load...
Environment
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0020_migrate_null_hidden_field.py
{ "start": 316, "end": 549 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0019_migrate_protected_versions_to_hidden"), ] operations = [ migrations.RunPython(forwards_func), ]
Migration
python
falconry__falcon
falcon/errors.py
{ "start": 72063, "end": 74325 }
class ____(HTTPError): """502 Bad Gateway. The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request. (See also: RFC 7231, Section 6.6.3) All the arguments are defined as keyword-only. Keyword A...
HTTPBadGateway
python
huggingface__transformers
src/transformers/models/blt/configuration_blt.py
{ "start": 6541, "end": 10654 }
class ____(PreTrainedConfig): r""" Configuration class for the Blt Patcher/Entropy model component. Args: vocab_size (`int`, *optional*, defaults to 260): Vocabulary size of the Blt patcher model. Defines the number of different tokens that can be represented by the `inputs_...
BltPatcherConfig
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 72704, "end": 97903 }
class ____: @pytest.fixture def _organization_invite(self, pyramid_user): self.initiator_user = pyramid_user self.user = UserFactory.create() EmailFactory.create(user=self.user, verified=True) self.desired_role = "Manager" self.organization_name = "example" self.m...
TestOrganizationMemberEmails
python
redis__redis-py
redis/asyncio/cluster.py
{ "start": 84697, "end": 98042 }
class ____(AbstractStrategy): NO_SLOTS_COMMANDS = {"UNWATCH"} IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"} UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"} SLOT_REDIRECT_ERRORS = (AskError, MovedError) CONNECTION_ERRORS = ( ConnectionError, OSError, ClusterDownError, ...
TransactionStrategy
python
tiangolo__fastapi
docs_src/security/tutorial004_an_py310.py
{ "start": 1101, "end": 4217 }
class ____(User): hashed_password: str password_hash = PasswordHash.recommended() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") app = FastAPI() def verify_password(plain_password, hashed_password): return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): ...
UserInDB
python
google__jax
tests/pallas/pallas_test.py
{ "start": 3415, "end": 27860 }
class ____(PallasBaseTest): def test_add_one(self): if jtu.test_device_matches(["tpu"]) and not self.INTERPRET: self.skipTest("On TPU the test works only in interpret mode") @functools.partial( self.pallas_call, out_shape=jax.ShapeDtypeStruct((), floatx)) def add_one(x_ref, o_ref): o_...
PallasCallTest
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 30873, "end": 31074 }
class ____(BaseModel): """Get the response content part of a Human-in-the-loop response.""" ti_id: UUID type: Literal["GetHITLDetailResponse"] = "GetHITLDetailResponse"
GetHITLDetailResponse
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_commits.py
{ "start": 332, "end": 3911 }
class ____(APITestCase): endpoint = "sentry-api-0-project-commits" def test_simple(self) -> None: project = self.create_project(name="komal") version = "1.1" repo = Repository.objects.create(organization_id=project.organization_id, name=project.name) release = Release.objects.cr...
ProjectCommitListTest
python
pytorch__pytorch
torch/_inductor/wrapper_benchmark.py
{ "start": 415, "end": 5256 }
class ____(Protocol): def __call__(self, times: int, repeat: int) -> float: ... _kernel_category_choices = [ "foreach", "persistent_reduction", "pointwise", "reduction", "split_scan", "template", ] def get_kernel_category_by_source_code(src_code: str) -> str: """ Similar to get_k...
BenchmarkCallableType
python
neetcode-gh__leetcode
python/2390-removing-stars-from-a-string.py
{ "start": 85, "end": 314 }
class ____(object) : def removeStars(self, s) : res = [] for c in s : if res and c == '*': res.pop() else: res.append(c) return ''.join(res)
Solution
python
huggingface__transformers
src/transformers/models/afmoe/modular_afmoe.py
{ "start": 1694, "end": 1740 }
class ____(GptOssRMSNorm): pass
AfmoeRMSNorm
python
readthedocs__readthedocs.org
readthedocs/proxito/views/hosting.py
{ "start": 28342, "end": 28442 }
class ____(SettingsOverrideObject): _default_class = BaseReadTheDocsConfigJson
ReadTheDocsConfigJson
python
huggingface__transformers
tests/test_backbone_common.py
{ "start": 799, "end": 10283 }
class ____: all_model_classes = () has_attentions = True def test_config(self): config_class = self.config_class # test default config config = config_class() self.assertIsNotNone(config) num_stages = len(config.depths) if hasattr(config, "depths") else config.num_h...
BackboneTesterMixin
python
fsspec__filesystem_spec
fsspec/implementations/tests/local/local_test.py
{ "start": 267, "end": 338 }
class ____(abstract.AbstractPutTests, LocalFixtures): pass
TestLocalPut
python
getsentry__sentry
src/sentry/middleware/subdomain.py
{ "start": 346, "end": 1860 }
class ____: """ Extracts any subdomain from request.get_host() relative to the `system.base-hostname` option, and attaches it to the request object under request.subdomain. If no subdomain is extracted, then request.subdomain is None. """ def __init__(self, get_response: Callable[[HttpRequest]...
SubdomainMiddleware
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 75506, "end": 75897 }
class ____(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): 1 / 0 def log_exception(self, typ, value, tb): 1 / 0 def test_buggy_log_exception(self): # Something gets logged even though the application's # logger is broken. wi...
BuggyLoggingTest
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 4368, "end": 6845 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention...
SplinterSelfAttention
python
getsentry__sentry
tests/sentry/workflow_engine/tasks/test_delayed_workflows.py
{ "start": 7159, "end": 8772 }
class ____(TestDelayedWorkflowTaskBase): @override_options({"delayed_processing.batch_size": 1}) @patch("sentry.workflow_engine.tasks.delayed_workflows.process_delayed_workflows.apply_async") def test_batched_cleanup(self, mock_process_delayed: MagicMock) -> None: self._push_base_events() pr...
TestDelayedWorkflowTaskIntegration
python
kamyu104__LeetCode-Solutions
Python/number-of-self-divisible-permutations.py
{ "start": 93, "end": 730 }
class ____(object): def selfDivisiblePermutationCount(self, n): """ :type n: int :rtype: int """ def popcount(x): return bin(x).count('1') def gcd(a, b): while b: a, b = b, a%b return a lookup = [[gcd(i+1, ...
Solution
python
doocs__leetcode
solution/0200-0299/0250.Count Univalue Subtrees/Solution.py
{ "start": 192, "end": 795 }
class ____: def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int: def dfs(root): if root is None: return True l, r = dfs(root.left), dfs(root.right) if not l or not r: return False a = root.val if root.left is None els...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/events.py
{ "start": 125363, "end": 131316 }
class ____(event.Events["registry"]): """Define events specific to :class:`_orm.registry` lifecycle. The :class:`_orm.RegistryEvents` class defines events that are specific to the lifecycle and operation of the :class:`_orm.registry` object. e.g.:: from typing import Any from sqlalch...
RegistryEvents
python
pydantic__pydantic
.github/actions/people/people.py
{ "start": 5689, "end": 5781 }
class ____(BaseModel): """Container for label nodes.""" nodes: list[LabelNode]
Labels
python
huggingface__transformers
src/transformers/models/speecht5/modeling_speecht5.py
{ "start": 100793, "end": 119613 }
class ____(SpeechT5PreTrainedModel): input_modalities = ("text",) main_input_name = "input_ids" def __init__(self, config: SpeechT5Config): super().__init__(config) if config.vocab_size is None: raise ValueError( f"You are trying to instantiate {self.__class__} ...
SpeechT5ForTextToSpeech
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 185363, "end": 189086 }
class ____(Response): """ Response of events.scalar_metrics_iter_raw endpoint. :param variants: Raw data points for each variant :type variants: dict :param total: Total data points count. If count_total is false, null is returned :type total: int :param returned: Number of data poi...
ScalarMetricsIterRawResponse
python
davidhalter__jedi
test/completion/django.py
{ "start": 4537, "end": 6505 }
class ____(BusinessModel): text_field = models.IntegerField() new_field = models.FloatField() inherited = Inherited() #? int() inherited.text_field #? str() inherited.char_field #? float() inherited.new_field #? Inherited.category_fk2.category_name #? str() inherited.category_fk2.category_name #? str() Inheri...
Inherited
python
TheAlgorithms__Python
web_programming/emails_from_url.py
{ "start": 430, "end": 3424 }
class ____(HTMLParser): def __init__(self, domain: str) -> None: super().__init__() self.urls: list[str] = [] self.domain = domain def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: """ This function parse html to take takes url from tags ...
Parser
python
pandas-dev__pandas
pandas/tseries/frequencies.py
{ "start": 4838, "end": 13031 }
class ____: """ Not sure if I can avoid the state machine here """ def __init__(self, index) -> None: self.index = index self.i8values = index.asi8 # For get_unit_from_dtype we need the dtype to the underlying ndarray, # which for tz-aware is not the same as index.dtyp...
_FrequencyInferer
python
bottlepy__bottle
test/test_environ.py
{ "start": 369, "end": 19717 }
class ____(unittest.TestCase): def test_app_property(self): e = {} r = BaseRequest(e) self.assertRaises(RuntimeError, lambda: r.app) e.update({'bottle.app': 5}) self.assertEqual(r.app, 5) def test_route_property(self): e = {'bottle.route': 5} r = BaseReq...
TestRequest
python
doocs__leetcode
solution/1500-1599/1529.Minimum Suffix Flips/Solution.py
{ "start": 0, "end": 180 }
class ____: def minFlips(self, target: str) -> int: ans = 0 for v in target: if (ans & 1) ^ int(v): ans += 1 return ans
Solution