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
python-attrs__attrs
tests/test_next_gen.py
{ "start": 10302, "end": 10595 }
class ____: def test_smoke(self): """ `attrs.asdict` only changes defaults, so we just call it and compare. """ inst = C("foo", {(1,): 42}) assert attrs.asdict(inst) == _attr.asdict( inst, retain_collection_types=True )
TestAsDict
python
kubernetes-client__python
kubernetes/client/models/v1_preferred_scheduling_term.py
{ "start": 383, "end": 4742 }
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...
V1PreferredSchedulingTerm
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 69626, "end": 69760 }
class ____(_TestBinaryOpsMutating, __TestCase): constructor1 = SetSubclass constructor2 = set
TestBinaryOpsMutating_Subclass_Set
python
ray-project__ray
doc/source/serve/doc_code/intel_gaudi_inference_serve.py
{ "start": 361, "end": 4425 }
class ____: def __init__(self, model_id_or_path: str): from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig from optimum.habana.transformers.modeling_utils import ( adapt_transformers_to_gaudi, ) # Tweak transformers to optimize performance ad...
LlamaModel
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/items/GLImageItem.py
{ "start": 324, "end": 6623 }
class ____(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem>` Displays image data as a textured quad. """ _shaderProgram = None def __init__(self, data, smooth=False, glOptions='translucent', parentItem=None): """ ...
GLImageItem
python
django__django
tests/mail/test_deprecated.py
{ "start": 2574, "end": 4008 }
class ____(SimpleTestCase): """ These undocumented features were removed without going through deprecation. In case they were being used, they now raise errors. """ def test_undocumented_mixed_subtype(self): """ Trying to use the previously undocumented, now unsupported Emai...
UndocumentedFeatureErrorTests
python
numpy__numpy
numpy/ctypeslib/_ctypeslib.py
{ "start": 5323, "end": 6180 }
class ____(_ndptr_base): @classmethod def from_param(cls, obj): if not isinstance(obj, np.ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError(f"array must have data type {cls._d...
_ndptr
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink39.py
{ "start": 315, "end": 906 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink39.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workb...
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/_typing.py
{ "start": 2397, "end": 2774 }
class ____(_CoreKnownExecutionOptions, total=False): populate_existing: bool autoflush: bool synchronize_session: SynchronizeSessionArgument dml_strategy: DMLStrategyArgument is_delete_using: bool is_update_from: bool render_nulls: bool OrmExecuteOptionsParameter = Union[ _OrmKnownExec...
_OrmKnownExecutionOptions
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/typehints.py
{ "start": 471, "end": 1243 }
class ____: CONST1: int CONST2: int = 1 CONST3: pathlib.PurePosixPath = pathlib.PurePosixPath('/a/b/c') def __init__(self, s: str, o: Any = None) -> None: pass def incr(self, a: int, b: int = 1) -> int: return a + b def decr(self, a, b=1): # type: (int, int) -> int ...
Math
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-singlestoredb/llama_index/vector_stores/singlestoredb/base.py
{ "start": 491, "end": 11430 }
class ____(BasePydanticVectorStore): """ SingleStore vector store. This vector store stores embeddings within a SingleStore database table. During query time, the index uses SingleStore to query for the top k most similar nodes. Args: table_name (str, optional): Specifies the name of ...
SingleStoreVectorStore
python
ApeWorX__ape
tests/functional/test_plugins.py
{ "start": 10147, "end": 11093 }
class ____: def test_str(self, plugin_metadata): representation = ApePluginsRepr(plugin_metadata) actual = str(representation) expected = f""" Installed Plugins installed {ape_version.base} Third-party Plugins thirdparty {ape_version.base} """ assert actual == exp...
TestApePluginsRepr
python
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 13123, "end": 16928 }
class ____(Scale): values: tuple | str | None = None norm: tuple | None = None def _setup( self, data: Series, prop: Property, axis: Axis | None = None, ) -> Scale: new = copy(self) if new._tick_params is None: new = new.tick() if new._label_params is None:...
ContinuousBase
python
PrefectHQ__prefect
src/prefect/server/database/query_components.py
{ "start": 1369, "end": 1874 }
class ____(NamedTuple): kind: Literal["flow-run", "task-run"] id: UUID label: str state_type: StateType start_time: DateTime end_time: Optional[DateTime] parent_ids: Optional[list[UUID]] child_ids: Optional[list[UUID]] encapsulating_ids: Optional[list[UUID]] ONE_HOUR = 60 * 60 ji...
FlowRunGraphV2Node
python
realpython__materials
python-range/float_range.py
{ "start": 3036, "end": 3733 }
class ____: """Non-public iterator. Should only be initialized by FloatRange.""" start: float | int stop: float | int step: float | int _num_steps: int = field(default=0, init=False) def __iter__(self): """Initialize the iterator.""" return self def __next__(self): ...
_FloatRangeIterator
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 11350, "end": 11765 }
class ____: def setup_method(self): class TestSerializer(serializers.Serializer): labeled = serializers.IntegerField(label='My label') self.serializer = TestSerializer() def test_label(self): """ A field's label may be set with the `label` argument. """ ...
TestLabel
python
doocs__leetcode
solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py
{ "start": 0, "end": 401 }
class ____: def maxSpending(self, values: List[List[int]]) -> int: n = len(values[0]) pq = [(row[-1], i, n - 1) for i, row in enumerate(values)] heapify(pq) ans = d = 0 while pq: d += 1 v, i, j = heappop(pq) ans += v * d if j: ...
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/assets/registry_entry.py
{ "start": 2210, "end": 30621 }
class ____(Exception): pass # HELPERS @sentry_sdk.trace def apply_spec_to_registry_entry(registry_entry: dict, spec_cache: SpecCache, registry_name: str) -> dict: cached_spec = spec_cache.find_spec_cache_with_fallback( registry_entry["dockerRepository"], registry_entry["dockerImageTag"], registry_na...
MissingCachedSpecError
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/utils/task_log_fetcher.py
{ "start": 1187, "end": 5364 }
class ____(Thread): """Fetch Cloudwatch log events with specific interval and send the log events to the logger.info.""" def __init__( self, *, log_group: str, log_stream_name: str, fetch_interval: timedelta, logger: Logger, aws_conn_id: str | None = "aws...
AwsTaskLogFetcher
python
getsentry__sentry
src/sentry/monitors/endpoints/base_monitor_environment_details.py
{ "start": 436, "end": 2678 }
class ____(BaseEndpointMixin): def update_monitor_environment( self, request: Request, project, monitor, monitor_environment ) -> Response: """ Update a monitor environment. """ # Only support muting/unmuting monitor environments is_muted = request.data.get("isMut...
MonitorEnvironmentDetailsMixin
python
jazzband__django-oauth-toolkit
tests/test_scopes.py
{ "start": 952, "end": 1148 }
class ____(ScopedProtectedResourceView): required_scopes = ["scope1", "scope2"] def get(self, request, *args, **kwargs): return "This is a protected resource"
MultiScopeResourceView
python
spyder-ide__spyder
spyder/api/asyncdispatcher.py
{ "start": 17447, "end": 17655 }
class ____(QEvent): """Event to execute a callback in the main Qt loop.""" def __init__(self, func: typing.Callable): super().__init__(QEvent.Type.User) self.func = func
_QCallbackEvent
python
huggingface__transformers
src/transformers/models/table_transformer/modeling_table_transformer.py
{ "start": 15435, "end": 17140 }
class ____(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, embedding_dim=256): super().__init__() self.row_embeddings = nn.Embedding(50, embedding_dim) self.column_embeddings = nn.Embedding(50, embedding_dim) def f...
TableTransformerLearnedPositionEmbedding
python
getsentry__sentry
src/sentry/api/endpoints/relay/__init__.py
{ "start": 41, "end": 925 }
class ____(serializers.Serializer): relay_id = serializers.RegexField( r"^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", required=True ) from .details import RelayDetailsEndpoint from .health_check import RelayHealthCheck from .index import RelayIndexEndpoint from .project_conf...
RelayIdSerializer
python
apache__airflow
providers/elasticsearch/src/airflow/providers/elasticsearch/hooks/elasticsearch.py
{ "start": 3440, "end": 4678 }
class ____: """wrapper class for elasticsearch.Elasticsearch.""" def __init__( self, host: str = "localhost", port: int = 9200, user: str | None = None, password: str | None = None, scheme: str = "http", **kwargs: Any, ): self.host = host ...
ESConnection
python
mlflow__mlflow
mlflow/types/llm.py
{ "start": 6526, "end": 8169 }
class ____(_BaseDataclass): """ A message in a chat request or response. Args: role (str): The role of the entity that sent the message (e.g. ``"user"``, ``"system"``, ``"assistant"``, ``"tool"``). content (str): The content of the message. **Optional** Can be ``None...
ChatMessage
python
walkccc__LeetCode
solutions/1260. Shift 2D Grid/1260.py
{ "start": 0, "end": 365 }
class ____: def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]: m = len(grid) n = len(grid[0]) ans = [[0] * n for _ in range(m)] k %= m * n for i in range(m): for j in range(n): index = (i * n + j + k) % (m * n) x = index // n y = index % n ...
Solution
python
numpy__numpy
tools/swig/test/testSuperTensor.py
{ "start": 12356, "end": 12673 }
class ____(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" #self.result = int(self.result) ######################################################################
ucharTestCase
python
apache__airflow
airflow-core/src/airflow/executors/workloads.py
{ "start": 4603, "end": 5659 }
class ____(BaseDagBundleWorkload): """Execute the given Callback.""" callback: Callback type: Literal["ExecuteCallback"] = Field(init=False, default="ExecuteCallback") @classmethod def make( cls, callback: CallbackModel, dag_run: DagRun, dag_rel_path: Path | None =...
ExecuteCallback
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 15294, "end": 19813 }
class ____(TestCase): class Schema: repo_url = c.URL() repo_name = c.RepoName('repo_url') edit_uri_template = c.EditURITemplate('edit_uri') edit_uri = c.EditURI('repo_url') def test_repo_name_github(self): conf = self.get_config( self.Schema, {'re...
EditURITest
python
pytorch__pytorch
torch/_refs/fft.py
{ "start": 7669, "end": 13042 }
class ____(NamedTuple): shape: tuple[int, ...] dims: tuple[int, ...] def _canonicalize_fft_shape_and_dim_args( input: TensorLikeType, shape: Optional[ShapeType], dim: Optional[DimsType] ) -> _ShapeAndDims: """Convert the shape and dim arguments into a canonical form where neither are optional""" i...
_ShapeAndDims
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1133541, "end": 1134982 }
class ____(sgqlc.types.Type, Node): """Describes the status of a given deployment attempt.""" __schema__ = github_schema __field_names__ = ("created_at", "creator", "deployment", "description", "environment_url", "log_url", "state", "updated_at") created_at = sgqlc.types.Field(sgqlc.types.non_null(Date...
DeploymentStatus
python
getsentry__sentry
src/sentry/notifications/notification_action/metric_alert_registry/handlers/msteams_metric_alert_handler.py
{ "start": 871, "end": 2578 }
class ____(BaseMetricAlertHandler): @classmethod def send_alert( cls, notification_context: NotificationContext, alert_context: AlertContext, metric_issue_context: MetricIssueContext, open_period_context: OpenPeriodContext, trigger_status: TriggerStatus, n...
MSTeamsMetricAlertHandler
python
pandas-dev__pandas
pandas/core/computation/ops.py
{ "start": 7816, "end": 12338 }
class ____(Op): """ Hold a binary operator and its operands. Parameters ---------- op : str lhs : Term or Op rhs : Term or Op """ def __init__(self, op: str, lhs, rhs) -> None: super().__init__(op, (lhs, rhs)) self.lhs = lhs self.rhs = rhs self._dis...
BinOp
python
scipy__scipy
scipy/optimize/tests/test_linprog.py
{ "start": 104925, "end": 104988 }
class ____(RRTests): options = {"rr_method": "SVD"}
TestRRSVD
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 23372, "end": 23493 }
class ____(Hostname): platform = 'Linux' distribution = 'Alinux' strategy_class = RedHatStrategy
AlinuxHostname
python
scipy__scipy
scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
{ "start": 18754, "end": 27642 }
class ____(TestCase): # From Example 16.2 Nocedal/Wright "Numerical # Optimization" p.452. def test_nocedal_example(self): H = csc_array([[6, 2, 1], [2, 5, 2], [1, 2, 4]]) A = csc_array([[1, 0, 1], [0, 1, 1]]) c = ...
TestProjectCG
python
google__pytype
pytype/tests/test_typing_annotated.py
{ "start": 122, "end": 3488 }
class ____(test_base.BaseTest): """Tests for typing.Annotated types.""" def test_basic(self): ty = self.Infer(""" from typing_extensions import Annotated i = ... # type: Annotated[int, "foo"] s: Annotated[str, "foo", "bar"] = "baz" """) self.assertTypesMatchPytd( ty, "...
AnnotatedTest
python
django__django
tests/migration_test_data_persistence/migrations/0002_add_book.py
{ "start": 240, "end": 441 }
class ____(migrations.Migration): dependencies = [("migration_test_data_persistence", "0001_initial")] operations = [ migrations.RunPython( add_book, ), ]
Migration
python
realpython__materials
dwitter-part-3/source_code_final/dwitter/migrations/0002_dweet.py
{ "start": 158, "end": 856 }
class ____(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('dwitter', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dweet', fields=[ ('id', models.BigAutoField(auto_created...
Migration
python
coleifer__peewee
tests/base_models.py
{ "start": 483, "end": 641 }
class ____(TestModel): from_person = ForeignKeyField(Person, backref='relations') to_person = ForeignKeyField(Person, backref='related_to')
Relationship
python
walkccc__LeetCode
solutions/2709. Greatest Common Divisor Traversal/2709.py
{ "start": 0, "end": 550 }
class ____: def __init__(self, n: int): self.id = list(range(n)) self.sz = [1] * n def unionBySize(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.sz[i] < self.sz[j]: self.sz[j] += self.sz[i] self.id[i] = j else: self....
UnionFind
python
huggingface__transformers
tests/models/hubert/test_modeling_hubert.py
{ "start": 22199, "end": 33335 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): from datasets import load_dataset ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( ...
HubertModelIntegrationTest
python
great-expectations__great_expectations
tests/data_context/test_data_context.py
{ "start": 24149, "end": 24825 }
class ____(BatchExpectation): metric_dependencies = ("table.color",) success_keys = ("color",) args_keys = ("color",) color: str @classmethod @renderer(renderer_type=".".join([AtomicRendererType.PRESCRIPTIVE, "custom_renderer_type"])) def _prescriptive_renderer_custom( cls, ...
ExpectSkyToBeColor
python
apache__airflow
providers/google/tests/unit/google/cloud/transfers/test_local_to_gcs.py
{ "start": 1167, "end": 9424 }
class ____: _config = { "bucket": "dummy", "mime_type": "application/octet-stream", "gzip": False, "chunk_size": 262144, } @pytest.fixture(autouse=True) def setup_method_fixture(self, tmp_path): args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1,...
TestFileToGcsOperator
python
yaml__pyyaml
lib/yaml/tokens.py
{ "start": 1720, "end": 1915 }
class ____(Token): id = '<alias>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark
AliasToken
python
realpython__materials
mandelbrot-set-python/mandelbrot_03.py
{ "start": 145, "end": 879 }
class ____: max_iterations: int escape_radius: float = 2.0 def __contains__(self, c: complex) -> bool: return self.stability(c) == 1 def stability(self, c: complex, smooth=False, clamp=True) -> float: value = self.escape_count(c, smooth) / self.max_iterations return max(0.0, mi...
MandelbrotSet
python
openai__openai-python
src/openai/types/responses/response_text_config_param.py
{ "start": 319, "end": 1381 }
class ____(TypedDict, total=False): format: ResponseFormatTextConfigParam """An object specifying the format that the model must output. Configuring `{ "type": "json_schema" }` enables Structured Outputs, which ensures the model will match your supplied JSON schema. Learn more in the [Structured Ou...
ResponseTextConfigParam
python
lepture__authlib
authlib/oauth2/rfc8628/errors.py
{ "start": 320, "end": 600 }
class ____(OAuth2Error): """A variant of "authorization_pending", the authorization request is still pending and polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests. """ error = "slow_down"
SlowDownError
python
Textualize__textual
docs/examples/widgets/footer.py
{ "start": 116, "end": 680 }
class ____(App): BINDINGS = [ Binding(key="q", action="quit", description="Quit the app"), Binding( key="question_mark", action="help", description="Show help screen", key_display="?", ), Binding(key="delete", action="delete", descripti...
FooterApp
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 12804, "end": 13782 }
class ____(_TypeVariable): """Representation of typing.TypeVar, as a function.""" _ABSTRACT_CLASS = abstract.TypeParameter @classmethod def make(cls, ctx, module): # We always want to use typing as the module, since pytype's typing.pytd # contains a _typevar_new helper. del module return super...
TypeVar
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 911245, "end": 913147 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Minimizable, Updatable, UpdatableComment, Reactable, RepositoryNode, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "commit", "diff_hunk", "...
PullRequestReviewComment
python
facebookresearch__faiss
benchs/bench_fw/benchmark.py
{ "start": 6896, "end": 9511 }
class ____(IndexOperator): codec_descs: List[CodecDescriptor] = field(default_factory=lambda: []) assemble_opaque: bool = True def get_desc(self, name: str) -> Optional[CodecDescriptor]: for desc in self.codec_descs: if desc.get_name() == name: return desc el...
TrainOperator
python
Netflix__metaflow
metaflow/plugins/argo/exit_hooks.py
{ "start": 249, "end": 699 }
class ____(JsonSerializable): # https://argoproj.github.io/argo-workflows/fields/#lifecyclehook def __init__(self, name): tree = lambda: defaultdict(tree) self.name = name self.payload = tree() def expression(self, expression): self.payload["expression"] = str(expression) ...
_LifecycleHook
python
marshmallow-code__marshmallow
src/marshmallow/schema.py
{ "start": 6962, "end": 8072 }
class ____: """Defines defaults for `marshmallow.Schema.Meta`.""" def __init__(self, meta: type): self.fields = getattr(meta, "fields", ()) if not isinstance(self.fields, (list, tuple)): raise ValueError("`fields` option must be a list or tuple.") self.exclude = getattr(meta...
SchemaOpts
python
joke2k__faker
faker/providers/ssn/dk_DK/__init__.py
{ "start": 42, "end": 344 }
class ____(BaseProvider): """ A Faker provider for the Danish VAT IDs """ vat_id_formats = ("DK########",) def vat_id(self) -> str: """ Returns a random generated Danish Tax ID """ return self.bothify(self.random_element(self.vat_id_formats))
Provider
python
getsentry__sentry-python
sentry_sdk/integrations/huggingface_hub.py
{ "start": 699, "end": 14952 }
class ____(Integration): identifier = "huggingface_hub" origin = f"auto.ai.{identifier}" def __init__(self, include_prompts=True): # type: (HuggingfaceHubIntegration, bool) -> None self.include_prompts = include_prompts @staticmethod def setup_once(): # type: () -> None ...
HuggingfaceHubIntegration
python
bokeh__bokeh
src/bokeh/models/map_plots.py
{ "start": 4771, "end": 7567 }
class ____(MapPlot): ''' A Bokeh Plot with a `Google Map`_ displayed underneath. Data placed on this plot should be specified in decimal lat/lon coordinates e.g. ``(37.123, -122.404)``. It will be automatically converted into the web mercator projection to display properly over google maps tiles. ...
GMapPlot
python
eth-brownie__brownie
brownie/_gui/opcodes.py
{ "start": 6017, "end": 7501 }
class ____(ToggleButton): def __init__(self, parent): super().__init__(parent, "Scope", "s") self.oplist = self.root.main.oplist def toggle_on(self): try: op = self.oplist.selection()[0] except IndexError: return False if self.oplist.item(op, "tag...
ScopingButton
python
getsentry__sentry
src/sentry/api/serializers/models/project_key.py
{ "start": 558, "end": 802 }
class ____(TypedDict): secret: str public: str csp: str security: str minidump: str nel: str unreal: str crons: str cdn: str playstation: str integration: str otlp_traces: str otlp_logs: str
DSN
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 8162, "end": 8261 }
class ____(VyperException): """Reference to an attribute that does not exist."""
UnknownAttribute
python
astropy__astropy
astropy/coordinates/representation/spherical.py
{ "start": 47175, "end": 51892 }
class ____(BaseSphericalCosLatDifferential): """Differential(s) of points on a unit sphere. Parameters ---------- d_lon_coslat, d_lat : `~astropy.units.Quantity` The longitude and latitude of the differentials. copy : bool, optional If `True` (default), arrays will be copied. If `Fa...
UnitSphericalCosLatDifferential
python
pytorch__pytorch
torch/nn/modules/loss.py
{ "start": 4565, "end": 10950 }
class ____(_WeightedLoss): r"""The negative log likelihood loss. It is useful to train a classification problem with `C` classes. If provided, the optional argument :attr:`weight` should be a 1D Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced ...
NLLLoss
python
huggingface__transformers
src/transformers/models/lxmert/modeling_lxmert.py
{ "start": 27207, "end": 27747 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.transform_act_fn = ACT2FN[config.hidden_act] self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12) def forward(self, hidden_states): ...
LxmertPredictionHeadTransform
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/vector/vectorize_observation.py
{ "start": 603, "end": 4700 }
class ____(VectorObservationWrapper): """Transforms an observation via a function provided to the wrapper. This function allows the manual specification of the vector-observation function as well as the single-observation function. This is desirable when, for example, it is possible to process vector obser...
TransformObservation
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/regular_languages/regex_parser.py
{ "start": 2974, "end": 7732 }
class ____(Node): def __init__( self, childnode: Node, min_repeat: int = 0, max_repeat: int | None = None, greedy: bool = True, ) -> None: self.childnode = childnode self.min_repeat = min_repeat self.max_repeat = max_repeat self.greedy = gr...
Repeat
python
marshmallow-code__marshmallow
tests/base.py
{ "start": 544, "end": 1934 }
class ____(Enum): date_1 = dt.date(2004, 2, 29) date_2 = dt.date(2008, 2, 29) date_3 = dt.date(2012, 2, 29) ALL_FIELDS = [ fields.String, fields.Integer, fields.Boolean, fields.Float, fields.DateTime, fields.Time, fields.Date, fields.TimeDelta, fields.Dict, fields.U...
DateEnum
python
pypa__pip
src/pip/_internal/index/package_finder.py
{ "start": 21639, "end": 39158 }
class ____: """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector: LinkCollector, target_python: TargetPython, allow_yanked: bool, ...
PackageFinder
python
getsentry__sentry
src/sentry/issue_detection/detectors/uncompressed_asset_detector.py
{ "start": 715, "end": 6567 }
class ____(PerformanceDetector): """ Checks for large assets that are affecting load time. """ __slots__ = ("any_compression",) settings_key = DetectorType.UNCOMPRESSED_ASSETS type = DetectorType.UNCOMPRESSED_ASSETS def __init__(self, settings: dict[DetectorType, Any], event: dict[str, An...
UncompressedAssetSpanDetector
python
celery__celery
t/unit/app/test_beat.py
{ "start": 32959, "end": 33558 }
class ____: def test_maybe_make_aware(self): x = schedule(10, app=self.app) x.utc_enabled = True d = x.maybe_make_aware(datetime.now(timezone.utc)) assert d.tzinfo x.utc_enabled = False d2 = x.maybe_make_aware(datetime.now(timezone.utc)) assert d2.tzinfo ...
test_schedule
python
pandas-dev__pandas
pandas/tests/series/test_arithmetic.py
{ "start": 30347, "end": 33110 }
class ____: @pytest.mark.parametrize("box", [list, tuple, np.array, Index, Series, pd.array]) @pytest.mark.parametrize("flex", [True, False]) def test_series_ops_name_retention(self, flex, box, names, all_binary_operators): # GH#33930 consistent name-retention op = all_binary_operators ...
TestNamePreservation
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/__init__.py
{ "start": 2250, "end": 2382 }
class ____(dict): # NoQA: FURB189 """Docstring.""" def function(foo, *args, **kwds): """Return spam.""" pass
CustomDict
python
django__django
tests/pagination/custom.py
{ "start": 79, "end": 389 }
class ____(Page): def next_page_number(self): if not self.has_next(): return None return super().next_page_number() def previous_page_number(self): if not self.has_previous(): return None return super().previous_page_number()
ValidAdjacentNumsPage
python
huggingface__transformers
src/transformers/models/superglue/image_processing_superglue.py
{ "start": 4810, "end": 5122 }
class ____(ImagesKwargs, total=False): r""" do_grayscale (`bool`, *optional*, defaults to `True`): Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method. """ do_grayscale: bool @requires(backends=("torch",))
SuperGlueImageProcessorKwargs
python
explosion__spaCy
spacy/lang/yo/__init__.py
{ "start": 216, "end": 309 }
class ____(Language): lang = "yo" Defaults = YorubaDefaults __all__ = ["Yoruba"]
Yoruba
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 15103, "end": 15264 }
class ____(AOTInput): """A subclass that classifies AOTInput that can be wrapped by GradAOTOutput""" @dataclasses.dataclass(frozen=True)
DifferentiableAOTInput
python
pallets__itsdangerous
src/itsdangerous/exc.py
{ "start": 87, "end": 436 }
class ____(Exception): """Raised if bad data of any sort was encountered. This is the base for all exceptions that ItsDangerous defines. .. versionadded:: 0.15 """ def __init__(self, message: str): super().__init__(message) self.message = message def __str__(self) -> str: ...
BadData
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_with_skeleton.py
{ "start": 15625, "end": 15976 }
class ____ { exampleMethod() { console.log("line1"); } } """ text_node = TextNode( text=text, ) chunks: List[RelatedNodeInfo] = code_splitter.get_nodes_from_documents([text_node]) # Fstrings don't like forward slash double_forward_slash: str = "//" assert ( chun...
Example
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/response_builder/__init__.py
{ "start": 124, "end": 229 }
class ____: @abc.abstractmethod def build(self) -> HttpResponse: pass
AbstractResponseBuilder
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/broadcast_to_ops_test.py
{ "start": 1139, "end": 8114 }
class ____(test_util.TensorFlowTestCase): def testBroadcastToBasic(self): for dtype in [ np.uint8, np.uint16, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype, dtypes.f...
BroadcastToTest
python
PrefectHQ__prefect
tests/server/orchestration/api/test_workers.py
{ "start": 57284, "end": 60158 }
class ____: async def test_work_pool_status_with_online_worker(self, client, work_pool): """Work pools with an online work should have a status of READY.""" await client.post( f"/work_pools/{work_pool.name}/workers/heartbeat", json=dict(name="test-worker"), ) ...
TestWorkPoolStatus
python
getsentry__sentry-python
tests/integrations/beam/test_beam.py
{ "start": 1293, "end": 1399 }
class ____(DoFn): def process(self, x): if x: 1 / 0 return [True]
SimpleFunc
python
xlwings__xlwings
xlwings/constants.py
{ "start": 101783, "end": 102012 }
class ____: xlRangeValueDefault = 10 # from enum XlRangeValueDataType xlRangeValueMSPersistXML = 12 # from enum XlRangeValueDataType xlRangeValueXMLSpreadsheet = 11 # from enum XlRangeValueDataType
RangeValueDataType
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 3042, "end": 3512 }
class ____: totp_value = wtforms.StringField( validators=[ wtforms.validators.InputRequired(), PreventNullBytesValidator(), wtforms.validators.Regexp( rf"^ *([0-9] *){{{otp.TOTP_LENGTH}}}$", message=_( "TOTP code must be...
TOTPValueMixin
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 109348, "end": 111247 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, api_token: str, dimensions: list[str], ingest_start: str, metrics: list[str], additional_metrics: Optional[list[str]] = None, until_today: Optional[bool] = None, ): ...
AdjustSource
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 13684, "end": 53049 }
class ____(Node): # subexprs [string] Class var holding names of subexpr node attrs # type PyrexType Type of the result # result_code string Code fragment # result_ctype string C type of result_code if different from type # is_temp boolean Result is in ...
ExprNode
python
sympy__sympy
sympy/assumptions/predicates/order.py
{ "start": 8907, "end": 9511 }
class ____(Predicate): """ Nonnegative extended real number predicate. Explanation =========== ``ask(Q.extended_nonnegative(x))`` is true iff ``x`` is extended real and ``x`` is not negative. Examples ======== >>> from sympy import ask, I, oo, Q >>> ask(Q.extended_nonnegative...
ExtendedNonNegativePredicate
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 128709, "end": 128999 }
class ____(TestCase): # Tests crash reported in https://github.com/pytorch/pytorch/issues/53565 def test_conv_after_fork(self): loader = DataLoader(ConvDataset(), num_workers=1) for x in loader: self.assertEqual(x.shape, (1, 1, 1, 23999))
TestConvAfterFork
python
huggingface__transformers
tests/models/vilt/test_modeling_vilt.py
{ "start": 1626, "end": 7942 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, image_size=30, patch_size=2, num_channels=3, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hi...
ViltModelTester
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/welcome_widget.py
{ "start": 80, "end": 225 }
class ____(App[None]): def compose(self) -> ComposeResult: yield Welcome() if __name__ == "__main__": WelcomeApp().run()
WelcomeApp
python
RaRe-Technologies__gensim
gensim/scripts/segment_wiki.py
{ "start": 9363, "end": 15638 }
class ____(WikiCorpus): """Treat a wikipedia articles dump (<LANG>wiki-<YYYYMMDD>-pages-articles.xml.bz2 or <LANG>wiki-latest-pages-articles.xml.bz2) as a (read-only) corpus. The documents are extracted on-the-fly, so that the whole (massive) dump can stay compressed on disk. """ def __init__(sel...
_WikiSectionsCorpus
python
jmcnamara__XlsxWriter
xlsxwriter/rich_value_types.py
{ "start": 325, "end": 3356 }
class ____(xmlwriter.XMLwriter): """ A class for writing the Excel XLSX rdRichValueTypes.xml file. """ ########################################################################### # # Private API. # ########################################################################### def _a...
RichValueTypes
python
pytorch__pytorch
test/nn/test_load_state_dict.py
{ "start": 20321, "end": 20630 }
class ____(torch.Tensor): @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): return load_torch_function_handler(cls, func, types, args, kwargs) # We use MyLoadTensor2 to test tensor subclass, wrapper tensor subclass # where neither inherits from each other
MyLoadTensor
python
numba__numba
numba/core/ir.py
{ "start": 683, "end": 7314 }
class ____(object): """Source location """ _defmatcher = re.compile(r'def\s+(\w+)') def __init__(self, filename, line, col=None, maybe_decorator=False): """ Arguments: filename - name of the file line - line in file col - column maybe_decorator - Set to True if ...
Loc
python
streamlit__streamlit
lib/streamlit/runtime/memory_media_file_storage.py
{ "start": 2723, "end": 6253 }
class ____(MediaFileStorage, CacheStatsProvider): def __init__(self, media_endpoint: str) -> None: """Create a new MemoryMediaFileStorage instance. Parameters ---------- media_endpoint The name of the local endpoint that media is served from. This endpoint sh...
MemoryMediaFileStorage
python
streamlit__streamlit
lib/tests/streamlit/web/server/routes_test.py
{ "start": 10184, "end": 11709 }
class ____(tornado.testing.AsyncHTTPTestCase): def setUp(self): super().setUp() def get_app(self): return tornado.web.Application( [ ( rf"/{HOST_CONFIG_ENDPOINT}", HostConfigHandler, ) ] ) ...
HostConfigHandlerTest
python
PyCQA__pylint
tests/functional/e/enum_subclasses.py
{ "start": 95, "end": 258 }
class ____(IntEnum): """https://github.com/pylint-dev/pylint/issues/1932""" FOO = 1 def whats_my_name(self): return self.name.lower()
Issue1932
python
kamyu104__LeetCode-Solutions
Python/sum-of-number-and-its-reverse.py
{ "start": 1065, "end": 1496 }
class ____(object): def sumOfNumberAndReverse(self, num): """ :type num: int :rtype: bool """ def reverse(n): result = 0 while n: result = result*10 + n%10 n //= 10 return result return a...
Solution2
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 16545, "end": 16770 }
class ____(QuantoQuantizationSerializationTest): EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" weights = "int4" @require_torch_accelerator
QuantoQuantizationQBitsTensorSerializationTest
python
huggingface__transformers
src/transformers/models/idefics3/modeling_idefics3.py
{ "start": 14310, "end": 16055 }
class ____(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Idefics3EncoderLayer`]. Args: config: Idefics3Config """ def __init__(self, config: Idefics3Config): super().__init__() self.config = config ...
Idefics3Encoder