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
allegroai__clearml
clearml/utilities/parallel.py
{ "start": 7659, "end": 20022 }
class ____(object): """ Used to zip multiple files in zip chunks of a particular size, all in parallel """ class ZipperObject(object): def __init__( self, chunk_size: int, zipper_queue: PriorityQueue, zipper_results: Queue, allow_zip_6...
ParallelZipper
python
huggingface__transformers
src/transformers/models/cvt/modeling_cvt.py
{ "start": 3534, "end": 4643 }
class ____(nn.Module): """ Image to Conv Embedding. """ def __init__(self, patch_size, num_channels, embed_dim, stride, padding): super().__init__() patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) self.patch_size = patch_...
CvtConvEmbeddings
python
run-llama__llama_index
llama-index-integrations/postprocessor/llama-index-postprocessor-flashrank-rerank/llama_index/postprocessor/flashrank_rerank/base.py
{ "start": 488, "end": 833 }
class ____(BaseEvent): """FlashRerankingQueryEvent.""" nodes: list[NodeWithScore] = Field(..., description="Nodes to rerank.") model_name: str = Field(..., description="Model name.") query_str: str = Field(..., description="Query string.") top_k: int = Field(..., description="Top k nodes to return....
FlashRerankingQueryEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/components.py
{ "start": 1044, "end": 1679 }
class ____(RecordExtractor): def extract_records(self, response: requests.Response) -> List[Mapping[str, Any]]: try: records = [] for definition in response.json()["definitions"]["conditions_all"]: definition["condition"] = "all" records.append(definit...
ZendeskSupportAttributeDefinitionsExtractor
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/abstractClass11.py
{ "start": 196, "end": 326 }
class ____(metaclass=CustomMeta): @abstractmethod def abstract(self): pass @final # This should generate an error.
A
python
jina-ai__jina
jina/clients/base/grpc.py
{ "start": 860, "end": 13852 }
class ____(BaseClient): """A simple Python client for connecting to the gRPC gateway. It manages the asyncio event loop internally, so all interfaces are synchronous from the outside. """ _lock = threading.RLock() async def _is_flow_ready(self, **kwargs) -> bool: """Sends a dry run to the...
GRPCBaseClient
python
python-pillow__Pillow
Tests/test_file_avif.py
{ "start": 20932, "end": 27757 }
class ____: @contextmanager def star_frames(self) -> Generator[list[Image.Image], None, None]: with Image.open("Tests/images/avif/star.png") as f: yield [f, f.rotate(90), f.rotate(180), f.rotate(270)] def test_n_frames(self) -> None: """ Ensure that AVIF format sets n_fr...
TestAvifAnimation
python
pytorch__pytorch
test/test_show_pickle.py
{ "start": 202, "end": 1082 }
class ____(TestCase): @unittest.skipIf(IS_WINDOWS, "Can't re-open temp file on Windows") def test_scripted_model(self): class MyCoolModule(torch.nn.Module): def __init__(self, weight): super().__init__() self.weight = weight def forward(self, x): ...
TestShowPickle
python
huggingface__transformers
src/transformers/data/datasets/glue.py
{ "start": 2239, "end": 6086 }
class ____(Dataset): args: GlueDataTrainingArguments output_mode: str features: list[InputFeatures] def __init__( self, args: GlueDataTrainingArguments, tokenizer: PreTrainedTokenizerBase, limit_length: int | None = None, mode: str | Split = Split.train, ...
GlueDataset
python
dagster-io__dagster
scripts/generate_changelog.py
{ "start": 1323, "end": 1679 }
class ____: name: str email: str def __str__(self) -> str: return f"{self.name} ({self.email})" @property def is_external(self) -> bool: return ( not any(domain in self.email for domain in ["elementl.com", "dagsterlabs.com"]) and self.name not in INTERNAL_AU...
Author
python
run-llama__llama_index
llama-index-integrations/retrievers/llama-index-retrievers-pathway/llama_index/retrievers/pathway/base.py
{ "start": 545, "end": 3722 }
class ____: def __init__( self, host: Optional[str] = None, port: Optional[int] = None, url: Optional[str] = None, ): """ A client you can use to query :py:class:`VectorStoreServer`. Please provide either the `url`, or `host` and `port`. Args: ...
_VectorStoreClient
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 32319, "end": 33063 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("it_IT") Faker.seed(0) def test_vat_id(self): for _ in range(100): assert re.search(r"^IT\d{11}$", self.fake.vat_id()) def test_ssn(self): for _ in range(100): assert re.search(r"^[A-Z...
TestItIT
python
kamyu104__LeetCode-Solutions
Python/query-kth-smallest-trimmed-number.py
{ "start": 2926, "end": 3846 }
class ____(object): def smallestTrimmedNumbers(self, nums, queries): """ :type nums: List[str] :type queries: List[List[int]] :rtype: List[int] """ def compare(a, b): for i in xrange(len(nums[a])-t, len(nums[a])): if nums[a][i] < nums[b][i]...
Solution3
python
pytorch__pytorch
torch/_dynamo/variables/functions.py
{ "start": 3733, "end": 11984 }
class ____: def __init__(self, func: FunctionType): code = func.__code__ vn = code.co_varnames self.posonly_count = code.co_posonlyargcount self.arg_count = code.co_argcount self.kwonly_count = code.co_kwonlyargcount self.posonly_names = vn[: self.posonly_count] ...
FunctionSpec
python
realpython__materials
python-oop/dog.py
{ "start": 0, "end": 278 }
class ____: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} is {self.age} years old" def speak(self, sound): return f"{self.name} says {sound}"
Dog
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 2065, "end": 3898 }
class ____(NonStrictDataModel): _schema = { "type": "object", "properties": { "key": { "description": "The key uniquely identifying the metadata item inside the given entity", "type": "string", }, "type": {"description": "The type o...
MetadataItem
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_auth_index.py
{ "start": 7183, "end": 22301 }
class ____(AuthProviderTestCase, APITestCase): path = "/api/0/auth/" @mock.patch("sentry.auth.authenticators.U2fInterface.is_available", return_value=True) @mock.patch("sentry.auth.authenticators.U2fInterface.validate_response", return_value=True) def test_superuser_sso_user_no_password_saas_product( ...
AuthVerifyEndpointSuperuserTest
python
pytorch__pytorch
test/functorch/test_aotdispatch.py
{ "start": 246566, "end": 264765 }
class ____(AOTTestCase): # Tests to add cases for (non-exhaustive list, mostly for my notes): # - subclass / mode introduced in the middle of the compiled fn # - various input mutation / intermediate base tests # - input mutation that changes a tensor into a subclass # - metadata mutation? (TBD) ...
TestAOTDispatch
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 15162, "end": 15490 }
class ____(TypedDict): widget_display: list[str] widget_preview: list[_WidgetPreview] created_by: dict[str, Any] | None permissions: NotRequired[dict[str, Any]] is_favorited: NotRequired[bool] projects: list[int] environment: list[str] filters: DashboardFilters last_visited: str | No...
_Widget
python
pyca__cryptography
tests/x509/verification/test_verification.py
{ "start": 8612, "end": 21979 }
class ____: leaf = _load_cert( os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, ) ca = _load_cert( os.path.join("x509", "rapidssl_sha256_ca_g3.pem"), x509.load_pem_x509_certificate, ) store = Store([ca]) validation_time = datetime.datet...
TestCustomExtensionPolicies
python
ray-project__ray
python/ray/tune/integration/pytorch_lightning.py
{ "start": 1491, "end": 2436 }
class ____(Callback): """Base class for Tune's PyTorch Lightning callbacks. Args: on: When to trigger checkpoint creations. Must be one of the PyTorch Lightning event hooks (less the ``on_``), e.g. "train_batch_start", or "train_end". Defaults to "validation_end" """ de...
TuneCallback
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 8022, "end": 11393 }
class ____: def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, f"error with {t!r}: got {b!r}") def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: ...
TestPower
python
ansible__ansible
test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py
{ "start": 681, "end": 845 }
class ____(LookupBase): def run(self, terms, variables, **kwargs): self.set_options(var_options=variables, direct=kwargs) return terms
LookupModule
python
huggingface__transformers
tests/quantization/higgs/test_higgs.py
{ "start": 2219, "end": 7695 }
class ____(unittest.TestCase): model_name = "unsloth/Llama-3.2-1B" input_text = "Font test: A quick brown fox jumps over the" max_new_tokens = 2 EXPECTED_OUTPUT = "Font test: A quick brown fox jumps over the lazy dog" device_map = "cuda" # called only once for all test in this class @cla...
HiggsTest
python
getsentry__sentry
tests/sentry/workflow_engine/tasks/test_workflows.py
{ "start": 191, "end": 1414 }
class ____(TestCase): @patch("sentry.workflow_engine.processors.schedule.process_buffered_workflows") def test_schedule_delayed_workflows_locked_out( self, mock_process_buffered_workflows: MagicMock, ) -> None: lock = locks.get( "workflow_engine:schedule_delayed_workflows...
ScheduleDelayedWorkflowsTest
python
pydata__xarray
xarray/tests/test_conventions.py
{ "start": 23195, "end": 24457 }
class ____(CFEncodedBase): @contextlib.contextmanager def create_store(self): yield CFEncodedInMemoryStore() @contextlib.contextmanager def roundtrip( self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False ): if save_kwargs is None: save_kwar...
TestCFEncodedDataStore
python
astropy__astropy
astropy/utils/masked/tests/test_function_helpers.py
{ "start": 40120, "end": 41444 }
class ____: @classmethod def setup_class(cls): cls.a = np.arange(1.0, 7.0).reshape(2, 3) cls.mask_a = np.array( [ [True, False, False], [False, True, False], ] ) cls.ma = Masked(cls.a, mask=cls.mask_a) cls.b = np.arr...
TestSpaceFunctions
python
great-expectations__great_expectations
great_expectations/datasource/fluent/spark_dbfs_datasource.py
{ "start": 655, "end": 2309 }
class ____(SparkFilesystemDatasource): """Spark based Datasource for DataBricks File System (DBFS) based data assets.""" # class attributes data_connector_type: ClassVar[Type[DBFSDataConnector]] = DBFSDataConnector # instance attributes # overridden from base `Literal['spark_filesystem']` type...
SparkDBFSDatasource
python
pandas-dev__pandas
pandas/tests/frame/methods/test_rename_axis.py
{ "start": 130, "end": 4539 }
class ____: def test_rename_axis_inplace(self, float_frame): # GH#15704 expected = float_frame.rename_axis("foo") result = float_frame.copy() return_value = no_return = result.rename_axis("foo", inplace=True) assert return_value is None assert no_return is None ...
TestDataFrameRenameAxis
python
airbytehq__airbyte
airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/source.py
{ "start": 315, "end": 2493 }
class ____(FileBasedSource): def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: """ Returns the specification describing what fields can be configured by a user when setting up a file-based source. """ return ConnectorSpecification( documentationUrl=sel...
SourceAzureBlobStorage
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_raise.py
{ "start": 676, "end": 1790 }
class ____(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): # Check if the import is the problematic one if fullname in redirect_imports: try: # Attempt to import the standalone module name = fullname.removeprefix("test.") ...
RedirectImportFinder
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py
{ "start": 70347, "end": 85266 }
class ____(Qwen3VLMoePreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = {} _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False config: Qwen3VLMoeConfig def __init__(self, config)...
Qwen3VLMoeForConditionalGeneration
python
huggingface__transformers
src/transformers/models/siglip2/modular_siglip2.py
{ "start": 21184, "end": 25226 }
class ____(SiglipForImageClassification): # Update: add `spatial_shapes` and `pixel_attention_mask` def forward( self, pixel_values: Optional[torch.Tensor] = None, pixel_attention_mask: Optional[torch.Tensor] = None, spatial_shapes: Optional[torch.LongTensor] = None, labe...
Siglip2ForImageClassification
python
coleifer__peewee
playhouse/postgres_ext.py
{ "start": 7165, "end": 8461 }
class ____(IndexedFieldMixin, Field): field_type = 'HSTORE' __hash__ = Field.__hash__ def __getitem__(self, key): return Expression(self, HKEY, Value(key)) def keys(self): return fn.akeys(self) def values(self): return fn.avals(self) def items(self): return fn...
HStoreField
python
pypa__pip
src/pip/_internal/req/req_file.py
{ "start": 2755, "end": 3185 }
class ____: # TODO: replace this with slots=True when dropping Python 3.9 support. __slots__ = ( "requirement", "is_editable", "comes_from", "constraint", "options", "line_source", ) requirement: str is_editable: bool comes_from: str constrain...
ParsedRequirement
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 124257, "end": 124624 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(RefOrderField), graphql_name="field") direction = sgqlc.types.Field( sgqlc.types.non_null(OrderDi...
RefOrder
python
scipy__scipy
benchmarks/benchmarks/signal.py
{ "start": 2247, "end": 2734 }
class ____(Benchmark): param_names = ['mode', 'size'] params = [ ['full', 'valid', 'same'], [(a,b) for a,b in product((1, 2, 8, 36, 60, 150, 200, 500), repeat=2) if b <= a] ] def setup(self, mode, size): rng = np.random.default_rng(1234) self.a = rng.standard_no...
FFTConvolve
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 175872, "end": 176388 }
class ____(TestCase): def test_empty(self): iterable = [] it = mi.countable(iterable) self.assertEqual(it.items_seen, 0) self.assertEqual(list(it), []) def test_basic(self): iterable = '0123456789' it = mi.countable(iterable) self.assertEqual(it.items_see...
CountableTests
python
ray-project__ray
python/ray/tests/unit/test_runtime_env_validation.py
{ "start": 9573, "end": 10846 }
class ____: def test_parse_runtime_env_from_json_env_variable(self): job_config_json = {"runtime_env": {"working_dir": "uri://abc"}} config = job_config.JobConfig.from_json(job_config_json) assert config.runtime_env == job_config_json.get("runtime_env") assert config.metadata == {} ...
TestParseJobConfig
python
readthedocs__readthedocs.org
readthedocs/projects/tests/test_docker_environment.py
{ "start": 293, "end": 1193 }
class ____: @pytest.fixture(autouse=True) def setup(self, requests_mock): # Save the reference to query it from inside the test self.requests_mock = requests_mock self.project = fixture.get( Project, slug="project", ) self.version = self.project.v...
TestDockerBuildEnvironmentNew
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_bigquery.py
{ "start": 34589, "end": 40529 }
class ____(_BigQueryBaseTestClass): @mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table.from_api_repr") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client") def test_create_table_view(self, mock_bq_client, mock_table): table_resource = { "view": { ...
TestTableOperations
python
getsentry__sentry
src/sentry/integrations/pagerduty/analytics.py
{ "start": 177, "end": 311 }
class ____(BaseNotificationSent): pass analytics.register(PagerdutyIntegrationNotificationSent)
PagerdutyIntegrationNotificationSent
python
wandb__wandb
wandb/sdk/artifacts/_generated/project_artifact_types.py
{ "start": 523, "end": 705 }
class ____(GQLResult): edges: List[ProjectArtifactTypesProjectArtifactTypesEdges] page_info: PageInfoFragment = Field(alias="pageInfo")
ProjectArtifactTypesProjectArtifactTypes
python
joke2k__faker
faker/providers/internet/de_AT/__init__.py
{ "start": 46, "end": 416 }
class ____(InternetProvider): free_email_domains = ( "chello.at", "gmail.com", "gmx.at", "kabsi.at", ) tlds = ("at", "co.at", "com", "net", "org") replacements = ( ("ä", "ae"), ("Ä", "Ae"), ("ö", "oe"), ("Ö", "Oe"), ("ü", "ue"), ...
Provider
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 209030, "end": 209337 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("ranges",) ranges = sgqlc.types.Field( sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null("BlameRange"))), graphql_name="ranges", )
Blame
python
jazzband__django-redis
django_redis/serializers/msgpack.py
{ "start": 99, "end": 308 }
class ____(BaseSerializer): def dumps(self, value: Any) -> bytes: return msgpack.dumps(value) def loads(self, value: bytes) -> Any: return msgpack.loads(value, raw=False)
MSGPackSerializer
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 35232, "end": 37017 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): import sklearn.neighbors if type(y) in ("binary", "multiclass"): kf = sklearn.model_selection.StratifiedKFold(n_splits=5) else: kf = sklearn.model_selection.KFold(n_splits=5) accuracy = ...
Landmark1NN
python
openai__openai-python
src/openai/types/chat/chat_completion_prediction_content_param.py
{ "start": 360, "end": 868 }
class ____(TypedDict, total=False): content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] """ The content that should be matched when generating a model response. If generated tokens would match this content, the entire model response can be returned much more quickly. """ ...
ChatCompletionPredictionContentParam
python
mlflow__mlflow
mlflow/types/type_hints.py
{ "start": 2895, "end": 3165 }
class ____(MlflowException): def __init__(self, type_hint): super().__init__( f"Unsupported type hint `{_type_hint_repr(type_hint)}`. {SUPPORTED_TYPE_HINT_MSG}", error_code=INVALID_PARAMETER_VALUE, )
UnsupportedTypeHintException
python
sympy__sympy
sympy/utilities/misc.py
{ "start": 343, "end": 16415 }
class ____(ValueError): # an error to be raised when a decision cannot be made definitively # where a definitive answer is needed pass def filldedent(s, w=70, **kwargs): """ Strips leading and trailing empty lines from a copy of ``s``, then dedents, fills and returns it. Empty line stripp...
Undecidable
python
cython__cython
docs/examples/userguide/extension_types/penguin.py
{ "start": 30, "end": 292 }
class ____: food: object def __cinit__(self, food): self.food = food def __init__(self, food): print("eating!") normal_penguin = Penguin('fish') fast_penguin = Penguin.__new__(Penguin, 'wheat') # note: not calling __init__() !
Penguin
python
tensorflow__tensorflow
tensorflow/tools/tensorflow_builder/compat_checker/compat_checker.py
{ "start": 3366, "end": 34424 }
class ____: """Class that checks configuration versions and dependency compatibilities. `ConfigCompatChecker` checks a given set of configurations and their versions against supported versions and dependency rules defined in `.ini` config file. For project `TensorFlow Builder`, it functions as a sub-module for...
ConfigCompatChecker
python
joke2k__faker
tests/providers/test_address.py
{ "start": 99649, "end": 101422 }
class ____: """Test vi_VN address provider methods""" def test_city_prefix(self, faker, num_samples): for _ in range(num_samples): city_prefix = faker.city_prefix() assert isinstance(city_prefix, str) assert city_prefix in ViVNAddressProvider.city_prefixes def t...
TestViVn
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_write_num_fmt.py
{ "start": 295, "end": 796 }
class ____(unittest.TestCase): """ Test the Styles _write_num_fmt() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_num_fmt(self): """Test the _write_num_fmt() method""" self.styl...
TestWriteNumFmt
python
spack__spack
lib/spack/spack/vendor/attr/validators.py
{ "start": 6770, "end": 7760 }
class ____: validator = attrib() def __call__(self, inst, attr, value): if value is None: return self.validator(inst, attr, value) def __repr__(self): return "<optional validator for {what} or None>".format( what=repr(self.validator) ) def optiona...
_OptionalValidator
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 45831, "end": 51496 }
class ____(BaseField): """A referencefield with cache fields to purpose pseudo-joins""" def __init__(self, document_type, fields=None, auto_sync=True, **kwargs): """Initialises the Cached Reference Field. :param document_type: The type of Document that will be referenced :param fields:...
CachedReferenceField
python
PrefectHQ__prefect
src/prefect/cli/deploy/_models.py
{ "start": 1975, "end": 3387 }
class ____(BaseModel): model_config = ConfigDict(populate_by_name=True, extra="ignore") # generic metadata (currently unused by CLI but allowed) prefect_version: Optional[str] = Field(default=None, alias="prefect-version") name: Optional[str] = None # global actions build: Optional[Union[List[...
PrefectYamlModel
python
pytorch__pytorch
test/profiler/test_torch_tidy.py
{ "start": 1220, "end": 1444 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 2) def forward(self, x): return self.fc2(self.fc1(x))
SimpleNet
python
xlwings__xlwings
xlwings/conversion/standard.py
{ "start": 8139, "end": 8629 }
class ____(Converter): @classmethod def base_reader(cls, options): return super(OrderedDictConverter, cls).base_reader( Options(options).override(ndim=2) ) @classmethod def read_value(cls, value, options): assert not value or len(value[0]) == 2 return Ordered...
OrderedDictConverter
python
facelessuser__pymdown-extensions
pymdownx/striphtml.py
{ "start": 3907, "end": 5202 }
class ____(Extension): """StripHTML extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'strip_comments': [ True, "Strip HTML comments at the end of processing. " "- Default: True" ], ...
StripHtmlExtension
python
catalyst-team__catalyst
examples/catalyst_rl/buffer.py
{ "start": 2652, "end": 4444 }
class ____: def __init__( self, capacity: int, space: spaces.Space = None, shape: Tuple = None, dtype=None, name: str = None, mode: str = "numpy", logdir: str = None, ): self._capacity = capacity self._space = space self._sh...
BufferWrapper
python
sqlalchemy__sqlalchemy
test/engine/test_execute.py
{ "start": 2240, "end": 2346 }
class ____: def __str__(self): return "foo" def __unicode__(self): return "fóó"
Foo
python
ijl__orjson
test/test_dataclass.py
{ "start": 221, "end": 278 }
class ____(Enum): ONE = 1 TWO = 2 @dataclass
AnEnum
python
pappasam__jedi-language-server
jedi_language_server/server.py
{ "start": 2937, "end": 7545 }
class ____(LanguageServerProtocol): """Override some built-in functions.""" _server: "JediLanguageServer" @lsp_method(INITIALIZE) def lsp_initialize( self, params: InitializeParams ) -> Generator[Any, Any, InitializeResult]: """Override built-in initialization. Here, we ca...
JediLanguageServerProtocol
python
pytorch__pytorch
test/dynamo/test_comptime.py
{ "start": 469, "end": 11353 }
class ____(torch._dynamo.test_case.TestCase): def test_print_single(self): global FILE FILE = StringIO() cnt = torch._dynamo.testing.CompileCounter() def comptime_print(e): @comptime def _(ctx): ctx.print(ctx.get_local("e"), file=FILE) ...
ComptimeTests
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 175669, "end": 178153 }
class ____(TestCase): def test_basic(self): dt_numeric = np.typecodes["AllFloat"] + np.typecodes["AllInteger"] dt_complex = np.typecodes["Complex"] # test real a = np.eye(3) for dt in dt_numeric: b = a.astype(dt) res = np.vdot(b, b) assert...
TestVdot
python
ray-project__ray
python/ray/serve/tests/test_api.py
{ "start": 1479, "end": 1714 }
class ____: async def __init__(self): await asyncio.sleep(0.01) self.count = 0 async def __call__(self): self.count += 1 await asyncio.sleep(0.01) return {"count": self.count}
AsyncCounter
python
facebook__pyre-check
scripts/explore_pysa_models.py
{ "start": 23673, "end": 24124 }
class ____(enum.Enum): SOURCE = 0 SINK = 1 @staticmethod def from_string(s: str) -> Optional["ConditionKind"]: if s == "source": return ConditionKind.SOURCE elif s == "sink": return ConditionKind.SINK else: return None def model_key(self)...
ConditionKind
python
getsentry__sentry
tests/sentry/monitors/clock_tasks/test_mark_unknown.py
{ "start": 593, "end": 3195 }
class ____(TestCase): @mock.patch("sentry.monitors.clock_tasks.mark_unknown.produce_task") def test_mark_unknown(self, mock_produce_task: mock.MagicMock) -> None: org = self.create_organization() project = self.create_project(organization=org) ts = timezone.now().replace(hour=0, minute=...
MonitorClockTasksMarkUnknownTest
python
django__django
django/contrib/auth/migrations/0005_alter_user_last_login_null.py
{ "start": 43, "end": 410 }
class ____(migrations.Migration): dependencies = [ ("auth", "0004_alter_user_username_opts"), ] operations = [ migrations.AlterField( model_name="user", name="last_login", field=models.DateTimeField( null=True, verbose_name="last login", b...
Migration
python
getsentry__sentry
src/sentry/web/frontend/debug/mail.py
{ "start": 14701, "end": 29956 }
class ____(View): def get_activity(self, request: AuthenticatedHttpRequest, event): raise NotImplementedError def get(self, request: AuthenticatedHttpRequest) -> HttpResponse: org = Organization(id=1, slug="organization", name="My Company") project = Project(id=1, organization=org, slug...
ActivityMailDebugView
python
spack__spack
lib/spack/spack/llnl/util/filesystem.py
{ "start": 46504, "end": 68024 }
class ____: """Base class and interface for :py:func:`visit_directory_tree`.""" def visit_file(self, root: str, rel_path: str, depth: int) -> None: """Handle the non-symlink file at ``os.path.join(root, rel_path)`` Parameters: root: root directory rel_path: relative pat...
BaseDirectoryVisitor
python
dagster-io__dagster
python_modules/dagster/dagster/_config/errors.py
{ "start": 1328, "end": 1390 }
class ____: field_name: str @record
FieldNotDefinedErrorData
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 166359, "end": 167019 }
class ____(SendrecvmsgDgramFlagsBase, SendrecvmsgConnectionlessBase, ThreadedSocketTestMixin, UDPLITE6TestBase): def checkRecvmsgAddress(self, addr1, addr2): # Called to compare the received address with the address of # the peer, ignoring...
SendrecvmsgUDPLITE6TestBase
python
pytorch__pytorch
torch/_inductor/scheduler.py
{ "start": 88340, "end": 94619 }
class ____(BaseSchedulerNode): """ This is a "fake" scheduler node that represents a group of scheduler nodes that are meant to be *grouped* together (it does not allow another node to be scheduled in between its constituent nodes, nor does it allow another node to fuse into any of its constituent nodes...
GroupedSchedulerNode
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 90959, "end": 91609 }
class ____(SingletonConstant, roles.ConstExprRole[None], ColumnElement[None]): """Represent the NULL keyword in a SQL statement. :class:`.Null` is accessed as a constant via the :func:`.null` function. """ __visit_name__ = "null" _traverse_internals: _TraverseInternalsType = [] _singleto...
Null
python
gevent__gevent
src/gevent/tests/test__issue607.py
{ "start": 203, "end": 1354 }
class ____(greentest.TestCase): def test_kill_without_exception(self): g = gevent.spawn(f) g.kill() assert g.successful() assert isinstance(g.get(), gevent.GreenletExit) def test_kill_with_exception(self): # issue-607 pointed this case. g = gevent.spawn(f) ...
TestKillWithException
python
gevent__gevent
src/gevent/resolver/dnspython.py
{ "start": 8137, "end": 11053 }
class ____(object): """ Class to parse the hosts file """ def __init__(self, fname=None, interval=HOSTS_TTL): self.hosts_file = HostsFile(fname) self.interval = interval self._last_load = 0 def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, ...
_HostsResolver
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 39035, "end": 40051 }
class ____(SetitemCastingEquivalents): # GH#44261 Setting a range with sufficiently-small integers into # small-itemsize integer dtypes should not need to upcast @pytest.fixture def obj(self, any_int_numpy_dtype): dtype = np.dtype(any_int_numpy_dtype) ser = Series(range(5), dtype=dtype...
TestSetitemRangeIntoIntegerSeries
python
HypothesisWorks__hypothesis
hypothesis-python/tests/conjecture/test_provider.py
{ "start": 9419, "end": 9775 }
class ____(TrivialProvider): lifetime = "forever and a day" def test_invalid_lifetime(): with ( temp_register_backend("invalid_lifetime", InvalidLifetime), pytest.raises(InvalidArgument), ): ConjectureRunner(lambda: True, settings=settings(backend="invalid_lifetime")) function_l...
InvalidLifetime
python
python-pillow__Pillow
src/PIL/ImageFilter.py
{ "start": 8969, "end": 9151 }
class ____(BuiltinFilter): name = "Sharpen" # fmt: off filterargs = (3, 3), 16, 0, ( -2, -2, -2, -2, 32, -2, -2, -2, -2, ) # fmt: on
SHARPEN
python
django-crispy-forms__django-crispy-forms
tests/forms.py
{ "start": 5537, "end": 5733 }
class ____(BaseForm): file_field = forms.FileField(widget=forms.FileInput) clearable_file = forms.FileField(widget=forms.ClearableFileInput, required=False, initial=FakeFieldFile())
FileForm
python
sqlalchemy__sqlalchemy
test/sql/test_update.py
{ "start": 1147, "end": 3775 }
class ____: @classmethod def define_tables(cls, metadata): Table( "mytable", metadata, Column("myid", Integer), Column("name", String(30)), Column("description", String(50)), ) Table( "mytable_with_onupdate", ...
_UpdateFromTestBase
python
astropy__astropy
astropy/visualization/stretch.py
{ "start": 13548, "end": 14520 }
class ____(PowerStretch): r""" A convenience class for a power stretch of 2. The stretch is given by: .. math:: y = x^2 Examples -------- .. plot:: :show-source-link: import numpy as np from astropy.visualization import SquaredStretch from matplotl...
SquaredStretch
python
huggingface__transformers
src/transformers/models/cvt/modeling_cvt.py
{ "start": 11092, "end": 11474 }
class ____(nn.Module): def __init__(self, embed_dim, mlp_ratio): super().__init__() self.dense = nn.Linear(embed_dim, int(embed_dim * mlp_ratio)) self.activation = nn.GELU() def forward(self, hidden_state): hidden_state = self.dense(hidden_state) hidden_state = self.acti...
CvtIntermediate
python
has2k1__plotnine
plotnine/geoms/geom_density.py
{ "start": 77, "end": 526 }
class ____(geom_area): """ Smooth density estimate {usage} Parameters ---------- {common_parameters} See Also -------- plotnine.geom_ribbon """ DEFAULT_AES = { **geom_area.DEFAULT_AES, "color": "black", "fill": None, "weight": 1, } ...
geom_density
python
pennersr__django-allauth
allauth/socialaccount/migrations/0001_initial.py
{ "start": 110, "end": 6268 }
class ____(migrations.Migration): dependencies = ( [ ("sites", "0001_initial"), ] if app_settings.SITES_ENABLED else [] ) + [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name=...
Migration
python
run-llama__llama_index
llama-index-integrations/storage/docstore/llama-index-storage-docstore-firestore/llama_index/storage/docstore/firestore/base.py
{ "start": 247, "end": 1397 }
class ____(KVDocumentStore): """ Firestore Document (Node) store. A Firestore store for Document and Node objects. Args: firestore_kvstore (FirestoreKVStore): Firestore key-value store namespace (str): namespace for the docstore """ def __init__( self, firesto...
FirestoreDocumentStore
python
tensorflow__tensorflow
third_party/xla/xla/python/profile_data_test.py
{ "start": 727, "end": 6275 }
class ____(absltest.TestCase): def test_find_plane_with_name(self): profile = profiler.ProfileData.from_text_proto(""" planes { name: "a" } planes { name: "b" } """) self.assertEqual(profile.find_plane_with_name('a').name, 'a') self.assertEqual(profile.find_plane_with_name('b').na...
ProfileDataTest
python
oauthlib__oauthlib
tests/openid/connect/core/endpoints/test_refresh_token.py
{ "start": 403, "end": 1182 }
class ____(TestCase): def setUp(self): self.validator = mock.MagicMock(spec=RequestValidator) self.validator.get_id_token.return_value='id_token' self.server = Server(self.validator) def test_refresh_token_with_openid(self): request_body = 'scope=openid+test_scope&grant_type=r...
TestRefreshToken
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 16489, "end": 18202 }
class ____: offset: int = 0 limit: Optional[int] = None def to_dict(self) -> Dict[str, Any]: """Convert the Limit to a dictionary for JSON serialization""" result = {"offset": self.offset} if self.limit is not None: result["limit"] = self.limit return result ...
Limit
python
getsentry__sentry
tests/sentry/seer/assisted_query/test_issues_tools.py
{ "start": 5247, "end": 16815 }
class ____(APITestCase, SnubaTestCase, OccurrenceTestMixin): databases = {"default", "control"} def setUp(self): super().setUp() self.min_ago = before_now(minutes=1) def test_get_filter_key_values_events_dataset(self): """Test getting values for a filter key in the events dataset""...
TestGetFilterKeyValues
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/checklist.py
{ "start": 4738, "end": 4958 }
class ____(SimpleParameter): @property def itemClass(self): if self.opts.get('type') == 'bool': return BoolParameterItem else: return RadioParameterItem
BoolOrRadioParameter
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 343488, "end": 343837 }
class ____(VegaLiteSchema): """ ExprRef schema wrapper. Parameters ---------- expr : str Vega expression (which can refer to Vega-Lite parameters). """ _schema = {"$ref": "#/definitions/ExprRef"} def __init__(self, expr: Optional[str] = Undefined, **kwds): super().__in...
ExprRef
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/histogram_ops_test.py
{ "start": 3099, "end": 7796 }
class ____(test.TestCase): def setUp(self): self.rng = np.random.RandomState(0) def test_with_invalid_value_range(self): values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] with self.assertRaisesRegex( (errors.InvalidArgumentError, ValueError), "Shape must be rank 1 but is rank 0|should be a vecto...
HistogramFixedWidthTest
python
numpy__numpy
numpy/typing/tests/data/pass/numeric.py
{ "start": 157, "end": 1492 }
class ____(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ... i8 = np.int64(1) A = np.arange(27).reshape(3, 3, 3) B = A.tolist() C = np.empty((27, 27)).view(SubClass) np.count_nonzero(i8) np.count_nonzero(A) np.count_nonzero(B) np.count_nonzero(A, keepdims=True) np.count_nonzero(A, axis=0) np.isfortran(i8) np...
SubClass
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_display_units01.py
{ "start": 315, "end": 1120 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_display_units01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(...
TestCompareXLSXFiles
python
django__django
tests/test_runner/test_parallel.py
{ "start": 2204, "end": 2546 }
class ____(SimpleTestCase): @classmethod def setUpClass(cls): raise ValueError("woops") super().setUpClass() # This method name doesn't begin with "test" to prevent test discovery # from seeing it. def dummy_test(self): raise AssertionError("SampleErrorTest.dummy_test() was ...
SampleErrorTest
python
jazzband__django-oauth-toolkit
oauth2_provider/models.py
{ "start": 11067, "end": 11201 }
class ____(models.Manager): def get_by_natural_key(self, client_id): return self.get(client_id=client_id)
ApplicationManager
python
encode__django-rest-framework
tests/schemas/test_openapi.py
{ "start": 7646, "end": 39907 }
class ____(TestCase): def test_path_without_parameters(self): path = '/example/' method = 'GET' view = create_view( views.DocStringExampleListView, method, create_request(path) ) inspector = AutoSchema() inspector.view = view ...
TestOperationIntrospection