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
fluentpython__example-code-2e
10-dp-1class-func/strategy_param.py
{ "start": 1178, "end": 1247 }
class ____(typing.NamedTuple): name: str fidelity: int
Customer
python
python-poetry__poetry
src/poetry/repositories/link_sources/json.py
{ "start": 364, "end": 1850 }
class ____(LinkSource): """Links as returned by PEP 691 compatible JSON-based Simple API.""" def __init__(self, url: str, content: dict[str, Any]) -> None: super().__init__(url=url) self.content = content @cached_property def _link_cache(self) -> LinkCache: links: LinkCache = d...
SimpleJsonPage
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/local_compute_log_manager.py
{ "start": 1255, "end": 9251 }
class ____(ComputeLogManager, ConfigurableClass): """Stores copies of stdout & stderr for each compute step locally on disk.""" def __init__( self, base_dir: str, polling_timeout: Optional[float] = None, inst_data: Optional[ConfigurableClassData] = None, ): self._bas...
LocalComputeLogManager
python
django__django
tests/db_functions/json/test_json_object.py
{ "start": 3371, "end": 3653 }
class ____(TestCase): def test_not_supported(self): msg = "JSONObject() is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(json_object=JSONObject()).get()
JSONObjectNotSupportedTests
python
huggingface__transformers
src/transformers/models/flava/modeling_flava.py
{ "start": 36567, "end": 40589 }
class ____(FlavaPreTrainedModel): config: FlavaTextConfig # This override allows us to load FlavaTextModel from FlavaModel/FlavaForPreTraining checkpoints. base_model_prefix = "flava.text_model" input_modalities = ("text",) def __init__(self, config: FlavaTextConfig, add_pooling_layer: bool = True)...
FlavaTextModel
python
Netflix__metaflow
metaflow/plugins/cards/card_decorator.py
{ "start": 736, "end": 1332 }
class ____(object): def __init__(self, info_func): self._info_func = info_func self._metadata_registered = {} def register_metadata(self, card_uuid) -> Tuple[bool, Dict]: info = self._info_func() # Check that metadata was not written yet. We only want to write once. if (...
MetadataStateManager
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 22690, "end": 22906 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("CHEVRON_UP", "DOT", "DOT_FILL", "HEART_FILL", "PLUS", "ZAP")
PinnedDiscussionPattern
python
redis__redis-py
tests/test_connection.py
{ "start": 13579, "end": 20064 }
class ____: def test_clears_cache_on_disconnect(self, mock_connection, cache_conf): cache = DefaultCache(CacheConfig(max_size=10)) cache_key = CacheKey( command="GET", redis_keys=("foo",), redis_args=("GET", "foo") ) cache.set( CacheEntry( cac...
TestUnitCacheProxyConnection
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/transpiler_test.py
{ "start": 1415, "end": 5421 }
class ____(test.TestCase): def test_basic(self): def f(a): return a + 1 tr = TestTranspiler() f, _, _ = tr.transform(f, None) self.assertEqual(f(1), 0) def test_closure(self): b = 1 def f(a): return a + b tr = TestTranspiler() f, _, _ = tr.transform(f, None) se...
PyToPyTest
python
pyca__cryptography
src/cryptography/hazmat/primitives/ciphers/algorithms.py
{ "start": 3229, "end": 3496 }
class ____(BlockCipherAlgorithm): name = "SM4" block_size = 128 key_sizes = frozenset([128]) def __init__(self, key: bytes): self.key = _verify_key_size(self, key) @property def key_size(self) -> int: return len(self.key) * 8
SM4
python
doocs__leetcode
solution/0500-0599/0519.Random Flip Matrix/Solution.py
{ "start": 0, "end": 593 }
class ____: def __init__(self, m: int, n: int): self.m = m self.n = n self.total = m * n self.mp = {} def flip(self) -> List[int]: self.total -= 1 x = random.randint(0, self.total) idx = self.mp.get(x, x) self.mp[x] = self.mp.get(self.total, self....
Solution
python
numba__numba
numba/core/types/containers.py
{ "start": 547, "end": 1255 }
class ____(Type): """ A heterogeneous pair. """ def __init__(self, first_type, second_type): self.first_type = first_type self.second_type = second_type name = "pair<%s, %s>" % (first_type, second_type) super(Pair, self).__init__(name=name) @property def key(sel...
Pair
python
weaviate__weaviate-python-client
weaviate/collections/classes/types.py
{ "start": 298, "end": 379 }
class ____(BaseModel): model_config = ConfigDict(extra="forbid")
_WeaviateInput
python
django__django
tests/admin_widgets/widgetadmin.py
{ "start": 405, "end": 746 }
class ____(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.filter(owner=request.user) return db_field.formfield(**kwargs) return super().formfield_for_foreignkey(db_field, request,...
CarTireAdmin
python
huggingface__transformers
src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py
{ "start": 6993, "end": 7599 }
class ____(GraniteMoeSharedPreTrainedModel): config: GraniteMoeHybridConfig _no_split_modules = ["GraniteMoeHybridDecoderLayer"] _is_stateful = True @torch.no_grad() def _init_weights(self, module): super()._init_weights(module) if isinstance(module, GraniteMoeHybridMambaLayer): ...
GraniteMoeHybridPreTrainedModel
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 112728, "end": 113422 }
class ____(nn.Module): """ Classification postprocessing for Perceiver. Can be used to convert the decoder output to classification logits. Args: config ([*PerceiverConfig*]): Model configuration. in_channels (`int`): Number of channels in the input. """ def...
PerceiverClassificationPostprocessor
python
scipy__scipy
scipy/optimize/_trustregion_constr/report.py
{ "start": 1066, "end": 1410 }
class ____(ReportBase): COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", "opt", "c viol", "penalty", "CG stop"] COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7] ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", "^10.2e",...
SQPReport
python
dask__distributed
distributed/recreate_tasks.py
{ "start": 271, "end": 1276 }
class ____: """A plugin for the scheduler to recreate tasks locally This adds the following routes to the scheduler * get_runspec * get_error_cause """ def __init__(self, scheduler): self.scheduler = scheduler self.scheduler.handlers["get_runspec"] = self.get_runspec ...
ReplayTaskScheduler
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 357637, "end": 361207 }
class ____(Response): """ Response of tasks.publish_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "tasks" _action = "publish_many" _version = "2.20" _schema = { "definitions": {}, ...
PublishManyResponse
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 223066, "end": 225323 }
class ____(GeneratedAirbyteSource): class PasswordAuthentication: @public def __init__(self, auth_user_password: str): self.auth_method = "SSH_PASSWORD_AUTH" self.auth_user_password = check.str_param(auth_user_password, "auth_user_password") class SSHKeyAuthentication: ...
SftpSource
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 14530, "end": 16818 }
class ____(TorchDistributionWrapper): """ A Beta distribution is defined on the interval [0, 1] and parameterized by shape parameters alpha and beta (also called concentration parameters). PDF(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z with Z = Gamma(alpha) Gamma(beta) / Gamma(alp...
TorchBeta
python
PyCQA__pydocstyle
src/tests/test_cases/test.py
{ "start": 3680, "end": 3963 }
class ____: """TrailingSpace.""" pass expect('LeadingAndTrailingSpaceMissing', 'D203: 1 blank line required before class docstring (found 0)') expect('LeadingAndTrailingSpaceMissing', 'D204: 1 blank line required after class docstring (found 0)')
TrailingSpace
python
django__django
tests/reverse_lookup/models.py
{ "start": 326, "end": 581 }
class ____(models.Model): name = models.CharField(max_length=100) poll = models.ForeignKey(Poll, models.CASCADE, related_name="poll_choice") related_poll = models.ForeignKey( Poll, models.CASCADE, related_name="related_choice" )
Choice
python
pytorch__pytorch
test/distributed/test_nvshmem.py
{ "start": 9088, "end": 26262 }
class ____(MultiProcContinuousTest): def _init_device(self) -> None: # TODO: relieve this (seems to hang if without) device_module.set_device(self.device) # Set NVSHMEM as SymmMem backend symm_mem.set_backend("NVSHMEM") @property def device(self) -> torch.device: ret...
NVSHMEMAll2AllTest
python
pennersr__django-allauth
allauth/socialaccount/forms.py
{ "start": 1205, "end": 2037 }
class ____(forms.Form): account = forms.ModelChoiceField( queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True, ) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") self.accounts = SocialAccount.objects.filter(user=sel...
DisconnectForm
python
django__django
tests/db_functions/text/test_sha512.py
{ "start": 228, "end": 2367 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ...
SHA512Tests
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_set.py
{ "start": 3980, "end": 6150 }
class ____(NamespacedKVSet): """Extend this class to define a set of metadata fields in the same namespace. Supports splatting to a dictionary that can be placed inside a metadata argument along with other dictionary-structured metadata. .. code-block:: python my_metadata: NamespacedMetadataS...
NamespacedMetadataSet
python
falconry__falcon
examples/recipes/raw_url_path_asgi.py
{ "start": 39, "end": 383 }
class ____: async def process_request(self, req, resp): raw_path = req.scope.get('raw_path') # NOTE: Decode the raw path from the raw_path bytestring, disallowing # non-ASCII characters, assuming they are correctly percent-coded. if raw_path: req.path = raw_path.decode...
RawPathComponent
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_new_release_email.py
{ "start": 725, "end": 5089 }
class ____(View): def get(self, request: HttpRequest) -> HttpResponse: org = Organization(id=1, slug="organization", name="My Company") projects = [ Project(id=1, organization=org, slug="project", name="My Project"), Project(id=2, organization=org, slug="another-project", nam...
DebugNewReleaseEmailView
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0091_upate_meta_options.py
{ "start": 120, "end": 448 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0090_dont_allow_ips_on_domains"), ] operations = [ migrations.AlterModelOptions( name="project", options={"ordering": ("slug",), "verbose_name": "project"}, ), ...
Migration
python
google__jax
jax/_src/buffer_callback.py
{ "start": 7583, "end": 10463 }
class ____(effects.Effect): def __str__(self): return "BufferCallback" _BufferCallbackEffect = BufferCallbackEffect() effects.lowerable_effects.add_type(BufferCallbackEffect) effects.control_flow_allowed_effects.add_type(BufferCallbackEffect) @buffer_callback_p.def_effectful_abstract_eval def _buffer_callback_...
BufferCallbackEffect
python
getsentry__sentry
src/sentry/release_health/base.py
{ "start": 3677, "end": 4360 }
class ____(TypedDict): #: Adoption rate (based on usercount) for a project's release from 0..100 adoption: float | None #: Adoption rate (based on sessioncount) for a project's release from 0..100 sessions_adoption: float | None #: User count for a project's release (past 24h) users_24h: int | N...
ReleaseAdoption
python
readthedocs__readthedocs.org
readthedocs/organizations/migrations/0014_update_dj_simple_history.py
{ "start": 149, "end": 1412 }
class ____(migrations.Migration): safe = Safe.before_deploy() dependencies = [ ("organizations", "0013_update_naming"), ] operations = [ migrations.AlterModelOptions( name="historicalorganization", options={ "get_latest_by": ("history_date", "hist...
Migration
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py
{ "start": 1580, "end": 1706 }
class ____: a: str = 0 b = field() c: int = foo() d = list() @attr.s(auto_attribs=True) # auto_attribs = True
C
python
kamyu104__LeetCode-Solutions
Python/minimum-path-cost-in-a-grid.py
{ "start": 40, "end": 566 }
class ____(object): def minPathCost(self, grid, moveCost): """ :type grid: List[List[int]] :type moveCost: List[List[int]] :rtype: int """ dp = [[0]*len(grid[0]) for _ in xrange(2)] dp[0] = [grid[0][j] for j in xrange(len(grid[0]))] for i in xrange(len...
Solution
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_state.py
{ "start": 2515, "end": 13251 }
class ____: def __init__( self, replica_id: ReplicaID, version: DeploymentVersion, ): self._replica_id = replica_id self._actor_name = replica_id.to_full_id_str() # Will be set when `start()` is called. self.started = False # Will be set when `reco...
MockReplicaActorWrapper
python
davidhalter__jedi
test/completion/descriptors.py
{ "start": 0, "end": 492 }
class ____(object): """ A data descriptor that sets and returns values normally and prints a message logging their access. """ def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print('Retrieving', self.name...
RevealAccess
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 762, "end": 801 }
class ____( object, # ) ): ...
A
python
PrefectHQ__prefect
src/integrations/prefect-aws/prefect_aws/s3.py
{ "start": 27096, "end": 87083 }
class ____(WritableFileSystem, WritableDeploymentStorage, ObjectStorageBlock): """ Block used to store data using AWS S3 or S3-compatible object storage like MinIO. Attributes: bucket_name: Name of your bucket. credentials: A block containing your credentials to AWS or MinIO. bucket...
S3Bucket
python
pytorch__pytorch
torch/ao/quantization/qconfig_mapping.py
{ "start": 7665, "end": 14845 }
class ____: """ Mapping from model ops to :class:`torch.ao.quantization.QConfig` s. The user can specify QConfigs using the following methods (in increasing match priority): ``set_global`` : sets the global (default) QConfig ``set_object_type`` : sets the QConfig for a given module type, ...
QConfigMapping
python
walkccc__LeetCode
solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py
{ "start": 0, "end": 285 }
class ____: def minOperations(self, grid: list[list[int]], x: int) -> int: arr = sorted([a for row in grid for a in row]) if any((a - arr[0]) % x for a in arr): return -1 ans = 0 for a in arr: ans += abs(a - arr[len(arr) // 2]) // x return ans
Solution
python
ipython__ipython
IPython/core/display.py
{ "start": 20455, "end": 22870 }
class ____(JSON): """GeoJSON expects JSON-able dict not an already-serialized JSON string. Scalar types (None, number, string) are not allowed, only dict containers. """ def __init__(self, *args, **kwargs): """Create a GeoJSON display object given raw data. Parameters ---...
GeoJSON
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 464689, "end": 468258 }
class ____(Request): """ For each passed query return projected frames matcing the conditions. One frame is returned per unique query field value :param versions: Dataset versions :type versions: Sequence[ViewEntry] :param query: The list of field queries :type query: Sequence[dict] """...
GetWithProjectionRequest
python
huggingface__transformers
src/transformers/models/speecht5/modeling_speecht5.py
{ "start": 34558, "end": 35198 }
class ____(nn.Module, EmbeddingAccessMixin): def __init__(self, config): super().__init__() self.config = config self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) def forward(self, hidden_states: torch.Tensor): return self.lm_head(hidden_states) de...
SpeechT5TextDecoderPostnet
python
getsentry__sentry
tests/sentry/api/helpers/test_group_index.py
{ "start": 23325, "end": 24130 }
class ____(TestCase): def setUp(self) -> None: self.group = self.create_group() self.group_list = [self.group] self.project_lookup = {self.group.project_id: self.group.project} def test_has_seen(self) -> None: handle_has_seen(True, self.group_list, self.project_lookup, [self.pro...
TestHandleHasSeen
python
django__django
tests/delete_regress/models.py
{ "start": 1438, "end": 1805 }
class ____(models.Model): contacts = models.ManyToManyField(Contact, related_name="research_contacts") primary_contact = models.ForeignKey( Contact, models.SET_NULL, null=True, related_name="primary_contacts" ) secondary_contact = models.ForeignKey( Contact, models.SET_NULL, null=True, r...
Researcher
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/transfers/test_google_api_to_s3.py
{ "start": 1086, "end": 7610 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( models.Connection( conn_id="google_test", host="google", conn_type="google_cloud_platform", schem...
TestGoogleApiToS3
python
openai__openai-python
src/openai/types/beta/threads/message_deleted.py
{ "start": 192, "end": 303 }
class ____(BaseModel): id: str deleted: bool object: Literal["thread.message.deleted"]
MessageDeleted
python
huggingface__transformers
tests/models/siglip2/test_modeling_siglip2.py
{ "start": 20944, "end": 23979 }
class ____(Siglip2ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (Siglip2Model,) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": Siglip2Model} if is_torch_available() else {} additional_model_inputs = [ "pixel_values", "pixel_at...
Siglip2ModelTest
python
Netflix__metaflow
metaflow/datastore/spin_datastore.py
{ "start": 129, "end": 3035 }
class ____(object): def __init__( self, flow_name: str, run_id: str, step_name: str, task_id: str, orig_datastore: TaskDataStore, spin_artifacts: Dict[str, Any], ): """ SpinTaskDatastore is a datastore for a task that is used to retrieve ...
SpinTaskDatastore
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 9405, "end": 9474 }
class ____(HTTPClientError): status_code = 424
HTTPFailedDependency
python
pallets__markupsafe
src/markupsafe/__init__.py
{ "start": 11088, "end": 12090 }
class ____(string.Formatter): __slots__ = ("escape",) def __init__(self, escape: _TPEscape) -> None: self.escape: _TPEscape = escape super().__init__() def format_field(self, value: t.Any, format_spec: str) -> str: if hasattr(value, "__html_format__"): rv = value.__html...
EscapeFormatter
python
kamyu104__LeetCode-Solutions
Python/kth-smallest-number-in-multiplication-table.py
{ "start": 42, "end": 545 }
class ____(object): def findKthNumber(self, m, n, k): """ :type m: int :type n: int :type k: int :rtype: int """ def count(target, m, n): return sum(min(target//i, n) for i in xrange(1, m+1)) left, right = 1, m*n while left <= righ...
Solution
python
Delgan__loguru
tests/exceptions/source/diagnose/multilines_repr.py
{ "start": 138, "end": 341 }
class ____: def __repr__(self): return "[[1, 2, 3]\n" " [4, 5, 6]\n" " [7, 8, 9]]" def multiline(): a = b = A() a + b try: multiline() except TypeError: logger.exception("")
A
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_set_column01.py
{ "start": 315, "end": 2148 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("set_column01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/assignment5.py
{ "start": 148, "end": 354 }
class ____: key: str next: Optional["Node"] = None node = Node() # This should analyze fine because node.next should be assigned # None before node is assigned None. node.next, node = None, None
Node
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/plugins.py
{ "start": 4371, "end": 4553 }
class ____(BaseModel): """Plugin Import Error Collection serializer.""" import_errors: list[PluginImportErrorResponse] total_entries: int
PluginImportErrorCollectionResponse
python
django__django
tests/test_client/views.py
{ "start": 6632, "end": 9536 }
class ____(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices) def clean(self): cleaned_data = self.cleaned_data if cleaned_data.get("t...
TestForm
python
pytest-dev__pytest
testing/test_pluginmanager.py
{ "start": 8667, "end": 14846 }
class ____: def test_register_imported_modules(self) -> None: pm = PytestPluginManager() mod = types.ModuleType("x.y.pytest_hello") pm.register(mod) assert pm.is_registered(mod) values = pm.get_plugins() assert mod in values pytest.raises(ValueError, pm.regist...
TestPytestPluginManager
python
google__flatbuffers
tests/namespace_test/NamespaceA/SecondTableInA.py
{ "start": 181, "end": 1515 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = SecondTableInA() x.Init(buf, n + offset) return x @classmethod def GetRootAsSecondTableInA(cls, buf, offset=0): """This method ...
SecondTableInA
python
scipy__scipy
scipy/sparse/linalg/_dsolve/tests/test_linsolve.py
{ "start": 28946, "end": 34644 }
class ____: def setup_method(self): use_solver(useUmfpack=False) @pytest.mark.parametrize("fmt",["csr","csc"]) def test_zero_diagonal(self,fmt): n = 5 rng = np.random.default_rng(43876432987) A = rng.standard_normal((n, n)) b = np.arange(n) A = scipy.sparse.t...
TestSpsolveTriangular
python
walkccc__LeetCode
solutions/47. Permutations II/47.py
{ "start": 0, "end": 556 }
class ____: def permuteUnique(self, nums: list[int]) -> list[list[int]]: ans = [] used = [False] * len(nums) def dfs(path: list[int]) -> None: if len(path) == len(nums): ans.append(path.copy()) return for i, num in enumerate(nums): if used[i]: continue ...
Solution
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/grouping.py
{ "start": 16140, "end": 17164 }
class ____: """A reducer is used for reducing a set of elements. A reducer is represented as a tuple of the three functions: - init_func - to define initial value: key => initial state - reducer_func - operation to perform on values with same key: (old state, input) => new state - finalize_func - value to re...
Reducer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassKwOnly1.py
{ "start": 320, "end": 544 }
class ____: b: int = field(kw_only=True, default=3) a: str DC2("hi") DC2(a="hi") DC2(a="hi", b=1) DC2("hi", b=1) # This should generate an error because "b" is keyword-only. DC2("hi", 1) @dataclass(kw_only=True)
DC2
python
django__django
django/contrib/staticfiles/management/commands/runserver.py
{ "start": 184, "end": 1373 }
class ____(RunserverCommand): help = ( "Starts a lightweight web server for development and also serves static files." ) def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--nostatic", action="store_false", dest="...
Command
python
langchain-ai__langchain
libs/langchain/tests/integration_tests/cache/fake_embeddings.py
{ "start": 2462, "end": 3469 }
class ____(Embeddings): """From angles (as strings in units of pi) to unit embedding vectors on a circle.""" def embed_documents(self, texts: list[str]) -> list[list[float]]: """Make a list of texts into a list of embedding vectors.""" return [self.embed_query(text) for text in texts] @ove...
AngularTwoDimensionalEmbeddings
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 1496, "end": 1682 }
class ____(BaseModel, extra='forbid'): pass KwargsForbidExtraModel(x=1) # MYPY: error: Unexpected keyword argument "x" for "KwargsForbidExtraModel" [call-arg]
KwargsForbidExtraModel
python
Pylons__pyramid
src/pyramid/predicates.py
{ "start": 1497, "end": 2489 }
class ____: def __init__(self, val, config): val = as_sorted_tuple(val) reqs = [] for p in val: k = p v = None if p.startswith('='): if '=' in p[1:]: k, v = p[1:].split('=', 1) k = '=' + k ...
RequestParamPredicate
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 31822, "end": 32506 }
class ____(enum.Enum): """Replication mode for input function. * `PER_WORKER`: The input function will be called on each worker independently, creating as many input pipelines as number of workers. Replicas will dequeue from the local Dataset on their worker. `tf.distribute.Strategy` doesn't manage any...
InputReplicationMode
python
huggingface__transformers
src/transformers/models/data2vec/modular_data2vec_audio.py
{ "start": 9036, "end": 9326 }
class ____(Wav2Vec2ForXVector): pass __all__ = [ "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", ]
Data2VecAudioForXVector
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 43762, "end": 43854 }
class ____(Protocol[_T_co]): def __call__(s, self: Any, /) -> None: ...
_HybridDeleterType
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 11655, "end": 12406 }
class ____: def test_robust_getitem(self) -> None: class UnreliableArrayFailure(Exception): pass class UnreliableArray: def __init__(self, array, failures=1): self.array = array self.failures = failures def __getitem__(self, key):...
TestCommon
python
facebook__pyre-check
tools/generate_taint_models/model.py
{ "start": 5133, "end": 6273 }
class ____(RawCallableModel): callable_object: Callable[..., object] def __init__( self, callable_object: Callable[..., object], parameter_annotation: Optional[ParameterAnnotation] = None, returns: Optional[str] = None, parameter_type_whitelist: Optional[Iterable[str]] =...
CallableModel
python
pyparsing__pyparsing
examples/infix_math_parser.py
{ "start": 965, "end": 6486 }
class ____: """A class for defining an infix notation parsers.""" # Supported infix binary operators, i.e., '1+1'. The key is the notation of the operator in infix format, # and the value the notation in parsed format. BINARY_OPERATORS: dict[str, str] = { "+": "Add", "-": "Subtract", ...
InfixExpressionParser
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/nodebase.py
{ "start": 464, "end": 4777 }
class ____(Generic[T]): """ An abstract node type. Nodes are immutable! This contains a (potentially empty) tuple of child nodes, along with non-child data. For uniform reconstruction and implementation of hashing and equality schemes, child classes need to provide a certain amount of meta...
Node
python
pypa__setuptools
setuptools/_vendor/backports/tarfile/__init__.py
{ "start": 58240, "end": 108491 }
class ____(object): """The TarFile Class provides an interface to tar archives. """ debug = 0 # May be set from 0 (no msgs) to 3 (all msgs) dereference = False # If true, add content of linked file to the # tar file, else the link. ignore_...
TarFile
python
simonw__sqlite-utils
sqlite_utils/db.py
{ "start": 5897, "end": 5990 }
class ____(Exception): "Could not tell which table this operation refers to"
NoObviousTable
python
pallets__werkzeug
src/werkzeug/wsgi.py
{ "start": 11762, "end": 14740 }
class ____: # private for now, but should we make it public in the future ? """This class can be used to convert an iterable object into an iterable that will only yield a piece of the underlying content. It yields blocks until the underlying stream range is fully read. The yielded blocks will have...
_RangeWrapper
python
pola-rs__polars
py-polars/src/polars/expr/string.py
{ "start": 1166, "end": 115235 }
class ____: """Namespace for string related expressions.""" _accessor = "str" def __init__(self, expr: Expr) -> None: self._pyexpr = expr._pyexpr def to_date( self, format: str | None = None, *, strict: bool = True, exact: bool = True, cache: bo...
ExprStringNameSpace
python
celery__celery
t/smoke/tests/test_canvas.py
{ "start": 541, "end": 945 }
class ____: def test_sanity(self, celery_setup: CeleryTestSetup): sig = group( group(add.si(1, 1), add.si(2, 2)), group([add.si(1, 1), add.si(2, 2)]), group(s for s in [add.si(1, 1), add.si(2, 2)]), ) res = sig.apply_async(queue=celery_setup.worker.worker_...
test_group
python
great-expectations__great_expectations
great_expectations/datasource/fluent/pandas_datasource.py
{ "start": 2508, "end": 13193 }
class ____(DataAsset): """ A Pandas DataAsset is a DataAsset that is backed by a Pandas DataFrame. """ _EXCLUDE_FROM_READER_OPTIONS: ClassVar[Set[str]] = { "batch_definitions", "batch_metadata", "name", "order_by", "type", "id", } class Config: ...
_PandasDataAsset
python
pandas-dev__pandas
pandas/tests/extension/base/methods.py
{ "start": 354, "end": 27303 }
class ____: """Various Series and DataFrame methods.""" def test_hash_pandas_object(self, data): # _hash_pandas_object should return a uint64 ndarray of the same length # as the data from pandas.core.util.hashing import _default_hash_key res = data._hash_pandas_object( ...
BaseMethodsTests
python
wandb__wandb
wandb/automations/_generated/fragments.py
{ "start": 1535, "end": 1713 }
class ____(GQLResult): typename__: Typename[ Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"] ]
GenericWebhookActionFieldsIntegrationIntegration
python
django__django
tests/postgres_tests/test_hstore.py
{ "start": 680, "end": 2387 }
class ____(PostgreSQLTestCase): def test_save_load_success(self): value = {"a": "b"} instance = HStoreModel(field=value) instance.save() reloaded = HStoreModel.objects.get() self.assertEqual(reloaded.field, value) def test_null(self): instance = HStoreModel(field...
SimpleTests
python
xlwings__xlwings
xlwings/constants.py
{ "start": 127822, "end": 127972 }
class ____: xlXmlImportSuccess = 0 # from enum XlXmlImportResult xlXmlImportValidationFailed = 2 # from enum XlXmlImportResult
XmlImportResult
python
openai__openai-python
src/openai/resources/images.py
{ "start": 94356, "end": 94817 }
class ____: def __init__(self, images: AsyncImages) -> None: self._images = images self.create_variation = _legacy_response.async_to_raw_response_wrapper( images.create_variation, ) self.edit = _legacy_response.async_to_raw_response_wrapper( images.edit, ...
AsyncImagesWithRawResponse
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 31173, "end": 31396 }
class ____(serializers.ModelSerializer): """Serializer used to remove a subproject relationship to a Project.""" class Meta: model = ProjectRelationship fields = ("alias",)
SubprojectDestroySerializer
python
fsspec__filesystem_spec
fsspec/implementations/zip.py
{ "start": 95, "end": 6072 }
class ____(AbstractArchiveFileSystem): """Read/Write contents of ZIP archive as a file-system Keeps file object open while instance lives. This class is pickleable, but not necessarily thread-safe """ root_marker = "" protocol = "zip" cachable = False def __init__( self, ...
ZipFileSystem
python
pallets__click
src/click/shell_completion.py
{ "start": 1417, "end": 5583 }
class ____: """Represents a completion value and metadata about the value. The default metadata is ``type`` to indicate special shell handling, and ``help`` if a shell supports showing a help string next to the value. Arbitrary parameters can be passed when creating the object, and accessed usi...
CompletionItem
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/maintainers_1/package.py
{ "start": 217, "end": 484 }
class ____(Package): """Package with a maintainers field.""" homepage = "http://www.example.com" url = "http://www.example.com/maintainers-1.0.tar.gz" maintainers("user1", "user2") version("1.0", md5="0123456789abcdef0123456789abcdef")
Maintainers1
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 270184, "end": 272620 }
class ____(ExternKernel): """ The result of a call to aten._assert_scalar """ def get_reads(self) -> OrderedSet[Dep]: return OrderedSet() def should_allocate(self) -> bool: return False def __init__(self, scalar: SympyBoolean, msg: str) -> None: super().__init__( ...
AssertScalar
python
catalyst-team__catalyst
catalyst/engines/torch.py
{ "start": 868, "end": 1234 }
class ____(Engine): """Multi-GPU-based engine.""" def __init__(self, *args, **kwargs) -> None: """Init.""" super().__init__(*args, cpu=False, **kwargs) def prepare_model(self, model): """Overrides.""" model = torch.nn.DataParallel(model) model = super().prepare_mode...
DataParallelEngine
python
oauthlib__oauthlib
examples/device_code_flow.py
{ "start": 7671, "end": 7892 }
class ____: def __init__(self): validator = ExampleRequestValidator self.server = Server(validator) # You should already have the /token endpoint implemented in your provider.
ServerSetupForTokenEndpoint
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/type_api.py
{ "start": 3033, "end": 3156 }
class ____(TypedDict): impl: TypeEngine[Any] result: Dict[Any, Optional[_ResultProcessorType[Any]]]
_BaseTypeMemoDict
python
gevent__gevent
src/gevent/testing/leakcheck.py
{ "start": 1928, "end": 8227 }
class ____(object): # Some builtin things that we ignore. # For awhile, we also ignored types.FrameType and types.TracebackType, # but those are important and often involved in leaks. IGNORED_TYPES = (tuple, dict,) try: CALLBACK_KIND = gevent.core.callback except AttributeError: ...
_RefCountChecker
python
Textualize__textual
tests/test_binding_inheritance.py
{ "start": 18888, "end": 20560 }
class ____(AppKeyRecorder): """An app with a non-default screen that handles movement key bindings, child no-inherit.""" SCREENS = {"main": ScreenWithMovementBindingsNoInheritEmptyChild} def on_mount(self) -> None: self.push_screen("main") async def test_focused_child_widget_no_inherit_empty_bin...
AppWithScreenWithBindingsWidgetEmptyBindingsNoInherit
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py
{ "start": 13909, "end": 17468 }
class ____(CheckDocumentationContent): name = "Prerequisites section of the documentation describes all required fields from specification" description = ( "The user facing connector documentation should update `Prerequisites`" " section with description for all required fields from source speci...
CheckPrerequisitesSectionDescribesRequiredFieldsFromSpec
python
dask__distributed
distributed/tests/test_nanny.py
{ "start": 3446, "end": 17508 }
class ____(Worker): # a subclass of Worker which is not Worker pass @gen_cluster(client=True, Worker=Nanny) async def test_nanny_worker_class(c, s, w1, w2): out = await c._run(lambda dask_worker=None: str(dask_worker.__class__)) assert "Worker" in list(out.values())[0] assert w1.Worker is Worker ...
Something
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_pubsub.py
{ "start": 14040, "end": 18763 }
class ____: def _generate_messages(self, count): return [ ReceivedMessage( ack_id=f"{i}", message={ "data": f"Message {i}".encode(), "attributes": {"type": "generated message"}, }, ) f...
TestPubSubPullOperator
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
{ "start": 8499, "end": 57107 }
class ____(graphene.ObjectType): # NOTE: properties/resolvers are listed alphabetically assetKey = graphene.NonNull(GrapheneAssetKey) assetMaterializations = graphene.Field( non_null_list(GrapheneMaterializationEvent), partitions=graphene.List(graphene.NonNull(graphene.String)), befo...
GrapheneAssetNode