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 | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/step_function.py | {
"start": 1514,
"end": 2099
} | class ____(BaseAwsLink):
"""Helper class for constructing link to State Machine Execution details page."""
name = "State Machine Executions Details"
key = "_state_machine_executions_details"
format_str = (
BASE_AWS_CONSOLE_LINK + "/states/home?region={region_name}#/v2/executions/details/{execut... | StateMachineExecutionsDetailsLink |
python | bokeh__bokeh | src/bokeh/models/map_plots.py | {
"start": 2622,
"end": 3435
} | class ____(Plot):
''' Abstract base class for map plot models.
'''
def __init__(self, *args, **kwargs) -> None:
from ..models.ranges import Range1d
for r in ('x_range', 'y_range'):
if r in kwargs and not isinstance(kwargs.get(r), Range1d):
raise ValueError(f"Inv... | MapPlot |
python | django__django | tests/sites_framework/models.py | {
"start": 137,
"end": 328
} | class ____(models.Model):
title = models.CharField(max_length=50)
objects = models.Manager()
on_site = CurrentSiteManager()
class Meta:
abstract = True
| AbstractArticle |
python | ashishps1__awesome-system-design-resources | implementations/python/rate_limiting/sliding_window_counter.py | {
"start": 13,
"end": 1493
} | class ____:
def __init__(self, window_size, max_requests):
self.window_size = window_size # Size of the sliding window in seconds
self.max_requests = max_requests # Maximum number of requests per window
self.current_window = time.time() // window_size
self.request_count = 0
... | SlidingWindowCounter |
python | python-jsonschema__jsonschema | jsonschema/tests/test_exceptions.py | {
"start": 11006,
"end": 12995
} | class ____(TestCase):
def test_short_paths_are_better_matches(self):
shallow = exceptions.ValidationError("Oh no!", path=["baz"])
deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])
match = max([shallow, deep], key=exceptions.relevance)
self.assertIs(match, shallow)
... | TestByRelevance |
python | walkccc__LeetCode | solutions/789. Escape The Ghosts/789.py | {
"start": 0,
"end": 253
} | class ____:
def escapeGhosts(self, ghosts: list[list[int]], target: list[int]) -> bool:
ghostSteps = min(abs(x - target[0]) +
abs(y - target[1]) for x, y in ghosts)
return abs(target[0]) + abs(target[1]) < ghostSteps
| Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_sensors.py | {
"start": 11684,
"end": 25218
} | class ____(NonLaunchableGraphQLContextTestMatrix):
@pytest.mark.parametrize(
"sensor_name, expected_type",
[
("always_no_config_sensor_with_tags_and_metadata", "STANDARD"),
("run_status", "RUN_STATUS"),
("single_asset_sensor", "ASSET"),
("many_asset_se... | TestSensors |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 32748,
"end": 32972
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ABUSE", "DUPLICATE", "OFF_TOPIC", "OUTDATED", "RESOLVED", "SPAM")
| ReportedContentClassifiers |
python | apache__airflow | airflow-core/tests/unit/listeners/file_write_listener.py | {
"start": 979,
"end": 1917
} | class ____:
def __init__(self, path):
self.path = path
def write(self, line: str):
with open(self.path, "a") as f:
f.write(line + "\n")
@hookimpl
def on_task_instance_running(self, previous_state, task_instance):
self.write("on_task_instance_running")
@hookimpl... | FileWriteListener |
python | django__django | tests/delete/models.py | {
"start": 5058,
"end": 5194
} | class ____(models.Model):
desc = models.TextField(null=True)
# This model is used to test a duplicate query regression (#25685)
| Avatar |
python | django__django | django/template/defaulttags.py | {
"start": 8411,
"end": 10370
} | class ____(Node):
child_nodelists = ("nodelist_true", "nodelist_false")
def __init__(self, nodelist_true, nodelist_false, *varlist):
self.nodelist_true = nodelist_true
self.nodelist_false = nodelist_false
self._varlist = varlist
def render(self, context):
# Init state stora... | IfChangedNode |
python | kamyu104__LeetCode-Solutions | Python/diameter-of-n-ary-tree.py | {
"start": 213,
"end": 1048
} | class ____(object):
def diameter(self, root):
"""
:type root: 'Node'
:rtype: int
"""
def iter_dfs(root):
result = [0]*2
stk = [(1, (root, result))]
while stk:
step, params = stk.pop()
if step == 1:
... | Solution |
python | astral-sh__uv | crates/uv-python/fetch-download-metadata.py | {
"start": 5643,
"end": 16262
} | class ____(Finder):
implementation = ImplementationName.CPYTHON
RELEASE_URL = (
"https://api.github.com/repos/astral-sh/python-build-standalone/releases"
)
FLAVOR_PREFERENCES = [
"install_only_stripped",
"install_only",
"shared-pgo",
"shared-noopt",
"sta... | CPythonFinder |
python | pandas-dev__pandas | pandas/tests/io/formats/test_eng_formatting.py | {
"start": 278,
"end": 8454
} | class ____:
def test_eng_float_formatter2(self, float_frame):
df = float_frame
df.loc[5] = 0
set_eng_float_format()
repr(df)
set_eng_float_format(use_eng_prefix=True)
repr(df)
set_eng_float_format(accuracy=0)
repr(df)
def test_eng_float_formatt... | TestEngFormatter |
python | hynek__structlog | src/structlog/processors.py | {
"start": 20945,
"end": 23554
} | class ____(enum.Enum):
"""
Callsite parameters that can be added to an event dictionary with the
`structlog.processors.CallsiteParameterAdder` processor class.
The string values of the members of this enum will be used as the keys for
the callsite parameters in the event dictionary.
.. version... | CallsiteParameter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple27.py | {
"start": 225,
"end": 945
} | class ____(Generic[*Ts, T]): ...
def deco1(x: Callable[[*tuple[*Ts, int]], None]) -> tuple[*Ts]: ...
def deco2(x: Callable[[*tuple[*Ts, str]], None]) -> tuple[*Ts]: ...
def deco3(x: Callable[[*tuple[str, int]], None]) -> None: ...
def deco4(x: Callable[[*Ts, T], None]) -> A[*Ts, T]:
return A()
def func1(a... | A |
python | django__django | tests/gis_tests/layermap/models.py | {
"start": 485,
"end": 816
} | class ____(NamedModel):
name_txt = models.TextField(default="")
name_short = models.CharField(max_length=5)
population = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
dt = models.DateField()
point = models.PointField()
class Meta:
app_label = "l... | City |
python | pypa__hatch | backend/src/hatchling/builders/plugin/interface.py | {
"start": 1007,
"end": 16217
} | class ____(ABC, Generic[BuilderConfigBound, PluginManagerBound]):
"""
Example usage:
```python tab="plugin.py"
from hatchling.builders.plugin.interface import BuilderInterface
class SpecialBuilder(BuilderInterface):
PLUGIN_NAME = "special"
...
```
```python tab="hooks.py"... | BuilderInterface |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_itertools.py | {
"start": 111089,
"end": 113883
} | class ____(__TestCase):
def test_sf_793826(self):
# Fix Armin Rigo's successful efforts to wreak havoc
def mutatingtuple(tuple1, f, tuple2):
# this builds a tuple t which is a copy of tuple1,
# then calls f(t), then mutates t to be equal to tuple2
# (needs len(t... | RegressionTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_vendored/dateutil/tz/tz.py | {
"start": 28028,
"end": 33860
} | class ____(tzrangebase):
"""
The ``tzrange`` object is a time zone specified by a set of offsets and
abbreviations, equivalent to the way the ``TZ`` variable can be specified
in POSIX-like systems, but using Python delta objects to specify DST
start, end and offsets.
:param stdabbr:
The... | tzrange |
python | Textualize__textual | tests/test_path.py | {
"start": 281,
"end": 361
} | class ____(App[None]):
CSS_PATH = Path("/tmp/test.tcss")
| AbsolutePathObjectApp |
python | django__django | tests/admin_changelist/admin.py | {
"start": 3818,
"end": 4046
} | class ____(admin.ModelAdmin):
list_display_links = None
list_display = ["name"]
list_editable = ["name"]
actions_on_bottom = True
site.register(Parent, NoListDisplayLinksParentAdmin)
| NoListDisplayLinksParentAdmin |
python | wandb__wandb | wandb/_pydantic/base.py | {
"start": 5116,
"end": 5727
} | class ____(GQLBase, ABC):
# For GraphQL inputs, exclude null values when preparing JSON-able request
# data.
__DUMP_DEFAULTS: ClassVar[Dict[str, Any]] = dict(exclude_none=True)
@override
def model_dump(self, *, mode: str = "json", **kwargs: Any) -> dict[str, Any]:
kwargs = {**self.__DUMP_DE... | GQLInput |
python | jazzband__django-pipeline | tests/tests/test_compiler.py | {
"start": 5997,
"end": 6831
} | class ____(TestCase):
def setUp(self):
default_collector.collect()
self.compiler = Compiler()
def test_compile(self):
with self.assertRaises(CompilerError) as cm:
self.compiler.compile([_("pipeline/js/dummy.coffee")])
e = cm.exception
self.assertEqual... | InvalidCompilerTest |
python | getsentry__sentry | src/sentry/integrations/services/integration/model.py | {
"start": 662,
"end": 1699
} | class ____(RpcModel):
id: int
provider: str
external_id: str
name: str
metadata: dict[str, Any] = Field(repr=False)
status: int
def __hash__(self) -> int:
return hash(self.id)
def get_status_display(self) -> str:
for status_id, display in ObjectStatus.as_choices():
... | RpcIntegration |
python | RaRe-Technologies__gensim | gensim/test/test_word2vec.py | {
"start": 57536,
"end": 58536
} | class ____(unittest.TestCase):
def test_word2vec_stand_alone_script(self):
"""Does Word2Vec script launch standalone?"""
cmd = [
sys.executable, '-m', 'gensim.scripts.word2vec_standalone',
'-train', datapath('testcorpus.txt'),
'-output', 'vec.txt', '-size', '200',... | TestWord2VecScripts |
python | tensorflow__tensorflow | tensorflow/python/module/module_test.py | {
"start": 13042,
"end": 13161
} | class ____(module.Module, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __call__(self, x):
pass
| AbstractModule |
python | jazzband__django-redis | django_redis/cache.py | {
"start": 1115,
"end": 8190
} | class ____(BaseCache):
def __init__(self, server: str, params: dict[str, Any]) -> None:
super().__init__(params)
self._server = server
self._params = params
self._default_scan_itersize = getattr(
settings,
"DJANGO_REDIS_SCAN_ITERSIZE",
10,
... | RedisCache |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/graalpy/__init__.py | {
"start": 345,
"end": 2330
} | class ____(ViaGlobalRefVirtualenvBuiltin, ABC):
@classmethod
def can_describe(cls, interpreter):
return interpreter.implementation == "GraalVM" and super().can_describe(interpreter)
@classmethod
def exe_stem(cls):
return "graalpy"
@classmethod
def exe_names(cls, interpreter):
... | GraalPy |
python | huggingface__transformers | tests/models/biogpt/test_tokenization_biogpt.py | {
"start": 919,
"end": 4277
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "microsoft/biogpt"
tokenizer_class = BioGptTokenizer
test_rust_tokenizer = False
@classmethod
def setUpClass(cls):
super().setUpClass()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/sub... | BioGptTokenizationTest |
python | getsentry__sentry | src/sentry/integrations/pagerduty/actions/notification.py | {
"start": 1000,
"end": 6673
} | class ____(IntegrationEventAction):
id = "sentry.integrations.pagerduty.notify_action.PagerDutyNotifyServiceAction"
label = "Send a notification to PagerDuty account {account} and service {service} with {severity} severity"
prompt = "Send a PagerDuty notification"
provider = IntegrationProviderSlug.PAGE... | PagerDutyNotifyServiceAction |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_utils.py | {
"start": 700,
"end": 21978
} | class ____:
@staticmethod
def test_combine_requests_with_affinity():
AFFINITY = ResourceRequestUtil.PlacementConstraintType.AFFINITY
ANTI_AFFINITY = ResourceRequestUtil.PlacementConstraintType.ANTI_AFFINITY
rqs = [
ResourceRequestUtil.make({"CPU": 1}, [(AFFINITY, "1", "1")]... | TestResourceRequestUtil |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_itertools.py | {
"start": 96907,
"end": 99773
} | class ____(__TestCase):
def makecycle(self, iterator, container):
container.append(iterator)
next(iterator)
del container, iterator
def test_accumulate(self):
a = []
self.makecycle(accumulate([1,2,a,3]), a)
def test_batched(self):
a = []
self.makecy... | TestGC |
python | realpython__materials | python-iterators-iterables/sequence_iter.py | {
"start": 0,
"end": 380
} | class ____:
def __init__(self, sequence):
self._sequence = sequence
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._sequence):
item = self._sequence[self._index]
self._index += 1
return item
... | SequenceIterator |
python | pypa__hatch | src/hatch/python/core.py | {
"start": 1285,
"end": 4020
} | class ____:
def __init__(self, directory: Path) -> None:
self.__directory = directory
@property
def directory(self) -> Path:
return self.__directory
def get_installed(self) -> dict[str, InstalledDistribution]:
if not self.directory.is_dir():
return {}
impor... | PythonManager |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_device_counter_consumption.py | {
"start": 383,
"end": 5403
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta1DeviceCounterConsumption |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_permission_details.py | {
"start": 339,
"end": 1628
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-permission-details"
def setUp(self) -> None:
super().setUp()
self.superuser = self.create_user(is_superuser=True)
self.add_user_permission(self.superuser, "users.admin")
self.staff_user = self.create_user(is_staff=True)
... | UserDetailsTest |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/vimeo_oauth2/tests.py | {
"start": 251,
"end": 1189
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = VimeoOAuth2Provider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"uri": "/users/12345",
"name": "AllAuth",
"link": "https://vimeo.com/user12345",
... | VimeoOAuth2Tests |
python | mozilla__bleach | bleach/html5lib_shim.py | {
"start": 5418,
"end": 7212
} | class ____:
"""Wraps an HTMLInputStream to remember characters since last <
This wraps existing HTMLInputStream classes to keep track of the stream
since the last < which marked an open tag state.
"""
def __init__(self, inner_stream):
self._inner_stream = inner_stream
self.reset =... | InputStreamWithMemory |
python | getsentry__sentry | src/sentry/release_health/metrics_sessions_v2.py | {
"start": 1996,
"end": 2345
} | class ____(Enum):
ABNORMAL = "abnormal"
CRASHED = "crashed"
ERRORED = "errored"
HEALTHY = "healthy"
UNHANDLED = "unhandled"
ALL_STATUSES = frozenset(iter(SessionStatus))
#: Used to filter results by session.status
StatusFilter = Optional[frozenset[SessionStatus]]
MAX_POSTGRES_LIMIT = 100
@dat... | SessionStatus |
python | pallets__click | src/click/types.py | {
"start": 28757,
"end": 35230
} | class ____(ParamType):
"""The ``Path`` type is similar to the :class:`File` type, but
returns the filename instead of an open file. Various checks can be
enabled to validate the type of file and permissions.
:param exists: The file or directory needs to exist for the value to
be valid. If this ... | Path |
python | sphinx-doc__sphinx | tests/test_util/typing_test_data.py | {
"start": 1907,
"end": 2044
} | class ____:
def __init__(self, parent: Optional['Node']) -> None:
pass
def children(self) -> List['Node']:
pass
| Node |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/base.py | {
"start": 84559,
"end": 86934
} | class ____(util.OrderedSet["ColumnClause[Any]"]):
def contains_column(self, col: ColumnClause[Any]) -> bool:
return col in self
def extend(self, cols: Iterable[Any]) -> None:
for col in cols:
self.add(col)
def __eq__(self, other):
l = []
for c in other:
... | ColumnSet |
python | streamlit__streamlit | lib/streamlit/connections/base_connection.py | {
"start": 897,
"end": 6842
} | class ____(ABC, Generic[RawConnectionT]):
"""The abstract base class that all Streamlit Connections must inherit from.
This base class provides connection authors with a standardized way to hook into the
``st.connection()`` factory function: connection authors are required to provide an
implementation ... | BaseConnection |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 20172,
"end": 20263
} | class ____(TestMaskedArrayCopyFilled, LongitudeSetup):
pass
| TestMaskedLongitudeCopyFilled |
python | google__jax | jax/_src/mesh.py | {
"start": 3813,
"end": 4930
} | class ____(enum.Enum):
Auto = enum.auto()
Explicit = enum.auto()
Manual = enum.auto()
def __repr__(self):
return self.name
def _normalize_axis_types(axis_names, axis_types, name):
axis_types = ((AxisType.Auto,) * len(axis_names)
if axis_types is None else axis_types)
if not isinstance(... | AxisType |
python | huggingface__transformers | tests/models/granitemoehybrid/test_modeling_granitemoehybrid.py | {
"start": 2642,
"end": 15214
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
model_tester_class = GraniteMoeHybridModelTester
all_model_classes = (
(
GraniteMoeHybridModel,
GraniteMoeHybridForCausalLM,
)
if is_torch_available()
else ()
... | GraniteMoeHybridModelTest |
python | langchain-ai__langchain | libs/core/tests/unit_tests/runnables/test_fallbacks.py | {
"start": 9986,
"end": 10884
} | class ____(BaseChatModel):
foo: int
@override
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
"""Top Level call."""
return ChatRe... | FakeStructuredOutputModel |
python | astropy__astropy | astropy/coordinates/tests/test_masked.py | {
"start": 16397,
"end": 16947
} | class ____(TestSkyCoordWithDifferentials):
@classmethod
def setup_class(cls):
super().setup_class()
# Overwrite SkyCoord using unmasked distance.
cls.mask_dis = False
cls.sc = SkyCoord(
ra=cls.ra,
dec=cls.dec,
distance=cls.dis,
pm_r... | TestSkyCoordWithOnlyDifferentialsMasked |
python | has2k1__plotnine | tests/test_helpers.py | {
"start": 193,
"end": 1263
} | class ____:
data = pd.DataFrame(
{
"x": [0, 1, 2, 3, 4, 5, 6],
"y": [0, 1, 2, 3, 4, 5, 6],
"g": list("aabbbcc"),
}
)
def test_continuous_limits(self):
p = ggplot(self.data, aes("x", "y")) + geom_point()
limits = cast("tuple[float, float]",... | TestGetAestheticLimits |
python | pola-rs__polars | py-polars/src/polars/series/plotting.py | {
"start": 430,
"end": 6673
} | class ____:
"""Series.plot namespace."""
_accessor = "plot"
def __init__(self, s: Series) -> None:
name = s.name or "value"
self._df = s.to_frame(name)
self._series_name = name
def hist(
self,
/,
**kwargs: Unpack[EncodeKwds],
) -> alt.Chart:
... | SeriesPlot |
python | pypa__warehouse | tests/unit/captcha/test_recaptcha.py | {
"start": 693,
"end": 7746
} | class ____:
@responses.activate
def test_verify_service_disabled(self):
responses.add(
responses.POST,
recaptcha.VERIFY_URL,
body="",
)
serv = recaptcha.Service.create_service(
context=None, request=pretend.stub(registry=pretend.stub(settin... | TestVerifyResponse |
python | kamyu104__LeetCode-Solutions | Python/valid-palindrome-iv.py | {
"start": 294,
"end": 683
} | class ____(object):
def makePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
cnt = 0
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
cnt += 1
if cnt > 2:
return False
... | Solution2 |
python | conda__conda | conda/exceptions.py | {
"start": 16605,
"end": 16692
} | class ____(ChannelNotAllowed):
warning = "Channel included in denylist"
| ChannelDenied |
python | python-markdown__markdown | markdown/extensions/codehilite.py | {
"start": 1685,
"end": 9778
} | class ____:
"""
Determine language of source code, and pass it on to the Pygments highlighter.
Usage:
```python
code = CodeHilite(src=some_code, lang='python')
html = code.hilite()
```
Arguments:
src: Source string or any object with a `.readline` attribute.
Keyword argum... | CodeHilite |
python | kamyu104__LeetCode-Solutions | Python/similar-rgb-color.py | {
"start": 29,
"end": 444
} | class ____(object):
def similarRGB(self, color):
"""
:type color: str
:rtype: str
"""
def rounding(color):
q, r = divmod(int(color, 16), 17)
if r > 8: q += 1
return '{:02x}'.format(17*q)
return '#' + \
rounding(colo... | Solution |
python | pytorch__pytorch | test/distributed/elastic/multiprocessing/api_test.py | {
"start": 1170,
"end": 2728
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.test_dir = tempfile.mkdtemp(prefix=f"{self.__class__.__name__}_")
def tearDown(self):
super().tearDown()
shutil.rmtree(self.test_dir)
def test_is_failed(self):
pr_success = RunProcsResult(return_values={0: ... | RunProcResultsTest |
python | Textualize__textual | tests/test_animation.py | {
"start": 5317,
"end": 7298
} | class ____(App[None]):
counter: var[float] = var(23)
def compose(self) -> ComposeResult:
yield CancelAnimWidget()
async def test_cancel_app_animation() -> None:
"""It should be possible to cancel a running app animation."""
async with CancelAnimApp().run_test() as pilot:
pilot.app.an... | CancelAnimApp |
python | kamyu104__LeetCode-Solutions | Python/longest-palindrome-after-substring-concatenation-i.py | {
"start": 64,
"end": 1290
} | class ____(object):
def longestPalindrome(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
P = [0]*len(s)
C, R = 0, 0
for i in xrange(1, len(s)-1):
... | Solution |
python | huggingface__transformers | src/transformers/models/llama/modeling_llama.py | {
"start": 14701,
"end": 15242
} | class ____(PreTrainedModel):
config: LlamaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["LlamaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
... | LlamaPreTrainedModel |
python | pytorch__pytorch | torch/_library/fake_class_registry.py | {
"start": 2994,
"end": 16208
} | class ____:
def __init__(self) -> None:
self._registered_class: dict[str, Any] = {}
def has_impl(self, full_qualname: str) -> bool:
return full_qualname in self._registered_class
def get_impl(self, full_qualname: str) -> Any:
self._check_registered(full_qualname)
return sel... | FakeClassRegistry |
python | sqlalchemy__sqlalchemy | test/ext/test_horizontal_shard.py | {
"start": 24952,
"end": 25960
} | class ____(ShardTest, fixtures.MappedTest):
"""Use modern schema conventions along with SQLite ATTACH."""
schema = "changeme"
def _init_dbs(self):
e = testing_engine("sqlite://")
with e.connect() as conn:
for i in range(1, 5):
conn.exec_driver_sql(
... | AttachedFileShardTest |
python | kubernetes-client__python | kubernetes/client/models/v1_service.py | {
"start": 383,
"end": 7106
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Service |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 113329,
"end": 114220
} | class ____:
def test_array_like(self):
# array_like not applicable with SCIPY_ARRAY_API=1
x = stats.norm.rvs(size=100, loc=0, random_state=54321)
lmbda = 1
llf = stats.yeojohnson_llf(lmbda, x)
llf2 = stats.yeojohnson_llf(lmbda, list(x))
assert_allclose(llf, llf2, rto... | TestYeojohnson_llf |
python | tox-dev__tox | src/tox/config/cli/parser.py | {
"start": 4919,
"end": 5424
} | class ____(Namespace):
"""CLI options."""
@property
def verbosity(self) -> int:
""":return: reporting verbosity"""
result: int = max(self.verbose - self.quiet, 0)
return result
@property
def is_colored(self) -> bool:
""":return: flag indicating if the output is colo... | Parsed |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 582320,
"end": 582954
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of EnablePullRequestAutoMerge"""
__schema__ = github_schema
__field_names__ = ("actor", "client_mutation_id", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
cl... | EnablePullRequestAutoMergePayload |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/assets/prediction_assets.py | {
"start": 573,
"end": 7839
} | class ____(dg.Config):
"""Configuration for real-time prediction processing."""
batch_size: int = 10 # Default number of images to process at once
device: str = "cuda" # Will fallback to CPU if CUDA not available
confidence_threshold: float = 0.9 # Higher threshold for real-time predictions
retu... | RealTimePredictionConfig |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 174991,
"end": 175890
} | class ____:
__slots__ = ()
_raw_columns: List[_ColumnsClauseElement]
_where_criteria: Tuple[ColumnElement[Any], ...]
_from_obj: Tuple[FromClause, ...]
def _iterate_from_elements(self) -> Iterator[FromClause]:
# note this does not include elements
# in _setup_joins
seen = s... | _SelectFromElements |
python | huggingface__transformers | src/transformers/models/distilbert/modeling_distilbert.py | {
"start": 2894,
"end": 5817
} | class ____(nn.Module):
def __init__(self, config: PreTrainedConfig):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
self.LayerN... | Embeddings |
python | facebook__pyre-check | client/json_rpc.py | {
"start": 9279,
"end": 11551
} | class ____(Response):
code: int
message: str = ""
data: Optional[object] = None
activity_key: Optional[JSON] = None
def json(self) -> JSON:
return {
"jsonrpc": JSONRPC_VERSION,
**({"id": self.id} if self.id is not None else {}),
**(
{"acti... | ErrorResponse |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/validators/detector_workflow_mutation.py | {
"start": 41,
"end": 160
} | class ____(serializers.Serializer):
enabled = serializers.BooleanField(required=True)
| DetectorWorkflowMutationValidator |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integration_request.py | {
"start": 49,
"end": 2166
} | class ____(APITestCase):
"""Unit tests for emailing organization owners asking them to install an integration."""
endpoint = "sentry-api-0-organization-integration-request"
method = "post"
def setUp(self) -> None:
self.owner = self.user
self.member = self.create_user(email="member@exam... | OrganizationIntegrationRequestTest |
python | great-expectations__great_expectations | tests/integration/sql_session_manager.py | {
"start": 563,
"end": 1329
} | class ____:
# The sqlalchemy connection pool class to use. In general we want to use QueuePool
poolclass: Type[Pool]
# The number of connections to keep in the pool
pool_size: int
# If all pool connections are used, we can create an additional max_overflow connections
# When returning connection... | PoolConfig |
python | apache__airflow | providers/docker/tests/unit/docker/operators/test_docker.py | {
"start": 5124,
"end": 34427
} | class ____:
@pytest.fixture(autouse=True)
def setup_patchers(self, docker_api_client_patcher):
self.tempdir_patcher = mock.patch("airflow.providers.docker.operators.docker.TemporaryDirectory")
self.tempdir_mock = self.tempdir_patcher.start()
self.tempdir_mock.return_value.__enter__.retur... | TestDockerOperator |
python | django__django | tests/test_client_regress/tests.py | {
"start": 42187,
"end": 44174
} | class ____(SimpleTestCase):
def test_get(self):
"Request a view via request method GET"
response = self.client.get("/request_methods/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"request method: GET")
def test_post(self):
"Request a ... | RequestMethodTests |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 8251,
"end": 8609
} | class ____(_NumcodecsArrayArrayCodec, codec_name="delta"):
def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec:
if astype := self.codec_config.get("astype"):
dtype = parse_dtype(np.dtype(astype), zarr_format=3) # type: ignore[call-overload]
return replace(chunk_spec, dtyp... | Delta |
python | pytorch__pytorch | torch/nn/cpp.py | {
"start": 1369,
"end": 3100
} | class ____(nn.Module):
"""A subclass of ``torch.nn.Module`` that wraps a C++ frontend module and delegates all access."""
def __init__(self, cpp_module) -> None:
# Assign before the super class constructor so ``self.training`` can be
# assigned to in the super class constructor.
self.cp... | ModuleWrapper |
python | huggingface__transformers | tests/models/luke/test_tokenization_luke.py | {
"start": 983,
"end": 5205
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "studio-ousia/luke-base"
tokenizer_class = LukeTokenizer
from_pretrained_kwargs = {"cls_token": "<s>"}
integration_expected_tokens = ['This', 'Ġis', 'Ġa', 'Ġtest', 'ĠðŁĺ', 'Ĭ', 'Ċ', 'I', 'Ġwas', 'Ġborn', 'Ġin', 'Ġ92', '000', ',',... | LukeTokenizerTest |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 116811,
"end": 124158
} | class ____(OpInfo):
"""Early version of a specialized OpInfo for foreach functions
The main differences from the parent class are (a) `dtypes`, `dtypesIfCUDA`, and `dtypesIfROCM`
are set to `get_all_dtypes(include_qint=False)`, and (b) the following arguments.
``supports_alpha_param=True`` means that ... | ForeachFuncInfo |
python | google__pytype | pytype/state_test.py | {
"start": 534,
"end": 951
} | class ____:
def __init__(self, name, true_compat, false_compat):
self._name = name
self.compatible = {True: true_compat, False: false_compat}
def __str__(self):
return self._name
ONLY_TRUE = FakeValue("T", True, False)
ONLY_FALSE = FakeValue("F", False, True)
AMBIGUOUS = FakeValue("?", True, True)
... | FakeValue |
python | justquick__django-activity-stream | actstream/managers.py | {
"start": 4052,
"end": 6829
} | class ____(GFKManager):
"""
Manager for Follow model.
"""
def for_object(self, instance, flag=''):
"""
Filter to a specific instance.
"""
check(instance)
content_type = ContentType.objects.get_for_model(instance).pk
queryset = self.filter(content_type=con... | FollowManager |
python | PyCQA__pydocstyle | src/pydocstyle/checker.py | {
"start": 866,
"end": 47225
} | class ____:
"""Checker for PEP 257, NumPy and Google conventions.
D10x: Missing docstrings
D20x: Whitespace issues
D30x: Docstring formatting
D40x: Docstring content issues
"""
NUMPY_SECTION_NAMES = (
'Short Summary',
'Extended Summary',
'Parameters',
'Retu... | ConventionChecker |
python | yaml__pyyaml | lib/yaml/cyaml.py | {
"start": 493,
"end": 692
} | class ____(CParser, SafeConstructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
SafeConstructor.__init__(self)
Resolver.__init__(self)
| CSafeLoader |
python | doocs__leetcode | solution/1000-1099/1062.Longest Repeating Substring/Solution.py | {
"start": 0,
"end": 368
} | class ____:
def longestRepeatingSubstring(self, s: str) -> int:
n = len(s)
f = [[0] * n for _ in range(n)]
ans = 0
for i in range(1, n):
for j in range(i):
if s[i] == s[j]:
f[i][j] = 1 + (f[i - 1][j - 1] if j else 0)
... | Solution |
python | pytorch__pytorch | torch/distributed/checkpoint/_experimental/barriers.py | {
"start": 2949,
"end": 4014
} | class ____(abc.ABC):
"""
Abstract base class for synchronization barriers.
A barrier ensures that all ranks in a distributed environment reach a certain
point in execution before any rank proceeds further, which is essential for
coordinating operations like checkpointing across multiple processes.
... | Barrier |
python | pytorch__pytorch | test/test_testing.py | {
"start": 73446,
"end": 93156
} | class ____(TestCase):
def test_unparametrized_names(self, device):
# This test exists to protect against regressions in device / dtype test naming
# due to parametrization logic.
device = self.device_type
class TestParametrized(TestCase):
def test_device_specific(self, ... | TestTestParametrizationDeviceType |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigquery.py | {
"start": 82110,
"end": 89539
} | class ____:
@pytest.mark.db_test
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryCheckOperator._validate_records")
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryCheckOperator.defer")
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHo... | TestBigQueryCheckOperator |
python | readthedocs__readthedocs.org | readthedocs/aws/security_token_service.py | {
"start": 1823,
"end": 8809
} | class ____(AWSTemporaryCredentials):
"""Subclass of AWSTemporaryCredentials to include S3 specific fields."""
bucket_name: str
region_name: str
def get_sts_client():
return boto3.client(
"sts",
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SE... | AWSS3TemporaryCredentials |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_add_column_with_default_app/migrations/0001_initial.py | {
"start": 153,
"end": 586
} | class ____(CheckedMigration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestTable",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, s... | Migration |
python | numba__numba | numba/tests/test_typedlist.py | {
"start": 25759,
"end": 28728
} | class ____(MemoryLeakMixin, TestCase):
def _cmp_dance(self, expected, pa, pb, na, nb):
# interpreter with regular list
self.assertEqual(cmp.py_func(pa, pb), expected)
# interpreter with typed-list
py_got = cmp.py_func(na, nb)
self.assertEqual(py_got, expected)
# co... | TestComparisons |
python | pytorch__pytorch | torch/_inductor/utils.py | {
"start": 47805,
"end": 47890
} | class ____:
value: str
line_map: list[tuple[int, LineContext]]
| ValueWithLineMap |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1180517,
"end": 1184572
} | class ____(sgqlc.types.Type, Node, Starrable, UniformResourceLocatable):
"""A Gist."""
__schema__ = github_schema
__field_names__ = (
"comments",
"created_at",
"description",
"files",
"forks",
"is_fork",
"is_public",
"name",
"owner",
... | Gist |
python | numba__numba | numba/tests/test_tuples.py | {
"start": 17393,
"end": 17777
} | class ____(TestCase, MemoryLeakMixin):
def test_tuple_add(self):
def pyfunc(x):
a = np.arange(3)
return (a,) + (x,)
cfunc = jit(nopython=True)(pyfunc)
x = 123
expect_a, expect_x = pyfunc(x)
got_a, got_x = cfunc(x)
np.testing.assert_equal(got_a... | TestTupleNRT |
python | google__pytype | pytype/rewrite/abstract/functions.py | {
"start": 17832,
"end": 19649
} | class ____(BaseFunction[_HasReturnT]):
"""Signature-based function implementation."""
def __init__(
self,
ctx: base.ContextType,
name: str,
signatures: tuple[Signature, ...],
module: str | None = None,
):
super().__init__(ctx)
self._name = name
self._signatures = signatu... | SimpleFunction |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 165,
"end": 1408
} | class ____:
params = (
["monotonic", "non_monotonic"],
["datetime", "date_string", "int", "strings", "ea_int"],
["intersection", "union", "symmetric_difference"],
)
param_names = ["index_structure", "dtype", "method"]
def setup(self, index_structure, dtype, method):
N = ... | SetOperations |
python | pytransitions__transitions | transitions/extensions/locking.py | {
"start": 1178,
"end": 1668
} | class ____:
"""A wrapper for threading.Lock which discards its state during pickling and
is reinitialized unlocked when unpickled.
"""
def __init__(self):
self.lock = Lock()
def __getstate__(self):
return ''
def __setstate__(self, value):
return self.__init__()
... | PicklableLock |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 33116,
"end": 33925
} | class ____(TypeSystemDefinition):
__slots__ = ('loc', 'definition',)
_fields = ('definition',)
def __init__(self, definition, loc=None):
self.loc = loc
self.definition = definition
def __eq__(self, other):
return (
self is other or (
isinstance(other... | TypeExtensionDefinition |
python | mlflow__mlflow | mlflow/environment_variables.py | {
"start": 1752,
"end": 51284
} | class ____(_EnvironmentVariable):
"""
Represents a boolean environment variable.
"""
def __init__(self, name, default):
# `default not in [True, False, None]` doesn't work because `1 in [True]`
# (or `0 in [False]`) returns True.
if not (default is True or default is False or de... | _BooleanEnvironmentVariable |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-deepinfra/llama_index/llms/deepinfra/types.py | {
"start": 71,
"end": 210
} | class ____(BaseModel):
name: str
"""The name of the function."""
arguments: str
"""The arguments of the function."""
| Function |
python | fastapi__sqlmodel | docs_src/tutorial/select/tutorial001.py | {
"start": 100,
"end": 1141
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
... | Hero |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.