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 | langchain-ai__langchain | libs/core/langchain_core/tracers/stdout.py | {
"start": 1250,
"end": 6425
} | class ____(BaseTracer):
"""Tracer that calls a function with a single str parameter."""
name: str = "function_callback_handler"
"""The name of the tracer. This is used to identify the tracer in the logs."""
def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:
"""Create a... | FunctionCallbackHandler |
python | TheAlgorithms__Python | graphs/minimum_spanning_tree_kruskal2.py | {
"start": 83,
"end": 283
} | class ____[T]:
# Disjoint Set Node to store the parent and rank
def __init__(self, data: T) -> None:
self.data = data
self.parent = self
self.rank = 0
| DisjointSetTreeNode |
python | pyparsing__pyparsing | examples/adventureEngine.py | {
"start": 6591,
"end": 6888
} | class ____(Command):
def __init__(self, quals):
super().__init__("LOOK", "looking")
@staticmethod
def help_description():
return "LOOK or L - describes the current room and any objects in it"
def _do_command(self, player):
player.room.describe()
| LookCommand |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 44605,
"end": 47282
} | class ____(unittest.TestCase):
def verify_custom_model_name_feature(
self, model, expected_class_name, expected_table_name
):
history_model = model.history.model
self.assertEqual(history_model.__name__, expected_class_name)
self.assertEqual(history_model._meta.db_table, expected_... | CustomModelNameTests |
python | django-guardian__django-guardian | guardian/admin.py | {
"start": 19597,
"end": 20452
} | class ____(forms.Form):
user = forms.CharField(
label=_("User identification"),
max_length=200,
error_messages={"does_not_exist": _("This user does not exist")},
help_text=_("Enter a value compatible with User.USERNAME_FIELD"),
)
def clean_user(self):
"""Returns `Use... | UserManage |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 18669,
"end": 21504
} | class ____:
def test_invalid_policy_identifier(self):
with pytest.raises(TypeError):
x509.PolicyInformation("notanoid", None) # type:ignore[arg-type]
def test_none_policy_qualifiers(self):
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), None)
assert pi.policy_id... | TestPolicyInformation |
python | walkccc__LeetCode | solutions/3167. Better Compression of String/3167.py | {
"start": 0,
"end": 435
} | class ____:
def betterCompression(self, compressed: str) -> str:
count = collections.Counter()
i = 0
while i < len(compressed):
c = compressed[i]
i += 1
freq = 0
while i < len(compressed) and compressed[i].isdigit():
freq = freq * 10 + int(compressed[i])
i += 1
... | Solution |
python | milvus-io__pymilvus | tests/test_search_result.py | {
"start": 2447,
"end": 10995
} | class ____:
@pytest.mark.parametrize("pk", [
schema_pb2.IDs(int_id=schema_pb2.LongArray(data=list(range(6)))),
schema_pb2.IDs(str_id=schema_pb2.StringArray(data=[str(i*10) for i in range(6)]))
])
@pytest.mark.parametrize("round_decimal", [
None,
-1,
4,
])
def ... | TestSearchResult |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 74548,
"end": 77261
} | class ____(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-caption
__slots__ = tuple()
def ignoreEndTagCaption(self):
return not self.tree.elementInScope("caption", variant="table")
def processEOF(self):
self.parser.phases["inBody"].processEOF()
def processCharacte... | InCaptionPhase |
python | apache__airflow | airflow-core/tests/unit/core/test_settings.py | {
"start": 1893,
"end": 2446
} | class ____:
def __init__(self, content: str, module_name: str):
self.content = content
self.settings_root = tempfile.mkdtemp()
filename = f"{module_name}.py"
self.settings_file = os.path.join(self.settings_root, filename)
def __enter__(self):
with open(self.settings_file... | SettingsContext |
python | astropy__astropy | astropy/modeling/polynomial.py | {
"start": 27574,
"end": 30885
} | class ____(_PolyDomainWindow1D):
r"""
1D Polynomial model.
It is defined as:
.. math::
P = \sum_{i=0}^{i=n}C_{i} * x^{i}
For explanation of ``domain``, and ``window`` see
:ref:`Notes regarding usage of domain and window <domain-window-note>`.
Parameters
----------
degree... | Polynomial1D |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 724,
"end": 865
} | class ____(Protocol1, Protocol3):
cm1 = 3
def __init__(self):
im1 = 0
# This should generate an error.
Concrete3()
| Concrete3 |
python | huggingface__transformers | src/transformers/models/donut/modeling_donut_swin.py | {
"start": 35251,
"end": 36043
} | class ____(PreTrainedModel):
config: DonutSwinConfig
base_model_prefix = "donut"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = True
_no_split_modules = ["DonutSwinStage"]
@torch.no_grad()
def _init_weights(self, module):
"""Init... | DonutSwinPreTrainedModel |
python | ray-project__ray | python/ray/_private/object_ref_generator.py | {
"start": 865,
"end": 10554
} | class ____:
"""A generator to obtain object references from a task in a streaming manner.
The class is compatible with the Python generator and async generator interfaces.
The class is not thread-safe.
Do not initialize the class and create an instance directly.
The instance should be created by ... | ObjectRefGenerator |
python | django-haystack__django-haystack | test_haystack/discovery/models.py | {
"start": 183,
"end": 338
} | class ____(models.Model):
author = models.CharField(max_length=255)
content = models.TextField()
def __str__(self):
return self.author
| Bar |
python | gevent__gevent | src/gevent/lock.py | {
"start": 1712,
"end": 3593
} | class ____(object):
__slots__ = (
'_owned_thread_id',
'_gil',
'_atomic',
'_recursion_depth',
)
# Don't allow re-entry to these functions in a single thread, as
# can happen if a sys.settrace is used. (XXX: What does that even
# mean? Our original implementation that d... | _GILLock |
python | PyCQA__isort | isort/exceptions.py | {
"start": 2161,
"end": 2532
} | class ____(FileSkipped):
"""Raised when an entire file is skipped due to provided isort settings"""
def __init__(self, file_path: str, **kwargs: str):
super().__init__(
f"{file_path} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting",
... | FileSkipSetting |
python | django__django | django/contrib/postgres/aggregates/general.py | {
"start": 822,
"end": 910
} | class ____(Aggregate):
function = "BOOL_AND"
output_field = BooleanField()
| BoolAnd |
python | ray-project__ray | python/ray/_common/tests/test_signature.py | {
"start": 9335,
"end": 11724
} | class ____:
"""Tests for the flatten_args utility function."""
def test_only_positional_args(self):
"""Test flattening with only positional arguments."""
def test_func(a, b, c):
return a + b + c
params = extract_signature(test_func)
flattened = flatten_args(params,... | TestFlattenArgs |
python | ray-project__ray | python/ray/dashboard/memory_utils.py | {
"start": 1361,
"end": 2622
} | class ____(Enum):
# We don't use enum because enum is not json serializable.
ACTOR_HANDLE = "ACTOR_HANDLE"
PINNED_IN_MEMORY = "PINNED_IN_MEMORY"
LOCAL_REFERENCE = "LOCAL_REFERENCE"
USED_BY_PENDING_TASK = "USED_BY_PENDING_TASK"
CAPTURED_IN_OBJECT = "CAPTURED_IN_OBJECT"
UNKNOWN_STATUS = "UNKNO... | ReferenceType |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 2043,
"end": 2190
} | class ____:
"""The aggregation result for a collection."""
properties: AProperties
total_count: Optional[int]
@dataclass
| AggregateReturn |
python | getsentry__sentry | tests/sentry/db/test_transactions.py | {
"start": 926,
"end": 4927
} | class ____:
def test_collect_transaction_queries(self) -> None:
with collect_transaction_queries() as queries, outbox_context(flush=False):
Organization.objects.filter(name="org1").first()
User.objects.filter(username="user1").first()
with transaction.atomic(using=router... | CaseMixin |
python | realpython__materials | python-class/vehicles.py | {
"start": 341,
"end": 686
} | class ____(Vehicle):
def __init__(self, make, model, year, num_seats):
super().__init__(make, model, year)
self.num_seats = num_seats
def drive(self):
print(f'Driving my "{self.make} - {self.model}" on the road')
def __str__(self):
return f'"{self.make} - {self.model}" has ... | Car |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 11890,
"end": 11978
} | class ____(AnyUrl):
allowed_schemes = {'http', 'https'}
__slots__ = ()
| AnyHttpUrl |
python | sqlalchemy__sqlalchemy | test/orm/test_dynamic.py | {
"start": 45631,
"end": 51129
} | class ____(
_WriteOnlyFixture,
_UOWTests,
_fixtures.FixtureTest,
testing.AssertsExecutionResults,
):
__sparse_driver_backend__ = True
@testing.fixture
def passive_deletes_fixture(self, decl_base, connection):
"""passive deletes fixture
this fixture is separate from the Fixt... | WriteOnlyUOWTest |
python | dask__distributed | distributed/shuffle/tests/test_shuffle.py | {
"start": 96825,
"end": 98815
} | class ____(_ShuffleRunManager):
def __init__(self, plugin):
super().__init__(plugin)
self.in_fetch = asyncio.Event()
self.block_fetch = asyncio.Event()
async def _fetch(self, *args, **kwargs):
result = await super()._fetch(*args, **kwargs)
self.in_fetch.set()
awa... | PostFetchBlockingManager |
python | PyCQA__pylint | tests/functional/c/class_protocol_ellipsis.py | {
"start": 164,
"end": 922
} | class ____:
"""The "invalid-*-returned" messages shouldn't be emitted for stub functions
Original issue: https://github.com/pylint-dev/pylint/issues/4736"""
def __len__(self) -> int:
...
def __hash__(self) -> int:
...
def __index__(self) -> int:
...
def __iter__(self)... | MyClass |
python | sqlalchemy__sqlalchemy | test/sql/test_syntax_extensions.py | {
"start": 8638,
"end": 9988
} | class ____(
fixtures.CacheKeyFixture, fixtures.TestBase, AssertsCompiledSQL
):
__dialect__ = "default"
def test_render(self):
t = Table(
"t1", MetaData(), Column("c1", Integer), Column("c2", Integer)
)
stmt = select(t).ext(ColumnExpressionExt(t.c.c1, t.c.c2))
se... | TestExpressionExtensions |
python | explosion__spaCy | spacy/lang/he/__init__.py | {
"start": 117,
"end": 298
} | class ____(BaseDefaults):
stop_words = STOP_WORDS
lex_attr_getters = LEX_ATTRS
writing_system = {"direction": "rtl", "has_case": False, "has_letters": True}
| HebrewDefaults |
python | allegroai__clearml | clearml/backend_api/services/v2_9/auth.py | {
"start": 8286,
"end": 10076
} | class ____(Response):
"""
Response of auth.edit_user endpoint.
:param updated: Number of users updated (0 or 1)
:type updated: float
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "auth"
_action = "edit_user"
_version = "2.9"
_schema = {
... | EditUserResponse |
python | django__django | tests/bash_completion/tests.py | {
"start": 253,
"end": 3911
} | class ____(unittest.TestCase):
"""
Testing the Python level bash completion code.
This requires setting up the environment as if we got passed data
from bash.
"""
def setUp(self):
self.old_DJANGO_AUTO_COMPLETE = os.environ.get("DJANGO_AUTO_COMPLETE")
os.environ["DJANGO_AUTO_COMP... | BashCompletionTests |
python | modin-project__modin | stress_tests/kaggle/kaggle4.py | {
"start": 10067,
"end": 12565
} | class ____(BaseEstimator, RegressorMixin, TransformerMixin):
def __init__(self, base_models, meta_model, n_folds=5):
self.base_models = base_models
self.meta_model = meta_model
self.n_folds = n_folds
def fit(self, X, y):
self.base_models_ = [[] for _ in self.base_models]
... | StackingAveragedModels |
python | django__django | tests/schema/models.py | {
"start": 1237,
"end": 1382
} | class ____(models.Model):
name = models.CharField(max_length=255, db_index=True)
class Meta:
apps = new_apps
| AuthorWithIndexedName |
python | aio-libs__aiohttp | aiohttp/client_proto.py | {
"start": 584,
"end": 12098
} | class ____(BaseProtocol, DataQueue[tuple[RawResponseMessage, StreamReader]]):
"""Helper class to adapt between Protocol and StreamReader."""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
BaseProtocol.__init__(self, loop=loop)
DataQueue.__init__(self, loop)
self._should_c... | ResponseHandler |
python | google__jax | jax/_src/interpreters/ad.py | {
"start": 34957,
"end": 36942
} | class ____(Tracer):
__slots__ = ['primal', 'tangent']
def __init__(self, trace, primal, tangent):
if config.enable_checks.value:
_primal_tangent_shapes_match(primal, tangent)
self._trace = trace
self.primal = primal
self.tangent = tangent
def _short_repr(self):
return f"GradTracer<{sel... | JVPTracer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gradient09.py | {
"start": 315,
"end": 1439
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gradient09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.... | TestCompareXLSXFiles |
python | python-poetry__poetry | src/poetry/poetry.py | {
"start": 676,
"end": 2399
} | class ____(BasePoetry):
VERSION = __version__
def __init__(
self,
file: Path,
local_config: dict[str, Any],
package: ProjectPackage,
locker: Locker,
config: Config,
disable_cache: bool = False,
) -> None:
from poetry.repositories.repository_po... | Poetry |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1514857,
"end": 1515760
} | class ____(Transform):
"""
FlattenTransform schema wrapper.
Parameters
----------
flatten : Sequence[str, :class:`FieldName`]
An array of one or more data fields containing arrays to flatten. If multiple fields
are specified, their array values should have a parallel structure, idea... | FlattenTransform |
python | pandas-dev__pandas | pandas/tests/arrays/categorical/test_analytics.py | {
"start": 283,
"end": 13378
} | class ____:
@pytest.mark.parametrize("aggregation", ["min", "max"])
def test_min_max_not_ordered_raises(self, aggregation):
# unordered cats have no min/max
cat = Categorical(["a", "b", "c", "d"], ordered=False)
msg = f"Categorical is not ordered for operation {aggregation}"
agg_... | TestCategoricalAnalytics |
python | getsentry__sentry | tests/sentry/relocation/api/endpoints/test_unpause.py | {
"start": 596,
"end": 14315
} | class ____(APITestCase):
endpoint = "sentry-api-0-relocations-unpause"
method = "put"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(
email="owner", is_superuser=False, is_staff=True, is_active=True
)
self.superuser = self.create_user(is_s... | UnpauseRelocationTest |
python | doocs__leetcode | solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/Solution.py | {
"start": 0,
"end": 216
} | class ____:
def minIncrementOperations(self, nums: List[int], k: int) -> int:
f = g = h = 0
for x in nums:
f, g, h = g, h, min(f, g, h) + max(k - x, 0)
return min(f, g, h)
| Solution |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 887,
"end": 1247
} | class ____(models.Model):
street = models.CharField(max_length=80)
city = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=5)
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
co... | Address |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 54291,
"end": 56922
} | class ____(InputMixin, HtmlElement):
"""
Represents an ``<input>`` element.
You can get the type with ``.type`` (which is lower-cased and
defaults to ``'text'``).
Also you can get and set the value with ``.value``
Checkboxes and radios have the attribute ``input.checkable ==
True`` (for a... | InputElement |
python | jina-ai__jina | jina/clients/base/websocket.py | {
"start": 693,
"end": 9839
} | class ____(BaseClient):
"""A Websocket Client."""
async def _is_flow_ready(self, **kwargs) -> bool:
"""Sends a dry run to the Flow to validate if the Flow is ready to receive requests
:param kwargs: kwargs coming from the public interface. Includes arguments to be passed to the `WebsocketClien... | WebSocketBaseClient |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/hooks/teradata.py | {
"start": 3526,
"end": 11572
} | class ____(DbApiHook):
"""
General hook for interacting with Teradata SQL Database.
This module contains basic APIs to connect to and interact with Teradata SQL Database. It uses teradatasql
client internally as a database driver for connecting to Teradata database. The config parameters like
Terad... | TeradataHook |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py | {
"start": 19718,
"end": 22832
} | class ____(HunYuanDenseV1PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model ... | HunYuanDenseV1ForCausalLM |
python | walkccc__LeetCode | solutions/1854. Maximum Population Year/1854.py | {
"start": 0,
"end": 565
} | class ____:
def maximumPopulation(self, logs: list[list[int]]) -> int:
MIN_YEAR = 1950
MAX_YEAR = 2050
ans = 0
maxPopulation = 0
runningPopulation = 0
# population[i] := the population of year i
population = [0] * (MAX_YEAR + 1)
for birth, death in logs:
population[birth] += 1
... | Solution |
python | fluentpython__example-code | 11-iface-abc/tombola.py | {
"start": 33,
"end": 845
} | class ____(abc.ABC): # <1>
@abc.abstractmethod
def load(self, iterable): # <2>
"""Add items from an iterable."""
@abc.abstractmethod
def pick(self): # <3>
"""Remove item at random, returning it.
This method should raise `LookupError` when the instance is empty.
"""
... | Tombola |
python | jazzband__django-polymorphic | example/orders/models.py | {
"start": 1385,
"end": 1652
} | class ____(Payment):
"""
Payment by bank
"""
bank_name = models.CharField(max_length=100)
swift = models.CharField(max_length=20)
class Meta:
verbose_name = _("Bank Payment")
verbose_name_plural = _("Bank Payments")
| BankPayment |
python | huggingface__transformers | tests/models/blenderbot/test_modeling_blenderbot.py | {
"start": 20071,
"end": 21254
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (BlenderbotDecoder, BlenderbotForCausalLM) if is_torch_available() else ()
is_encoder_decoder = False
def setUp(
self,
):
self.model_tester = BlenderbotStandaloneDecoderModelTester(self, is_trai... | BlenderbotStandaloneDecoderModelTest |
python | numba__numba | numba/tests/test_generators.py | {
"start": 2290,
"end": 9257
} | class ____(MemoryLeakMixin, TestCase):
def check_generator(self, pygen, cgen):
self.assertEqual(next(cgen), next(pygen))
# Use list comprehensions to make sure we trash the generator's
# former C stack.
expected = [x for x in pygen]
got = [x for x in cgen]
self.assert... | TestGenerators |
python | sympy__sympy | sympy/sets/sets.py | {
"start": 64236,
"end": 65807
} | class ____(Set):
"""Represents the set of elements which are in either of the
sets and not in their intersection.
Examples
========
>>> from sympy import SymmetricDifference, FiniteSet
>>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5))
{1, 2, 4, 5}
See Also
========
... | SymmetricDifference |
python | ray-project__ray | python/ray/_private/log.py | {
"start": 930,
"end": 4780
} | class ____(logging.StreamHandler):
"""A plain log handler.
This handler writes to whatever sys.stderr points to at emit-time,
not at instantiation time. See docs for logging._StderrHandler.
"""
def __init__(self):
super().__init__()
self.plain_handler = logging._StderrHandler()
... | PlainRayHandler |
python | aimacode__aima-python | csp.py | {
"start": 23830,
"end": 28186
} | class ____(CSP):
"""
Make a CSP for the nQueens problem for search with min_conflicts.
Suitable for large n, it uses only data structures of size O(n).
Think of placing queens one per column, from left to right.
That means position (x, y) represents (var, val) in the CSP.
The main structures are... | NQueensCSP |
python | django__django | django/test/utils.py | {
"start": 20458,
"end": 24100
} | class ____(TestContextDecorator):
"""
Act as a decorator. Override list of registered system checks.
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
you also need to exclude its system checks.
"""
def __init__(self, new_checks, deployment_checks=None):
from dj... | override_system_checks |
python | realpython__materials | python-314/tstrings.py | {
"start": 147,
"end": 2252
} | class ____:
statement: str
params: list[Any]
def __init__(self, template: Template) -> None:
items, params = [], []
for item in template:
match item:
case str():
items.append(item)
case Interpolation(value, _, conversion, forma... | SQLQuery |
python | apache__airflow | airflow-core/src/airflow/timetables/datasets.py | {
"start": 966,
"end": 1451
} | class ____:
"""Deprecated alias for `AssetOrTimeSchedule`."""
def __new__(cls, *, timetable, datasets) -> AssetOrTimeSchedule: # type: ignore[misc]
warnings.warn(
"DatasetOrTimeSchedule is deprecated and will be removed in Airflow 3.2. Use `airflow.timetables.AssetOrTimeSchedule` instead."... | DatasetOrTimeSchedule |
python | python__mypy | mypyc/test/test_run.py | {
"start": 15619,
"end": 16379
} | class ____(TestRun):
"""Run the main multi-module tests in separate compilation mode.
In this mode there are multiple compilation groups, which are compiled
incrementally. Each group is compiled to a separate C file, and these C
files are compiled separately.
Each compiled module is placed into a ... | TestRunSeparate |
python | openai__openai-python | src/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py | {
"start": 662,
"end": 848
} | class ____(BaseModel):
data: List[Data]
has_more: bool
object: Literal["list"]
first_id: Optional[str] = None
last_id: Optional[str] = None
| PermissionRetrieveResponse |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 3810,
"end": 3950
} | class ____:
config_schema: dict[str, Any] | None = None
data_schema: dict[str, Any] | None = None
@dataclasses.dataclass
| ActionSchemas |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 4274,
"end": 9599
} | class ____(TestCase):
def setUp(self):
self.a = np.arange(10)
@xfail
def test_writeable(self):
mydict = locals()
self.a.flags.writeable = False
assert_raises(ValueError, runstring, "self.a[0] = 3", mydict)
assert_raises(ValueError, runstring, "self.a[0:1].itemset(3)"... | TestFlag |
python | pytorch__pytorch | test/jit/test_graph_rewrite_passes.py | {
"start": 225,
"end": 2373
} | class ____(JitTestCase):
def test_fuse_linear(self):
class FunctionalLinear(torch.nn.Module):
def __init__(self, weight, bias):
super().__init__()
self.weight = weight
self.bias = bias
def forward(self, x):
res = torch.... | TestGraphRewritePasses |
python | viewflow__viewflow | viewflow/workflow/flow/viewset.py | {
"start": 11687,
"end": 14963
} | class ____(BulkActionsViewsMixin, Application):
"""
Viewset includes multiples flow with common Inbox/Queue/Archive views as an
separate App into Site.
`Life demo
<https://demo.viewflow.io/workflow/inbox/>`_
Usage:
.. code-block:: python
site = Site(
viewsets=[
... | WorkflowAppViewset |
python | joblib__joblib | joblib/_parallel_backends.py | {
"start": 9821,
"end": 11027
} | class ____(ParallelBackendBase):
"""A ParallelBackend which will execute all batches sequentially.
Does not use/create any threading objects, and hence has minimal
overhead. Used when n_jobs == 1.
"""
uses_threads = True
supports_timeout = False
supports_retrieve_callback = False
suppo... | SequentialBackend |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 300624,
"end": 301115
} | class ____(sgqlc.types.Input):
"""Ordering options for connections to get sponsor entities for
GitHub Sponsors.
"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(SponsorOrderField), graphql_name="field")
"""The field to or... | SponsorOrder |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/vala.py | {
"start": 296,
"end": 10164
} | class ____(Task.Task):
vars = ["VALAC", "VALAC_VERSION", "VALAFLAGS"]
ext_out = ['.h']
def run(self):
cmd = self.env.VALAC + self.env.VALAFLAGS
resources = getattr(self, 'vala_exclude', [])
cmd.extend([a.abspath() for a in self.inputs if a not in resources])
ret = self.exec_... | valac |
python | pytorch__pytorch | test/ao/sparsity/test_data_sparsifier.py | {
"start": 26407,
"end": 30520
} | class ____(TestCase):
def test_ptq_sparsify_first(self):
"""The expectation is post_training_sparse_quantize function
1. Takes in a model
2. Sparsifies the embeddings
3. Quantize the embeddings
This unit test checks that
1. Embeddings and EmbeddingBags are sparsified... | TestQuantizationUtils |
python | django__django | tests/urlpatterns_reverse/tests.py | {
"start": 65686,
"end": 68070
} | class ____(SimpleTestCase):
url_patterns = [
path("inner/", views.empty_view, name="urlobject-view"),
re_path(
r"^inner/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$",
views.empty_view,
name="urlobject-view",
),
re_path(r"^inner/\+\\\$\*/$", views.empty_view... | IncludeTests |
python | pennersr__django-allauth | allauth/socialaccount/models.py | {
"start": 3260,
"end": 5722
} | class ____(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# Given a `SocialApp` from which this account originates, this field equals
# the app's `app.provider_id` if available, `app.provider` otherwise.
provider = models.CharField(
verbose_name=_("pr... | SocialAccount |
python | realpython__materials | thread-safety-locks/bank_rlock.py | {
"start": 81,
"end": 1188
} | class ____:
def __init__(self):
self.balance = 0
self.lock = threading.RLock()
def deposit(self, amount):
print(
f"Thread {threading.current_thread().name} "
"waiting to acquire lock for .deposit()"
)
with self.lock:
print(
... | BankAccount |
python | huggingface__transformers | src/transformers/models/glm4_moe/configuration_glm4_moe.py | {
"start": 1317,
"end": 10422
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Glm4MoeModel`]. It is used to instantiate a
Glm4Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar confi... | Glm4MoeConfig |
python | doocs__leetcode | lcci/17.10.Find Majority Element/Solution.py | {
"start": 0,
"end": 289
} | class ____:
def majorityElement(self, nums: List[int]) -> int:
cnt = m = 0
for v in nums:
if cnt == 0:
m, cnt = v, 1
else:
cnt += 1 if m == v else -1
return m if nums.count(m) > len(nums) // 2 else -1
| Solution |
python | google__pytype | pytype/output.py | {
"start": 908,
"end": 46459
} | class ____(utils.ContextWeakrefMixin):
"""Functions for converting abstract classes into PyTD."""
class OutputMode(enum.IntEnum):
"""Controls the level of detail in pytd types. See set_output_mode."""
NORMAL = 0
DETAILED = 1
LITERAL = 2
def __init__(self, ctx):
super().__init__(ctx)
sel... | Converter |
python | huggingface__transformers | src/transformers/models/exaone4/modeling_exaone4.py | {
"start": 15551,
"end": 16135
} | class ____(PreTrainedModel):
config: Exaone4Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Exaone4DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True... | Exaone4PreTrainedModel |
python | astropy__astropy | astropy/io/fits/tests/test_table.py | {
"start": 134927,
"end": 154849
} | class ____(FitsTestCase):
def test_column_format_interpretation(self):
"""
Test to ensure that when Numpy-style record formats are passed in to
the Column constructor for the format argument, they are recognized so
long as it's unambiguous (where "unambiguous" here is questionable
... | TestColumnFunctions |
python | keras-team__keras | keras/src/backend/tensorflow/layer.py | {
"start": 198,
"end": 4334
} | class ____(KerasAutoTrackable):
def __init__(self, *args, **kwargs):
# Export-related attributes
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._tracked = []
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inpu... | TFLayer |
python | spack__spack | lib/spack/spack/ci/generator_registry.py | {
"start": 803,
"end": 974
} | class ____(spack.error.SpackError):
def __init__(self, generator_name):
super().__init__(f"No registered generator for {generator_name}")
| UnknownGeneratorException |
python | openai__openai-python | src/openai/types/beta/threads/message_create_params.py | {
"start": 1891,
"end": 2083
} | class ____(TypedDict, total=False):
file_id: str
"""The ID of the file to attach to the message."""
tools: Iterable[AttachmentTool]
"""The tools to add this file to."""
| Attachment |
python | numba__numba | numba/pycc/compiler.py | {
"start": 1700,
"end": 13204
} | class ____(object):
"""A base class to compile Python modules to a single shared library or
extension module.
:param export_entries: a list of ExportEntry instances.
:param module_name: the name of the exported module.
"""
#: Structure used to describe a method of an extension type.
#: str... | _ModuleCompiler |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/tensor_to_test.py | {
"start": 1276,
"end": 1956
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, dtype_one, dtype_two, device):
self.inputs = {
"input": torch.rand(
M, N, device=device, requires_grad=False, dtype=torch.float
).to(dtype=dtype_one)
}
self.dtype_one = dtype_one
sel... | TensorConversionBenchmark |
python | pytorch__pytorch | test/onnx/exporter/test_verification.py | {
"start": 3305,
"end": 4180
} | class ____(common_utils.TestCase):
def test_interpreter_stores_correct_info(self):
class Model(torch.nn.Module):
def forward(self, a, b):
c = a + b
return c - 1
model = Model()
args = (torch.tensor([1.0]), torch.tensor([2.0]))
onnx_program... | VerificationInterpreterTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/__init__.py | {
"start": 523,
"end": 2740
} | class ____(OptionCompletionFinder):
"""
Custom option completion finder for argcomplete which allows completion results to be registered.
These registered completions, if provided, are used to filter the final completion results.
This works around a known bug: https://github.com/kislyuk/argcomplete/issu... | RegisteredCompletionFinder |
python | streamlit__streamlit | lib/streamlit/web/server/routes.py | {
"start": 4301,
"end": 4426
} | class ____(tornado.web.RequestHandler):
@tornado.web.removeslash
def get(self) -> None:
pass
| RemoveSlashHandler |
python | getsentry__sentry | src/sentry/utils/locking/backends/redis.py | {
"start": 3038,
"end": 3658
} | class ____(BaseRedisLockBackend):
cluster: RedisCluster[str] | StrictRedis[str]
def __init__(
self,
cluster: str | RedisCluster[str] | StrictRedis[str],
prefix: str = "l:",
uuid: str | None = None,
):
if isinstance(cluster, str):
cluster = redis.redis_clu... | RedisClusterLockBackend |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_indexing.py | {
"start": 4225,
"end": 6001
} | class ____:
def test_where_doesnt_retain_freq(self):
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
cond = [True, True, False]
expected = TimedeltaIndex([tdi[0], tdi[1], tdi[0]], freq=None, name="idx")
result = tdi.where(cond, tdi[::-1])
tm.assert_index_equa... | TestWhere |
python | fluentpython__example-code | attic/dicts/test_transformdict.py | {
"start": 9317,
"end": 9366
} | class ____(TransformDict):
pass
| MyTransformDict |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 29519,
"end": 32439
} | class ____(NonStrictDataModel):
"""
:param id: Worker ID
:type id: str
:param name: Worker name
:type name: str
:param next_task: Next task in the queue
:type next_task: IdNameEntry
:param num_tasks: Number of task entries in the queue
:type num_tasks: int
"""
_schema = {
... | QueueEntry |
python | getsentry__sentry | src/sentry/relay/types/generic_filters.py | {
"start": 111,
"end": 282
} | class ____(TypedDict):
"""Configuration for a generic filter that filters incoming events."""
id: str
isEnabled: bool
condition: RuleCondition
| GenericFilter |
python | PrefectHQ__prefect | src/integrations/prefect-ray/prefect_ray/context.py | {
"start": 214,
"end": 2014
} | class ____(ContextModel):
"""
The context for Ray remote_options management.
Attributes:
current_remote_options: A set of current remote_options in the context.
"""
__var__: ContextVar = ContextVar("remote_options")
current_remote_options: Dict[str, Any] = Field(default_factory=dict)
... | RemoteOptionsContext |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 39631,
"end": 42542
} | class ____(ProjectAdminMixin, PrivateViewMixin, TemplateView):
template_name = "projects/projects_search_analytics.html"
http_method_names = ["get"]
feature_type = TYPE_SEARCH_ANALYTICS
def get(self, request, *args, **kwargs):
download_data = request.GET.get("download", False)
if downlo... | SearchAnalytics |
python | huggingface__transformers | src/transformers/models/xlstm/modeling_xlstm.py | {
"start": 52982,
"end": 55560
} | class ____:
"""
Cache for xLSTM model which does not have attention mechanism and key value states.
Arguments:
config (`PreTrainedConfig):
The configuration file defining the shape-related attributes required to initialize the static cache.
max_batch_size (`int`):
Th... | xLSTMCache |
python | keras-team__keras | keras/src/regularizers/regularizers.py | {
"start": 7167,
"end": 7945
} | class ____(Regularizer):
"""A regularizer that applies a L1 regularization penalty.
The L1 regularization penalty is computed as:
`loss = l1 * reduce_sum(abs(x))`
L1 may be passed to a layer as a string identifier:
>>> dense = Dense(3, kernel_regularizer='l1')
In this case, the default value... | L1 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hardcoded-records/source_hardcoded_records/streams.py | {
"start": 834,
"end": 3601
} | class ____(HardcodedStream):
sample_record = {
"id": 6569096478909,
"email": "test@test.com",
"created_at": "2023-04-13T02:30:04-07:00",
"updated_at": "2023-04-24T06:53:48-07:00",
"first_name": "New Test",
"last_name": "Customer",
"orders_count": 0,
"s... | Customers |
python | paramiko__paramiko | tests/pkey.py | {
"start": 324,
"end": 9521
} | class ____:
# NOTE: this is incidentally tested by a number of other tests, such as the
# agent.py test suite
class from_type_string:
def loads_from_type_and_bytes(self, keys):
obj = PKey.from_type_string(keys.full_type, keys.pkey.asbytes())
assert obj == keys.pkey
#... | PKey_ |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec19.py | {
"start": 1111,
"end": 1892
} | class ____:
def func1(self, handler: CommandHandler2[P]) -> Command2[P]:
return Command2(handler)
def func2(
self,
handler: CommandHandler2[P],
) -> Callable[[CommandHandler2[P]], Command2[P]]:
def decorator(handler: CommandHandler2[P]) -> Command2[P]:
return sel... | Application2 |
python | sqlalchemy__sqlalchemy | test/orm/dml/test_evaluator.py | {
"start": 12437,
"end": 13938
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Parent(Base):
__tablename__ = "parent"
id = Column(Integer, primary_key=True)
class Child(Base):
__tablename__ = "child"
_i... | M2OEvaluateTest |
python | sanic-org__sanic | guide/webapp/display/markdown.py | {
"start": 4494,
"end": 5543
} | class ____(TableOfContents):
def generate_heading_id(self, token, index):
return slugify(token["text"])
RST_CODE_BLOCK_PATTERN = re.compile(
r"\.\.\scode-block::\s(\w+)\n\n((?:\n|(?:\s\s\s\s[^\n]*))+)"
)
_render_markdown = create_markdown(
renderer=DocsRenderer(),
plugins=[
RSTDirecti... | SanicTableOfContents |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py | {
"start": 9384,
"end": 9645
} | class ____(PreTrainedModel):
config: PromptDepthAnythingConfig
base_model_prefix = "prompt_depth_anything"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = True
| PromptDepthAnythingPreTrainedModel |
python | networkx__networkx | networkx/classes/tests/test_graphviews.py | {
"start": 169,
"end": 1471
} | class ____:
def setup_method(self):
self.G = nx.path_graph(9, create_using=nx.DiGraph())
self.rv = nx.reverse_view(self.G)
def test_pickle(self):
import pickle
rv = self.rv
prv = pickle.loads(pickle.dumps(rv, -1))
assert rv._node == prv._node
assert rv._... | TestReverseView |
python | mlflow__mlflow | mlflow/webhooks/types.py | {
"start": 2289,
"end": 3044
} | class ____(TypedDict):
"""Payload sent when a tag is set on a model version.
Example payload:
.. code-block:: python
{
"name": "example_model",
"version": "1",
"key": "example_key",
"value": "example_value",
}
"""
name: str
"""... | ModelVersionTagSetPayload |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.