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 | django__django | tests/migrations/test_base.py | {
"start": 776,
"end": 8700
} | class ____(TransactionTestCase):
"""
Contains an extended set of asserts for testing migrations and schema
operations.
"""
available_apps = ["migrations"]
databases = {"default", "other"}
def tearDown(self):
# Reset applied-migrations state.
for db in self.databases:
... | MigrationTestBase |
python | PyCQA__pylint | doc/data/messages/n/no-method-argument/bad.py | {
"start": 0,
"end": 87
} | class ____:
def print_greeting(): # [no-method-argument]
print("hello")
| Person |
python | google__jax | tests/lax_numpy_indexing_test.py | {
"start": 52563,
"end": 54538
} | class ____(enum.Enum):
UPDATE = 0
ADD = 1
SUB = 2
MUL = 3
DIV = 4
POW = 5
MIN = 6
MAX = 7
def np_fn(op, indexer, x, y):
x = x.copy()
if op == UpdateOps.UPDATE:
x[indexer] = y
elif op == UpdateOps.ADD:
np.add.at(x, indexer, y)
elif op == UpdateOps.SUB:
np.subtract.at(... | UpdateOps |
python | spyder-ide__spyder | spyder/plugins/help/widgets.py | {
"start": 1743,
"end": 2177
} | class ____:
# Toggles
ToggleAutomaticImport = 'toggle_automatic_import_action'
ToggleLocked = 'toggle_locked_action'
TogglePlainMode = 'toggle_plain_mode_action'
ToggleRichMode = 'toggle_rich_mode_action'
ToggleShowSource = 'toggle_show_source_action'
ToggleWrap = 'toggle_wrap_action'
Co... | HelpWidgetActions |
python | getsentry__sentry | src/sentry/api/serializers/models/group.py | {
"start": 33723,
"end": 35201
} | class ____(GroupSerializer):
def serialize( # type: ignore[override] # return value is a subset
self,
obj: Group,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> SharedGroupSerializerResponse:
result = super().serialize(obj, a... | SharedGroupSerializer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 10869,
"end": 11980
} | class ____(_AbstractORMCompileState):
"""ORM compile state that is a passthrough, except for autoflush."""
@classmethod
def orm_pre_session_exec(
cls,
session,
statement,
params,
execution_options,
bind_arguments,
is_pre_event,
):
# consum... | _AutoflushOnlyORMCompileState |
python | huggingface__transformers | tests/utils/import_structures/import_structure_raw_register_with_versions.py | {
"start": 1273,
"end": 1415
} | class ____:
def __init__(self):
pass
@requires(backends=("torch==2.5",))
def d4():
pass
@requires(backends=("torch!=2.5",))
| D4 |
python | django__django | tests/gis_tests/geoapp/feeds.py | {
"start": 341,
"end": 859
} | class ____(TestGeoRSS1):
def geometry(self, obj):
# This should attach a <georss:box> element for the extent of
# the cities in the database. This tuple came from
# calling `City.objects.aggregate(Extent())` -- we can't do that call
# here because `Extent` is not implemented for MySQ... | TestGeoRSS2 |
python | getsentry__sentry | src/sentry/consumers/synchronized.py | {
"start": 701,
"end": 1500
} | class ____(Generic[T]):
"""
This class wraps a value that is shared between multiple threads,
providing thread-safe ``get`` and ``set`` methods for reading and writing
(replacing) the value.
"""
def __init__(self, value: T) -> None:
self.__value = value
self.__lock = Lock()
... | Synchronized |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 264844,
"end": 265197
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("CreatedRepositoryContribution", graphql_name="node"... | CreatedRepositoryContributionEdge |
python | xlwings__xlwings | tests/test_names.py | {
"start": 48,
"end": 4875
} | class ____(TestBase):
def test_get_names_index(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.wb1.sheets[0].range("A1").name = "test2"
self.assertEqual(self.wb1.names(1).name, "test1")
self.assertEqual(self.wb1.names[1].name, "test2")
def test_names_contain(self):... | TestNames |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 27590,
"end": 27724
} | class ____(RayError):
"""Raised when an asyncio actor intentionally exits via exit_actor()."""
pass
@PublicAPI
| AsyncioActorExit |
python | numba__numba | numba/tests/test_debug.py | {
"start": 4986,
"end": 5903
} | class ____(DebugTestBase):
func_name = 'simple_gen'
def compile_simple_gen(self):
with captured_stdout() as out:
cfunc = njit((types.int64, types.int64))(simple_gen)
# Sanity check compiled function
self.assertPreciseEqual(list(cfunc(2, 5)), [2, 5])
return o... | TestGeneratorDebugOutput |
python | getsentry__sentry | src/sentry/notifications/api/endpoints/notification_actions_index.py | {
"start": 1667,
"end": 7578
} | class ____(OrganizationEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
"""
View existing NotificationActions or create a new one.
GET: Returns paginated, serialized NotificationActions for an organizatio... | NotificationActionsIndexEndpoint |
python | tiangolo__fastapi | tests/test_sub_callbacks.py | {
"start": 669,
"end": 14142
} | class ____(BaseModel):
name: str
total: float
events_callback_router = APIRouter()
@events_callback_router.get("{$callback_url}/events/{$request.body.title}")
def event_callback(event: Event):
pass # pragma: nocover
subrouter = APIRouter()
@subrouter.post("/invoices/", callbacks=invoices_callback_r... | Event |
python | getsentry__sentry | tests/sentry/issues/test_ingest_incident_integration.py | {
"start": 1449,
"end": 13977
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
self.alert_rule = self.create_alert_rule(
organization=self.organization,
projects=... | IncidentGroupOpenPeriodIntegrationTest |
python | django__django | tests/admin_inlines/admin.py | {
"start": 2881,
"end": 3404
} | class ____(admin.ModelAdmin):
fieldsets = [
(None, {"fields": ["firstname", "fullname"]}),
("Advanced options", {"fields": ["nationality", "residency"]}),
(
"Advanced options", # Fieldset name intentionally duplicated
{"fields": ["siblings", "children"], "classes": [... | PhotographerAdmin |
python | coleifer__peewee | peewee.py | {
"start": 151693,
"end": 152019
} | class ____(CursorWrapper):
def initialize(self):
description = self.cursor.description
self.tuple_class = collections.namedtuple('Row', [
t[0][t[0].rfind('.') + 1:].strip('()"`') for t in description])
def process_row(self, row):
return self.tuple_class(*row)
| NamedTupleCursorWrapper |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 9535,
"end": 11350
} | class ____(DatabricksBaseTask[jobs.PythonWheelTask]):
@property
def task_type(self) -> str:
return "python_wheel"
@property
def task_config_metadata(self) -> Mapping[str, Any]:
task_config_metadata = {}
wheel_config = self.task_config["python_wheel_task"]
task_config_met... | DatabricksPythonWheelTask |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/looker.py | {
"start": 7418,
"end": 8900
} | class ____(api_settings.ApiSettings):
"""Custom implementation of Looker SDK's `ApiSettings` class."""
def __init__(
self,
conn: Connection,
) -> None:
self.conn = conn # need to init before `read_config` is called in super
super().__init__()
def read_config(self):
... | LookerApiSettings |
python | doocs__leetcode | solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py | {
"start": 0,
"end": 238
} | class ____:
def numberOfBeams(self, bank: List[str]) -> int:
ans = pre = 0
for row in bank:
if (cur := row.count("1")) > 0:
ans += pre * cur
pre = cur
return ans
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 105880,
"end": 107855
} | class ____(Response):
"""
Response of projects.get_model_metadata_values endpoint.
:param total: Total number of distinct values
:type total: int
:param values: The list of the unique values
:type values: Sequence[str]
"""
_service = "projects"
_action = "get_model_metadata_values"... | GetModelMetadataValuesResponse |
python | tensorflow__tensorflow | tensorflow/python/summary/writer/writer_test.py | {
"start": 1861,
"end": 16410
} | class ____:
def _FileWriter(self, *args, **kwargs):
return writer.FileWriter(*args, **kwargs)
def _TestDir(self, test_name):
test_dir = os.path.join(self.get_temp_dir(), test_name)
return test_dir
def _CleanTestDir(self, test_name):
test_dir = self._TestDir(test_name)
if os.path.exists(test... | FileWriterTestBase |
python | kamyu104__LeetCode-Solutions | Python/coin-path.py | {
"start": 33,
"end": 801
} | class ____(object):
def cheapestJump(self, A, B):
"""
:type A: List[int]
:type B: int
:rtype: List[int]
"""
result = []
if not A or A[-1] == -1:
return result
n = len(A)
dp, next_pos = [float("inf")] * n, [-1] * n
dp[n-1] = ... | Solution |
python | fluentpython__example-code-2e | 01-data-model/vector2d.py | {
"start": 522,
"end": 1010
} | class ____:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
... | Vector |
python | kubernetes-client__python | kubernetes/client/models/v2_hpa_scaling_rules.py | {
"start": 383,
"end": 8995
} | 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... | V2HPAScalingRules |
python | kamyu104__LeetCode-Solutions | Python/handshakes-that-dont-cross.py | {
"start": 641,
"end": 1021
} | class ____(object):
def numberOfWays(self, num_people):
"""
:type num_people: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(num_people//2+1)
dp[0] = 1
for k in xrange(1, num_people//2+1):
for i in xrange(k):
dp[k] = (dp[k] + d... | Solution2 |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/unconstrainable_conflict/package.py | {
"start": 216,
"end": 730
} | class ____(Package):
"""Package with a conflict whose trigger cannot constrain its constraint."""
homepage = "http://www.realurl.com"
url = "http://www.realurl.com/unconstrainable-conflict-1.0.tar.gz"
version("1.0", sha256="2e34cc4505556d1c1f085758e26f2f8eea0972db9382f051b2dcfb1d7d9e1825")
# Two ... | UnconstrainableConflict |
python | pandas-dev__pandas | pandas/tests/groupby/test_counting.py | {
"start": 266,
"end": 13495
} | class ____:
def test_cumcount(self):
df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"])
g = df.groupby("A")
sg = g.A
expected = Series([0, 1, 2, 0, 3])
tm.assert_series_equal(expected, g.cumcount())
tm.assert_series_equal(expected, sg.cumcount())
... | TestCounting |
python | astropy__astropy | astropy/modeling/core.py | {
"start": 2308,
"end": 19271
} | class ____(abc.ABCMeta):
"""
Metaclass for Model.
Currently just handles auto-generating the param_names list based on
Parameter descriptors declared at the class-level of Model subclasses.
"""
_is_dynamic = False
"""
This flag signifies whether this class was created in the "normal" w... | _ModelMeta |
python | numba__numba | numba/core/ir.py | {
"start": 28746,
"end": 29458
} | class ____(Stmt):
"""Enter a "with" context
"""
def __init__(self, contextmanager, begin, end, loc):
"""
Parameters
----------
contextmanager : IR value
begin, end : int
The beginning and the ending offset of the with-body.
loc : ir.Loc instance
... | EnterWith |
python | django__django | tests/auth_tests/test_validators.py | {
"start": 11907,
"end": 14172
} | class ____(SimpleTestCase):
def test_validate(self):
expected_error = "This password is too common."
self.assertIsNone(CommonPasswordValidator().validate("a-safe-password"))
with self.assertRaises(ValidationError) as cm:
CommonPasswordValidator().validate("godzilla")
sel... | CommonPasswordValidatorTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/untappd/views.py | {
"start": 222,
"end": 1111
} | class ____(OAuth2Adapter):
client_class = UntappdOAuth2Client
provider_id = "untappd"
access_token_url = "https://untappd.com/oauth/authorize/" # nosec
access_token_method = "GET" # nosec
authorize_url = "https://untappd.com/oauth/authenticate/"
user_info_url = "https://api.untappd.com/v4/user... | UntappdOAuth2Adapter |
python | ray-project__ray | doc/source/serve/doc_code/custom_request_router.py | {
"start": 1199,
"end": 3921
} | class ____(
FIFOMixin, MultiplexMixin, LocalityMixin, RequestRouter
):
async def choose_replicas(
self,
candidate_replicas: List[RunningReplica],
pending_request: Optional[PendingRequest] = None,
) -> List[List[RunningReplica]]:
"""
This method chooses the best replic... | ThroughputAwareRequestRouter |
python | GoogleCloudPlatform__python-docs-samples | monitoring/snippets/v3/alerts-client/snippets_test.py | {
"start": 1513,
"end": 8459
} | class ____:
"""A test fixture that creates an alert POlicy and a notification CHANnel,
hence the name, pochan.
"""
def __init__(self):
self.project_id = snippets.project_id()
self.project_name = snippets.project_name()
self.alert_policy_client = monitoring_v3.AlertPolicyServiceC... | PochanFixture |
python | huggingface__transformers | tests/models/blenderbot_small/test_modeling_blenderbot_small.py | {
"start": 20483,
"end": 21691
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (BlenderbotSmallDecoder, BlenderbotSmallForCausalLM) if is_torch_available() else ()
is_encoder_decoder = False
def setUp(
self,
):
self.model_tester = BlenderbotSmallStandaloneDecoderModelTeste... | BlenderbotSmallStandaloneDecoderModelTest |
python | optuna__optuna | optuna/exceptions.py | {
"start": 0,
"end": 91
} | class ____(Exception):
"""Base class for Optuna specific errors."""
pass
| OptunaError |
python | Pylons__pyramid | src/pyramid/events.py | {
"start": 6309,
"end": 7302
} | class ____:
"""An instance of this class is emitted as an :term:`event` after
the :app:`Pyramid` :term:`router` finds a :term:`context`
object (after it performs traversal) but before any view code is
executed. The instance has an attribute, ``request``, which is
the request object generated by :ap... | ContextFound |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/color.py | {
"start": 141,
"end": 556
} | class ____(WidgetParameterItem):
"""Registered parameter type which displays a :class:`ColorButton <pyqtgraph.ColorButton>` """
def makeWidget(self):
w = ColorButton()
w.sigChanged = w.sigColorChanged
w.sigChanging = w.sigColorChanging
w.value = w.color
w.setValue = w.set... | ColorParameterItem |
python | celery__celery | t/unit/backends/test_asynchronous.py | {
"start": 7553,
"end": 8066
} | class ____(DrainerTests):
@pytest.fixture(autouse=True)
def setup_drainer(self):
self.drainer = self.get_drainer('default')
@cached_property
def sleep(self):
from time import sleep
return sleep
def result_consumer_drain_events(self, timeout=None):
time.sleep(timeout... | test_Drainer |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/alloy_db.py | {
"start": 1708,
"end": 1910
} | class ____(BaseGoogleLink):
"""Helper class for constructing AlloyDB backups Link."""
name = "AlloyDB Backups"
key = "alloy_db_backups"
format_str = ALLOY_DB_BACKUPS_LINK
| AlloyDBBackupsLink |
python | doocs__leetcode | solution/0700-0799/0704.Binary Search/Solution.py | {
"start": 0,
"end": 311
} | class ____:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) >> 1
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l if nums[l] == target else -1
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/db_io_manager.py | {
"start": 1011,
"end": 1129
} | class ____(NamedTuple):
partition_expr: str
partitions: Union[TimeWindow, Sequence[str]]
| TablePartitionDimension |
python | nedbat__coveragepy | coverage/results.py | {
"start": 10386,
"end": 17242
} | class ____:
"""The numerical results of measuring coverage.
This holds the basic statistics from `Analysis`, and is used to roll
up statistics across files.
"""
precision: int = 0
n_files: int = 0
n_statements: int = 0
n_excluded: int = 0
n_missing: int = 0
n_branches: int = 0... | Numbers |
python | django__django | tests/cache/tests.py | {
"start": 112855,
"end": 115030
} | class ____(SimpleTestCase):
def test_same_instance(self):
"""
Attempting to retrieve the same alias should yield the same instance.
"""
cache1 = caches["default"]
cache2 = caches["default"]
self.assertIs(cache1, cache2)
def test_per_thread(self):
"""
... | CacheHandlerTest |
python | openai__gym | gym/error.py | {
"start": 4227,
"end": 4323
} | class ____(Error):
"""Error message for using wrap after configure."""
| WrapAfterConfigureError |
python | weaviate__weaviate-python-client | weaviate/collections/aggregations/hybrid/sync.py | {
"start": 188,
"end": 245
} | class ____(_HybridExecutor[ConnectionSync]):
pass
| _Hybrid |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 6201,
"end": 6569
} | class ____(TestAtomFeed):
"""
A feed with timezone-aware dates.
"""
def item_pubdate(self, item):
# Provide a weird offset so that the test can know it's getting this
# specific offset and not accidentally getting on from
# settings.TIME_ZONE.
return item.published.repla... | TZAwareDatesFeed |
python | django__django | tests/queries/models.py | {
"start": 2925,
"end": 3284
} | class ____(models.Model):
rank = models.IntegerField()
author = models.ForeignKey(Author, models.CASCADE)
class Meta:
# A complex ordering specification. Should stress the system a bit.
ordering = ("author__extra__note", "author__name", "rank")
def __str__(self):
return "%d: %s... | Ranking |
python | Lightning-AI__lightning | src/lightning/pytorch/tuner/lr_finder.py | {
"start": 18133,
"end": 19144
} | class ____(LRScheduler):
"""Linearly increases the learning rate between two boundaries over a number of iterations.
Args:
optimizer: wrapped optimizer.
end_lr: the final learning rate.
num_iter: the number of iterations over which the test occurs.
last_epoch: the index of l... | _LinearLR |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/special_math_test.py | {
"start": 7507,
"end": 8020
} | class ____(NdtrTest):
_use_log = True
_grid32 = GridSpec(min=-100., max=sm.LOGNDTR_FLOAT32_LOWER, shape=[100])
_grid64 = GridSpec(min=-100., max=sm.LOGNDTR_FLOAT64_LOWER, shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-4, atol=0.)
# The errors are quite large when the inpu... | LogNdtrTestLower |
python | conda__conda | conda/auxlib/collection.py | {
"start": 264,
"end": 1941
} | class ____(dict):
"""Sub-classes dict, and further allows attribute-like access to dictionary items.
Examples:
>>> d = AttrDict({'a': 1})
>>> d.a, d['a'], d.get('a')
(1, 1, 1)
>>> d.b = 2
>>> d.b, d['b']
(2, 2)
"""
def __init__(self, *args, **kwargs):
... | AttrDict |
python | getsentry__sentry | src/sentry/integrations/types.py | {
"start": 157,
"end": 637
} | class ____(ValueEqualityEnum):
UNUSED_GH = 0
UNUSED_GL = 1
EMAIL = 100
SLACK = 110
MSTEAMS = 120
PAGERDUTY = 130
DISCORD = 140
OPSGENIE = 150
GITHUB = 200
GITHUB_ENTERPRISE = 201
GITLAB = 210
JIRA_SERVER = 300
PERFORCE = 400
# TODO: do migration to delete this f... | ExternalProviders |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 6681,
"end": 6840
} | class ____:
def setup(self):
self.df = DataFrame(np.random.randn(100, 10))
def time_to_string_floats(self):
self.df.to_string()
| ToString |
python | doocs__leetcode | solution/1600-1699/1687.Delivering Boxes from Storage to Ports/Solution.py | {
"start": 0,
"end": 775
} | class ____:
def boxDelivering(
self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int
) -> int:
n = len(boxes)
ws = list(accumulate((box[1] for box in boxes), initial=0))
c = [int(a != b) for a, b in pairwise(box[0] for box in boxes)]
cs = list(accum... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-airflow/dagster_airflow/resources/airflow_persistent_db.py | {
"start": 519,
"end": 4257
} | class ____(AirflowDatabase):
"""A persistent Airflow database Dagster resource."""
def __init__(self, dagster_run: DagsterRun, uri: str, dag_run_config: Optional[dict] = None):
self.uri = uri
super().__init__(dagster_run=dagster_run, dag_run_config=dag_run_config)
@staticmethod
def _in... | AirflowPersistentDatabase |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 21166,
"end": 21272
} | class ____(Resolvable, Model):
existing_cluster_id: str
@preview
| ResolvedDatabricksExistingClusterConfig |
python | has2k1__plotnine | tests/test_save_as_pdf_pages.py | {
"start": 2472,
"end": 3329
} | class ____:
def test_plot_exception(self):
# Force an error in drawing
fn = next(filename_gen)
plots = list(p())
plots[0] += aes(color="unknown")
with pytest.raises(PlotnineError):
save_as_pdf_pages(plots, fn, verbose=False)
# TODO: Remove when MPL>=3.10.... | TestExceptions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/types.py | {
"start": 2616,
"end": 2739
} | class ____(FromDictMixin):
prefix: str
suffix: str
FieldType = Dict[Any, Any]
@dataclasses.dataclass
| AutoNumberDict |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor2.py | {
"start": 473,
"end": 530
} | class ____(Animal[int, int], Generic[_T3]):
pass
| Donkey |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 26950,
"end": 33324
} | class ____(MoshiAttention):
"""
Moshi flash attention module. This module inherits from `MoshiAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in ... | MoshiFlashAttention2 |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 8915,
"end": 10190
} | class ____(BosonicOperator, Annihilator):
"""
Bosonic annihilation operator.
Examples
========
>>> from sympy.physics.secondquant import B
>>> from sympy.abc import x
>>> B(x)
AnnihilateBoson(x)
"""
op_symbol = 'b'
def _dagger_(self):
return CreateBoson(self.state... | AnnihilateBoson |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py | {
"start": 792,
"end": 30563
} | class ____:
"""Tool that fails a certain number of times before succeeding."""
def __init__(self, fail_count: int):
"""Initialize with the number of times to fail.
Args:
fail_count: Number of times to fail before succeeding.
"""
self.fail_count = fail_count
... | TemporaryFailureTool |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_details.py | {
"start": 5042,
"end": 30190
} | class ____(SentryAppDetailsTest):
method = "PUT"
def _validate_updated_published_app(self, response: Response) -> None:
data = response.data
data["featureData"] = sorted(data["featureData"], key=lambda a: a["featureId"])
assert data == {
"name": self.published_app.name,
... | UpdateSentryAppDetailsTest |
python | pytorch__pytorch | test/functorch/test_eager_transforms.py | {
"start": 7402,
"end": 35662
} | class ____(TestCase):
def test_primitive(self, device):
x = torch.randn([], device=device)
result = grad(torch.sin)(x)
self.assertEqual(result, torch.cos(x))
def test_composite_simple(self, device):
x = torch.randn(2, 3, 4, device=device)
result = grad(lambda x: torch.fl... | TestGradTransform |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 72472,
"end": 77469
} | class ____(MoshiPreTrainedModel, GenerationMixin):
input_modalities = ("text",)
# Copied from transformers.models.gemma.modeling_gemma.GemmaForCausalLM.__init__ with Gemma->Moshi
def __init__(self, config):
super().__init__(config)
self.model = MoshiModel(config)
self.vocab_size = c... | MoshiForCausalLM |
python | pallets__click | src/click/exceptions.py | {
"start": 9662,
"end": 9954
} | class ____(RuntimeError):
"""An exception that indicates that the application should exit with some
status code.
:param code: the status code to exit with.
"""
__slots__ = ("exit_code",)
def __init__(self, code: int = 0) -> None:
self.exit_code: int = code
| Exit |
python | doocs__leetcode | solution/1400-1499/1462.Course Schedule IV/Solution2.py | {
"start": 0,
"end": 724
} | class ____:
def checkIfPrerequisite(
self, n: int, prerequisites: List[List[int]], queries: List[List[int]]
) -> List[bool]:
f = [[False] * n for _ in range(n)]
g = [[] for _ in range(n)]
indeg = [0] * n
for a, b in prerequisites:
g[a].append(b)
in... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/attributes.py | {
"start": 50656,
"end": 52759
} | class ____:
__slots__ = ()
collection: bool
_is_has_collection_adapter = True
def _dispose_previous_collection(
self,
state: InstanceState[Any],
collection: _AdaptedCollectionProtocol,
adapter: CollectionAdapter,
fire_event: bool,
) -> None:
raise No... | _HasCollectionAdapter |
python | django__django | tests/template_tests/filter_tests/test_wordcount.py | {
"start": 868,
"end": 1236
} | class ____(SimpleTestCase):
def test_empty_string(self):
self.assertEqual(wordcount(""), 0)
def test_count_one(self):
self.assertEqual(wordcount("oneword"), 1)
def test_count_multiple(self):
self.assertEqual(wordcount("lots of words"), 3)
def test_non_string_input(self):
... | FunctionTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py | {
"start": 41669,
"end": 45112
} | class ____(GKEOperatorMixin, KubernetesCreateResourceOperator):
"""
Create a resource in the specified Google Kubernetes Engine cluster.
This Operator assumes that the system has gcloud installed and has configured a
connection id with a service account.
.. seealso::
For more detail about ... | GKECreateCustomResourceOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 56700,
"end": 63217
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "search_query_performance_report_hourly"
report_file = "search_query_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "search_query_performance_report_hourly_increme... | TestSearchQueryPerformanceReportHourlyStream |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 18231,
"end": 18901
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | ChineseCLIPTextIntermediate |
python | django__django | tests/queries/tests.py | {
"start": 85734,
"end": 86559
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Note.objects.create(note="n1", misc="foo", id=1)
def test_ticket14729(self):
# Test representation of raw query with one or few parameters passed as
# list
query = "SELECT * FROM queries_note WHERE note = %s"
... | RawQueriesTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/slots3.py | {
"start": 139,
"end": 337
} | class ____:
def __init__(self, *, slot: str): ...
def __set__(self, instance: object, value: object) -> None: ...
def __get__(self, instance: object, owner: Any) -> Any: ...
| MyDescriptor |
python | doocs__leetcode | lcof/面试题58 - I. 翻转单词顺序/Solution2.py | {
"start": 0,
"end": 104
} | class ____:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 179,
"end": 247
} | class ____:
if ...:
def __eq__(self, other): ...
| MaybeEqIf |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 1067,
"end": 1733
} | class ____(TestCase):
def test_basic(self):
y1 = [0, 0, 1, 0]
y2 = [0, 0, 0, 0]
y3 = [1, 0, 1, 0]
assert np.any(y1)
assert np.any(y3)
assert not np.any(y2)
def test_nd(self):
y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
assert np.any(y1)
assert_... | TestAny |
python | huggingface__transformers | src/transformers/models/aria/modular_aria.py | {
"start": 40512,
"end": 40899
} | class ____(ProcessingKwargs, total=False):
images_kwargs: AriaImagesKwargs
_defaults = {
"text_kwargs": {
"padding": False,
"return_mm_token_type_ids": False,
},
"images_kwargs": {
"max_image_size": 980,
"split_image": False,
},
... | AriaProcessorKwargs |
python | kamyu104__LeetCode-Solutions | Python/find-minimum-time-to-reach-last-room-i.py | {
"start": 89,
"end": 1274
} | class ____(object):
def minTimeToReach(self, moveTime):
"""
:type moveTime: List[List[int]]
:rtype: int
"""
def dijkstra(start, target):
DIRECTIONS = [(1, 0), (0, 1), (-1, 0), (0, -1)]
dist = [[float("inf")]*len(moveTime[0]) for _ in xrange(len(moveTim... | Solution |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/api_test.py | {
"start": 7715,
"end": 10152
} | class ____(TestCase):
def setUp(self) -> None:
self._params = RendezvousParameters(
backend="dummy_backend",
endpoint="dummy_endpoint",
run_id="dummy_run_id",
min_nodes=1,
max_nodes=1,
)
self._registry = RendezvousHandlerRegistry()... | RendezvousHandlerRegistryTest |
python | walkccc__LeetCode | solutions/190. Reverse Bits/190.py | {
"start": 0,
"end": 157
} | class ____:
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
if n >> i & 1:
ans |= 1 << 31 - i
return ans
| Solution |
python | apache__airflow | providers/amazon/tests/system/amazon/aws/utils/__init__.py | {
"start": 6650,
"end": 14933
} | class ____:
"""
This builder class ultimately constructs a TaskFlow task which is run at
runtime (task execution time). This task generates and stores the test ENV_ID as well
as any external resources requested (e.g.g IAM Roles, VPC, etc)
"""
def __init__(self):
self.variables = set()
... | SystemTestContextBuilder |
python | pyinstaller__pyinstaller | PyInstaller/depend/imphook.py | {
"start": 26690,
"end": 27568
} | class ____:
"""
Cache for storing what binaries and datas were pushed by what modules when import hooks were processed.
"""
def __init__(self):
self._binaries = {}
self._datas = {}
def add(self, modname, binaries, datas):
self._binaries.setdefault(modname, [])
self.... | AdditionalFilesCache |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 19525,
"end": 19638
} | class ____(OpcodeWithArg):
_FLAGS = HAS_ARGUMENT | HAS_JREL | NO_NEXT
__slots__ = ()
| JUMP_BACKWARD_NO_INTERRUPT |
python | pallets__click | src/click/core.py | {
"start": 74961,
"end": 75122
} | class ____(Group, metaclass=_FakeSubclassCheck):
"""
.. deprecated:: 8.2
Will be removed in Click 9.0. Use ``Group`` instead.
"""
| _MultiCommand |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/shell-script-component/with-config-schema-meta-yaml.py | {
"start": 61,
"end": 558
} | class ____(dg.Component, dg.Model, dg.Resolvable):
"""Models a shell script as a Dagster asset."""
script_path: str
asset_specs: Sequence[dg.ResolvedAssetSpec]
# highlight-start
@classmethod
def get_spec(cls) -> dg.ComponentTypeSpec:
return dg.ComponentTypeSpec(
owners=["jo... | ShellCommand |
python | walkccc__LeetCode | solutions/3347. Maximum Frequency of an Element After Performing Operations II/3347.py | {
"start": 42,
"end": 740
} | class ____:
# Same as 3346. Maximum Frequency of an Element After Performing Operations I
def maxFrequency(self, nums: list[int], k: int, numOperations: int) -> int:
ans = 1
adjustable = 0
count = collections.Counter(nums)
line = SortedDict()
candidates = set()
for num in nums:
line[n... | Solution |
python | ApeWorX__ape | src/ape_ethereum/ecosystem.py | {
"start": 11537,
"end": 12781
} | class ____(BlockAPI):
"""
Class for representing a block on a chain.
"""
gas_limit: HexInt = Field(alias="gasLimit")
gas_used: HexInt = Field(alias="gasUsed")
base_fee: HexInt = Field(default=0, alias="baseFeePerGas")
difficulty: HexInt = 0
total_difficulty: HexInt = Field(default=0, al... | Block |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_process_event.py | {
"start": 27014,
"end": 27862
} | class ____(LanguageSpecificDeriveCodeMappings):
platform = "python"
def test_auto_source_code_config_stack_and_source_root_do_not_match(self) -> None:
self._process_and_assert_configuration_changes(
repo_trees={REPO1: ["src/sentry/foo/bar.py"]},
frames=[self.frame("sentry/foo/ba... | TestPythonDeriveCodeMappings |
python | spack__spack | lib/spack/spack/test/installer_tui.py | {
"start": 6215,
"end": 10467
} | class ____:
"""Test output rendering for TTY and non-TTY modes"""
def test_non_tty_output(self):
"""Test that non-TTY mode prints simple state changes"""
status, _, fake_stdout = create_build_status(is_tty=False)
spec = MockSpec("mypackage", "1.0")
status.add_build(spec, explic... | TestOutputRendering |
python | pypa__warehouse | tests/common/db/accounts.py | {
"start": 2356,
"end": 2482
} | class ____(WarehouseFactory):
class Meta:
model = User.Event
source = factory.SubFactory(User)
| UserEventFactory |
python | conda__conda | conda/plugins/types.py | {
"start": 8052,
"end": 8394
} | class ____(ChannelNameMixin, AuthBase):
"""
Base class that we require all plugin implementations to use to be compatible.
Authentication is tightly coupled with individual channels. Therefore, an additional
``channel_name`` property must be set on the ``requests.auth.AuthBase`` based class.
"""
... | ChannelAuthBase |
python | django__django | tests/admin_filters/tests.py | {
"start": 5693,
"end": 5787
} | class ____(UserAdmin):
list_filter = ("books_authored", "books_contributed")
| CustomUserAdmin |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_required.py | {
"start": 1349,
"end": 2888
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpr.Required()
def test_valid(self) -> None:
prop = bcpr.Required(List(Int))
assert prop.is_valid([])
assert prop.is_valid([1, 2, 3])
def test_invalid(self) -> None:
prop = bcpr.Re... | Test_Required |
python | ray-project__ray | rllib/examples/algorithms/appo_custom_algorithm_w_shared_data_actor.py | {
"start": 5949,
"end": 7729
} | class ____(ConnectorV2):
def __call__(self, *, episodes, batch, metrics, **kwargs):
if not isinstance(episodes[0], SingleAgentEpisode):
raise ValueError("This connector only works on `SingleAgentEpisodes`.")
# Get the manipulated rewards from the shared actor and add them to the train
... | ManipulatedRewardConnector |
python | wandb__wandb | wandb/vendor/pygments/lexers/lisp.py | {
"start": 652,
"end": 7071
} | class ____(RegexLexer):
"""
A Scheme lexer, parsing a stream and outputting the tokens
needed to highlight scheme code.
This lexer could be most probably easily subclassed to parse
other LISP-Dialects like Common Lisp, Emacs Lisp or AutoLisp.
This parser is checked with pastes from the LISP pas... | SchemeLexer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_write_col.py | {
"start": 297,
"end": 749
} | class ____(unittest.TestCase):
"""
Test the Drawing _write_col() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_col(self):
"""Test the _write_col() method"""
self.drawing._wri... | TestWriteXdrcol |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_L.py | {
"start": 5637,
"end": 7203
} | class ____(Benchmark):
r"""
Levy 3 objective function.
This class defines the Levy 3 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Levy03}}(\mathbf{x}) =
\sin^2(\pi y_1)+\sum_{i=1}^{n-1}(y_i-1)^2[1+10\sin^2(\pi ... | Levy03 |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 3738,
"end": 3887
} | class ____(SlotsManipulationTest):
__slots__ += ["d", "e", "f"] # pylint: disable=undefined-variable
T = TestChild()
print(T.__slots__)
| TestChild |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.