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
pytorch__pytorch
torch/ao/pruning/_experimental/data_sparsifier/lightning/tests/test_callbacks.py
{ "start": 5142, "end": 12022 }
class ____(TestCase): """Class to test in-training version of lightning callback Simulates model training and makes sure that each hook is doing what is expected """ def _check_on_train_start( self, pl_module, callback, sparsifier_args, scheduler_args ): """Makes sure that the data_...
TestTrainingAwareCallback
python
getsentry__sentry
src/social_auth/fields.py
{ "start": 323, "end": 2141 }
class ____(TextField): """Simple JSON field that stores python structures as JSON strings on database. """ def contribute_to_class(self, cls: type[Model], name: str, private_only: bool = False) -> None: """ Add a descriptor for backwards compatibility with previous Django behavi...
JSONField
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_compute.py
{ "start": 20348, "end": 25848 }
class ____: def setup_method(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_no_default_project_id, ): self.gce_hook_no_project_id = ComputeEngineHook(gcp_conn_id="test") @mock.patch(...
TestGcpComputeHookNoDefaultProjectId
python
openai__openai-python
tests/api_resources/test_models.py
{ "start": 4391, "end": 8753 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: model = await async_client.models.retri...
TestAsyncModels
python
pydata__xarray
asv_bench/benchmarks/groupby.py
{ "start": 2941, "end": 3488 }
class ____(GroupBy): """Run groupby tests using dask DataFrame.""" def setup(self, *args, **kwargs): # Skip testing in CI as it won't ever change in a commit: _skip_slow() requires_dask() super().setup(**kwargs) self.ds1d = self.ds1d.chunk({"dim_0": 50}).to_dask_datafra...
GroupByDaskDataFrame
python
pytorch__pytorch
benchmarks/serialization/simple_measurement.py
{ "start": 87, "end": 1062 }
class ____(Benchmark): def benchmark(self): x = [torch.ones(200, 200) for i in range(30)] with Timer() as big1: torch.save(x, "big_tensor.zip", _use_new_zipfile_serialization=use_new) with Timer() as big2: torch.load("big_tensor.zip") x = [torch.ones(10, 10)...
Basic
python
pytorch__pytorch
test/test_sparse_semi_structured.py
{ "start": 9985, "end": 23528 }
class ____(TestCase): def setUp(self): if len(SEMI_STRUCTURED_SUPPORTED_BACKENDS) == 0: self.skipTest('semi-structured sparsity has no available backend!') if IS_WINDOWS: self.skipTest("torch.compile not supported on windows") @inference_dtypes @parametrize_backends...
TestSparseSemiStructured
python
python-poetry__poetry
src/poetry/utils/env/python/manager.py
{ "start": 1341, "end": 11052 }
class ____: @overload def __init__(self, *, python: findpython.PythonVersion) -> None: ... @overload def __init__( self, executable: str | Path, version: Version | None = None ) -> None: ... # we overload __init__ to ensure we do not break any downstream plugins # that use the this...
Python
python
getsentry__sentry-python
sentry_sdk/scope.py
{ "start": 3183, "end": 3304 }
class ____(Enum): CURRENT = "current" ISOLATION = "isolation" GLOBAL = "global" MERGED = "merged"
ScopeType
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/cfg.py
{ "start": 5495, "end": 8445 }
class ____(object): """Base class for a CFG visitors. This implementation is not thread safe. The visitor has some facilities to simplify dataflow analyses. In particular, it allows revisiting the nodes at the decision of the subclass. This can be used to visit the graph until the state reaches a fixed poin...
GraphVisitor
python
plotly__plotly.py
plotly/graph_objs/scattergeo/_stream.py
{ "start": 233, "end": 3526 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergeo" _path_str = "scattergeo.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set...
Stream
python
walkccc__LeetCode
solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py
{ "start": 0, "end": 793 }
class ____: # Same as 2829. Determine the Minimum Sum of a k-avoiding Array def minimumPossibleSum(self, n: int, target: int) -> int: # These are the unique pairs that sum up to k (target): # (1, k - 1), (2, k - 2), ..., (ceil(k // 2), floor(k // 2)). # Our optimal strategy is to select 1, 2, ..., floor...
Solution
python
readthedocs__readthedocs.org
readthedocs/core/views/__init__.py
{ "start": 3070, "end": 4952 }
class ____(TemplateView): """ Render templated error pages. This can be used both for testing and as a generic error view. This supports multiple subpaths for errors, as we need to show application themed errors for dashboard users and minimal error pages for documentation readers. Template re...
ErrorView
python
kamyu104__LeetCode-Solutions
Python/minimum-right-shifts-to-sort-the-array.py
{ "start": 37, "end": 445 }
class ____(object): def minimumRightShifts(self, nums): """ :type nums: List[int] :rtype: int """ i = next((i for i in xrange(len(nums)) if not nums[i] < nums[(i+1)%len(nums)]), len(nums)) j = next((j for j in xrange(i+1, len(nums)) if not nums[j%len(nums)] < nums[(j+...
Solution
python
celery__celery
celery/worker/pidbox.py
{ "start": 2155, "end": 3630 }
class ____(Pidbox): """Worker pidbox (greenlet).""" _node_shutdown = None _node_stopped = None _resets = 0 def start(self, c): c.pool.spawn_n(self.loop, c) def on_stop(self): if self._node_stopped: self._node_shutdown.set() debug('Waiting for broadcast ...
gPidbox
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property1.py
{ "start": 1434, "end": 1626 }
class ____: @property def name(self) -> str: return "bar" p1: property = ClassA.read_only_prop p2: property = ClassA.read_write_prop p3: property = ClassA.deletable_prop
ClassB
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 9032, "end": 9294 }
class ____(PydanticValueError): code = 'frozenset.min_items' msg_template = 'ensure this value has at least {limit_value} items' def __init__(self, *, limit_value: int) -> None: super().__init__(limit_value=limit_value)
FrozenSetMinLengthError
python
scipy__scipy
benchmarks/benchmarks/cluster.py
{ "start": 250, "end": 1017 }
class ____(XPBenchmark): method = ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'] param_names = (*XPBenchmark.param_names, "size", "method") if is_xslow(): size = [100, 180, 325, 585, 1054, 1898, 3420, 6162, 11101, 20000] else: size = [2000] params = (*XPB...
Linkage
python
huggingface__transformers
src/transformers/models/vilt/modeling_vilt.py
{ "start": 12038, "end": 13361 }
class ____(nn.Module): """ Image to Patch Embedding. """ def __init__(self, config): super().__init__() image_size, patch_size = config.image_size, config.patch_size num_channels, hidden_size = config.num_channels, config.hidden_size image_size = image_size if isinstanc...
ViltPatchEmbeddings
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/firebase/firenotes/backend/main.py
{ "start": 1050, "end": 3860 }
class ____(ndb.Model): """NDB model class for a user's note. Key is user id from decrypted token. """ friendly_id = ndb.StringProperty() message = ndb.TextProperty() created = ndb.DateTimeProperty(auto_now_add=True) # [START gae_python_query_database] # This code is for illustration purposes...
Note
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/exceptions.py
{ "start": 1033, "end": 1146 }
class ____(AirflowException): """Raised when there is an error in sql execution."""
DatabricksSqlExecutionError
python
numpy__numpy
numpy/_core/tests/test_umath_complex.py
{ "start": 21059, "end": 21737 }
class ____: @pytest.mark.parametrize("arraysize", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 18, 19]) @pytest.mark.parametrize("stride", [-4, -3, -2, -1, 1, 2, 3, 4]) @pytest.mark.parametrize("astype", [np.complex64, np.complex128]) # test to ensure masking and strides ...
TestComplexAbsoluteAVX
python
fastapi__sqlmodel
docs_src/tutorial/where/tutorial001.py
{ "start": 100, "end": 1172 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): ...
Hero
python
matplotlib__matplotlib
lib/matplotlib/collections.py
{ "start": 71729, "end": 78683 }
class ____(LineCollection): """ A collection of locations along a single axis at which an "event" occurred. The events are given by a 1-dimensional array. They do not have an amplitude and are displayed as parallel lines. """ _edge_default = True def __init__(self, positi...
EventCollection
python
redis__redis-py
tests/test_pubsub.py
{ "start": 41808, "end": 43328 }
class ____: def test_base_exception(self, r: redis.Redis): """ Manually trigger a BaseException inside the parser's .read_response method and verify that it isn't caught """ pubsub = r.pubsub() pubsub.subscribe("foo") def is_connected(): return pu...
TestBaseException
python
sympy__sympy
sympy/matrices/expressions/factorizations.py
{ "start": 233, "end": 338 }
class ____(Factorization): @property def predicates(self): return (Q.lower_triangular,)
LofLU
python
spyder-ide__spyder
spyder/plugins/completion/tests/test_plugin.py
{ "start": 751, "end": 7931 }
class ____(SpyderCompletionProvider): COMPLETION_PROVIDER_NAME = 'fake' CONF_DEFAULTS = [ ('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 4) ] CONF_VERSION = "0.1.0" @pytest.fixture def completion_receiver(completion_plugin_all_started): complet...
FakeProvider
python
wandb__wandb
wandb/vendor/pygments/lexers/objective.py
{ "start": 8561, "end": 8900 }
class ____(objective(CppLexer)): """ For Objective-C++ source code with preprocessor directives. """ name = 'Objective-C++' aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++'] filenames = ['*.mm', '*.hh'] mimetypes = ['text/x-objective-c++'] priority = 0.05 # Lower than ...
ObjectiveCppLexer
python
scikit-learn__scikit-learn
sklearn/cluster/_dbscan.py
{ "start": 7927, "end": 20552 }
class ____(ClusterMixin, BaseEstimator): """Perform DBSCAN clustering from vector array or distance matrix. DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. This algorithm is particularly good for data which contain...
DBSCAN
python
PyCQA__pylint
tests/functional/n/non/non_iterator_returned.py
{ "start": 1253, "end": 1654 }
class ____: def __init__(self, path): self.path = path self.file = None def __iter__(self): if self.file is not None: self.file.close() self.file = open(self.path, encoding="utf-8") # self file has two inferred values: None and <instance of 'file'> # ...
FileBasedIterator
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 54952, "end": 55066 }
class ____(Structure): pass # opaque handle c_nvmlDevice_t = POINTER(struct_c_nvmlDevice_t)
struct_c_nvmlDevice_t
python
kamyu104__LeetCode-Solutions
Python/make-array-elements-equal-to-zero.py
{ "start": 129, "end": 621 }
class ____(object): def countValidSelections(self, nums): """ :type nums: List[int] :rtype: int """ total = sum(nums) result = curr = 0 for x in nums: if not x: result += max(2-abs(curr-(total-curr)), 0) else: ...
Solution
python
astropy__astropy
astropy/io/ascii/sextractor.py
{ "start": 4534, "end": 4634 }
class ____(core.BaseData): start_line = 0 delimiter = " " comment = r"\s*#"
SExtractorData
python
justquick__django-activity-stream
actstream/feeds.py
{ "start": 11572, "end": 11778 }
class ____(ObjectActivityMixin, JSONActivityFeed): """ JSON feed of Activity for a given object (where actions involve the given object as any of the entities). """ pass
ObjectJSONActivityFeed
python
spyder-ide__spyder
spyder/widgets/onecolumntree.py
{ "start": 514, "end": 781 }
class ____: CollapseAllAction = "collapse_all_action" ExpandAllAction = "expand_all_action" RestoreAction = "restore_action" CollapseSelectionAction = "collapse_selection_action" ExpandSelectionAction = "expand_selection_action"
OneColumnTreeActions
python
apache__airflow
providers/common/sql/src/airflow/providers/common/sql/operators/sql.py
{ "start": 50067, "end": 55745 }
class ____(BaseSQLOperator): """ Insert rows (e.g. a collection of tuples) into a database table directly from an XCom or Python data structure. :param table: the name of the table in which the rows will be inserted (templated). :param conn_id: the connection ID used to connect to the database :par...
SQLInsertRowsOperator
python
dagster-io__dagster
helm/dagster/schema/schema/charts/utils/kubernetes.py
{ "start": 1282, "end": 1325 }
class ____(Image): tag: str
ExternalImage
python
getsentry__sentry
tests/sentry/uptime/endpoints/__init__.py
{ "start": 49, "end": 188 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user)
UptimeAlertBaseEndpointTest
python
doocs__leetcode
solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py
{ "start": 0, "end": 397 }
class ____: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: @cache def dfs(i: int) -> int: if i >= len(rides): return 0 st, ed, tip = rides[i] j = bisect_left(rides, ed, lo=i + 1, key=lambda x: x[0]) return max(dfs(i +...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/source_google_ads/source.py
{ "start": 538, "end": 1425 }
class ____(YamlDeclarativeSource): def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: TState, **kwargs): super().__init__(catalog=catalog, config=config, state=state, **{"path_to_yaml": "manifest.yaml"}) # Raise exceptions on missing streams ...
SourceGoogleAds
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/GraphicsItem.py
{ "start": 509, "end": 1096 }
class ____(OrderedDict): 'Limit size, evicting the least recently looked-up key when full' def __init__(self, maxsize=128, *args, **kwds): self.maxsize = maxsize super().__init__(*args, **kwds) def __getitem__(self, key): value = super().__getitem__(key) self.move_to_end(ke...
LRU
python
has2k1__plotnine
plotnine/themes/theme_gray.py
{ "start": 224, "end": 5226 }
class ____(theme): """ A gray background with white gridlines. This is the default theme Parameters ---------- base_size : int Base font size. All text sizes are a scaled versions of the base font size. base_family : str Base font family. If `None`, use [](`plotnine...
theme_gray
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/param.py
{ "start": 1420, "end": 5370 }
class ____: """ Class to hold the default value of a Param and rule set to do the validations. Without the rule set it always validates and returns the default value. :param default: The value this Param object holds :param description: Optional help text for the Param :param schema: The valid...
Param
python
facebook__pyre-check
client/command_arguments.py
{ "start": 1636, "end": 1737 }
class ____(str, enum.Enum): _value_: str OBSCURE = "obscure" TYPE = "type"
MissingFlowsKind
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/components.py
{ "start": 204, "end": 1044 }
class ____(RecordExtractor): def extract_records(self, response: requests.Response) -> List[Mapping[str, Any]]: try: records = response.json().get("ticket_events") or [] except requests.exceptions.JSONDecodeError: records = [] events = [] for record in record...
ZendeskSupportExtractorEvents
python
nedbat__coveragepy
coverage/types.py
{ "start": 3615, "end": 4557 }
class ____(Protocol): """Something that can proxy to the coverage configuration settings.""" def get_option(self, option_name: str) -> TConfigValueOut | None: """Get an option from the configuration. `option_name` is a colon-separated string indicating the section and option name. For...
TConfigurable
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 6707, "end": 7144 }
class ____(_TestDCTBase): def test_definition_ortho(self): # Test orthornomal mode. dt = np.result_type(np.float32, self.rdt) for xr in X: x = np.array(xr, dtype=self.rdt) y = dct(x, norm='ortho', type=1) y2 = naive_dct1(x, norm='ortho') assert...
_TestDCTIBase
python
pennersr__django-allauth
allauth/mfa/models.py
{ "start": 550, "end": 2126 }
class ____(models.Model): class Type(models.TextChoices): RECOVERY_CODES = "recovery_codes", _("Recovery codes") TOTP = "totp", _("TOTP Authenticator") WEBAUTHN = "webauthn", _("WebAuthn") objects = AuthenticatorManager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete...
Authenticator
python
numpy__numpy
numpy/_core/tests/test_simd_module.py
{ "start": 892, "end": 3950 }
class ____: @pytest.mark.parametrize('sfx', all_sfx) def test_num_lanes(self, sfx): nlanes = getattr(npyv, "nlanes_" + sfx) vector = getattr(npyv, "setall_" + sfx)(1) assert len(vector) == nlanes @pytest.mark.parametrize('sfx', all_sfx) def test_type_name(self, sfx): ve...
Test_SIMD_MODULE
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 7588, "end": 8098 }
class ____(BaseModel, alias_generator=lambda x: x + '_'): # MYPY: error: Required dynamic aliases disallowed [pydantic-alias] x: int = Field(..., alias='y') # MYPY: error: Required dynamic aliases disallowed [pydantic-alias] KwargsAliasGeneratorModel2(x=1) # MYPY: error: Unexpected keyword argument "x" for "Kwa...
KwargsAliasGeneratorModel2
python
davidhalter__parso
parso/python/errors.py
{ "start": 45338, "end": 45516 }
class ____(_CheckAssignmentRule): def is_issue(self, with_item): self._check_assignment(with_item.children[2]) @ErrorFinder.register_rule(type='del_stmt')
_WithItemRule
python
pytorch__pytorch
torch/fx/experimental/symbolic_shapes.py
{ "start": 105122, "end": 105335 }
class ____(ShapeGuardPythonPrinter): def __init__(self, var_to_sources: Mapping[sympy.Symbol, list[Source]]): super().__init__(var_to_sources, lambda n: n.name(), var_to_sources)
LoggingShapeGuardPrinter
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 109755, "end": 109962 }
class ____(TestCase): def test_test_zero_rank(self): x = np.array([1, 2, 3]) assert_(isinstance(x[0], (np.int_, np.ndarray))) assert_(type(x[0, ...]) is np.ndarray)
TestSubscripting
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 19062, "end": 19585 }
class ____(NameWrapper): def __init__(self, instance, class_member_name): super().__init__(class_member_name) self._instance = instance @iterator_to_value_set def infer(self): for result_value in self._wrapped_name.infer(): yield from result_value.py__get__(self._instanc...
LazyInstanceClassName
python
charliermarsh__ruff
crates/ruff_python_parser/resources/valid/statement/class.py
{ "start": 83, "end": 119 }
class ____(a=1, *A, **k): ...
Test
python
readthedocs__readthedocs.org
readthedocs/storage/s3_storage.py
{ "start": 3685, "end": 4098 }
class ____(S3PrivateBucketMixin, S3Boto3Storage): bucket_name = getattr(settings, "S3_BUILD_TOOLS_STORAGE_BUCKET", None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.bucket_name: raise ImproperlyConfigured( "AWS S3 not configure...
S3BuildToolsStorage
python
ansible__ansible
lib/ansible/utils/collection_loader/_collection_finder.py
{ "start": 38057, "end": 55019 }
class ____: # FUTURE: introspect plugin loaders to get these dynamically? VALID_REF_TYPES = frozenset(_to_text(r) for r in ['action', 'become', 'cache', 'callback', 'cliconf', 'connection', 'doc_fragments', 'filter', 'httpapi', 'inventory', 'lookup', ...
AnsibleCollectionRef
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/datetime.py
{ "start": 11650, "end": 14079 }
class ____(SearchStrategy): def __init__(self, min_value, max_value): super().__init__() assert isinstance(min_value, dt.date) assert isinstance(max_value, dt.date) assert min_value < max_value self.min_value = min_value self.max_value = max_value def do_draw(sel...
DateStrategy
python
airbytehq__airbyte
airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/stream_reader.py
{ "start": 3575, "end": 7978 }
class ____(AbstractFileBasedStreamReader): _credentials = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._config = None @property def config(self) -> SourceAzureBlobStorageSpec: return self._config @config.setter def config(self, value...
SourceAzureBlobStorageStreamReader
python
django__django
tests/admin_ordering/tests.py
{ "start": 4217, "end": 7244 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.b1 = Band.objects.create(name="Pink Floyd", bio="", rank=1) cls.b2 = Band.objects.create(name="Foo Fighters", bio="", rank=5) def setUp(self): # we need to register a custom ModelAdmin (instead of just using # Mo...
TestRelatedFieldsAdminOrdering
python
openai__openai-python
src/openai/types/beta/threads/runs/run_step_delta_event.py
{ "start": 237, "end": 585 }
class ____(BaseModel): id: str """The identifier of the run step, which can be referenced in API endpoints.""" delta: RunStepDelta """The delta containing the fields that have changed on the run step.""" object: Literal["thread.run.step.delta"] """The object type, which is always `thread.run.s...
RunStepDeltaEvent
python
walkccc__LeetCode
solutions/299. Bulls and Cows/299.py
{ "start": 0, "end": 239 }
class ____: def getHint(self, secret: str, guess: str) -> str: bulls = sum(map(operator.eq, secret, guess)) bovine = sum(min(secret.count(x), guess.count(x)) for x in set(guess)) return '%dA%dB' % (bulls, bovine - bulls)
Solution
python
huggingface__transformers
src/transformers/models/clip/modeling_clip.py
{ "start": 37207, "end": 39389 }
class ____(CLIPPreTrainedModel): config: CLIPTextConfig input_modalities = ("text",) _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"] def __init__(self, config: CLIPTextConfig): super().__init__(config) text_model = CLIPTextModel._from_config(config) self.text_mo...
CLIPTextModelWithProjection
python
sympy__sympy
sympy/core/coreerrors.py
{ "start": 303, "end": 642 }
class ____: """Wrapper class that lets you specify an expensive to compute error message that is only evaluated if the error is rendered.""" callback: Callable[[], str] def __init__(self, callback: Callable[[], str]): self.callback = callback def __str__(self): return self.callback...
LazyExceptionMessage
python
pytorch__pytorch
torch/ao/quantization/quantizer/xpu_inductor_quantizer.py
{ "start": 2029, "end": 3797 }
class ____(X86InductorQuantizer): """ XPUInductorQuantizer is a class designed to facilitate quantization capability at Intel GPU backend. The class highly reuses the existing implementation of X86InductorQuantizer as both are intended to take advantage of the optimized kernels in oneDNN library...
XPUInductorQuantizer
python
huggingface__transformers
src/transformers/models/mbart/modeling_mbart.py
{ "start": 4064, "end": 5676 }
class ____(nn.Embedding): """ This module overrides nn.Embeddings' forward by multiplying with embeddings scale. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0): super().__init__(num_embeddings, embedding_dim, padding_idx) ...
MBartScaledWordEmbedding
python
doocs__leetcode
solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py
{ "start": 0, "end": 377 }
class ____: def shareCandies(self, candies: List[int], k: int) -> int: cnt = Counter(candies[k:]) ans = len(cnt) for i in range(k, len(candies)): cnt[candies[i - k]] += 1 cnt[candies[i]] -= 1 if cnt[candies[i]] == 0: cnt.pop(candies[i]) ...
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_mlengine.py
{ "start": 29456, "end": 47038 }
class ____: def setup_method(self): with mock.patch( "airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = hook.MLEngineHook() @mock.patch( "airflow.providers.google.common.hoo...
TestMLEngineHookWithDefaultProjectId
python
mlflow__mlflow
tests/utils/test_annotations.py
{ "start": 1273, "end": 8250 }
class ____: """ A deprecated dataclass with decorators in different order. """ m: int n: int def test_deprecated_method(): msg = "``tests.utils.test_annotations.MyClass.method`` is deprecated" with pytest.warns(FutureWarning, match=re.escape(msg)): assert MyClass().method() == 0 ...
AnotherDeprecatedDataClassOrder
python
langchain-ai__langchain
libs/partners/deepseek/tests/unit_tests/test_chat_models.py
{ "start": 3527, "end": 9436 }
class ____: """Custom tests specific to DeepSeek chat model.""" def test_create_chat_result_with_reasoning_content(self) -> None: """Test that reasoning_content is properly extracted from response.""" chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key")) mock_message...
TestChatDeepSeekCustomUnit
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-seller-partner/components.py
{ "start": 1046, "end": 1969 }
class ____(DeclarativeOauth2Authenticator): """ This class extends the DeclarativeOauth2Authenticator functionality and allows to pass custom headers to the refresh access token requests """ host: Union[InterpolatedString, str] = None def __post_init__(self, parameters: Mapping[str, Any]) -> N...
AmazonSPOauthAuthenticator
python
doocs__leetcode
solution/2700-2799/2746.Decremental String Concatenation/Solution.py
{ "start": 0, "end": 440 }
class ____: def minimizeConcatenatedLength(self, words: List[str]) -> int: @cache def dfs(i: int, a: str, b: str) -> int: if i >= len(words): return 0 s = words[i] x = dfs(i + 1, a, s[-1]) - int(s[0] == b) y = dfs(i + 1, s[0], b) - int(...
Solution
python
google__jax
tests/shard_map_test.py
{ "start": 177299, "end": 178134 }
class ____(jtu.JaxTestCase): @staticmethod def make_mesh(mesh_shape): return jtu.create_mesh(tuple(mesh_shape.values()), tuple(mesh_shape)) @parameterized.parameters( sample(jtu.NUM_GENERATED_CASES.value, sample_smap)) def test_against_ref(self, fun_spec, mesh_shape, in_axes, out_axes, axis_name, ar...
SmapSystematicTest
python
getsentry__sentry
src/sentry/integrations/jira/actions/create_ticket.py
{ "start": 358, "end": 1544 }
class ____(TicketEventAction): id = "sentry.integrations.jira.notify_action.JiraCreateTicketAction" label = "Create a Jira issue in {integration} with these " ticket_type = "a Jira issue" link = "https://docs.sentry.io/product/integrations/issue-tracking/jira/#issue-sync" provider = IntegrationProvi...
JiraCreateTicketAction
python
huggingface__transformers
src/transformers/models/longt5/modeling_longt5.py
{ "start": 12560, "end": 13391 }
class ____(nn.Module): def __init__(self, config: LongT5Config): super().__init__() self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) self....
LongT5DenseGatedActDense
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 1030, "end": 1545 }
class ____(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.reset() logging.Handler.__init__(self, *args, **kwargs) def emit(self, record): self.messages[record.levelname.lower()].append(record.getMessage()) def...
MockLoggingHandler
python
python-attrs__attrs
typing-examples/mypy.py
{ "start": 7599, "end": 8131 }
class ____: a: int = attr.ib() b: int = attr.ib() attr.asdict(FactoryTest()) attr.asdict(FactoryTest(), retain_collection_types=False) def accessing_from_attr() -> None: """ Use a function to keep the ns clean. """ attr.converters.optional attr.exceptions.FrozenError attr.filters.inc...
MatchArgs
python
pytest-dev__pytest
src/_pytest/logging.py
{ "start": 5111, "end": 11898 }
class ____(logging.PercentStyle): """A logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. """ def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> ...
PercentStyleMultiline
python
getlogbook__logbook
src/logbook/handlers.py
{ "start": 25688, "end": 27472 }
class ____(FileHandler): """A file handler that will check if the file was moved while it was open. This might happen on POSIX systems if an application like logrotate moves the logfile over. Because of different IO concepts on Windows, this handler will not work on a windows system. """ ...
MonitoringFileHandler
python
xlwings__xlwings
xlwings/constants.py
{ "start": 90111, "end": 90270 }
class ____: xlDoNotRepeatLabels = 1 # from enum XlPivotFieldRepeatLabels xlRepeatLabels = 2 # from enum XlPivotFieldRepeatLabels
PivotFieldRepeatLabels
python
huggingface__transformers
src/transformers/models/swiftformer/modeling_swiftformer.py
{ "start": 10847, "end": 11951 }
class ____(GradientCheckpointingLayer): """ A Swiftformer stage consisting of a series of `SwiftFormerConvEncoder` blocks and a final `SwiftFormerEncoderBlock`. Input: tensor in shape `[batch_size, channels, height, width]` Output: tensor in shape `[batch_size, channels, height, width]` """ ...
SwiftFormerStage
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 117694, "end": 117931 }
class ____(Response): """ Response of models.move endpoint. """ _service = "models" _action = "move" _version = "2.23" _schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
MoveResponse
python
graphql-python__graphene
graphene/types/tests/test_definition.py
{ "start": 1106, "end": 1147 }
class ____(Interface): pass
MyInterface
python
tensorflow__tensorflow
tensorflow/compiler/tests/slice_ops_test.py
{ "start": 4579, "end": 10403 }
class ____(xla_test.XLATestCase): def test1D(self): for dtype in self.numeric_types: with self.session(): i = array_ops.placeholder(dtype, shape=[10]) with self.test_scope(): o = array_ops.strided_slice(i, [2], [6], [2]) params = { i: [0, 1, 2, 3, 4, 5, 6, 7, 8...
StridedSliceTest
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 38644, "end": 38854 }
class ____(Pix2SkyProjection, QuadCube): r""" COBE quadrilateralized spherical cube projection - pixel to sky. Corresponds to the ``CSC`` projection in FITS WCS. """
Pix2Sky_COBEQuadSphericalCube
python
huggingface__transformers
src/transformers/models/colqwen2/modeling_colqwen2.py
{ "start": 2812, "end": 4739 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): The embeddings of the model. ...
ColQwen2ForRetrievalOutput
python
doocs__leetcode
solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py
{ "start": 0, "end": 677 }
class ____: __slots__ = ["n", "c", "d"] def __init__(self, n): self.n = n self.c = [0] * (n + 1) self.d = [0] * (n + 1) def update(self, x, v, cnt): while x <= self.n: if self.c[x] < v: self.c[x] = v self.d[x] = cnt el...
BinaryIndexedTree
python
bokeh__bokeh
src/bokeh/colors/groups.py
{ "start": 7246, "end": 7767 }
class ____(ColorGroup): ''' CSS "Red" Color Group as defined by https://www.w3schools.com/colors/colors_groups.asp .. bokeh-color:: lightsalmon .. bokeh-color:: salmon .. bokeh-color:: darksalmon .. bokeh-color:: lightcoral .. bokeh-color:: indianred .. bokeh-color:: crimson .. bokeh-co...
red
python
getsentry__sentry
src/sentry/workflow_engine/buffer/batch_client.py
{ "start": 1761, "end": 4508 }
class ____: """ Client for interacting with batch processing of delayed workflows. This is used for managing the listing of projects that need to be processed """ _BUFFER_KEY = "workflow_engine_delayed_processing_buffer" _BUFFER_SHARDS = 8 option = "delayed_workflow.rollout" def __init...
DelayedWorkflowClient
python
davidhalter__parso
parso/python/errors.py
{ "start": 23839, "end": 24520 }
class ____(SyntaxRule): message = "'return' with value in async generator" message_async_yield = "'yield' inside async function" def get_node(self, leaf): return leaf.parent def is_issue(self, leaf): if self._normalizer.context.node.type != 'funcdef': self.add_issue(self.ge...
_ReturnAndYieldChecks
python
huggingface__transformers
src/transformers/models/paligemma/modeling_paligemma.py
{ "start": 1566, "end": 2117 }
class ____(BaseModelOutputWithPast): r""" image_hidden_states (`torch.FloatTensor`, *optional*): A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. ...
PaligemmaModelOutputWithPast
python
numba__numba
numba/tests/test_heapq.py
{ "start": 571, "end": 14226 }
class ____(MemoryLeakMixin): def setUp(self): super(_TestHeapq, self).setUp() self.rnd = np.random.RandomState(42) def test_heapify_basic_sanity(self): pyfunc = heapify cfunc = jit(nopython=True)(pyfunc) a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] b = self.listimpl(a) ...
_TestHeapq
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 47198, "end": 49825 }
class ____(List): """A vertical list of boxes.""" def __init__(self, elements: T.Sequence[Node], h: float = 0.0, m: T.Literal['additional', 'exactly'] = 'additional'): super().__init__(elements) self.vpack(h=h, m=m) def vpack(self, h: float = 0.0, m: T.Litera...
Vlist
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar10.py
{ "start": 315, "end": 1371 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar10.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_f...
TestCompareXLSXFiles
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 21085, "end": 22396 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook") def test_assert_valid_hook_call(self, mock_hook) -> None: with pytest.warns(AirflowProviderDeprecationWarning): task = CloudDataCatalogDeleteTagTemplateOperator( task_id="task...
TestCloudDataCatalogDeleteTagTemplateOperator
python
ray-project__ray
python/ray/_private/telemetry/open_telemetry_metric_recorder.py
{ "start": 472, "end": 10305 }
class ____: """ A class to record OpenTelemetry metrics. This is the main entry point for exporting all ray telemetries to Prometheus server. It uses OpenTelemetry's Prometheus exporter to export metrics. """ _metrics_initialized = False _metrics_initialized_lock = threading.Lock() def...
OpenTelemetryMetricRecorder
python
tensorflow__tensorflow
tensorflow/python/distribute/strategy_common_test.py
{ "start": 11237, "end": 17105 }
class ____(test.TestCase, parameterized.TestCase): def testDense(self, strategy, tf_function): if (strategy_test_lib.is_tpu_strategy(strategy) and tf_function is combinations.no_tf_function): self.skipTest('Skip TPUStrategy + eager combination.') @tf_function def fn(): def replica_f...
ReplicaCtxAllReduceTest
python
joke2k__faker
faker/providers/currency/de/__init__.py
{ "start": 100, "end": 6465 }
class ____(CurrencyProvider): # source: https://www.laenderdaten.info/waehrungen/ currencies: ElementsType[Tuple[str, str]] = ( ("AED", "Arabische Dirham"), ("AFN", "Afghani"), ("ALL", "Albanische Lek"), ("AMD", "Armenische Dram"), ("ANG", "Antillen Gulden"), ("A...
Provider
python
getsentry__sentry
src/sentry/tasks/assemble.py
{ "start": 2356, "end": 10550 }
class ____(NamedTuple): # File object stored in the database. bundle: File # Temporary in-memory object representing the file used for efficiency. bundle_temp_file: IO def delete_bundle(self): self.bundle.delete() self.bundle_temp_file.close() @sentry_sdk.tracing.trace def assembl...
AssembleResult
python
aio-libs__aiohttp
aiohttp/http_writer.py
{ "start": 982, "end": 1343 }
class ____(NamedTuple): major: int minor: int HttpVersion10 = HttpVersion(1, 0) HttpVersion11 = HttpVersion(1, 1) _T_OnChunkSent = Optional[ Callable[ [Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]], Awaitable[None], ] ] _T_OnHeadersSent = Optional[Callable[["CIMult...
HttpVersion