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 | getsentry__sentry | tests/sentry/event_manager/grouping/test_group_creation_lock.py | {
"start": 303,
"end": 3840
} | class ____:
@staticmethod
@contextlib.contextmanager
def atomic(*args, **kwds):
yield
def save_event(project_id: int, return_values: list[GroupInfo]) -> None:
event = Event(
project_id,
"11212012123120120415201309082013",
data={"timestamp": time.time()},
)
grou... | FakeTransactionModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 687054,
"end": 687624
} | class ____(sgqlc.types.Type):
"""Describes a License's conditions, permissions, and limitations"""
__schema__ = github_schema
__field_names__ = ("description", "key", "label")
description = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="description")
"""A description of the rule"""
... | LicenseRule |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_trace_item_attributes.py | {
"start": 67753,
"end": 69006
} | class ____(
OrganizationTraceItemAttributeValuesEndpointBaseTest, TraceMetricsTestCase
):
feature_flags = {"organizations:tracemetrics-enabled": True}
item_type = SupportedTraceItemType.TRACEMETRICS
def test_no_feature(self) -> None:
response = self.do_request(features={}, key="test.attribute")... | OrganizationTraceItemAttributeValuesEndpointTraceMetricsTest |
python | huggingface__transformers | tests/models/owlvit/test_modeling_owlvit.py | {
"start": 22418,
"end": 33430
} | class ____(unittest.TestCase):
@slow
def test_inference(self):
model_name = "google/owlvit-base-patch32"
model = OwlViTModel.from_pretrained(model_name).to(torch_device)
processor = OwlViTProcessor.from_pretrained(model_name)
image = prepare_img()
inputs = processor(
... | OwlViTModelIntegrationTest |
python | kamyu104__LeetCode-Solutions | Python/confusing-number.py | {
"start": 35,
"end": 498
} | class ____(object):
def confusingNumber(self, N):
"""
:type N: int
:rtype: bool
"""
lookup = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"}
S = str(N)
result = []
for i in xrange(len(S)):
if S[i] not in lookup:
retur... | Solution |
python | pypa__setuptools | setuptools/config/setupcfg.py | {
"start": 25836,
"end": 26588
} | class ____(SetuptoolsDeprecationWarning):
_SUMMARY = "Ambiguous requirement marker."
_DETAILS = """
One of the parsed requirements in `{field}` looks like a valid environment marker:
{req!r}
Please make sure that the configuration file is correct.
You can use dangling lines to avoid this p... | _AmbiguousMarker |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/konlpy.py | {
"start": 238,
"end": 1049
} | class ____(TextSplitter):
"""Splitting text using Konlpy package.
It is good for splitting Korean text.
"""
def __init__(
self,
separator: str = "\n\n",
**kwargs: Any,
) -> None:
"""Initialize the Konlpy text splitter."""
super().__init__(**kwargs)
s... | KonlpyTextSplitter |
python | getsentry__sentry | src/sentry/integrations/msteams/client.py | {
"start": 7102,
"end": 7603
} | class ____(ApiClient):
integration_name = IntegrationProviderSlug.MSTEAMS.value
# 24 hour cache is recommended: https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-authentication?view=azure-bot-service-4.0#connector-to-bot-step-3
cache_time = 60 * 60 * 24
OPEN_ID_CON... | MsTeamsJwtClient |
python | scipy__scipy | scipy/special/tests/test_kolmogorov.py | {
"start": 4219,
"end": 8757
} | class ____:
def test_nan(self):
assert_(np.isnan(smirnovi(1, np.nan)))
def test_basic(self):
dataset = [(1, 0.4, 0.6),
(1, 0.6, 0.4),
(1, 0.99, 0.01),
(1, 0.01, 0.99),
(2, 0.125 * 0.125, 0.875),
(3, 0... | TestSmirnovi |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_partition_status_cache.py | {
"start": 132,
"end": 321
} | class ____(TestPartitionStatusCache):
@pytest.fixture
def instance(self):
with dg.instance_for_test() as the_instance:
yield the_instance
| TestSqlPartitionStatusCache |
python | pytorch__pytorch | torch/nn/modules/padding.py | {
"start": 30090,
"end": 31660
} | class ____(ConstantPad3d):
r"""Pads the input tensor boundaries with zero.
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
Args:
padding (int, tuple): the size of the padding. If is `int`, uses the same
padding in all boundaries. If a 6-`tuple`, uses
(:m... | ZeroPad3d |
python | getsentry__sentry | src/sentry/models/grouplink.py | {
"start": 1080,
"end": 2639
} | class ____(Model):
"""
Link a group with an external resource like a commit, issue, or pull request
"""
__relocation_scope__ = RelocationScope.Excluded
class Relationship:
unknown = 0
resolves = 1
references = 2
class LinkedType:
unknown = 0
commit = 1
... | GroupLink |
python | getsentry__sentry | src/sentry/codecov/endpoints/repository_tokens/serializers.py | {
"start": 189,
"end": 409
} | class ____(serializers.Serializer):
"""
Serializer for individual repository nodes from GraphQL response
"""
name = serializers.CharField()
token = serializers.CharField()
| RepositoryTokenNodeSerializer |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 2627,
"end": 3327
} | class ____(ModelOutput):
r"""
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
"""
image_embeds: Optional[torch.F... | CLIPVisionModelOutput |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 22892,
"end": 23158
} | class ____(RayError):
"""Indicates an error in the underlying RPC system."""
def __init__(self, message, rpc_code=None):
self.message = message
self.rpc_code = rpc_code
def __str__(self):
return self.message
@DeveloperAPI
| RpcError |
python | astropy__astropy | astropy/nddata/nduncertainty.py | {
"start": 2802,
"end": 3015
} | class ____(Exception):
"""This exception should be used to indicate that an uncertainty instance
has not been associated with a parent `~astropy.nddata.NDData` object.
"""
| MissingDataAssociationException |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/config_lib.py | {
"start": 1456,
"end": 1731
} | class ____(Rule):
"""Indicates that this module should be converted."""
def __str__(self):
return 'Convert rule for {}'.format(self._prefix)
def get_action(self, module):
if self.matches(module.__name__):
return Action.CONVERT
return Action.NONE
| Convert |
python | sympy__sympy | sympy/stats/frv.py | {
"start": 5342,
"end": 6513
} | class ____(Distribution, NamedArgsMixin):
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
@property # type: ignore
@cacheit
def dict(self):
if self.is_symbolic:
return Den... | SingleFiniteDistribution |
python | pyca__cryptography | tests/x509/test_ocsp.py | {
"start": 43296,
"end": 57707
} | class ____:
def test_bad_response(self):
with pytest.raises(ValueError):
ocsp.load_der_ocsp_response(b"invalid")
def test_load_response(self):
resp = _load_data(
os.path.join("x509", "ocsp", "resp-sha256.der"),
ocsp.load_der_ocsp_response,
)
i... | TestOCSPResponse |
python | pandas-dev__pandas | pandas/tests/series/methods/test_argsort.py | {
"start": 125,
"end": 2539
} | class ____:
def test_argsort_axis(self):
# GH#54257
ser = Series(range(3))
msg = "No axis named 2 for object type Series"
with pytest.raises(ValueError, match=msg):
ser.argsort(axis=2)
def test_argsort_numpy(self, datetime_series):
ser = datetime_series
... | TestSeriesArgsort |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/base.py | {
"start": 656,
"end": 824
} | class ____(str, Enum):
"""The kinds of rag data examples."""
HUMAN = "human"
AI = "ai"
def __str__(self) -> str:
return self.value
| CreatedByType |
python | huggingface__transformers | src/transformers/models/dots1/modeling_dots1.py | {
"start": 20704,
"end": 21702
} | class ____(PreTrainedModel):
config: Dots1Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Dots1DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
... | Dots1PreTrainedModel |
python | great-expectations__great_expectations | tests/integration/fixtures/partition_and_sample_data/sampler_test_cases_and_fixtures.py | {
"start": 157,
"end": 785
} | class ____:
def __init__(self, test_df: pd.DataFrame, test_column_name: str):
self._test_df = test_df
self._test_column_name = test_column_name
@property
def test_df(self):
return self._test_df
@property
def test_column_name(self):
return self._test_column_name
... | SamplerTaxiTestData |
python | getsentry__sentry | src/sentry/similarity/features.py | {
"start": 920,
"end": 1215
} | class ____:
def __init__(self, function):
self.function = function
def extract(self, event):
try:
interface = event.interfaces["logentry"]
except KeyError:
raise InterfaceDoesNotExist()
return self.function(interface)
| MessageFeature |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 13158,
"end": 13229
} | class ____(nodes.Part, nodes.TextElement):
"""Deprecated."""
| centered |
python | tensorflow__tensorflow | tensorflow/compiler/tests/image_ops_test.py | {
"start": 26334,
"end": 29872
} | class ____(parameterized.TestCase, xla_test.XLATestCase):
def _assertForwardOpMatchesExpected(self,
image_np,
target_shape,
expected=None,
large_tolerance=False,
... | ResizeBilinearTest |
python | django__django | django/views/generic/dates.py | {
"start": 12852,
"end": 13354
} | class ____(BaseDateListView):
"""
Base view for archives of date-based items.
This requires subclassing to provide a response mixin.
"""
context_object_name = "latest"
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
qs = self.get_dat... | BaseArchiveIndexView |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_repositories.py | {
"start": 9718,
"end": 11880
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user)
org = self.create_organization(owner=self.user, name="baz")
with patch.object(DummyRepositoryProvider, "needs_auth", return_value=False):
url = reverse("sentry-api-0-organization-repositories"... | OrganizationRepositoriesCreateTest |
python | milvus-io__pymilvus | tests/test_schema.py | {
"start": 203,
"end": 2200
} | class ____:
@pytest.fixture(scope="function")
def raw_dict(self):
return {
"description": "TestCollectionSchema_description",
"enable_dynamic_field": True,
"fields": [
{
"name": "vec1",
"description": "desc1",
... | TestCollectionSchema |
python | astropy__astropy | astropy/time/tests/test_ut1.py | {
"start": 2558,
"end": 4560
} | class ____:
"""Test Time.ut1 using IERS tables"""
def test_ut1_to_utc(self):
"""Also test the reverse, around the leap second
(round-trip test closes #2077)"""
with iers_conf.set_temp("auto_download", False):
t = Time(
[
"2012-06-30 12:00:... | TestTimeUT1 |
python | django-extensions__django-extensions | django_extensions/management/commands/show_template_tags.py | {
"start": 2112,
"end": 3915
} | class ____(BaseCommand):
help = "Displays template tags and filters available in the current project."
results = ""
def add_result(self, s, depth=0):
self.results += "%s\n" % s.rjust(depth * 4 + len(s))
@signalcommand
def handle(self, *args, **options):
if options["no_color"]:
... | Command |
python | huggingface__transformers | src/transformers/models/exaone4/modular_exaone4.py | {
"start": 14252,
"end": 14291
} | class ____(Olmo2MLP):
pass
| Exaone4MLP |
python | pypa__hatch | tests/project/test_core.py | {
"start": 3011,
"end": 3280
} | class ____:
def test_selected(self, temp_dir):
project = Project(temp_dir, name="foo")
assert project.chosen_name == "foo"
def test_cwd(self, temp_dir):
project = Project(temp_dir)
assert project.chosen_name is None
| TestChosenName |
python | anthropics__anthropic-sdk-python | src/anthropic/types/model_info.py | {
"start": 215,
"end": 646
} | class ____(BaseModel):
id: str
"""Unique model identifier."""
created_at: datetime
"""RFC 3339 datetime string representing the time at which the model was released.
May be set to an epoch value if the release date is unknown.
"""
display_name: str
"""A human-readable name for the mod... | ModelInfo |
python | google__pytype | pytype/tools/xref/callgraph.py | {
"start": 240,
"end": 348
} | class ____:
name: str
node_type: str
type: Any
attrib: str
location: str
@dataclasses.dataclass
| Attr |
python | python__mypy | mypy/types.py | {
"start": 50697,
"end": 52831
} | class ____:
"""Summary of module attributes and types.
This is used for instances of types.ModuleType, because they can have different
attributes per instance, and for type narrowing with hasattr() checks.
"""
def __init__(
self,
attrs: dict[str, Type],
immutable: set[str] ... | ExtraAttrs |
python | getsentry__sentry | src/sentry/replays/endpoints/project_replay_details.py | {
"start": 1185,
"end": 3613
} | class ____(ProjectEndpoint):
owner = ApiOwner.REPLAY
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (ReplayDetailsPermission,)
def get(self, request: Request, project: Project, replay_id: str) -> Response:
if no... | ProjectReplayDetailsEndpoint |
python | redis__redis-py | tests/test_cache.py | {
"start": 43995,
"end": 48440
} | class ____:
def test_type(self):
policy = LRUPolicy()
assert policy.type == EvictionPolicyType.time_based
def test_evict_next(self, mock_connection):
cache = DefaultCache(
CacheConfig(max_size=5, eviction_policy=EvictionPolicy.LRU)
)
policy = cache.eviction_p... | TestUnitLRUPolicy |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass6.py | {
"start": 1298,
"end": 1601
} | class ____(Protocol):
def __call__(self) -> None:
pass
def func7(obj: CallableProto):
match obj:
case Callable():
reveal_type(obj, expected_text="CallableProto")
return obj()
case x:
reveal_type(obj, expected_text="Never")
| CallableProto |
python | tensorflow__tensorflow | tensorflow/python/training/saving/saveable_object_util_test.py | {
"start": 3964,
"end": 4449
} | class ____(saveable_object.SaveableObject):
def __init__(self, obj, name):
self.obj = obj
specs = [
saveable_object.SaveSpec(obj.a, "", name + "-a"),
saveable_object.SaveSpec(obj.b, "", name + "-b")]
super(_MultiSpecSaveable, self).__init__(None, specs, name)
def restore(self, restored... | _MultiSpecSaveable |
python | getsentry__sentry | src/sentry/backup/services/import_export/model.py | {
"start": 7075,
"end": 7573
} | class ____(str, Enum):
"""
Scope values are rendered as strings for JSON interchange, but can easily be mapped back to
their set-based values when necessary.
"""
User = "User"
Organization = "Organization"
Config = "Config"
Global = "Global"
def from_rpc(self) -> ExportScope:
... | RpcExportScope |
python | uqfoundation__dill | dill/_dill.py | {
"start": 23023,
"end": 36074
} | class ____:
"""
Make avaialable a limited structural pattern matching-like syntax for Python < 3.10
Patterns can be only tuples (without types) currently.
Inspired by the package pattern-matching-PEP634.
Usage:
>>> with match(args) as m:
>>> if m.case(('x', 'y')):
>>> # u... | match |
python | kamyu104__LeetCode-Solutions | Python/remove-adjacent-almost-equal-characters.py | {
"start": 38,
"end": 420
} | class ____(object):
def removeAlmostEqualCharacters(self, word):
"""
:type word: str
:rtype: int
"""
result = 0
for i in xrange(len(word)-1):
if (i+1)+result >= len(word):
break
if abs(ord(word[(i+1)+result])-ord(word[i+result])... | Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 121175,
"end": 123637
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class SubItem(Base):
__tablename__ = "sub_items"
id = Column(Integer, primary_key=True, autoincrement=True)
item_id = Column(Integer, ForeignKey("ite... | Issue11173Test |
python | pypa__warehouse | tests/unit/admin/views/test_sponsors.py | {
"start": 3210,
"end": 5099
} | class ____:
def test_serialize_form_to_create_sponsor(self, db_request):
result = views.create_sponsor(db_request)
assert len(result) == 1
assert isinstance(result["form"], views.SponsorForm)
def test_serialize_form_errors_if_invalid_post(self, db_request):
db_request.method = ... | TestCreateSponsor |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 2917,
"end": 3004
} | class ____(TestRss2Feed):
feed_type = feedgenerator.RssUserland091Feed
| TestRss091Feed |
python | pallets__jinja | src/jinja2/lexer.py | {
"start": 13395,
"end": 13527
} | class ____(t.NamedTuple):
pattern: t.Pattern[str]
tokens: str | tuple[str, ...] | tuple[Failure]
command: str | None
| _Rule |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial002_py39.py | {
"start": 610,
"end": 3197
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
teams: list[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
sqlite_file_name = "da... | Hero |
python | getsentry__sentry | src/sentry/notifications/notification_action/types.py | {
"start": 14664,
"end": 20071
} | class ____(ABC):
ACTIVITIES_TO_INVOKE_ON = [ActivityType.SET_RESOLVED.value]
@classmethod
def build_notification_context(cls, action: Action) -> NotificationContext:
return NotificationContext.from_action_model(action)
@classmethod
def build_alert_context(
cls,
detector: De... | BaseMetricAlertHandler |
python | pandas-dev__pandas | pandas/tests/libs/test_libalgos.py | {
"start": 1399,
"end": 3474
} | class ____:
def test_backfill(self):
old = np.array([1, 5, 10], dtype=np.int64)
new = np.array(list(range(12)), dtype=np.int64)
filler = libalgos.backfill["int64_t"](old, new)
expect_filler = np.array([0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, -1], dtype=np.intp)
tm.assert_numpy_arr... | TestPadBackfill |
python | plotly__plotly.py | plotly/graph_objs/mesh3d/colorbar/title/_font.py | {
"start": 233,
"end": 9908
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "mesh3d.colorbar.title"
_path_str = "mesh3d.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Font |
python | encode__starlette | starlette/responses.py | {
"start": 817,
"end": 5807
} | class ____:
media_type = None
charset = "utf-8"
def __init__(
self,
content: Any = None,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:
self.sta... | Response |
python | PyCQA__pylint | doc/data/messages/b/bad-classmethod-argument/good.py | {
"start": 0,
"end": 78
} | class ____:
@classmethod
def get_instance(cls):
return cls()
| Klass |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels38.py | {
"start": 315,
"end": 1659
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels38.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 1285,
"end": 1473
} | class ____(Package):
version("2.1")
version("2.0")
variant("v1", default=True)
depends_on("y4@4.1", when="+v1")
depends_on("y4")
""",
)
_pkgy3 = (
"y3",
"""\
| Y2 |
python | pytest-dev__pytest | src/_pytest/logging.py | {
"start": 1801,
"end": 2746
} | class ____(logging.Formatter):
"""A logging formatter which formats record with
:func:`datetime.datetime.strftime` formatter instead of
:func:`time.strftime` in case of microseconds in format string.
"""
def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str:
if datefmt ... | DatetimeFormatter |
python | django__django | tests/model_forms/models.py | {
"start": 6474,
"end": 6534
} | class ____(models.Model):
url = models.URLField()
| Homepage |
python | django__django | tests/model_enums/tests.py | {
"start": 9896,
"end": 10846
} | class ____(SimpleTestCase):
def test_labels_valid(self):
enums = (
Separator,
Constants,
Set,
MoonLandings,
DateAndTime,
MealTimes,
Frequency,
Number,
IPv4Address,
IPv6Address,
... | CustomChoicesTests |
python | fastai__fastai | fastai/torch_core.py | {
"start": 23962,
"end": 24171
} | class ____(Str, ShowTitle):
_show_args = {'label': 'text'}
def show(self, ctx=None, **kwargs):
"Show self"
return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))
| TitledStr |
python | keon__algorithms | algorithms/linkedlist/remove_duplicates.py | {
"start": 0,
"end": 1264
} | class ____():
def __init__(self, val = None):
self.val = val
self.next = None
def remove_dups(head):
"""
Time Complexity: O(N)
Space Complexity: O(N)
"""
hashset = set()
prev = Node()
while head:
if head.val in hashset:
prev.next = head.next
e... | Node |
python | huggingface__transformers | src/transformers/models/informer/modeling_informer.py | {
"start": 8792,
"end": 10382
} | class ____(nn.Embedding):
"""This module produces sinusoidal positional embeddings of any length."""
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
super().__init__(num_positions, embedding_dim, _freeze=True)
def create_weight(self):
... | InformerSinusoidalPositionalEmbedding |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/caching_instance_queryer.py | {
"start": 2276,
"end": 49375
} | class ____(DynamicPartitionsStore):
"""Provides utility functions for querying for asset-materialization related data from the
instance which will attempt to limit redundant expensive calls. Intended for use within the
scope of a single "request" (e.g. GQL request, sensor tick).
Args:
instance ... | CachingInstanceQueryer |
python | django__django | django/test/client.py | {
"start": 22068,
"end": 25780
} | class ____(RequestFactory):
"""
Class that lets you create mock ASGI-like Request objects for use in
testing. Usage:
rf = AsyncRequestFactory()
get_request = rf.get("/hello/")
post_request = rf.post("/submit/", {"foo": "bar"})
Once you have a request object you can pass it to any view func... | AsyncRequestFactory |
python | pytorch__pytorch | test/distributed/tensor/test_convolution_ops.py | {
"start": 1045,
"end": 12894
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
# hard code world size to 2
return 2
@with_comms
def test_downsampling_convolution(self):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(3)]
input_list = torch.rand(ITER_TIME, 7, 3, ... | DistConvolutionOpsTest |
python | pypa__pipenv | pipenv/patched/pip/_internal/cli/cmdoptions.py | {
"start": 3904,
"end": 32044
} | class ____(Option):
TYPES = Option.TYPES + ("path", "package_name")
TYPE_CHECKER = Option.TYPE_CHECKER.copy()
TYPE_CHECKER["package_name"] = _package_name_option_check
TYPE_CHECKER["path"] = _path_option_check
###########
# options #
###########
help_: Callable[..., Option] = partial(
Option,
... | PipOption |
python | langchain-ai__langchain | libs/core/langchain_core/language_models/fake.py | {
"start": 465,
"end": 2057
} | class ____(LLM):
"""Fake LLM for testing purposes."""
responses: list[str]
"""List of responses to return in order."""
# This parameter should be removed from FakeListLLM since
# it's only used by sub-classes.
sleep: float | None = None
"""Sleep time in seconds between responses.
Ignor... | FakeListLLM |
python | ray-project__ray | python/ray/_private/external_storage.py | {
"start": 2276,
"end": 9311
} | class ____(metaclass=abc.ABCMeta):
"""The base class for external storage.
This class provides some useful functions for zero-copy object
put/get from plasma store. Also it specifies the interface for
object spilling.
When inheriting this class, please make sure to implement validation
logic i... | ExternalStorage |
python | huggingface__transformers | utils/test_module/custom_pipeline.py | {
"start": 239,
"end": 1100
} | class ____(Pipeline):
def _sanitize_parameters(self, **kwargs):
preprocess_kwargs = {}
if "second_text" in kwargs:
preprocess_kwargs["second_text"] = kwargs["second_text"]
return preprocess_kwargs, {}, {}
def preprocess(self, text, second_text=None):
return self.toke... | PairClassificationPipeline |
python | getsentry__sentry | tests/sentry/middleware/test_access_log_middleware.py | {
"start": 6461,
"end": 7846
} | class ____(LogCaptureAPITestCase):
endpoint = "snuba-ratelimit-endpoint"
def test_access_log_snuba_rate_limited(self) -> None:
"""Test that Snuba rate limits are properly logged by access log middleware."""
self._caplog.set_level(logging.INFO, logger="sentry")
self.get_error_response(st... | TestAccessLogSnubaRateLimited |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 69149,
"end": 69464
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("headline", "body")
headline = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="headline")
body = sgqlc.types.Field(String, graphql_name="body")
| CommitMessage |
python | spack__spack | var/spack/test_repos/spack_repo/duplicates_test/packages/hdf5/package.py | {
"start": 216,
"end": 554
} | class ____(Package):
"""Requires gmake at a version that doesn't match that of its dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/tdep-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
depends_on("pinned-gmake", type="link")
depends_on("gmake@... | Hdf5 |
python | spyder-ide__spyder | spyder/plugins/pylint/main_widget.py | {
"start": 2565,
"end": 3992
} | class ____(QTreeWidgetItem):
"""
Category item for results.
Notes
-----
Possible categories are Convention, Refactor, Warning and Error.
"""
CATEGORIES = {
"Convention": {
'translation_string': _("Convention"),
'icon': ima.icon("convention")
},
... | CategoryItem |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox11.py | {
"start": 315,
"end": 868
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox11.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/65. Valid Number/65.py | {
"start": 0,
"end": 641
} | class ____:
def isNumber(self, s: str) -> bool:
s = s.strip()
if not s:
return False
seenNum = False
seenDot = False
seenE = False
for i, c in enumerate(s):
if c == '.':
if seenDot or seenE:
return False
seenDot = True
elif c == 'e' or c == 'E':
... | Solution |
python | great-expectations__great_expectations | great_expectations/data_context/data_context_variables.py | {
"start": 8055,
"end": 8546
} | class ____(DataContextVariables):
@override
def _init_store(self) -> DataContextStore:
from great_expectations.data_context.store.data_context_store import (
DataContextStore,
)
store = DataContextStore(
store_name="ephemeral_data_context_store",
stor... | EphemeralDataContextVariables |
python | django-haystack__django-haystack | haystack/fields.py | {
"start": 7565,
"end": 8673
} | class ____(SearchField):
field_type = "location"
def prepare(self, obj):
from haystack.utils.geo import ensure_point
value = super().prepare(obj)
if value is None:
return None
pnt = ensure_point(value)
pnt_lng, pnt_lat = pnt.coords
return "%s,%s" %... | LocationField |
python | google__jax | docs/autodidax.py | {
"start": 5458,
"end": 6979
} | class ____(NamedTuple):
level: int
trace_type: type['Trace']
global_data: Any | None
trace_stack: list[MainTrace] = []
dynamic_trace: MainTrace | None = None # to be employed in Part 3
@contextmanager
def new_main(trace_type: type['Trace'], global_data=None):
level = len(trace_stack)
main = MainTrace(level... | MainTrace |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/common_transformers/anf.py | {
"start": 1758,
"end": 2803
} | class ____(collections.namedtuple(
'ASTEdgePattern', ['parent', 'field', 'child'])):
"""A pattern defining a type of AST edge.
This consists of three components:
- The type of the parent node, checked with isinstance,
- The name of the field, checked with string equality, and
- The type of the child node... | ASTEdgePattern |
python | neetcode-gh__leetcode | python/0303-range-sum-query-immutable.py | {
"start": 0,
"end": 357
} | class ____:
def __init__(self, nums: List[int]):
self.prefix = []
cur = 0
for n in nums:
cur += n
self.prefix.append(cur)
def sumRange(self, left: int, right: int) -> int:
r = self.prefix[right]
l = self.prefix[left - 1] if left... | NumArray |
python | keras-team__keras | keras/src/distillation/distiller_test.py | {
"start": 1064,
"end": 18187
} | class ____(TestCase):
"""Essential test cases for the Distiller class."""
def setUp(self):
"""Set up test fixtures."""
super().setUp()
# Create test data
self.x = np.random.random((20, 5)).astype(np.float32)
self.y = np.random.randint(0, 10, (20,)).astype(np.int32)
... | TestDistiller |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 227882,
"end": 232625
} | class ____(TestCase):
def test_array_scalar_relational_operation(self):
# All integer
for dt1 in np.typecodes["AllInteger"]:
assert_(1 > np.array(0, dtype=dt1), f"type {dt1} failed")
assert_(not 1 < np.array(0, dtype=dt1), f"type {dt1} failed")
for dt2 in np.type... | TestConversion |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 7883,
"end": 8191
} | class ____:
async def process_spider_exception(self, response, exception):
yield {"foo": 1}
d = defer.Deferred()
call_later(0, d.callback, None)
await maybe_deferred_to_future(d)
yield {"foo": 2}
yield {"foo": 3}
| ProcessSpiderExceptionAsyncIteratorMiddleware |
python | realpython__materials | python-312/typing/accounts.py | {
"start": 345,
"end": 701
} | class ____:
account_number: str
balance: float
@classmethod
def from_balance(cls, balance: float) -> Self:
return cls(generate_account_number(), balance)
def deposit(self, amount: float) -> None:
self.balance += amount
def withdraw(self, amount: float) -> None:
self.ba... | BankAccount |
python | getsentry__sentry | src/sentry/integrations/jira_server/integration.py | {
"start": 4841,
"end": 4917
} | class ____(TypedDict):
on_resolve: str
on_unresolve: str
| _ColumnLabels |
python | tiangolo__fastapi | docs_src/extra_models/tutorial002.py | {
"start": 264,
"end": 300
} | class ____(UserBase):
pass
| UserOut |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_area05.py | {
"start": 315,
"end": 1536
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_area05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | Lightning-AI__lightning | examples/fabric/build_your_own_trainer/trainer.py | {
"start": 523,
"end": 23333
} | class ____:
def __init__(
self,
accelerator: Union[str, Accelerator] = "auto",
strategy: Union[str, Strategy] = "auto",
devices: Union[list[int], str, int] = "auto",
precision: Union[str, int] = "32-true",
plugins: Optional[Union[str, Any]] = None,
callbacks: ... | MyCustomTrainer |
python | explosion__spaCy | spacy/lang/fr/__init__.py | {
"start": 741,
"end": 1380
} | class ____(Language):
lang = "fr"
Defaults = FrenchDefaults
@French.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={
"model": None,
"mode": "rule",
"overwrite": False,
"scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"},
},
default_score_wei... | French |
python | pytorch__pytorch | test/inductor/test_flex_flash.py | {
"start": 7700,
"end": 24012
} | class ____(InductorTestCase):
@dtypes(torch.float16, torch.bfloat16)
def test_flash_attention_basic(self, device, dtype):
q, k, v = create_test_tensors(dtype=dtype, device=device)
flash_vs_triton(q, k, v)
@dtypes(torch.float16, torch.bfloat16)
@parametrize("score_mod", [_times_two, _cau... | TestFlexFlash |
python | has2k1__plotnine | plotnine/_utils/context.py | {
"start": 2389,
"end": 3906
} | class ____:
"""
Context within which a plot composition is built
Parameters
----------
cmp :
composition object to be built within the context.
show :
Whether to show the plot.
"""
cmp: Compose
show: bool
def __post_init__(self):
import matplotlib as mp... | plot_composition_context |
python | mlflow__mlflow | dev/clint/src/clint/linter.py | {
"start": 2924,
"end": 4012
} | class ____:
rule: rules.Rule
path: Path
range: Range
cell: int | None = None
def __str__(self) -> str:
# Use the same format as ruff
cell_loc = f"cell {self.cell}:" if self.cell is not None else ""
return (
# Since `Range` is 0-indexed, lineno and col_offset are ... | Violation |
python | google__pytype | pytype/pyi/parser_test.py | {
"start": 17809,
"end": 18442
} | class ____(parser_test_base.ParserTestBase):
def test_annotation(self):
self.check(
"""
class A: ...
x: "A"
y: "List[A]" = ...
""",
"""
x: A
y: List[A] = ...
class A: ...
""",
)
def test_def(self):
self.check(
"""
def f(x: "int... | QuotedTypeTest |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/utils.py | {
"start": 3393,
"end": 3480
} | class ____(TypedDict):
type: str
decayedValue: NotRequired[str | None]
| DecayingFn |
python | google__jax | jax/_src/cudnn/fused_attention_stablehlo.py | {
"start": 2315,
"end": 2373
} | class ____(enum.Enum):
BTNH = 0
BNTH = 1
| AttentionLayout |
python | getsentry__sentry | tests/sentry/api/serializers/test_apitoken.py | {
"start": 238,
"end": 527
} | class ____(TestCase):
def setUp(self) -> None:
self._user = self.create_user()
self._scopes = ["test_scope"]
self._token = self.create_user_auth_token(user=self._user, scope_list=self._scopes)
self._serializer = ApiTokenSerializer()
| TestApiTokenSerializer |
python | pydata__xarray | xarray/tests/test_merge.py | {
"start": 32679,
"end": 35398
} | class ____:
def test_merge_datasets_false_warning(self):
data = create_test_data(add_attrs=False, use_extension_array=True)
with set_options(use_new_combine_kwarg_defaults=False):
old = xr.merge([data, data])
with set_options(use_new_combine_kwarg_defaults=True):
ne... | TestNewDefaults |
python | realpython__materials | hangman-pysimplegui/source_code_step_5/hangman.py | {
"start": 112,
"end": 6950
} | class ____:
def __init__(self) -> None:
layout = [
[
self._build_canvas_frame(),
self._build_letters_frame(),
],
[
self._build_guessed_word_frame(),
],
[
self._build_action_buttons_fra... | Hangman |
python | arrow-py__arrow | arrow/locales.py | {
"start": 51989,
"end": 52086
} | class ____(PortugueseLocale):
names = ["pt-br"]
past = "faz {0}"
| BrazilianPortugueseLocale |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 8904,
"end": 9798
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_delete_deidentify_template(self, mock_hook):
mock_hook.return_value.delete_deidentify_template.return_value = mock.MagicMock()
operator = CloudDLPDeleteDeidentifyTemplateOperator(
template_i... | TestCloudDLPDeleteDeidentifyTemplateOperator |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 10927,
"end": 11007
} | class ____(Exception):
"""Contract source cannot be parsed."""
| ParserException |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.