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
microsoft__pyright
packages/pyright-internal/src/tests/samples/function8.py
{ "start": 249, "end": 490 }
class ____(Generic[T]): values: Sequence[float | T] def create_container(values: Sequence[float | T]) -> Container[T]: return Container(values) arg: Sequence[float | int] = (1, 2.0) x: Container[int] = create_container(arg)
Container
python
joke2k__faker
tests/providers/test_address.py
{ "start": 76428, "end": 78472 }
class ____: """Test en_IN address provider methods""" def test_city_name(self, faker, num_samples): """Tests `city names` are fetched correctly""" for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name i...
TestEnIn
python
getsentry__sentry
tests/sentry/stacktraces/test_in_app_normalization.py
{ "start": 1048, "end": 2028 }
class ____(TestCase): def test_sets_client_in_app(self) -> None: event_data_with_client_values = make_event( [ make_stacktrace( frame_0_in_app=True, frame_1_in_app=False, ) ] ) normalize_stacktra...
NormalizeStacktracesFroGroupingTest
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_param_validation.py
{ "start": 1113, "end": 1518 }
class ____: """A class to test the _InstancesOf constraint and the validation of methods.""" @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) def _method(self, a): """A validated method""" @deprecated() @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) ...
_Class
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 75870, "end": 76671 }
class ____(DefaultProvider): """Metadata provider for egg directories Usage:: # Development eggs: egg_info = "/path/to/PackageName.egg-info" base_dir = os.path.dirname(egg_info) metadata = PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(e...
PathMetadata
python
django__django
tests/auth_tests/test_models.py
{ "start": 1727, "end": 2027 }
class ____(TestCase): fixtures = ["regular.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get())
LoadDataWithoutNaturalKeysTestCase
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_d9m_test.py
{ "start": 3004, "end": 8337 }
class ____( sparse_xent_op_test_base.SparseXentOpTestBase): """Test that SparseSoftmaxCrossEntropyWithLogits operates reproducibly. Inheriting from sparse_xent_op_test_base.SparseXentOpTestBase ensures that regular op functionality is correct when the deterministic code-path is selected. Note that becau...
SparseXentOpDeterministicTest
python
getsentry__sentry
src/sentry/replays/usecases/query/conditions/base.py
{ "start": 161, "end": 1259 }
class ____: """Computed expression base column. Computed expressions are not passed as arguments to the condition visitor methods. They are computed on the fly within the visitor. """ @staticmethod def visit_eq(value: Any) -> Condition: not_supported() @staticmethod def visit_...
ComputedBase
python
kubernetes-client__python
kubernetes/client/models/v1_endpoint_hints.py
{ "start": 383, "end": 5003 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1EndpointHints
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 57535, "end": 57702 }
class ____(_PrintableStructure): _fields_ = [ ('pci', nvmlPciInfo_t), ('uuid', c_char * NVML_DEVICE_UUID_BUFFER_SIZE) ]
c_nvmlExcludedDeviceInfo_t
python
FactoryBoy__factory_boy
tests/test_declarations.py
{ "start": 5775, "end": 6899 }
class ____(unittest.TestCase): def test_post_generation(self): call_params = [] def foo(*args, **kwargs): call_params.append(args) call_params.append(kwargs) helpers.build( dict, foo=declarations.PostGeneration(foo), foo__bar=42, ...
PostGenerationDeclarationTestCase
python
huggingface__transformers
src/transformers/models/vitdet/modeling_vitdet.py
{ "start": 13445, "end": 14808 }
class ____(nn.Module): """ The standard bottleneck residual block without the last activation layer. It contains 3 conv layers with kernels 1x1, 3x3, 1x1. """ def __init__(self, config, in_channels, out_channels, bottleneck_channels): """ Args: config (`VitDetConfig`): ...
VitDetResBottleneckBlock
python
geekcomputers__Python
Split_Circular_Linked_List.py
{ "start": 94, "end": 1805 }
class ____: def __init__(self): self.head = None def Push(self, data): temp = Node(data) temp.next = self.head temp1 = self.head if self.head is not None: while temp1.next is not None: temp1 = temp1.next temp1.next = temp e...
Circular_Linked_List
python
python__mypy
mypy/types.py
{ "start": 106999, "end": 113686 }
class ____(ProperType): """Type of TypedDict object {'k1': v1, ..., 'kn': vn}. A TypedDict object is a dictionary with specific string (literal) keys. Each key has a value with a distinct type that depends on the key. TypedDict objects are normal dict objects at runtime. A TypedDictType can be eit...
TypedDictType
python
jazzband__pip-tools
piptools/resolver.py
{ "start": 1616, "end": 5001 }
class ____: """ Summary of a requirement's properties for comparison purposes. """ def __init__(self, ireq: InstallRequirement) -> None: self.req = ireq.req self.key = key_from_ireq(ireq) self.extras = frozenset(ireq.extras) self.specifier = ireq.specifier def __eq_...
RequirementSummary
python
ray-project__ray
rllib/offline/feature_importance.py
{ "start": 3944, "end": 10680 }
class ____(OfflineEvaluator): @override(OfflineEvaluator) def __init__( self, policy: Policy, repeat: int = 1, limit_fraction: float = 1.0, perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame] = _perturb_df, ): """Feature importance in a model inspection te...
FeatureImportance
python
huggingface__transformers
src/transformers/models/qwen2_moe/modeling_qwen2_moe.py
{ "start": 28068, "end": 32536 }
class ____(Qwen2MoePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = Qwen...
Qwen2MoeForCausalLM
python
langchain-ai__langchain
libs/core/langchain_core/runnables/graph.py
{ "start": 731, "end": 907 }
class ____(Protocol): """Protocol for objects that can be converted to a string.""" def __str__(self) -> str: """Convert the object to a string."""
Stringifiable
python
sphinx-doc__sphinx
sphinx/transforms/__init__.py
{ "start": 7824, "end": 8164 }
class ____(SphinxTransform): """Update source and rawsource attributes""" default_priority = 10 def apply(self, **kwargs: Any) -> None: for node in self.document.findall(): if isinstance(node, (nodes.TextElement, nodes.image, nodes.topic)): apply_source_workaround(node)...
ApplySourceWorkaround
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox25.py
{ "start": 315, "end": 867 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox25.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workb...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/serialization/serialized_data.py
{ "start": 3092, "end": 3229 }
class ____(NamedTuple): dag_id: str task_id: str created_at: str updated_at: str @whitelist_for_serdes
DatasetProducingTask
python
pyca__cryptography
src/cryptography/hazmat/decrepit/ciphers/algorithms.py
{ "start": 1065, "end": 1097 }
class ____: key_size = 64
_DES
python
django__django
django/forms/widgets.py
{ "start": 19415, "end": 19690 }
class ____(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "")
TimeInput
python
ray-project__ray
python/ray/tune/tests/test_soft_imports.py
{ "start": 29, "end": 767 }
class ____(unittest.TestCase): """Tests whether it's possible to use Ray Tune without soft dependencies""" def testSoftImports(self): import ray.tune.schedulers # noqa: F401 from ray.tune.search import SEARCH_ALG_IMPORT for name, import_func in SEARCH_ALG_IMPORT.items(): p...
TestSoftImports
python
charliermarsh__ruff
scripts/ty_benchmark/src/benchmark/projects.py
{ "start": 117, "end": 10256 }
class ____(NamedTuple): name: str """The name of the project to benchmark.""" repository: str """The git repository to clone.""" revision: str install_arguments: list[str] """Arguments passed to `uv pip install`. Dependencies are pinned using a `--exclude-newer` flag when installing ...
Project
python
pytorch__pytorch
torch/fx/proxy.py
{ "start": 18165, "end": 25463 }
class ____: """ ``Proxy`` objects are ``Node`` wrappers that flow through the program during symbolic tracing and record all the operations (``torch`` function calls, method calls, operators) that they touch into the growing FX Graph. If you're doing graph transforms, you can wrap your own ``Pr...
Proxy
python
ApeWorX__ape
src/ape/cli/arguments.py
{ "start": 1257, "end": 6433 }
class ____: """ Helper callback class for handling CLI-given contract paths. """ def __init__(self, value, project: Optional["ProjectManager"] = None): from ape.utils.basemodel import ManagerAccessMixin self.value = value self.missing_compilers: set[str] = set() # set of .ext ...
_ContractPaths
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image13.py
{ "start": 315, "end": 1189 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image13.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_c...
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/shared_integrations/exceptions/__init__.py
{ "start": 628, "end": 2827 }
class ____(Exception): """ Base class for errors which arise while making outgoing requests to third-party APIs. """ code: int | None = None def __init__( self, text: str, code: int | None = None, url: str | None = None, host: str | None = None, path...
ApiError
python
langchain-ai__langchain
libs/langchain/langchain_classic/memory/entity.py
{ "start": 1113, "end": 1959 }
class ____(BaseModel, ABC): """Abstract base class for Entity store.""" @abstractmethod def get(self, key: str, default: str | None = None) -> str | None: """Get entity value from store.""" @abstractmethod def set(self, key: str, value: str | None) -> None: """Set entity value in s...
BaseEntityStore
python
pytorch__pytorch
test/test_functionalization_of_rng_ops.py
{ "start": 816, "end": 10980 }
class ____(TestCase): @dtypes(torch.float32) @patch.object(torch._functorch.config, "functionalize_rng_ops", True) def test_rand_like(self, dtype, device): def fn(x): a = torch.rand_like(x) * x a = torch.rand_like(x) * a return a x = torch.rand(10, device...
TestFunctionalizationRngOps
python
PrefectHQ__prefect
src/prefect/settings/sources.py
{ "start": 11394, "end": 13545 }
class ____(TomlConfigSettingsSourceBase): """Custom pydantic settings source to load settings from a pyproject.toml file""" def __init__( self, settings_cls: Type[BaseSettings], ): super().__init__(settings_cls) self.toml_file_path: Path = Path("pyproject.toml") self...
PyprojectTomlConfigSettingsSource
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 16531, "end": 17211 }
class ____: def setup(self): N = 10000 # this is the worst case, where every column has NaNs. arr = np.random.randn(N, 100) arr[::2] = np.nan self.df = DataFrame(arr) self.df2 = DataFrame( { "A": np.arange(0, N), "B": np.r...
Interpolate
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_api.py
{ "start": 3104, "end": 28092 }
class ____(TestCase): fixtures = ["eric.json", "test_data.json"] def setUp(self): self.user = User.objects.get(username="eric") self.project = get(Project, users=[self.user]) self.version = self.project.versions.get(slug=LATEST) def test_healthcheck(self): # Build cloning s...
APIBuildTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 266181, "end": 266663 }
class ____(sgqlc.types.Input): """Autogenerated input type of PublishSponsorsTier""" __schema__ = github_schema __field_names__ = ("tier_id", "client_mutation_id") tier_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="tierId") """The ID of the draft tier to publish.""" client_mut...
PublishSponsorsTierInput
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_doughnut03.py
{ "start": 315, "end": 1237 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_doughnut03.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self....
TestCompareXLSXFiles
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/transfers/test_hive_to_mysql.py
{ "start": 1229, "end": 8232 }
class ____(TestHiveEnvironment): def setup_method(self, method): self.kwargs = dict( sql="sql", mysql_table="table", hiveserver2_conn_id="hiveserver2_default", mysql_conn_id="mysql_default", task_id="test_hive_to_mysql", ) super().s...
TestHiveToMySqlTransfer
python
wandb__wandb
wandb/sdk/internal/sender.py
{ "start": 3911, "end": 4697 }
class ____: resumed: bool step: int history: int events: int output: int runtime: float wandb_runtime: Optional[int] summary: Optional[Dict[str, Any]] config: Optional[Dict[str, Any]] tags: Optional[List[str]] def __init__(self) -> None: self.resumed = False ...
ResumeState
python
tiangolo__fastapi
docs_src/authentication_error_status_code/tutorial001_an.py
{ "start": 189, "end": 628 }
class ____(HTTPBearer): def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())] @app.get("/me") def read_me(cr...
HTTPBearer403
python
ray-project__ray
python/ray/experimental/channel/common.py
{ "start": 5625, "end": 8587 }
class ____: """ Abstraction for a transport between a writer actor and some number of reader actors. """ def __init__( self, writer: Optional[ray.actor.ActorHandle], readers: List[Optional[ray.actor.ActorHandle]], typ: Optional["ChannelOutputType"], ): ""...
ChannelInterface
python
walkccc__LeetCode
solutions/2192. All Ancestors of a Node in a Directed Acyclic Graph/2192.py
{ "start": 0, "end": 481 }
class ____: def getAncestors(self, n: int, edges: list[list[int]]) -> list[list[int]]: ans = [[] for _ in range(n)] graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) def dfs(u: int, ancestor: int, seen: set[int]) -> None: seen.add(u) for v in graph[u]: if...
Solution
python
protocolbuffers__protobuf
python/google/protobuf/text_format.py
{ "start": 30833, "end": 49135 }
class ____(object): """Text format parser for protocol message.""" def __init__(self, allow_unknown_extension=False, allow_field_number=False, descriptor_pool=None, allow_unknown_field=False): self.allow_unknown_extension = allow_unknown_extension ...
_Parser
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 32186, "end": 32699 }
class ____(BaseRealtimeConnectionResource): def update( self, *, session: transcription_session_update_param.Session, event_id: str | NotGiven = NOT_GIVEN ) -> None: """Send this event to update a transcription session.""" self._connection.send( cast( Realtime...
RealtimeTranscriptionSessionResource
python
rq__rq
rq/job.py
{ "start": 1318, "end": 1916 }
class ____(str, Enum): """The Status of Job within its lifecycle at any given time.""" CREATED = 'created' QUEUED = 'queued' FINISHED = 'finished' FAILED = 'failed' STARTED = 'started' DEFERRED = 'deferred' SCHEDULED = 'scheduled' STOPPED = 'stopped' CANCELED = 'canceled' def ...
JobStatus
python
getsentry__sentry
tests/snuba/rules/conditions/test_event_frequency.py
{ "start": 31122, "end": 31733 }
class ____(StandardIntervalTestBase): __test__ = Abstract(__module__, __qualname__) rule_cls = EventFrequencyCondition def increment(self, event, count, environment=None, timestamp=None): timestamp = timestamp if timestamp else before_now(minutes=1) data = {"fingerprint": event.data["finge...
EventFrequencyConditionTestCase
python
ipython__ipython
IPython/terminal/ipapp.py
{ "start": 2137, "end": 6248 }
class ____(CrashHandler): """sys.excepthook for IPython itself, leaves a detailed report on disk.""" def __init__(self, app): contact_name = release.author contact_email = release.author_email bug_tracker = 'https://github.com/ipython/ipython/issues' super(IPAppCrashHandler,self...
IPAppCrashHandler
python
pytorch__pytorch
torch/distributed/fsdp/_fully_shard/_fsdp_common.py
{ "start": 1857, "end": 2328 }
class ____(DataParallelMeshInfo): def __post_init__(self): super().__post_init__() if self.replicate_mesh_dim is None: raise AssertionError("Expects non-None replicate_mesh_dim") self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim) self.replicate_proces...
DDPMeshInfo
python
pytorch__pytorch
torch/distributed/checkpoint/_pg_transport.py
{ "start": 1167, "end": 1486 }
class ____: """ This is the metadata for a DTensor that is used to transfer checkpoints. It contains the metadata for the local tensor and the spec of the DTensor. This must be pickleable so that it can be sent over the wire. """ local: _TensorMeta spec: _DTensorSpec @dataclass
_DTensorMeta
python
huggingface__transformers
utils/models_to_deprecate.py
{ "start": 5082, "end": 14131 }
class ____: """ Utility for getting models from the hub based on tags. Handles errors without crashing the script. """ def __init__(self, tags): self.tags = tags self.model_list = api.list_models(filter=tags) def __iter__(self): try: yield from self.model_list ...
HubModelLister
python
django__django
tests/admin_inlines/models.py
{ "start": 9368, "end": 9606 }
class ____(models.Model): collection = models.ForeignKey( ProfileCollection, models.SET_NULL, blank=True, null=True ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100)
Profile
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/lambda_sources.py
{ "start": 3699, "end": 16913 }
class ____: # Opcodes, from dis.opmap. These may change between major versions. NOP = 9 LOAD_FAST = 85 LOAD_FAST_LOAD_FAST = 88 LOAD_FAST_BORROW = 86 LOAD_FAST_BORROW_LOAD_FAST_BORROW = 87 def _normalize_code(f, l): # A small selection of possible peephole code transformations, based on wh...
_op
python
doocs__leetcode
solution/1300-1399/1349.Maximum Students Taking Exam/Solution.py
{ "start": 0, "end": 902 }
class ____: def maxStudents(self, seats: List[List[str]]) -> int: def f(seat: List[str]) -> int: mask = 0 for i, c in enumerate(seat): if c == '.': mask |= 1 << i return mask @cache def dfs(seat: int, i: int) -> int: ...
Solution
python
PyCQA__pylint
pylint/reporters/ureports/nodes.py
{ "start": 1449, "end": 2646 }
class ____(VNode): """Base container node. attributes * children : components in this table (i.e. the table's cells) """ def __init__(self, children: Iterable[Text | str] = ()) -> None: super().__init__() for child in children: if isinstance(child, VNode): ...
BaseLayout
python
mlflow__mlflow
dev/set_matrix.py
{ "start": 2169, "end": 2391 }
class ____(BaseModel): model_config = ConfigDict(extra="forbid") pip_release: str install_dev: str | None = None module_name: str | None = None genai: bool = False repo: str | None = None
PackageInfo
python
sphinx-doc__sphinx
sphinx/transforms/post_transforms/images.py
{ "start": 1280, "end": 4388 }
class ____(BaseImageConverter): default_priority = 100 def match(self, node: nodes.image) -> bool: if not self.env._builder_cls.supported_image_types: return False if self.env._builder_cls.supported_remote_images: return False return '://' in node['uri'] def...
ImageDownloader
python
pytorch__pytorch
benchmarks/transformer/attention_bias_benchmarks.py
{ "start": 2078, "end": 7582 }
class ____(torch.nn.Module): def __init__(self, num_heads, embed_dim, device=None, dtype=None): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.head_dim = embed_dim // num_heads self.embed_dim = embed_dim assert self.head_dim * num_heads == self.e...
CompositeMHA
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/tree/tree_root_retriever.py
{ "start": 487, "end": 1750 }
class ____(BaseRetriever): """ Tree root retriever. This class directly retrieves the answer from the root nodes. Unlike GPTTreeIndexLeafQuery, this class assumes the graph already stores the answer (because it was constructed with a query_str), so it does not attempt to parse information down...
TreeRootRetriever
python
wandb__wandb
wandb/sdk/lib/service/service_connection.py
{ "start": 780, "end": 2198 }
class ____(Exception): """Failed to execute an API request to wandb-core.""" def connect_to_service( asyncer: asyncio_manager.AsyncioManager, settings: wandb_settings.Settings, ) -> ServiceConnection: """Connect to the service process, starting one up if necessary.""" token = service_token.from_en...
WandbApiFailedError
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/image_deplot/base.py
{ "start": 181, "end": 3137 }
class ____(BaseReader): """ Image parser. Extract tabular data from a chart or figure. """ def __init__( self, parser_config: Optional[Dict] = None, keep_image: bool = False, max_output_tokens=512, prompt: str = "Generate underlying data table of the figure...
ImageTabularChartReader
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_namers.py
{ "start": 2049, "end": 2421 }
class ____(TestCase): def test_basic(self): filename = namers.source_hashed( thumbnailer=FakeThumbnailer(), prepared_options=['100x100', 'q80', 'crop', 'upscale'], source_filename='source.jpg', thumbnail_extension='jpg', ) self.assertEqual(fil...
SourceHashed
python
tornadoweb__tornado
tornado/test/autoreload_test.py
{ "start": 157, "end": 9176 }
class ____(unittest.TestCase): def setUp(self): # When these tests fail the output sometimes exceeds the default maxDiff. self.maxDiff = 1024 self.path = mkdtemp() # Most test apps run themselves twice via autoreload. The first time it manually triggers # a reload (could al...
AutoreloadTest
python
arrow-py__arrow
arrow/locales.py
{ "start": 123744, "end": 126374 }
class ____(Locale): names = ["zu", "zu-za"] past = "{0} edlule" future = "{0} " and_word = "futhi" timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[Mapping[str, str], str]]] = { "now": "manje", "second": {"past": "umzuzwana", "future": "ngomzuzwana"}, "seconds": {"past"...
ZuluLocale
python
yaml__pyyaml
lib/yaml/tokens.py
{ "start": 1677, "end": 1720 }
class ____(Token): id = ','
FlowEntryToken
python
getsentry__sentry
tests/sentry/deletions/tasks/test_nodestore.py
{ "start": 417, "end": 3919 }
class ____(TestCase): def create_n_events_with_group(self, n_events: int) -> list[Event]: events = [] for _ in range(n_events): event = self.store_event( data={"fingerprint": [uuid4().hex]}, project_id=self.project.id ) events.append(event) ...
NodestoreDeletionTaskTest
python
milvus-io__pymilvus
pymilvus/orm/connections.py
{ "start": 1437, "end": 1911 }
class ____(type): instance = None def __init__(cls, *args, **kwargs) -> None: super().__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): if cls.instance: return cls.instance cls.instance = cls.__new__(cls) cls.instance.__init__(*args, **kwargs) ...
SingleInstanceMetaClass
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 2485, "end": 2616 }
class ____(ConcreteTemplate): key = cuda.threadfence_system cases = [signature(types.none)] @register
Cuda_threadfence_system
python
kamyu104__LeetCode-Solutions
Python/maximum-split-of-positive-even-integers.py
{ "start": 44, "end": 423 }
class ____(object): def maximumEvenSplit(self, finalSum): """ :type finalSum: int :rtype: List[int] """ if finalSum%2: return [] result = [] i = 2 while i <= finalSum: result.append(i) finalSum -= i i += ...
Solution
python
huggingface__transformers
src/transformers/models/llava_next/modeling_llava_next.py
{ "start": 9522, "end": 10684 }
class ____(PreTrainedModel): config: LlavaNextConfig base_model_prefix = "model" input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = ["LlamaDecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_sd...
LlavaNextPreTrainedModel
python
django__django
django/contrib/postgres/lookups.py
{ "start": 1230, "end": 1620 }
class ____(SearchVectorExact): lookup_name = "search" def process_lhs(self, qn, connection): if not isinstance(self.lhs.output_field, SearchVectorField): config = getattr(self.rhs, "config", None) self.lhs = SearchVector(self.lhs, config=config) lhs, lhs_params = super()...
SearchLookup
python
great-expectations__great_expectations
great_expectations/experimental/metric_repository/metrics.py
{ "start": 1547, "end": 1798 }
class ____(MetricRepositoryBaseModel): type: str = Field(description="Exception type if an exception is thrown") message: str = Field(description="Exception message if an exception is thrown") _ValueType = TypeVar("_ValueType")
MetricException
python
davidhalter__jedi
test/completion/pep0484_comments.py
{ "start": 544, "end": 764 }
class ____: class BB: pass def test(a): # type: (AA.BB) -> None #? AA.BB() a def test(a): # type: (AA.BB,) -> None #? AA.BB() a a,b = 1, 2 # type: str, float #? str() a #? float() b
AA
python
kamyu104__LeetCode-Solutions
Python/construct-binary-search-tree-from-preorder-traversal.py
{ "start": 191, "end": 916 }
class ____(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ def bstFromPreorderHelper(preorder, left, right, index): if index[0] == len(preorder) or \ preorder[index[0]] < left or \ preo...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-omni/dagster_omni/component.py
{ "start": 775, "end": 7555 }
class ____(StateBackedComponent, dg.Model, dg.Resolvable): """Pulls in the contents of an Omni workspace into Dagster assets. Example: .. code-block:: yaml # defs.yaml type: dagster_omni.OmniComponent attributes: workspace: base_url: ...
OmniComponent
python
openai__openai-python
tests/api_resources/test_webhooks.py
{ "start": 1211, "end": 8900 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @mock.patch("time.time", mock.MagicMock(return_value=TEST_TIMESTAMP)) @parametrize def test_unwrap_with_secret(self, client: openai.OpenAI) -> None: headers = create_test_headers()...
TestWebhooks
python
pytest-dev__pytest
src/_pytest/terminal.py
{ "start": 10084, "end": 11068 }
class ____: """Simple structure to hold warnings information captured by ``pytest_warning_recorded``. :ivar str message: User friendly message about the warning. :ivar str|None nodeid: nodeid that generated the warning (see ``get_location``). :ivar tuple fslocation: File system ...
WarningReport
python
pallets__werkzeug
src/werkzeug/debug/console.py
{ "start": 3310, "end": 5516 }
class ____(code.InteractiveInterpreter): locals: dict[str, t.Any] def __init__(self, globals: dict[str, t.Any], locals: dict[str, t.Any]) -> None: self.loader = _ConsoleLoader() locals = { **globals, **locals, "dump": dump, "help": helper, ...
_InteractiveConsole
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_exceptions.py
{ "start": 2309, "end": 2389 }
class ____(Exception): def __init__(self, x): self.x = x
NaiveException
python
python__mypy
mypy/constraints.py
{ "start": 27683, "end": 27886 }
class ____(BoolTypeQuery): def __init__(self) -> None: super().__init__(ALL_STRATEGY) def visit_uninhabited_type(self, t: UninhabitedType) -> bool: return False
CompleteTypeVisitor
python
numba__numba
numba/cuda/tests/cudadrv/test_deallocations.py
{ "start": 2564, "end": 4740 }
class ____(CUDATestCase): def test_basic(self): harr = np.arange(5) darr1 = cuda.to_device(harr) deallocs = cuda.current_context().memory_manager.deallocations deallocs.clear() self.assertEqual(len(deallocs), 0) with cuda.defer_cleanup(): darr2 = cuda.to_d...
TestDeferCleanup
python
walkccc__LeetCode
solutions/1576. Replace All ?'s to Avoid Consecutive Repeating Characters/1576.py
{ "start": 0, "end": 438 }
class ____: def modifyString(self, s: str) -> str: ans = [] def nextAvailable(ans: list[int], s: str, i: int) -> str: c = 'a' while ((i > 0 and ans[i - 1] == c) or (i + 1 < len(s) and c == s[i + 1])): c = chr(ord(c) + 1) return c for i, c in enumerate(s): if ...
Solution
python
ApeWorX__ape
src/ape_ethereum/transactions.py
{ "start": 2028, "end": 4753 }
class ____(TransactionAPI): def serialize_transaction(self) -> bytes: if not self.signature: message = "The transaction is not signed." if not self.sender: message = ( f"{message} " "Did you forget to add the `sender=` kwarg to ...
BaseTransaction
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 6130, "end": 6427 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "RepositoryLocationNotFound" def __init__(self, location_name): super().__init__() self.message = f"Location {location_name} does not exist."
GrapheneRepositoryLocationNotFound
python
apache__airflow
providers/alibaba/tests/unit/alibaba/cloud/operators/test_analyticdb_spark.py
{ "start": 2849, "end": 4784 }
class ____: @mock.patch(ADB_SPARK_OPERATOR_STRING.format("AnalyticDBSparkHook")) def test_execute(self, mock_hook): """Test submit AnalyticDB Spark Batch Application works as expected.""" operator = AnalyticDBSparkBatchOperator( file=MOCK_FILE, cluster_id=MOCK_CLUSTER_ID,...
TestAnalyticDBSparkBatchOperator
python
google__pytype
pytype/tests/test_attributes2.py
{ "start": 80, "end": 1060 }
class ____(test_base.BaseTest): """Tests for strict attribute checking on None.""" def test_explicit_none(self): errors = self.CheckWithErrors(""" from typing import Optional def f(x: Optional[str]): return x.upper() # attribute-error[e] """) self.assertErrorRegexes(errors, {"e": r...
TestStrictNone
python
dask__dask
dask/dataframe/dask_expr/io/parquet.py
{ "start": 7308, "end": 7862 }
class ____(Expr): _parameters = [ "frame", "path", "fs", "fmd", "engine", "offset", "partition_on", "write_metadata_file", "name_function", "write_kwargs", "append", ] @property def _meta(self): return None ...
ToParquet
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 25291, "end": 25564 }
class ____(sgqlc.types.Enum): """The privacy of a Gist Enumeration Choices: * `ALL`: Gists that are public and secret * `PUBLIC`: Public * `SECRET`: Secret """ __schema__ = github_schema __choices__ = ("ALL", "PUBLIC", "SECRET")
GistPrivacy
python
wireservice__csvkit
csvkit/utilities/csvsql.py
{ "start": 422, "end": 13430 }
class ____(CSVKitUtility): description = 'Generate SQL statements for one or more CSV files, or execute those statements directly on a ' \ 'database, and execute one or more SQL queries.' # Override 'f' because the utility accepts multiple files. override_flags = ['f'] def add_argumen...
CSVSQL
python
ethereum__web3.py
tests/core/utilities/test_attach_modules.py
{ "start": 488, "end": 5204 }
class ____(Module): def start_ws(self): return True def test_attach_modules(): mods = { "geth": ( MockGeth, { "admin": MockGethAdmin, }, ), "eth": MockEth, } w3 = Web3(EthereumTesterProvider(), modules={}) attach_m...
MockGethAdmin
python
encode__django-rest-framework
rest_framework/utils/encoders.py
{ "start": 347, "end": 2826 }
class ____(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time/timedelta, decimal types, generators and other basic python objects. """ def default(self, obj): # For Date Time string spec, see ECMA 262 # https://ecma-international.org/ecma-262/5.1/#sec-15.9...
JSONEncoder
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/events.py
{ "start": 5245, "end": 5314 }
class ____(CollectionStartEvent): __slots__ = ()
SequenceStartEvent
python
google__jax
tests/pallas/tpu_pallas_test.py
{ "start": 93940, "end": 95279 }
class ____(PallasBaseTest): def test_scratch_input_vmap(self): """Test that vmapp-ing a kernel with scratch inputs works correctly.""" # Scratch inputs are only available for PallasTPU. This is why this test # does not live with the other vmap tests in: # jax/tests/pallas/pallas_test.py def add_...
PallasCallVmapTest
python
ray-project__ray
python/ray/autoscaler/_private/node_launcher.py
{ "start": 695, "end": 6841 }
class ____: """Launches Ray nodes in the main thread using `BaseNodeLauncher.launch_node()`. This is a superclass of NodeLauncher, which launches nodes asynchronously in the background. By default, the subclass NodeLauncher is used to launch nodes in subthreads. That behavior can be flagged of...
BaseNodeLauncher
python
getsentry__sentry
src/sentry/api/authentication.py
{ "start": 5822, "end": 6829 }
class ____(BasicAuthentication): def authenticate_header(self, request: Request) -> str: return 'xBasic realm="%s"' % self.www_authenticate_realm def transform_auth( self, user: int | User | RpcUser | None | AnonymousUser, request_auth: Any, entity_id_tag: str | None = N...
QuietBasicAuthentication
python
huggingface__transformers
src/transformers/models/cohere/configuration_cohere.py
{ "start": 1138, "end": 8664 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to...
CohereConfig
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 18985, "end": 20767 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = Stat() x.Init(buf, n + offset) return x @classmethod def GetRootAsStat(cls, buf, offset=0): """Th...
Stat
python
PyCQA__pylint
tests/functional/a/assignment/assignment_from_no_return.py
{ "start": 677, "end": 950 }
class ____: """Parent class""" def compute(self): """This isn't supported by all child classes""" raise ValueError('Not supported for this object') def test(self): """Test""" result = self.compute() return result
Parent
python
astropy__astropy
astropy/modeling/spline.py
{ "start": 21928, "end": 24128 }
class ____(_SplineFitter): """ Fit a spline using least-squares regression. """ def __call__(self, model, x, y, **kwargs): """ Fit a spline to data using least-squares with exact knots. Parameters ---------- model : `Spline1D` The spline model to fit...
SplineExactKnotsFitter
python
mitmproxy__pdoc
pdoc/doc.py
{ "start": 33528, "end": 39786 }
class ____(Doc[types.FunctionType]): """ Representation of a function's documentation. This class covers all "flavors" of functions, for example it also supports `@classmethod`s or `@staticmethod`s. """ kind = "function" wrapped: WrappedFunction """The original wrapped function (e.g.,...
Function
python
ansible__ansible
lib/ansible/executor/module_common.py
{ "start": 41550, "end": 60406 }
class ____: """Cached Python module created by AnsiballZ.""" # FIXME: switch this to use a locked down pickle config or don't use pickle- easy to mess up and reach objects that shouldn't be pickled zip_data: bytes metadata: ModuleMetadata source_mapping: dict[str, str] """A mapping of controll...
_CachedModule
python
sympy__sympy
sympy/polys/matrices/sdm.py
{ "start": 509, "end": 65339 }
class ____(dict): r"""Sparse matrix based on polys domain elements This is a dict subclass and is a wrapper for a dict of dicts that supports basic matrix arithmetic +, -, *, **. In order to create a new :py:class:`~.SDM`, a dict of dicts mapping non-zero elements to their corresponding row a...
SDM