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 | numpy__numpy | numpy/distutils/tests/test_exec_command.py | {
"start": 1316,
"end": 3357
} | class ____:
"""Context manager to emulate os.name != 'posix' """
def __init__(self, osname='non-posix'):
self._new_name = osname
def __enter__(self):
self._old_name = os.name
os.name = self._new_name
def __exit__(self, exc_type, exc_value, traceback):
os.name = self._ol... | emulate_nonposix |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 790,
"end": 877
} | class ____(Protocol[T]):
def m1(self, p0: T) -> None:
pass
attr: T
| Proto |
python | readthedocs__readthedocs.org | readthedocs/api/mixins.py | {
"start": 369,
"end": 1901
} | class ____:
"""
Add cache tags for project and version to the response of this view.
The view inheriting this mixin should implement the
`self._get_project` and `self._get_version` methods.
If `self._get_version` returns `None`,
only the project level tags are added.
You can add an extra ... | CDNCacheTagsMixin |
python | google__pytype | pytype/constant_folding.py | {
"start": 4495,
"end": 7086
} | class ____:
"""A simple opcode stack."""
def __init__(self):
self.stack = []
self.consts = {}
def __iter__(self):
return self.stack.__iter__()
def push(self, val):
self.stack.append(val)
def pop(self):
return self.stack.pop()
def _preserve_constant(self, c):
if c and (
n... | _Stack |
python | pytorch__pytorch | torch/_inductor/compile_fx_ext.py | {
"start": 2414,
"end": 3544
} | class ____(contextlib.ExitStack):
"""
Helper for _VirtualizedSerializer.patch()
"""
def __init__(self, virtualized: _VirtualizedSerializer) -> None:
super().__init__()
self.virtualized = virtualized
@override
def __enter__(self) -> Self:
super().__enter__()
for... | _VirtualizedSerializerContextManager |
python | pypa__warehouse | warehouse/subscriptions/models.py | {
"start": 4225,
"end": 5174
} | class ____(db.Model):
__tablename__ = "stripe_subscription_prices"
__repr__ = make_repr("price_id", "unit_amount", "recurring")
price_id: Mapped[str | None] # generated by Payment Service Provider
currency: Mapped[str] # https://stripe.com/docs/currencies
subscription_product_id: Mapped[UUID] = ... | StripeSubscriptionPrice |
python | getsentry__sentry | src/sentry/users/services/usersocialauth/model.py | {
"start": 407,
"end": 722
} | class ____(RpcModel):
id: int
user_id: int
provider: str
uid: str
extra_data: dict[str, Any]
def get_backend(self) -> type[BaseAuth] | None:
return get_backend(instance=self)
@property
def tokens(self) -> dict[str, Any]:
return tokens(instance=self)
| RpcUserSocialAuth |
python | apache__airflow | providers/apache/kafka/src/airflow/providers/apache/kafka/operators/consume.py | {
"start": 1249,
"end": 9825
} | class ____(BaseOperator):
"""
An operator that consumes from Kafka a topic(s) and processing the messages.
The operator creates a Kafka consumer that reads a batch of messages from the cluster and processes them
using the user supplied callable function. The consumer will continue to read in batches un... | ConsumeFromTopicOperator |
python | Textualize__textual | docs/examples/app/question01.py | {
"start": 87,
"end": 502
} | class ____(App[str]):
def compose(self) -> ComposeResult:
yield Label("Do you love Textual?")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id)
if... | QuestionApp |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 890,
"end": 1082
} | class ____(models.Model):
pass
def decorate(fn):
@wraps(fn)
def wrapper(self, request, *args, **kwargs):
return fn(self, request, *args, **kwargs)
return wrapper
| Action |
python | great-expectations__great_expectations | great_expectations/self_check/sqlalchemy_connection_manager.py | {
"start": 1295,
"end": 2008
} | class ____:
def __init__(self, sa, connection_string) -> None:
self.lock = threading.Lock()
self.sa = sa
self.connection_string = connection_string
self._is_valid = None
def is_valid(self):
with self.lock:
if self._is_valid is None:
try:
... | LockingConnectionCheck |
python | modin-project__modin | modin/core/execution/unidist/implementations/pandas_on_unidist/dataframe/dataframe.py | {
"start": 1070,
"end": 2413
} | class ____(PandasDataframe):
"""
The class implements the interface in ``PandasDataframe`` using unidist.
Parameters
----------
partitions : np.ndarray
A 2D NumPy array of partitions.
index : sequence
The index for the dataframe. Converted to a ``pandas.Index``.
columns : se... | PandasOnUnidistDataframe |
python | pydata__xarray | xarray/backends/file_manager.py | {
"start": 12554,
"end": 16239
} | class ____(FileManager[T_File]):
"""File manager that supports pickling by reopening a file object.
Use PickleableFileManager for wrapping file-like objects that do not natively
support pickling (e.g., netCDF4.Dataset and h5netcdf.File) in cases where a
global cache is not desirable (e.g., for netCDF f... | PickleableFileManager |
python | streamlit__streamlit | lib/tests/streamlit/elements/lib/options_selector_utils_test.py | {
"start": 3231,
"end": 5682
} | class ____(unittest.TestCase):
@parameterized.expand(
[
(np.array([1, 2, 3, 4, 5]), 5, 4),
# This one will have 0.15000000000000002 because of floating point precision
(np.arange(0.0, 0.25, 0.05), 0.15, 3),
([0, 1, 2, 3], 3, 3),
([0.1, 0.2, 0.3], 0... | TestIndexMethod |
python | python__mypy | mypy/stubutil.py | {
"start": 11718,
"end": 12083
} | class ____:
def __init__(
self,
name: str,
self_var: str,
docstring: str | None = None,
cls: type | None = None,
parent: ClassInfo | None = None,
) -> None:
self.name = name
self.self_var = self_var
self.docstring = docstring
self.c... | ClassInfo |
python | lazyprogrammer__machine_learning_examples | rnn_class/mlp_parity.py | {
"start": 491,
"end": 903
} | class ____(object):
def __init__(self, M1, M2, an_id):
self.id = an_id
self.M1 = M1
self.M2 = M2
W = init_weight(M1, M2)
b = np.zeros(M2)
self.W = theano.shared(W, 'W_%s' % self.id)
self.b = theano.shared(b, 'b_%s' % self.id)
self.params = [self.W, sel... | HiddenLayer |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/blobstore/django/main.py | {
"start": 1644,
"end": 3546
} | class ____(blobstore.BlobstoreDownloadHandler):
def get(self, environ, photo_key):
if not blobstore.get(photo_key):
return HttpResponse("Photo key not found", status=404)
else:
response = HttpResponse(headers=self.send_blob(environ, photo_key))
# Prevent Django f... | ViewPhotoHandler |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 94362,
"end": 94845
} | class ____(sgqlc.types.Enum):
"""Possible roles a user may have in relation to an organization.
Enumeration Choices:
* `DIRECT_MEMBER`: A user who is a direct member of the
organization.
* `OWNER`: A user with full administrative access to the
organization.
* `UNAFFILIATED`: A user who... | RoleInOrganization |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 28391,
"end": 28513
} | class ____(BaseModel):
dag_id: str
run_id: str
type: Literal["GetDagRunState"] = "GetDagRunState"
| GetDagRunState |
python | GoogleCloudPlatform__python-docs-samples | datastore/cloud-client/snippets_test.py | {
"start": 784,
"end": 1365
} | class ____(datastore.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.entities_to_delete = []
self.keys_to_delete = []
def cleanup(self):
batch = self.batch()
batch.begin()
self.delete_multi(
list({x.key for x in se... | CleanupClient |
python | neetcode-gh__leetcode | python/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.py | {
"start": 0,
"end": 753
} | class ____:
def minFlips(self, s: str) -> int:
n = len(s)
s = s + s
alt1, alt2 = "", ""
for i in range(len(s)):
alt1 += "0" if i % 2 == 0 else "1"
alt2 += "1" if i % 2 == 0 else "0"
res = float('inf')
diff1, diff2 = 0, 0
l = 0
... | Solution |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 8290,
"end": 8357
} | class ____(HTTPClientError):
status_code = 408
| HTTPRequestTimeout |
python | walkccc__LeetCode | solutions/974. Subarray Sums Divisible by K/974.py | {
"start": 0,
"end": 273
} | class ____:
def subarraysDivByK(self, nums: list[int], k: int) -> int:
ans = 0
prefix = 0
count = [0] * k
count[0] = 1
for num in nums:
prefix = (prefix + num % k + k) % k
ans += count[prefix]
count[prefix] += 1
return ans
| Solution |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/decisionTree/python/Decision_Tree.py | {
"start": 239,
"end": 4810
} | class ____:
def __init__(self, depth = 5, min_leaf_size = 5):
self.depth = depth
self.decision_boundary = 0
self.left = None
self.right = None
self.min_leaf_size = min_leaf_size
self.prediction = None
def mean_squared_error(self, labels, prediction):
"""
... | Decision_Tree |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 108852,
"end": 108977
} | class ____(_pkg_config_info):
section = 'xft'
append_config_exe = 'xft'
version_macro_name = 'XFT_VERSION'
| xft_info |
python | great-expectations__great_expectations | tests/datasource/fluent/conftest.py | {
"start": 5181,
"end": 9832
} | class ____(ExecutionEngine):
def __init__(self, *args, **kwargs):
pass
@override
def get_batch_data_and_markers(self, batch_spec) -> tuple[BatchData, BatchMarkers]: # type: ignore[override] # FIXME CoP
return BatchData(self), BatchMarkers(ge_load_time=None)
@pytest.fixture
def inject_eng... | ExecutionEngineDouble |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial003_py310.py | {
"start": 85,
"end": 456
} | class ____(SQLModel, table=True):
team_id: int | None = Field(default=None, foreign_key="team.id", primary_key=True)
hero_id: int | None = Field(default=None, foreign_key="hero.id", primary_key=True)
is_training: bool = False
team: "Team" = Relationship(back_populates="hero_links")
hero: "Hero" = R... | HeroTeamLink |
python | sqlalchemy__sqlalchemy | test/orm/test_versioning.py | {
"start": 4581,
"end": 17653
} | class ____(fixtures.MappedTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"version_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Co... | VersioningTest |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 32469,
"end": 33177
} | class ____(InlineProcessor):
"""Convert emails to clickable email links."""
ANCESTOR_EXCLUDES = ('a',)
def email_encode(self, code):
"""Return entity definition by code, or the code if not defined."""
return f"{md_util.AMP_SUBSTITUTE}#{code:d};"
def handleMatch(self, m, data):
... | MagiclinkMailPattern |
python | wandb__wandb | wandb/sdk/artifacts/_generated/create_registry_members.py | {
"start": 272,
"end": 376
} | class ____(GQLResult):
success: bool
CreateRegistryMembers.model_rebuild()
| CreateRegistryMembersResult |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 37378,
"end": 37618
} | class ____(ChainedSource):
def name(self) -> str:
return f"___as_tensor({self.base.name()})"
def guard_source(self) -> GuardSource:
return self.base.guard_source()
@dataclasses.dataclass(frozen=True)
| FloatTensorSource |
python | neetcode-gh__leetcode | python/0153-find-minimum-in-rotated-sorted-array.py | {
"start": 0,
"end": 540
} | class ____:
def findMin(self, nums: List[int]) -> int:
start , end = 0, len(nums) - 1
curr_min = float("inf")
while start < end :
mid = start + (end - start ) // 2
curr_min = min(curr_min,nums[mid])
# right has the min
... | Solution |
python | scikit-learn__scikit-learn | sklearn/metrics/tests/test_score_objects.py | {
"start": 5023,
"end": 5163
} | class ____(BaseEstimator):
"""Dummy estimator to test scoring validators"""
def fit(self, X, y):
return self
| EstimatorWithFit |
python | pytorch__pytorch | test/test_mps.py | {
"start": 413790,
"end": 428415
} | class ____(TestCaseMPS):
def _compare_tensors(self, y, ref):
denom = torch.maximum(ref.abs(), torch.tensor([1e-6], device=ref.device, dtype=ref.dtype))
err = ((y - ref).abs() / denom).mean().item()
self.assertLess(err, 0.01)
def _test_sdpa_no_mask(
self,
is_causal: bool,... | TestSDPA |
python | run-llama__llama_index | llama-index-core/tests/prompts/test_mixin.py | {
"start": 653,
"end": 2153
} | class ____(PromptMixin):
def __init__(self) -> None:
self.mock_object_2 = MockObject2()
self._prompt_dict_1 = {
"summary": PromptTemplate("{summary}"),
"foo": PromptTemplate("{foo} {bar}"),
}
def _get_prompts(self) -> PromptDictType:
return self._prompt_d... | MockObject1 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 685638,
"end": 686190
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("upvote_count", "viewer_can_upvote", "viewer_has_upvoted")
upvote_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="upvoteCount"
)
viewer_ca... | Votable |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py | {
"start": 257,
"end": 493
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
hero_id: int = Field(foreign_key="hero.id")
hero: "Hero" = Relationship(back_populates="powers")
| Power |
python | geekcomputers__Python | binary_search_tree.py | {
"start": 0,
"end": 313
} | class ____:
"""Class for node of a tree"""
def __init__(self, info):
"""Initialising a node"""
self.info = info
self.left = None
self.right = None
# self.level = None
def __str__(self):
return str(self.info)
def __del__(self):
del self
| Node |
python | google__python-fire | fire/docstrings.py | {
"start": 2664,
"end": 2765
} | class ____(ArgInfo):
pass
KwargInfo.__new__.__defaults__ = (None,) * len(KwargInfo._fields)
| KwargInfo |
python | aio-libs__aiohttp | tests/test_flowcontrol_streams.py | {
"start": 493,
"end": 5267
} | class ____:
async def test_read(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"da")
res = await stream.read(1)
assert res == b"d"
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_read_resume_paused(self, stream: stre... | TestFlowControlStreamReader |
python | kamyu104__LeetCode-Solutions | Python/unique-substrings-with-equal-digit-frequency.py | {
"start": 69,
"end": 652
} | class ____(object):
def equalDigitFrequency(self, s):
"""
:type s: str
:rtype: int
"""
MOD = 10**9+7
D = 27
lookup = set()
for i in xrange(len(s)):
cnt = collections.Counter()
h = max_cnt = 0
for j in xrange(i, len(s... | Solution |
python | getsentry__sentry | src/sentry/integrations/bitbucket_server/integration.py | {
"start": 6336,
"end": 7963
} | class ____:
"""
Start the OAuth dance by creating a request token
and redirecting the user to approve it.
"""
@method_decorator(csrf_exempt)
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
with IntegrationPipelineViewEvent(
Integr... | OAuthLoginView |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/callbacks/fake_callback_handler.py | {
"start": 2965,
"end": 6215
} | class ____(BaseCallbackHandler, BaseFakeCallbackHandlerMixin):
"""Fake callback handler for testing."""
@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_
@property
def ignore_chain(self) -> bool:
"""Whether to ignore chai... | FakeCallbackHandler |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 62413,
"end": 62644
} | class ____(Qwen3MoeDecoderLayer):
def __init__(self, config, layer_idx):
super().__init__(config, layer_idx)
self.self_attn = Qwen3OmniMoeThinkerTextAttention(config, layer_idx)
| Qwen3OmniMoeThinkerTextDecoderLayer |
python | walkccc__LeetCode | solutions/59. Spiral Matrix II/59.py | {
"start": 0,
"end": 557
} | class ____:
def generateMatrix(self, n: int) -> list[list[int]]:
ans = [[0] * n for _ in range(n)]
count = 1
for mn in range(n // 2):
mx = n - mn - 1
for i in range(mn, mx):
ans[mn][i] = count
count += 1
for i in range(mn, mx):
ans[i][mx] = count
count +=... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/pytest/test_parametrized_db_keys.py | {
"start": 1275,
"end": 1674
} | class ____:
# Regression test for https://github.com/HypothesisWorks/hypothesis/issues/3733
@given(x=st.text())
@pytest.mark.parametrize("i", range(2))
def test_method(self, x, i):
pass
@settings(suppress_health_check=[HealthCheck.function_scoped_fixture])
@given(x=st.text())
def t... | TestNoDifferingExecutorsHealthCheck |
python | Netflix__metaflow | metaflow/includefile.py | {
"start": 8702,
"end": 15325
} | class ____(Parameter):
"""
Includes a local file as a parameter for the flow.
`IncludeFile` behaves like `Parameter` except that it reads its value from a file instead of
the command line. The user provides a path to a file on the command line. The file contents
are saved as a read-only artifact wh... | IncludeFile |
python | fastai__fastai | fastai/callback/schedule.py | {
"start": 7825,
"end": 14455
} | class ____(ParamScheduler):
"Training with exponentially growing learning rate"
def __init__(self, start_lr=1e-7, end_lr=10, num_it=100, stop_div=True):
if num_it < 6: num_it = 6
self.scheds = {'lr': [SchedExp(s, e) for (s,e) in zip(start_lr,end_lr)
] if is_listy(sta... | LRFinder |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 13130,
"end": 15726
} | class ____:
nanfuncs = {
np.nanmin: np.min,
np.nanmax: np.max,
np.nanargmin: np.argmin,
np.nanargmax: np.argmax,
np.nansum: np.sum,
np.nanprod: np.prod,
np.nancumsum: np.cumsum,
np.nancumprod: np.cumprod,
np.nanmean: np.mean,
np.nanmedi... | TestNanFunctions_NumberTypes |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 910,
"end": 961
} | class ____(D1, D2): ...
_T_E = TypeVar("_T_E")
| DSub |
python | gevent__gevent | src/greentest/3.10/test_wsgiref.py | {
"start": 19941,
"end": 20144
} | class ____(ErrorHandler):
"""Simple handler subclass for testing BaseHandler, w/error passthru"""
def handle_error(self):
raise # for testing, we want to see what's happening
| TestHandler |
python | django__django | tests/postgres_tests/models.py | {
"start": 2406,
"end": 2546
} | class ____(PostgreSQLModel):
field = HStoreField(blank=True, null=True)
array_field = ArrayField(HStoreField(), null=True)
| HStoreModel |
python | pytorch__pytorch | torch/_inductor/utils.py | {
"start": 113017,
"end": 114455
} | class ____:
type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND
override_return_dtype: Optional[torch.dtype]
op_dtype_propagation_rules: dict[str, OpDtypeRule] = {}
def register_op_dtype_propagation_rules(
name: str,
type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND,
override_return_dtype: O... | OpDtypeRule |
python | pypa__pip | src/pip/_internal/distributions/installed.py | {
"start": 275,
"end": 929
} | class ____(AbstractDistribution):
"""Represents an installed package.
This does not need any preparation as the required information has already
been computed.
"""
@property
def build_tracker_id(self) -> str | None:
return None
def get_metadata_distribution(self) -> BaseDistributi... | InstalledDistribution |
python | ray-project__ray | python/ray/_private/runtime_env/plugin_schema_manager.py | {
"start": 258,
"end": 3504
} | class ____:
"""This manager is used to load plugin json schemas."""
default_schema_path = os.path.join(
os.path.dirname(__file__), "../../runtime_env/schemas"
)
schemas = {}
loaded = False
@classmethod
def _load_schemas(cls, schema_paths: List[str]):
for schema_path in sche... | RuntimeEnvPluginSchemaManager |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 59851,
"end": 60054
} | class ____(themeable):
"""
Length of ticks in the legend
Parameters
----------
theme_element : float
A good value should be in the range `[0, 0.5]`.
"""
| legend_ticks_length |
python | geekcomputers__Python | BlackJack_game/blackjack_simulate.py | {
"start": 11646,
"end": 19598
} | class ____:
def __init__(self, username):
self.deck = Deck()
self.dealer = Dealer("Bob")
self.player = Player(username.title(), 1000)
self.recorder = Recorder()
self.go_on = True
self.first_hand = True
self.choice = None
self.winner = None
self... | BlackJack |
python | plotly__plotly.py | plotly/graph_objs/layout/slider/_font.py | {
"start": 235,
"end": 9878
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.slider"
_path_str = "layout.slider.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@proper... | Font |
python | PrefectHQ__prefect | tests/blocks/test_notifications.py | {
"start": 29608,
"end": 35033
} | class ____:
URL_PARAMS = {
# default notify format
"format": "html",
# default overflow mode
"overflow": "upstream",
}
async def test_notify_async(self):
with patch("apprise.Apprise", autospec=True) as AppriseMock:
apprise_instance_mock = AppriseMock.retu... | TestSendgridEmail |
python | realpython__materials | rp-portfolio/projects/admin.py | {
"start": 71,
"end": 163
} | class ____(admin.ModelAdmin):
pass
admin.site.register(Project, ProjectAdmin)
| ProjectAdmin |
python | allegroai__clearml | clearml/binding/frameworks/tensorflow_bind.py | {
"start": 43173,
"end": 52806
} | class ____(object):
_current_task = None
__original_getattribute = None
__original_getattributeX = None
__patched = False
_original_add_event = None
_original_add_eventT = None
_original_add_eventX = None
defaults_dict = dict(
report_freq=1,
image_report_freq=1,
h... | PatchSummaryToEventTransformer |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 11336,
"end": 11562
} | class ____(Where):
"""Not contains comparison for document content"""
key: str
content: str
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$not_contains": self.content}}
@dataclass
| NotContains |
python | getsentry__sentry | src/sentry/api/endpoints/organization_sdk_deprecations.py | {
"start": 877,
"end": 992
} | class ____(TypedDict):
projectId: str
minimumVersion: str
sdkName: str
sdkVersion: str
| SDKDeprecation |
python | h5py__h5py | h5py/_hl/group.py | {
"start": 29812,
"end": 30297
} | class ____:
"""
Represents a symbolic ("soft") link in an HDF5 file. The path
may be absolute or relative. No checking is performed to ensure
that the target actually exists.
"""
@property
def path(self):
""" Soft link value. Not guaranteed to be a valid path. """
... | SoftLink |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/model_service.py | {
"start": 4762,
"end": 8297
} | class ____(GoogleCloudBaseOperator):
"""
Retrieves a Model.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param model_id: Required. The ID of the Model resource to... | GetModelOperator |
python | jazzband__django-simple-history | simple_history/registry_tests/tests.py | {
"start": 2648,
"end": 3038
} | class ____(unittest.TestCase):
def test_accessor_default(self):
register(UserAccessorDefault)
self.assertFalse(hasattr(User, "historicaluseraccessordefault_set"))
def test_accessor_override(self):
register(UserAccessorOverride, user_related_name="my_history_model_accessor")
self... | TestUserAccessor |
python | ethereum__web3.py | web3/eth/eth.py | {
"start": 1710,
"end": 20433
} | class ____(BaseEth):
# mypy types
w3: "Web3"
_default_contract_factory: type[Contract | ContractCaller] = Contract
# eth_accounts
_accounts: Method[Callable[[], tuple[ChecksumAddress]]] = Method(
RPC.eth_accounts,
is_property=True,
)
@property
def accounts(self) -> tu... | Eth |
python | walkccc__LeetCode | solutions/419. Battleships in a Board/419.py | {
"start": 0,
"end": 367
} | class ____:
def countBattleships(self, board: list[list[str]]) -> int:
ans = 0
for i, row in enumerate(board):
for j, cell in enumerate(row):
if cell == '.':
continue
if i > 0 and board[i - 1][j] == 'X':
continue
if j > 0 and board[i][j - 1] == 'X':
... | Solution |
python | getsentry__sentry-python | tests/integrations/wsgi/test_wsgi.py | {
"start": 334,
"end": 501
} | class ____:
def __init__(self, iterable):
self.iterable = iterable
def __call__(self, environ, start_response):
return self.iterable
| IterableApp |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 18382,
"end": 27777
} | class ____:
def _create_MyArray(self):
class MyArray:
def __init__(self, function=None):
self.function = function
def __array_function__(self, func, types, args, kwargs):
assert func is getattr(np, func.__name__)
try:
... | TestArrayLike |
python | streamlit__streamlit | lib/tests/streamlit/elements/lib/column_types_test.py | {
"start": 1147,
"end": 19849
} | class ____(unittest.TestCase):
def test_generic_column(self):
"""Test Column creation."""
assert remove_none_values(Column()) == {}, (
"Should not have any properties defined."
)
assert remove_none_values(
Column(
"Col1",
widt... | ColumnTypesTest |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 14636,
"end": 14774
} | class ____(AnsiblePluginError):
"""A collection is not supported by this version of Ansible."""
| AnsibleCollectionUnsupportedVersionError |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 1735,
"end": 8242
} | class ____:
"""Test various input options to fitting routines."""
def setup_class(self):
self.x1 = np.arange(10)
self.y, self.x = np.mgrid[:10, :10]
def test_linear_fitter_1set(self):
"""1 set 1D x, 1pset"""
expected = np.array([0, 1, 1, 1])
p1 = models.Polynomial1... | TestFitting |
python | wepe__MachineLearning | DeepLearning Tutorials/cnn_LeNet/convolutional_mlp_commentate.py | {
"start": 5124,
"end": 16688
} | class ____(object):
def __init__(self, input, n_in, n_out):
#W大小是n_in行n_out列,b为n_out维向量。即:每个输出对应W的一列以及b的一个元素。
self.W = theano.shared(
value=numpy.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
... | LogisticRegression |
python | pypa__pip | src/pip/_vendor/packaging/_parser.py | {
"start": 691,
"end": 771
} | class ____(Node):
def serialize(self) -> str:
return f'"{self}"'
| Value |
python | plotly__plotly.py | plotly/graph_objs/volume/_hoverlabel.py | {
"start": 233,
"end": 11234
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
... | Hoverlabel |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/hooks.py | {
"start": 1120,
"end": 5948
} | class ____(session_run_hook.SessionRunHook):
"""Command-line-interface debugger hook.
Can be used as a hook for `tf.compat.v1.train.MonitoredSession`.
"""
def __init__(self,
ui_type="readline",
dump_root=None,
thread_name_filter=None,
config_file_pat... | LocalCLIDebugHook |
python | sympy__sympy | sympy/assumptions/predicates/order.py | {
"start": 5314,
"end": 6646
} | class ____(Predicate):
r"""
Positive real number predicate.
Explanation
===========
``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x``
is in the interval `(0, \infty)`. In particular, infinity is not
positive.
A few important facts about positive numbers:
... | PositivePredicate |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/dataframe.py | {
"start": 2227,
"end": 4456
} | class ____(ABC):
"""
Data in the buffer is guaranteed to be contiguous in memory.
Note that there is no dtype attribute present, a buffer can be thought of
as simply a block of memory. However, if the column that the buffer is
attached to has a dtype that's supported by DLPack and ``__dlpack__`` is... | ProtocolBuffer |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 11481,
"end": 24071
} | class ____(TriInterpolator):
r"""
Cubic interpolator on a triangular grid.
In one-dimension - on a segment - a cubic interpolating function is
defined by the values of the function and its derivative at both ends.
This is almost the same in 2D inside a triangle, except that the values
of the fu... | CubicTriInterpolator |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/test_annotated_types.py | {
"start": 4094,
"end": 5164
} | class ____:
__is_annotated_types_grouped_metadata__ = True
def __init__(self, *args) -> None:
self._args = args
def __iter__(self):
return iter(self._args)
def __repr__(self) -> str:
return f"GroupedStuff({', '.join(map(repr, self._args))})"
def test_flattens_grouped_metadat... | GroupedStuff |
python | spack__spack | lib/spack/spack/modules/common.py | {
"start": 37509,
"end": 37685
} | class ____(AttributeError, ModulesError):
"""Raised if the attribute ``default_template`` has not been specified
in the derived classes.
"""
| DefaultTemplateNotDefined |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_select_dtypes.py | {
"start": 534,
"end": 954
} | class ____(ExtensionArray):
def __init__(self, data, dtype) -> None:
self.data = data
self._dtype = dtype
def __array__(self, dtype=None, copy=None):
return self.data
@property
def dtype(self):
return self._dtype
def __len__(self) -> int:
return len(self.da... | DummyArray |
python | huggingface__transformers | tests/models/mamba2/test_modeling_mamba2.py | {
"start": 14426,
"end": 20473
} | class ____(unittest.TestCase):
def setUp(self):
self.model_id = "mistralai/Mamba-Codestral-7B-v0.1"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, from_slow=True, legacy=False)
self.prompt = ("[INST]Write a hello world program in C++.",)
@require_read_token
@slow
... | Mamba2IntegrationTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/cwise_ops_unary_test.py | {
"start": 2396,
"end": 27843
} | class ____(test.TestCase):
def _compareCpu(self, x, np_func, tf_func, grad_rtol=None, grad_atol=None):
if grad_rtol is None:
grad_rtol = _default_tolerance(x.dtype)
if grad_atol is None:
grad_atol = _default_tolerance(x.dtype)
np_ans = np_func(x)
with self.cached_session(use_gpu=False):
... | UnaryOpTest |
python | python-markdown__markdown | markdown/extensions/footnotes.py | {
"start": 16601,
"end": 17429
} | class ____(Treeprocessor):
""" Build and append footnote div to end of document. """
def __init__(self, footnotes: FootnoteExtension):
self.footnotes = footnotes
def run(self, root: etree.Element) -> None:
footnotesDiv = self.footnotes.makeFootnotesDiv(root)
if footnotesDiv is not ... | FootnoteTreeprocessor |
python | openai__openai-python | src/openai/types/chat/chat_completion.py | {
"start": 1572,
"end": 3488
} | class ____(BaseModel):
id: str
"""A unique identifier for the chat completion."""
choices: List[Choice]
"""A list of chat completion choices.
Can be more than one if `n` is greater than 1.
"""
created: int
"""The Unix timestamp (in seconds) of when the chat completion was created."""
... | ChatCompletion |
python | donnemartin__interactive-coding-challenges | online_judges/mult_other_numbers/test_mult_other_numbers.py | {
"start": 18,
"end": 673
} | class ____(unittest.TestCase):
def test_mult_other_numbers(self):
solution = Solution()
self.assertRaises(TypeError, solution.mult_other_numbers, None)
self.assertEqual(solution.mult_other_numbers([0]), [])
self.assertEqual(solution.mult_other_numbers([0, 1]), [1, 0])
self.a... | TestMultOtherNumbers |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 59137,
"end": 66361
} | class ____(Collection):
_attr = "shapes"
_kw = kw.shape
_wrap = Shape
@atexit.register
def cleanup():
"""
Since AppleScript cannot access Excel while a Macro is running, we have to run the
Python call in a background process which makes the call return immediately: we
rely on the StatusBar... | Shapes |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_workflows.py | {
"start": 5572,
"end": 6535
} | class ____:
@mock.patch(BASE_PATH.format("WorkflowsHook"))
def test_execute(
self,
mock_hook,
):
op = WorkflowsDeleteWorkflowOperator(
task_id="test_task",
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
r... | TestWorkflowsDeleteWorkflowOperator |
python | kamyu104__LeetCode-Solutions | Python/greatest-english-letter-in-upper-and-lower-case.py | {
"start": 450,
"end": 756
} | class ____(object):
def greatestLetter(self, s):
"""
:type s: str
:rtype: str
"""
lookup = set(s)
return next((C for c, C in itertools.izip(reversed(string.ascii_lowercase), reversed(string.ascii_uppercase)) if c in lookup and C in lookup), "")
| Solution2 |
python | sympy__sympy | sympy/geometry/line.py | {
"start": 53808,
"end": 56585
} | class ____(LinearEntity):
"""A base class for all linear entities (line, ray and segment)
in a 2-dimensional Euclidean space.
Attributes
==========
p1
p2
coefficients
slope
points
Notes
=====
This is an abstract class and is not meant to be instantiated.
See Also... | LinearEntity2D |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py | {
"start": 1476,
"end": 2840
} | class ____(GenericFakeChatModel):
tool_style: Literal["openai", "anthropic"] = "openai"
def bind_tools(
self,
tools: typing.Sequence[Union[dict[str, Any], type[BaseModel], typing.Callable, BaseTool]],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
if len(tool... | FakeModel |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 7588,
"end": 8690
} | class ____(Boolean):
"""
Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`.
"""
is_Boolean = True
is_Atom = True
_op_priority = 11 # higher than Expr
def simplify(self, *a, **kw):
return self
def expand(self, *a, **kw):
return self
@property
... | BooleanAtom |
python | getsentry__sentry | src/sentry/web/frontend/oauth_token.py | {
"start": 1652,
"end": 14711
} | class ____(View):
# Token responses must not be cached per RFC 6749 §5.1/§5.2. We apply
# never_cache at dispatch so every response from this endpoint is marked
# appropriately without repeating headers across handlers.
@csrf_exempt
@method_decorator(never_cache)
def dispatch(self, request, *arg... | OAuthTokenView |
python | huggingface__transformers | src/transformers/models/resnet/modeling_resnet.py | {
"start": 1999,
"end": 2907
} | class ____(nn.Module):
"""
ResNet Embeddings (stem) composed of a single aggressive convolution.
"""
def __init__(self, config: ResNetConfig):
super().__init__()
self.embedder = ResNetConvLayer(
config.num_channels, config.embedding_size, kernel_size=7, stride=2, activation=... | ResNetEmbeddings |
python | numpy__numpy | numpy/_core/tests/test_ufunc.py | {
"start": 1002,
"end": 2011
} | class ____:
def test_kwarg_exact(self):
assert_raises(TypeError, np.add, 1, 2, castingx='safe')
assert_raises(TypeError, np.add, 1, 2, dtypex=int)
assert_raises(TypeError, np.add, 1, 2, extobjx=[4096])
assert_raises(TypeError, np.add, 1, 2, outx=None)
assert_raises(TypeError,... | TestUfuncKwargs |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/save_restore_ops_test.py | {
"start": 1271,
"end": 2191
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters(_TEST_DTYPES)
@test_util.run_in_graph_and_eager_modes
def testRelativePath(self, dtype):
os.chdir(self.get_temp_dir())
self.evaluate(
io_ops.save_v2(
"ckpt", ["x"], [""], [constant_op.constant(2, dtype=dtype)... | SaveRestoreTest |
python | walkccc__LeetCode | solutions/1805. Number of Different Integers in a String/1805-2.py | {
"start": 0,
"end": 124
} | class ____:
def numDifferentIntegers(self, word: str) -> int:
return len(set(map(int, re.findall(r'\d+', word))))
| Solution |
python | spack__spack | lib/spack/spack/test/oci/mock_registry.py | {
"start": 9903,
"end": 10520
} | class ____(urllib.request.BaseHandler):
"""Glue between urllib and DummyServer, routing requests to
the correct mock server for a given domain."""
def __init__(self) -> None:
self.servers: Dict[str, DummyServer] = {}
def add_server(self, domain: str, api: DummyServer):
self.servers[dom... | DummyServerUrllibHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.