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 | google__pytype | pytype/rewrite/convert.py | {
"start": 196,
"end": 297
} | class ____:
def __init__(self):
self.classes = {}
self.funcs = {}
self.types = {}
| _Cache |
python | falconry__falcon | tests/test_uri_templates.py | {
"start": 1849,
"end": 2111
} | class ____:
def __init__(self):
self.file_id = None
self.ext = None
self.called = False
def on_get(self, req, resp, file_id, ext):
self.file_id = file_id
self.ext = ext
self.called = True
| FileDetailsResource |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/pooling.py | {
"start": 6327,
"end": 9428
} | class ____(keras_layers.AveragePooling2D, base.Layer):
"""Average pooling layer for 2D inputs (e.g. images).
Args:
pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width)
specifying the size of the pooling window.
Can be a single integer to specify the same value for
all ... | AveragePooling2D |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/stream_reader.py | {
"start": 798,
"end": 2352
} | class ____(Oauth2Authenticator, TokenCredential):
def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs):
super().__init__(
token_refresh_endpoint=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token",
client_id=client_id,
client_sec... | AzureClientCredentialsAuthenticator |
python | gawel__pyquery | tests/test_pyquery.py | {
"start": 26689,
"end": 27977
} | class ____(TestCase):
xml = "<div>I'm valid XML</div>"
html = '''<div class="portlet">
<a href="/toto">TestimageMy link text</a>
<a href="/toto2">imageMy link text 2</a>
Behind you, a three-headed HTML‐Entity!
</div>'''
def test_parser_persistance(self):
d = pq(self.xml, ... | TestHTMLParser |
python | realpython__materials | python-protocol/birds_v2.py | {
"start": 0,
"end": 119
} | class ____:
def quack(self):
raise NotImplementedError("Subclasses must implement this method")
| QuackingThing |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 55545,
"end": 55635
} | class ____(lock_tests.RLockTests):
locktype = staticmethod(threading._CRLock)
| CRLockTests |
python | kamyu104__LeetCode-Solutions | Python/implement-strstr.py | {
"start": 1013,
"end": 1335
} | class ____(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in xrange(len(haystack) - len(needle) + 1):
if haystack[i : i + len(needle)] == needle:
return i
return -1
| Solution2 |
python | sympy__sympy | sympy/functions/special/polynomials.py | {
"start": 1063,
"end": 1511
} | class ____(DefinedFunction):
"""Base class for orthogonal polynomials.
"""
@classmethod
def _eval_at_order(cls, n, x):
if n.is_integer and n >= 0:
return cls._ortho_poly(int(n), _x).subs(_x, x)
def _eval_conjugate(self):
return self.func(self.args[0], self.args[1].conju... | OrthogonalPolynomial |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 603567,
"end": 604174
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"actor",
"client_mutation_id",
"pull_request",
"requested_reviewers_edge",
)
actor = sgqlc.types.Field(Actor, graphql_name="actor")
client... | RequestReviewsPayload |
python | pypa__warehouse | warehouse/observations/models.py | {
"start": 737,
"end": 1118
} | class ____(db.Model):
"""Associate an Observer with a given parent."""
__tablename__ = "observer_association"
discriminator: Mapped[str] = mapped_column(comment="The type of the parent")
observer: Mapped[Observer] = relationship(
back_populates="_association", uselist=False
)
__mapper... | ObserverAssociation |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/parallel.py | {
"start": 1186,
"end": 4515
} | class ____(Strategy, ABC):
"""Strategy for training with multiple processes in parallel."""
def __init__(
self,
accelerator: Optional[Accelerator] = None,
parallel_devices: Optional[list[torch.device]] = None,
cluster_environment: Optional[ClusterEnvironment] = None,
che... | ParallelStrategy |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 47584,
"end": 53105
} | class ____(fixtures.MappedTest):
"""test that lots of post update cols batch together into a single
UPDATE."""
@classmethod
def define_tables(cls, metadata):
Table(
"parent",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoin... | PostUpdateBatchingTest |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/variables.py | {
"start": 911,
"end": 2806
} | class ____(converter.Base):
"""Rewrites basic symbol reads.
This transformer rewrites variable reads with a "read" operator which allows
tracking activity.
Example:
For a basic statement:
a = b + c
This is translated to:
a = ld(b) + ld(c)
Augmented assignment operations also introduce a... | VariableAccessTransformer |
python | imageio__imageio | imageio/plugins/opencv.py | {
"start": 1189,
"end": 11629
} | class ____(PluginV3):
def __init__(self, request: Request) -> None:
super().__init__(request)
self.file_handle = request.get_local_filename()
if request._uri_type is URI_BYTES:
self.filename = "<bytes>"
else:
self.filename = request.raw_uri
mode = re... | OpenCVPlugin |
python | catalyst-team__catalyst | catalyst/metrics/_classification.py | {
"start": 16879,
"end": 21222
} | class ____(BinaryStatisticsMetric):
"""Precision, recall, f1_score and support metrics for binary classification.
Args:
zero_division: value to set in case of zero division during metrics
(precision, recall) computation; should be one of 0 or 1
compute_on_call: if True, allows compu... | BinaryPrecisionRecallF1Metric |
python | getsentry__sentry | src/sentry/models/groupinbox.py | {
"start": 917,
"end": 1107
} | class ____(Enum):
NEW = 0
REGRESSION = 2
MANUAL = 3
REPROCESSED = 4
ESCALATING = 5
ONGOING = 6
# DEPRECATED: Use ONGOING instead
UNIGNORED = 1
| GroupInboxReason |
python | matplotlib__matplotlib | lib/matplotlib/widgets.py | {
"start": 71066,
"end": 75749
} | class ____(Widget):
"""
Provide a vertical (default) and/or horizontal line cursor shared between
multiple Axes.
For the cursor to remain responsive you must keep a reference to it.
Parameters
----------
canvas : object
This parameter is entirely unused and only kept for back-compa... | MultiCursor |
python | huggingface__transformers | tests/models/longt5/test_modeling_longt5.py | {
"start": 41790,
"end": 45735
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (LongT5EncoderModel,) if is_torch_available() else ()
test_resize_embeddings = False
def setUp(self):
self.model_tester = LongT5EncoderOnlyModelTester(self)
self.config_tester = ConfigTester(self, config_class=LongT5Confi... | LongT5EncoderOnlyModelTest |
python | kamyu104__LeetCode-Solutions | Python/make-array-empty.py | {
"start": 40,
"end": 418
} | class ____(object):
def countOperationsToEmptyArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
idxs = range(len(nums))
idxs.sort(key=lambda x: nums[x])
return len(idxs)+sum(len(idxs)-(i+1) for i in xrange(len(idxs)-1) if idxs[i] > idxs[i+1])
# Ti... | Solution |
python | ray-project__ray | python/ray/data/tests/unit/test_arrow_type_conversion.py | {
"start": 684,
"end": 6106
} | class ____:
i: int = field()
@pytest.mark.parametrize(
"input",
[
# Python native lists
[
[1, 2],
[3, 4],
],
# Python native tuples
[
(1, 2),
(3, 4),
],
# Lists as PA scalars
[
pa.sc... | UserObj |
python | readthedocs__readthedocs.org | readthedocs/oauth/migrations/0002_combine_services.py | {
"start": 163,
"end": 7337
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("oauth", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="RemoteOrganization",
fields=[
... | Migration |
python | celery__celery | celery/contrib/abortable.py | {
"start": 2704,
"end": 3682
} | class ____(AsyncResult):
"""Represents an abortable result.
Specifically, this gives the `AsyncResult` a :meth:`abort()` method,
that sets the state of the underlying Task to `'ABORTED'`.
"""
def is_aborted(self):
"""Return :const:`True` if the task is (being) aborted."""
return se... | AbortableAsyncResult |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/cache.py | {
"start": 1592,
"end": 8651
} | class ____:
def __init__(self, cache_name: str, partition_key: str):
self.version = 1
self.cache = caches[cache_name]
self.partition_key = partition_key
@property
def randomized_ttl(self) -> int:
# introduce jitter in the cache_ttl so that when we have large
# amount... | StringIndexerCache |
python | google__pytype | pytype/tests/test_reingest2.py | {
"start": 79,
"end": 1274
} | class ____(test_base.BaseTest):
"""Tests for reloading the pyi we generate."""
def test_type_parameter_bound(self):
foo = """
from typing import TypeVar
T = TypeVar("T", bound=float)
def f(x: T) -> T: return x
"""
with self.DepTree([("foo.py", foo)]):
errors = self.CheckWithErro... | ReingestTest |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 6679,
"end": 6861
} | class ____(HypothesisWarning):
"""SearchStrategy.example() is designed for interactive use,
but should never be used in the body of a test.
"""
| NonInteractiveExampleWarning |
python | streamlit__streamlit | lib/streamlit/runtime/metrics_util.py | {
"start": 7146,
"end": 17844
} | class ____:
_instance_lock = threading.Lock()
_instance: Installation | None = None
@classmethod
def instance(cls) -> Installation:
"""Returns the singleton Installation."""
# We use a double-checked locking optimization to avoid the overhead
# of acquiring the lock in the commo... | Installation |
python | Textualize__textual | src/textual/_log.py | {
"start": 298,
"end": 436
} | class ____(Enum):
"""Tags log messages as being verbose and potentially excluded from output."""
NORMAL = 0
HIGH = 1
| LogVerbosity |
python | django__django | tests/select_related_regress/models.py | {
"start": 2813,
"end": 2876
} | class ____(Base):
b_field = models.CharField(max_length=10)
| B |
python | kamyu104__LeetCode-Solutions | Python/sort-integers-by-the-power-value.py | {
"start": 1823,
"end": 2426
} | class ____(object):
dp = {}
def getKth(self, lo, hi, k):
"""
:type lo: int
:type hi: int
:type k: int
:rtype: int
"""
def power_value(x):
y, result = x, 0
while x > 1 and x not in Solution2.dp:
result += 1
... | Solution2 |
python | docker__docker-py | docker/types/services.py | {
"start": 21230,
"end": 23000
} | class ____(dict):
"""
Describes properties to access and load-balance a service.
Args:
mode (string): The mode of resolution to use for internal load
balancing between tasks (``'vip'`` or ``'dnsrr'``). Defaults to
``'vip'`` if not provided.
ports (dict): Exposed ports t... | EndpointSpec |
python | pandas-dev__pandas | pandas/tests/indexing/test_categorical.py | {
"start": 807,
"end": 20439
} | class ____:
def test_loc_scalar(self, df):
dtype = CategoricalDtype(list("cab"))
result = df.loc["a"]
bidx = Series(list("aaa"), name="B").astype(dtype)
assert bidx.dtype == dtype
expected = DataFrame({"A": [0, 1, 5]}, index=Index(bidx))
tm.assert_frame_equal(result,... | TestCategoricalIndex |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/test_basic_configuration.py | {
"start": 2763,
"end": 2965
} | class ____(SimpleTestCase):
@given(integers())
def test_that_doesnt_need_db(self, z: int):
company = Company(name="Company-" + str(z))
assert company.name.endswith(str(z))
| TestSimple |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 41924,
"end": 44466
} | class ____(ToolContainerBase, QtWidgets.QToolBar):
def __init__(self, toolmanager, parent=None):
ToolContainerBase.__init__(self, toolmanager)
QtWidgets.QToolBar.__init__(self, parent)
self.setAllowedAreas(QtCore.Qt.ToolBarArea(
_to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
... | ToolbarQt |
python | django__django | tests/user_commands/management/commands/no_system_checks.py | {
"start": 54,
"end": 168
} | class ____(BaseCommand):
requires_system_checks = []
def handle(self, *args, **options):
pass
| Command |
python | streamlit__streamlit | lib/streamlit/git_util.py | {
"start": 2102,
"end": 6516
} | class ____:
repo: Repo | None
def __init__(self, path: str) -> None:
# If we have a valid repo, git_version will be a tuple
# of 3+ ints: (major, minor, patch, possible_additional_patch_number)
self.git_version: tuple[int, ...] | None = None
self.module: str = ""
try:
... | GitRepo |
python | cython__cython | Cython/Compiler/Tests/TestParseTreeTransforms.py | {
"start": 289,
"end": 2282
} | class ____(TransformTest):
def test_parserbehaviour_is_what_we_coded_for(self):
t = self.fragment("if x: y").root
self.assertLines("""
(root): StatListNode
stats[0]: IfStatNode
if_clauses[0]: IfClauseNode
condition: NameNode
body: ExprStatNode
expr: NameNode
""", self.treet... | TestNormalizeTree |
python | pypa__hatch | tests/backend/metadata/test_build.py | {
"start": 1523,
"end": 2156
} | class ____:
def test_default(self, isolation):
metadata = BuildMetadata(str(isolation), {})
assert metadata.build_backend == metadata.build_backend == ""
def test_not_string(self, isolation):
metadata = BuildMetadata(str(isolation), {"build-backend": 10})
with pytest.raises(Ty... | TestBuildBackend |
python | Lightning-AI__lightning | tests/tests_pytorch/utilities/test_model_summary.py | {
"start": 2062,
"end": 2817
} | class ____(LightningModule):
"""A model in which the layers not defined in order of execution."""
def __init__(self):
super().__init__()
# note: the definition order is intentionally scrambled for this test
self.layer2 = nn.Linear(10, 2)
self.combine = nn.Linear(7, 9)
se... | UnorderedModel |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py | {
"start": 45598,
"end": 48397
} | class ____(nn.Module):
def __init__(self, config: Phi4MultimodalConfig):
super().__init__()
self.config = config
self.layer_idx = config.audio_config.feature_layer
self.drop = nn.Dropout(config.embd_pdrop)
self.encoder = Phi4MultimodalAudioModel._from_config(config.audio_con... | Phi4MultimodalAudioEmbedding |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/TC005.py | {
"start": 150,
"end": 513
} | class ____:
if TYPE_CHECKING:
pass # TC005
x = 2
if TYPE_CHECKING:
if 2:
pass
if TYPE_CHECKING:
x: List
from typing_extensions import TYPE_CHECKING
if TYPE_CHECKING:
pass # TC005
# https://github.com/astral-sh/ruff/issues/11368
if TYPE_CHECKING:
pass
else:
pass
if T... | Test |
python | spack__spack | lib/spack/spack/compilers/libraries.py | {
"start": 9218,
"end": 12121
} | class ____:
"""Remove rpaths to directories that are default search paths of the dynamic linker."""
_CACHE: Dict[Optional[str], Set[Tuple[int, int]]] = {}
def __init__(self, dynamic_linker: Optional[str]) -> None:
if dynamic_linker not in DefaultDynamicLinkerFilter._CACHE:
# Identify d... | DefaultDynamicLinkerFilter |
python | huggingface__transformers | tests/models/qwen3_next/test_modeling_qwen3_next.py | {
"start": 1296,
"end": 1768
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = Qwen3NextModel
def __init__(self, parent):
super().__init__(parent=parent)
self.layer_types = ["linear_attention", "full_attention"]
self.linear_conv_kernel_dim = 2
self.linear_key_head_dim = 16... | Qwen3NextModelTester |
python | ray-project__ray | python/ray/dashboard/modules/metrics/dashboards/common.py | {
"start": 999,
"end": 11708
} | class ____:
"""Defines a Grafana target (time-series query) within a panel.
A panel will have one or more targets. By default, all targets are rendered as
stacked area charts, with the exception of legend="MAX", which is rendered as
a blue dotted line. Any legend="FINISHED|FAILED|DEAD|REMOVED" series w... | Target |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-chroma/llama_index/vector_stores/chroma/base.py | {
"start": 3460,
"end": 24430
} | class ____(BasePydanticVectorStore):
"""
Chroma vector store.
In this vector store, embeddings are stored within a ChromaDB collection.
During query time, the index uses ChromaDB to query for the top
k most similar nodes.
Supports MMR (Maximum Marginal Relevance) search mode for improved dive... | ChromaVectorStore |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 4315,
"end": 36880
} | class ____(UserDefinedVariable):
value: type[object]
def __init__(self, value, **kwargs) -> None:
super().__init__(**kwargs)
self.value = value
# Used when we materialize class.__dict__ to a MappingProxyObject. In
# this case, we don't want to allow mutation in the class because... | UserDefinedClassVariable |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 15892,
"end": 16422
} | class ____(LocalizableStreamlitException):
"""Exception raised when a component is missing required content."""
def __init__(self, component_name: str) -> None:
super().__init__(
"Component `{component_name}` must have either JavaScript content "
"(`js_content` or `js_url`) or H... | BidiComponentMissingContentError |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 4453,
"end": 4750
} | class ____(RequestHandler):
def get(self):
self.finish(self.request.headers["Foo"].encode("ISO8859-1"))
# These tests end up getting run redundantly: once here with the default
# HTTPClient implementation, and then again in each implementation's own
# test suite.
| HeaderEncodingHandler |
python | django__django | tests/aggregation_regress/models.py | {
"start": 1674,
"end": 1906
} | class ____(models.Model):
ID = models.AutoField(primary_key=True)
EntryID = models.ForeignKey(
Entries, models.CASCADE, verbose_name="Entry", db_column="Entry ID"
)
Clue = models.CharField(max_length=150)
| Clues |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/pyodbc.py | {
"start": 17112,
"end": 17776
} | class ____:
"""Wraps binary values in dialect-specific Binary wrapper.
If the value is null, return a pyodbc-specific BinaryNull
object to prevent pyODBC [and FreeTDS] from defaulting binary
NULL types to SQLWCHAR and causing implicit conversion errors.
"""
def bind_processor(self, dialect):
... | _ms_binary_pyodbc |
python | pypa__pip | src/pip/_internal/resolution/legacy/resolver.py | {
"start": 3696,
"end": 24060
} | class ____(BaseResolver):
"""Resolves which packages need to be installed/uninstalled to perform \
the requested operation without breaking the requirements of any package.
"""
_allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
def __init__(
self,
preparer: Requir... | Resolver |
python | walkccc__LeetCode | solutions/3271. Hash Divided String/3271.py | {
"start": 0,
"end": 292
} | class ____:
def stringHash(self, s: str, k: int) -> str:
ans = []
for i in range(0, len(s), k):
sumHash = sum(string.ascii_lowercase.index(s[j])
for j in range(i, i + k))
ans.append(string.ascii_lowercase[sumHash % 26])
return ''.join(ans)
| Solution |
python | ray-project__ray | python/ray/util/client/common.py | {
"start": 6523,
"end": 8379
} | class ____(raylet.ActorID):
def __init__(
self,
id: Union[bytes, Future],
weak_ref: Optional[bool] = False,
):
self._weak_ref = weak_ref
self._mutex = threading.Lock()
self._worker = ray.get_context().client_worker
if isinstance(id, bytes):
sel... | ClientActorRef |
python | getsentry__sentry | src/sentry/models/groupassignee.py | {
"start": 9467,
"end": 10982
} | class ____(Model):
"""
Identifies an assignment relationship between a user/team and an
aggregated event (Group).
"""
__relocation_scope__ = RelocationScope.Excluded
objects: ClassVar[GroupAssigneeManager] = GroupAssigneeManager()
project = FlexibleForeignKey("sentry.Project", related_nam... | GroupAssignee |
python | getsentry__sentry | src/sentry/replays/_case_studies/INC_1184_consumer_backlog_from_increased_threads/report.py | {
"start": 1242,
"end": 1545
} | class ____(ProcessingStrategy[FilteredPayload | None]):
def __init__(self):
self.consumed_count = 0
def submit(self, message):
self.consumed_count += 1
def poll(self): ...
def close(self): ...
def join(self, timeout=None): ...
def terminate(self): ...
| Consumer |
python | huggingface__transformers | src/transformers/models/qwen2/modeling_qwen2.py | {
"start": 14521,
"end": 15062
} | class ____(PreTrainedModel):
config: Qwen2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
... | Qwen2PreTrainedModel |
python | viewflow__viewflow | tests/test_urls__base.py | {
"start": 426,
"end": 608
} | class ____(NestedViewset):
app_name = "nested"
page_path = path(
"page2/", TemplateView.as_view(template_name="viewflow/base.html"), name="page"
)
| InheritedViewset |
python | plotly__plotly.py | plotly/graph_objs/carpet/aaxis/_title.py | {
"start": 233,
"end": 3564
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "carpet.aaxis"
_path_str = "carpet.aaxis.title"
_valid_props = {"font", "offset", "text"}
@property
def font(self):
"""
Sets this axis' title font.
The 'font' property is an instance of Font
that may be specifi... | Title |
python | huggingface__transformers | tests/models/canine/test_modeling_canine.py | {
"start": 20795,
"end": 36418
} | class ____(unittest.TestCase):
@slow
def test_inference_no_head(self):
model = CanineModel.from_pretrained("google/canine-s")
# this one corresponds to the first example of the TydiQA dev set (in Swahili)
# fmt: off
input_ids = [57344, 57349, 85, 107, 117, 98, 119, 97, 32, 119, 9... | CanineModelIntegrationTest |
python | huggingface__transformers | src/transformers/models/mistral/modeling_mistral.py | {
"start": 11825,
"end": 14844
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: MistralConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self... | MistralRotaryEmbedding |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py | {
"start": 2767,
"end": 4564
} | class ____(dg.PipesClient, TreatAsResourceParam):
"""An in-process pipes clients unusable in test cases. A function inside the orchestration
process actually serves as the "external" execution. This allows us to test the inner machinery
of pipes without actually launching subprocesses, which makes the tests... | InProcessPipesClient |
python | kamyu104__LeetCode-Solutions | Python/apply-discount-to-prices.py | {
"start": 917,
"end": 1321
} | class ____(object):
def discountPrices(self, sentence, discount):
"""
:type sentence: str
:type discount: int
:rtype: str
"""
def format(discount, x):
return "${:d}.{:02d}".format(*divmod(int(x[1:])*(100-discount), 100)) if x[0] == '$' and x[1:].isdigit() ... | Solution2 |
python | pytorch__pytorch | test/jit/test_torchbind.py | {
"start": 615,
"end": 16167
} | class ____(JitTestCase):
def setUp(self):
load_torchbind_test_lib()
def test_torchbind(self):
def test_equality(f, cmp_key):
obj1 = f()
obj2 = torch.jit.script(f)()
return (cmp_key(obj1), cmp_key(obj2))
def f():
val = torch.classes._Torch... | TestTorchbind |
python | mlflow__mlflow | mlflow/data/http_dataset_source.py | {
"start": 605,
"end": 4599
} | class ____(DatasetSource):
"""
Represents the source of a dataset stored at a web location and referred to
by an HTTP or HTTPS URL.
"""
def __init__(self, url):
self._url = url
@property
def url(self):
"""The HTTP/S URL referring to the dataset source location.
Ret... | HTTPDatasetSource |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 4193,
"end": 4938
} | class ____(BaseLinksSerializer, serializers.Serializer):
build = serializers.URLField(source="get_full_url")
project = serializers.SerializerMethodField()
version = serializers.SerializerMethodField()
def get_project(self, obj):
path = reverse("projects_detail", kwargs={"project_slug": obj.proj... | BuildURLsSerializer |
python | modin-project__modin | modin/core/storage_formats/pandas/groupby.py | {
"start": 1109,
"end": 9114
} | class ____:
"""Provide TreeReduce implementations for certain groupby aggregations."""
@classmethod
def get_impl(cls, agg_name):
"""
Get TreeReduce implementations for the specified `agg_name`.
Parameters
----------
agg_name : hashable
Returns
-----... | GroupbyReduceImpl |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/json.py | {
"start": 1250,
"end": 2178
} | class ____:
def _format_value(self, value: Any) -> str:
raise NotImplementedError()
def bind_processor(self, dialect: Dialect) -> _BindProcessorType[Any]:
super_proc = self.string_bind_processor(dialect) # type: ignore[attr-defined] # noqa: E501
def process(value: Any) -> Any:
... | _FormatTypeMixin |
python | realpython__materials | python-raise-exception/divide2.py | {
"start": 0,
"end": 171
} | class ____(Exception):
pass
def divide(a, b):
try:
return a / b
except ZeroDivisionError as error:
raise MathLibraryError(error)
| MathLibraryError |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 25699,
"end": 26190
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a block document."""
block_schema_id: Optional[UUID] = Field(
default=None, description="A block schema ID"
)
data: dict[str, Any] = Field(
default_factory=dict, description="The block document's data"
)
... | BlockDocumentUpdate |
python | walkccc__LeetCode | solutions/954. Array of Doubled Pairs/954.py | {
"start": 0,
"end": 259
} | class ____:
def canReorderDoubled(self, arr: list[int]) -> bool:
count = collections.Counter(arr)
for key in sorted(count, key=abs):
if count[key] > count[2 * key]:
return False
count[2 * key] -= count[key]
return True
| Solution |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 36363,
"end": 38295
} | class ____:
@classmethod
def setup_class(cls):
cls.a = np.arange(36.0).reshape(6, 6)
cls.mask_a = np.zeros_like(cls.a, bool)
# On purpose fill diagonal, so we get all masked elements.
cls.mask_a[np.tril_indices_from(cls.a)] = True
cls.ma = Masked(cls.a, mask=cls.mask_a)
... | TestPartitionLikeFunctions |
python | doocs__leetcode | solution/1600-1699/1615.Maximal Network Rank/Solution.py | {
"start": 0,
"end": 390
} | class ____:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
g = defaultdict(set)
for a, b in roads:
g[a].add(b)
g[b].add(a)
ans = 0
for a in range(n):
for b in range(a + 1, n):
if (t := len(g[a]) + len(g[b]) - (... | Solution |
python | modin-project__modin | modin/config/envvars.py | {
"start": 41114,
"end": 41283
} | class ____(EnvironmentVariable, type=int):
"""Number of threads per Dask worker."""
varname = "MODIN_DASK_THREADS_PER_WORKER"
default = 1
| DaskThreadsPerWorker |
python | huggingface__transformers | tests/models/layoutlmv2/test_image_processing_layoutlmv2.py | {
"start": 1293,
"end": 2708
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
apply_ocr=True,
):
size = size if size is not None else {"height": 18, "w... | LayoutLMv2ImageProcessingTester |
python | google__pytype | pytype/tests/test_operators1.py | {
"start": 6830,
"end": 8062
} | class ____(test_base.BaseTest, test_utils.OperatorsTestMixin):
"""Tests for overloading operators."""
def test_add(self):
self.check_binary("__add__", "+")
def test_and(self):
self.check_binary("__and__", "&")
def test_or(self):
self.check_binary("__or__", "|")
def test_sub(self):
self.che... | OverloadTest |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 1887,
"end": 2798
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.max_text_len = config.max_text_len
self.bias = nn.Parameter(torch.tensor(0.0))
def forward(
self,
vision_hidden_state: torch.FloatTensor,
text_hidden_state: torch.FloatTensor,
text... | MMGroundingDinoContrastiveEmbedding |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 145515,
"end": 146224
} | class ____(sgqlc.types.Input):
"""Parameters to be used for the branch_name_pattern rule"""
__schema__ = github_schema
__field_names__ = ("name", "negate", "operator", "pattern")
name = sgqlc.types.Field(String, graphql_name="name")
"""How this rule will appear to users."""
negate = sgqlc.type... | BranchNamePatternParametersInput |
python | ipython__ipython | IPython/lib/display.py | {
"start": 10185,
"end": 11643
} | class ____(IFrame):
"""Class for embedding a YouTube Video in an IPython session, based on its video id.
e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
do::
vid = YouTubeVideo("foo")
display(vid)
To start from 30 seconds::
vid = YouTubeVideo("abc... | YouTubeVideo |
python | google__pytype | pytype_extensions/instrumentation_for_testing_test.py | {
"start": 1987,
"end": 2334
} | class ____(WithCtor, i4t.ProductionType[WithCtor]):
def __init__(self): # pylint: disable=super-init-not-called
# Assume state is difficult to generate via the normal __init__, which is
# therefore intentionally not called from here.
self.state = 5
def ProductionCodePassWithCtor(obj: WithCtor):
retu... | FakeWithCtor |
python | fluentpython__example-code-2e | 24-class-metaprog/checked/initsub/checkedlib.py | {
"start": 2919,
"end": 4748
} | class ____:
@classmethod
def _fields(cls) -> dict[str, type]: # <1>
return get_type_hints(cls)
def __init_subclass__(subclass) -> None: # <2>
super().__init_subclass__() # <3>
for name, constructor in subclass._fields().items(): # <4>
setattr(subclass, name... | Checked |
python | geekcomputers__Python | BlackJack_game/blackjack_rr.py | {
"start": 16,
"end": 695
} | class ____:
BLACK = "\033[30m"
RED = "\033[91m"
GREEN = "\033[32m"
END = "\033[0m"
suits = (
Colour.RED + "Hearts" + Colour.END,
Colour.RED + "Diamonds" + Colour.END,
Colour.BLACK + "Spades" + Colour.END,
Colour.BLACK + "Clubs" + Colour.END,
)
ranks = (
"Two",
"Three",
"Fou... | Colour |
python | getsentry__sentry | tests/sentry/db/models/test_utils.py | {
"start": 2816,
"end": 4147
} | class ____(TestCase):
def test_no_conflict(self) -> None:
org = Organization(name="matt")
slugify_instance(org, org.name)
assert org.slug == "matt"
def test_conflict(self) -> None:
base_slug = self.organization.slug
org = Organization(name="foo")
slugify_instance... | SlugifyInstanceTest |
python | joke2k__faker | faker/providers/credit_card/fa_IR/__init__.py | {
"start": 122,
"end": 5042
} | class ____(CreditCardProvider):
"""Implement credit card provider for ``fa_IR`` locale.
For all methods that take ``card_type`` as an argument, a random card type
will be used if the supplied value is ``None``. The list of valid card types
includes ``'ansar'``, ``'bim'``, ``'day'``, ``'eghtesad_novin'`... | Provider |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 631501,
"end": 646198
} | class ____:
"""
IRect() - all zeros
IRect(x0, y0, x1, y1) - 4 coordinates
IRect(top-left, x1, y1) - point and 2 coordinates
IRect(x0, y0, bottom-right) - 2 coordinates and point
IRect(top-left, bottom-right) - 2 points
IRect(sequ) - new from sequence or rect-like
"""
def __add__(sel... | IRect |
python | keon__algorithms | algorithms/dp/knapsack.py | {
"start": 461,
"end": 849
} | class ____:
def __init__(self, value, weight):
self.value = value
self.weight = weight
def get_maximum_value(items, capacity):
dp = [0] * (capacity + 1)
for item in items:
for cur_weight in reversed(range(item.weight, capacity+1)):
dp[cur_weight] = max(dp[cur_weight], ... | Item |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 15615,
"end": 16042
} | class ____(AbstractTemplate):
key = cuda.atomic.cas
def generic(self, args, kws):
assert not kws
ary, idx, old, val = args
dty = ary.dtype
if dty not in integer_numba_types:
return
if ary.ndim == 1:
return signature(dty, ary, types.intp, dty, dt... | Cuda_atomic_cas |
python | numba__llvmlite | llvmlite/tests/test_binding.py | {
"start": 19110,
"end": 20139
} | class ____(TestCase):
def setUp(self):
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
gc.collect()
self.old_garbage = gc.garbage[:]
gc.garbage[:] = []
def tearDown(self):
# Test that no uncollectable objects were created
# (llvmlite ... | BaseTest |
python | walkccc__LeetCode | solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py | {
"start": 0,
"end": 228
} | class ____:
def makeSimilar(self, nums: list[int], target: list[int]) -> int:
nums.sort(key=lambda x: (x % 2, x))
target.sort(key=lambda x: (x % 2, x))
return sum(abs(a - b) for a, b in zip(nums, target)) // 4
| Solution |
python | sanic-org__sanic | sanic/mixins/listeners.py | {
"start": 863,
"end": 16473
} | class ____(metaclass=SanicMeta):
def __init__(self, *args, **kwargs) -> None:
self._future_listeners: list[FutureListener] = []
def _apply_listener(self, listener: FutureListener):
raise NotImplementedError # noqa
@overload
def listener(
self,
listener_or_event: Listen... | ListenerMixin |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 199062,
"end": 199500
} | class ____:
_col_type = INT8MULTIRANGE
_col_str = "INT8MULTIRANGE"
def _data_str(self):
return (
"{[9223372036854775801,9223372036854775803),"
+ "[9223372036854775805,9223372036854775807)}"
)
def _data_obj(self):
return [
Range(92233720368547... | _Int8MultiRangeTests |
python | sympy__sympy | sympy/stats/stochastic_process_types.py | {
"start": 11397,
"end": 11852
} | class ____(TransitionMatrixOf):
"""
Assumes that the matrix is the generator matrix
of the process.
"""
def __new__(cls, process, matrix):
if not isinstance(process, ContinuousMarkovChain):
raise ValueError("Currently only ContinuousMarkovChain "
... | GeneratorMatrixOf |
python | jd__tenacity | tenacity/stop.py | {
"start": 2574,
"end": 3350
} | class ____(stop_base):
"""
Stop when the time from the first attempt >= limit.
Note: `max_delay` will be exceeded, so when used with a `wait`, the actual total delay will be greater
than `max_delay` by some of the final sleep period before `max_delay` is exceeded.
If you need stricter timing with ... | stop_after_delay |
python | google__pytype | pytype/pytd/type_match.py | {
"start": 2138,
"end": 2416
} | class ____(node.Node):
"""A type that doesn't allow sub- or superclasses to match.
For example, "int" is considered a valid argument for a function that accepts
"object", but StrictType("int") is not.
"""
name: str
def __str__(self):
return self.name
| StrictType |
python | celery__celery | t/unit/backends/test_redis.py | {
"start": 50187,
"end": 54965
} | class ____:
def get_backend(self):
from celery.backends.redis import SentinelBackend
class _SentinelBackend(SentinelBackend):
redis = redis
sentinel = sentinel
return _SentinelBackend
def get_E_LOST(self):
from celery.backends.redis import E_LOST
... | test_SentinelBackend |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp-pyspark/dagster_gcp_pyspark/bigquery/bigquery_pyspark_type_handler.py | {
"start": 7348,
"end": 11283
} | class ____(BigQueryIOManager):
"""An I/O manager definition that reads inputs from and writes PySpark DataFrames to BigQuery.
Returns:
IOManagerDefinition
Examples:
.. code-block:: python
from dagster_gcp_pyspark import BigQueryPySparkIOManager
from dagster import ... | BigQueryPySparkIOManager |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 11405,
"end": 11685
} | class ____:
params = other_offsets
param_names = ["offset"]
def setup(self, offset):
N = 10000
rng = date_range(start="1/1/2000", periods=N, freq="min")
self.rng = rng
def time_apply_index(self, offset):
self.rng + offset
| ApplyIndex |
python | gabrielfalcao__HTTPretty | httpretty/core.py | {
"start": 11505,
"end": 11632
} | class ____(dict):
"""A dict subclass used as internal representation of empty request
headers
"""
| EmptyRequestHeaders |
python | Textualize__textual | tests/test_message_pump.py | {
"start": 1833,
"end": 5367
} | class ____(App):
def __init__(self) -> None:
self.input_changed_events = []
super().__init__()
def compose(self) -> ComposeResult:
yield Input()
def on_input_changed(self, event: Input.Changed) -> None:
self.input_changed_events.append(event)
async def test_message_queue_... | PreventTestApp |
python | weaviate__weaviate-python-client | weaviate/collections/classes/filters.py | {
"start": 4109,
"end": 4243
} | class ____(_WeaviateInput):
link_on: str
target: Optional["_FilterTargets"] = Field(exclude=True, default=None)
| _SingleTargetRef |
python | walkccc__LeetCode | solutions/559. Maximum Depth of N-ary Tree/559.py | {
"start": 0,
"end": 200
} | class ____:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
if not root.children:
return 1
return 1 + max(self.maxDepth(child) for child in root.children)
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.