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/langchain/langchain_classic/agents/xml/base.py | {
"start": 1033,
"end": 8165
} | class ____(BaseSingleActionAgent):
"""Agent that uses XML tags.
Args:
tools: list of tools the agent can choose from
llm_chain: The LLMChain to call to predict the next action
Examples:
```python
from langchain_classic.agents import XMLAgent
from langchain
... | XMLAgent |
python | ray-project__ray | doc/source/serve/doc_code/multiplexed.py | {
"start": 126,
"end": 1393
} | class ____:
def __init__(self):
self.bucket_name = "my_bucket"
@serve.multiplexed(max_num_models_per_replica=3)
async def get_model(self, model_id: str):
session = aioboto3.Session()
async with session.resource("s3") as s3:
obj = await s3.Bucket(self.bucket_name)
... | ModelInferencer |
python | doocs__leetcode | solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py | {
"start": 152,
"end": 450
} | class ____:
def postorder(self, root: 'Node') -> List[int]:
def dfs(root):
if root is None:
return
for child in root.children:
dfs(child)
ans.append(root.val)
ans = []
dfs(root)
return ans
| Solution |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py | {
"start": 13773,
"end": 22720
} | class ____(_LoadBalancer):
"""
Processing-Time based Round-Robin (PTRR) load balancer. This load balancer should
only be used for flex_attention() since it leverages `BlockMask`.
"""
def __init__(
self,
block_mask: BlockMask,
world_size: int,
):
"""
`bloc... | _PTRRLoadBalancer |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/subscribers/threaded_ray_installer.py | {
"start": 583,
"end": 708
} | class ____:
# Instance manager's instance id.
im_instance_id: str
# Error details.
details: str
| RayInstallError |
python | pytest-dev__pluggy | src/pluggy/_hooks.py | {
"start": 12239,
"end": 12732
} | class ____:
"""Hook holder object for performing 1:N hook calls where N is the number
of registered plugins."""
__slots__ = ("__dict__",)
def __init__(self) -> None:
""":meta private:"""
if TYPE_CHECKING:
def __getattr__(self, name: str) -> HookCaller: ...
# Historical name (pl... | HookRelay |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/test_kubernetes_helper_functions.py | {
"start": 1339,
"end": 2033
} | class ____:
def __init__(self, exception=None):
self.outcome = mock.Mock() if exception is not None else None
if self.outcome:
self.outcome.exception = mock.Mock(return_value=exception)
def test_should_retry_api():
exc = HTTPError()
assert _should_retry_api(exc)
exc = Kube... | DummyRetryState |
python | openai__openai-python | src/openai/resources/moderations.py | {
"start": 3835,
"end": 6826
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncModerationsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://ww... | AsyncModerations |
python | kubernetes-client__python | kubernetes/base/dynamic/exceptions.py | {
"start": 2795,
"end": 2903
} | class ____(Exception):
""" kubernetes-validate is not installed """
# HTTP Errors
| KubernetesValidateMissing |
python | getsentry__sentry | src/sentry/deletions/defaults/apigrant.py | {
"start": 213,
"end": 861
} | class ____(ModelDeletionTask[ApiGrant]):
"""
Normally ApiGrants are deleted in bulk, but for cascades originating from sentry app installation, we wish to use
the orm so that set null behavior functions correctly. Do not register this as the default, but instead use it as
the task= parameter to a relat... | ModelApiGrantDeletionTask |
python | getsentry__sentry | src/sentry/api/endpoints/organization_traces.py | {
"start": 4501,
"end": 6638
} | class ____(OrganizationTracesEndpointBase):
def get(self, request: Request, organization: Organization) -> Response:
if not features.has(
"organizations:performance-trace-explorer", organization, actor=request.user
) and not features.has(
"organizations:visibility-explore-vie... | OrganizationTracesEndpoint |
python | doocs__leetcode | lcof/面试题06. 从尾到头打印链表/Solution2.py | {
"start": 136,
"end": 347
} | class ____:
def reversePrint(self, head: ListNode) -> List[int]:
if head is None:
return []
ans = self.reversePrint(head.next)
ans.append(head.val)
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/bases/base-normalization/normalization/transform_catalog/table_name_registry.py | {
"start": 2799,
"end": 3632
} | class ____(Dict[str, List[NormalizedNameMetadata]]):
"""
An intermediate registry used by TableNameRegistry to detect conflicts in file names
"""
def __init__(self):
super(NormalizedFilesRegistry, self).__init__()
def add(
self, intermediate_schema: str, schema: str, json_path: Lis... | NormalizedFilesRegistry |
python | miyuchina__mistletoe | mistletoe/span_tokenizer.py | {
"start": 2638,
"end": 3915
} | class ____:
def __init__(self, start, end, match, string, cls, fallback_token):
self.start = start
self.end = end
self.parse_start = match.start(cls.parse_group)
self.parse_end = match.end(cls.parse_group)
self.match = match
self.string = string
self.cls = cls... | ParseToken |
python | sympy__sympy | sympy/tensor/tensor.py | {
"start": 97260,
"end": 115777
} | class ____(TensExpr):
"""
Base tensor class, i.e. this represents a tensor, the single unit to be
put into an expression.
Explanation
===========
This object is usually created from a ``TensorHead``, by attaching indices
to it. Indices preceded by a minus sign are considered contravariant,... | Tensor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generic1.py | {
"start": 587,
"end": 728
} | class ____(Generic[T]):
# This should generate an error.
x: Generic[T]
def func3(x: type):
if x is Generic:
return
| Class5 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/upath_io_manager.py | {
"start": 498,
"end": 20014
} | class ____(IOManager):
"""Abstract IOManager base class compatible with local and cloud storage via `universal-pathlib` and `fsspec`.
Features:
- handles partitioned assets
- handles loading a single upstream partition
- handles loading multiple upstream partitions (with respect to :py:class:`Pa... | UPathIOManager |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_year.py | {
"start": 5171,
"end": 7542
} | class ____:
def test_misspecified(self):
with pytest.raises(ValueError, match="Month must go from 1 to 12"):
YearEnd(month=13)
offset_cases = []
offset_cases.append(
(
YearEnd(),
{
datetime(2008, 1, 1): datetime(2008, 12, 31),
... | TestYearEnd |
python | huggingface__transformers | src/transformers/models/fsmt/modeling_fsmt.py | {
"start": 26099,
"end": 32490
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim,
num_heads,
dropout=0.0,
bias=True,
encoder_decoder_attention=False, # otherwise self_attention
layer_idx=None,
):
super(... | Attention |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/configure_warning/package.py | {
"start": 228,
"end": 1001
} | class ____(AutotoolsPackage):
"""This package prints output that looks like an error during configure, but
it actually installs successfully."""
homepage = "http://www.example.com"
url = "http://www.example.com/configure-warning-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
... | ConfigureWarning |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-instagram/unit_tests/integration/test_media.py | {
"start": 2162,
"end": 5431
} | class ____(TestCase):
@staticmethod
def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput:
return read_output(
config_builder=config_,
stream_name=_STREAM_NAME,
sync_mode=SyncMode.full_refresh,
expecting_exception=expecti... | TestFullRefresh |
python | huggingface__transformers | tests/models/mlcd/test_modeling_mlcd.py | {
"start": 1105,
"end": 4063
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
dropout=0.1,
... | MLCDVisionModelTester |
python | readthedocs__readthedocs.org | readthedocs/api/v3/mixins.py | {
"start": 4506,
"end": 5557
} | class ____(NestedParentObjectMixin):
"""
Mixin to define queryset permissions for ViewSet only in one place.
All APIv3 ViewSet should inherit this mixin, unless specific permissions
required. In that case, a specific mixin for that case should be defined.
.. note::
When using nested views,... | ProjectQuerySetMixin |
python | PyCQA__pylint | tests/functional/u/unused/unused_import.py | {
"start": 2792,
"end": 2862
} | class ____:
def get_all_classes(self) -> "List[Bee]":
pass
| Bee |
python | django__django | tests/expressions/models.py | {
"start": 92,
"end": 278
} | class ____(models.Model):
name = models.CharField(max_length=50)
secretary = models.ForeignKey(
"Employee", models.CASCADE, null=True, related_name="managers"
)
| Manager |
python | pypa__setuptools | setuptools/_distutils/command/config.py | {
"start": 862,
"end": 12724
} | class ____(Command):
description = "prepare to build"
user_options = [
('compiler=', None, "specify the compiler type"),
('cc=', None, "specify the compiler executable"),
('include-dirs=', 'I', "list of directories to search for header files"),
('define=', 'D', "C preprocessor m... | config |
python | euske__pdfminer | pdfminer/cmapdb.py | {
"start": 3356,
"end": 3779
} | class ____(CMap):
def add_code2cid(self, code, cid):
assert isinstance(code, bytes) and isinstance(cid, int)
d = self.code2cid
for c in code[:-1]:
c = ord(c)
if c in d:
d = d[c]
else:
t = {}
d[c] = t
... | FileCMap |
python | getsentry__sentry | src/sentry/issues/issue_occurrence.py | {
"start": 1222,
"end": 1654
} | class ____:
name: str
value: str
# Whether to prioritise displaying this evidence to users over other issue evidence. Should
# only be one important row per occurrence.
important: bool
def to_dict(
self,
) -> IssueEvidenceData:
return {
"name": self.name,
... | IssueEvidence |
python | modin-project__modin | modin/core/computation/ops.py | {
"start": 13345,
"end": 14737
} | class ____(Op):
"""
Hold a unary operator and its operands.
Parameters
----------
op : str
The token used to represent the operator.
operand : Term or Op
The Term or Op operand to the operator.
Raises
------
ValueError
* If no function associated with the pa... | UnaryOp |
python | Textualize__textual | examples/dictionary.py | {
"start": 321,
"end": 2464
} | class ____(App):
"""Searches a dictionary API as-you-type."""
CSS_PATH = "dictionary.tcss"
results = getters.query_one("#results", Markdown)
input = getters.query_one(Input)
def compose(self) -> ComposeResult:
yield Input(placeholder="Search for a word", id="dictionary-search")
wi... | DictionaryApp |
python | faif__python-patterns | patterns/behavioral/catalog.py | {
"start": 2391,
"end": 3419
} | class ____:
"""catalog of multiple class methods that are executed depending on an init
parameter
"""
x1 = "x1"
x2 = "x2"
def __init__(self, param: str) -> None:
# simple test to validate param value
if param in self._class_method_choices:
self.param = param
... | CatalogClass |
python | django__django | django/db/migrations/operations/models.py | {
"start": 35515,
"end": 40703
} | class ____(IndexOperation):
"""Rename an index."""
category = OperationCategory.ALTERATION
def __init__(self, model_name, new_name, old_name=None, old_fields=None):
if not old_name and not old_fields:
raise ValueError(
"RenameIndex requires one of old_name and old_field... | RenameIndex |
python | huggingface__transformers | tests/models/t5/test_modeling_t5.py | {
"start": 84489,
"end": 85942
} | class ____(unittest.TestCase):
def build_model_and_check_forward_pass(self, **kwargs):
tester = T5ModelTester(self, **kwargs)
config, *inputs = tester.prepare_config_and_inputs()
(
input_ids,
decoder_input_ids,
attention_mask,
decoder_attention... | TestAsymmetricT5 |
python | google__jax | jax/_src/interpreters/mlir.py | {
"start": 31674,
"end": 34496
} | class ____:
"""Per-rule context information for MLIR lowering."""
module_context: ModuleContext
# Even though we assigned name_stack entries to each jaxpr equation during
# tracing, we need to propagate name stacks during lowering as well because
# lowering may effectively inline multiple jaxprs into a single... | LoweringRuleContext |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 61797,
"end": 65706
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = Elasticsearch5FacetingMockSearchIndex()
se... | Elasticsearch5FacetingTestCase |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/cancellation.py | {
"start": 2350,
"end": 3590
} | class ____(asyncio.CancelledError):
# We want our `CancelledError` to be treated as a `BaseException` and defining it
# here simplifies downstream logic that needs to know "which" cancelled error to
# handle.
pass
def _get_thread_shield(thread: threading.Thread) -> ThreadShield:
with _THREAD_SHIEL... | CancelledError |
python | ray-project__ray | python/ray/autoscaler/_private/local/node_provider.py | {
"start": 6240,
"end": 11806
} | class ____(NodeProvider):
"""NodeProvider for private/local clusters.
`node_id` is overloaded to also be `node_ip` in this class.
When `cluster_name` is provided, it manages a single cluster in a cluster
specific state file. But when `cluster_name` is None, it manages multiple
clusters in a unifie... | LocalNodeProvider |
python | pytorch__pytorch | test/dynamo/test_base_hop.py | {
"start": 798,
"end": 1575
} | class ____(torch._dynamo.test_case.TestCase):
# TODO: flip to False later, we're landing a refactor PR and don't want to merge conflict
@torch._dynamo.config.patch(assume_static_by_default=True)
def test_dynamo(self):
def inner(x, y):
return (x @ y).sin().cos()
x = torch.randn(3... | BaseHOPTest |
python | facelessuser__soupsieve | tests/test_level3/test_last_of_type.py | {
"start": 57,
"end": 1980
} | class ____(util.TestCase):
"""Test last of type selectors."""
def test_last_of_type_at_middle(self):
"""Test last of type that is not the last sibling."""
markup = """
<body>
<p id="0"></p>
<p id="1"></p>
<span id="2"></span>
<span id="3"></span>
... | TestLastOfType |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_logging/LOG002.py | {
"start": 327,
"end": 410
} | class ____:
def getLogger(self):
pass
logging.getLogger(__file__)
| logging |
python | tensorflow__tensorflow | tensorflow/lite/tools/flatbuffer_utils_test.py | {
"start": 1107,
"end": 3233
} | class ____(test_util.TensorFlowTestCase):
def testWriteReadModel(self):
# 1. SETUP
# Define the initial model
initial_model = test_utils.build_mock_model()
# Define temporary files
tmp_dir = self.get_temp_dir()
model_filename = os.path.join(tmp_dir, 'model.tflite')
# 2. INVOKE
# Invo... | WriteReadModelTest |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 34187,
"end": 34252
} | class ____(AsyncSession):
sync_session_class = _MySession
| _MyAS |
python | walkccc__LeetCode | solutions/2744. Find Maximum Number of String Pairs/2744.py | {
"start": 0,
"end": 342
} | class ____:
def maximumNumberOfStringPairs(self, words: list[str]) -> int:
ans = 0
seen = [False] * (26 * 26)
def val(c: str) -> int:
return ord(c) - ord('a')
for word in words:
if seen[val(word[1]) * 26 + val(word[0])]:
ans += 1
seen[val(word[0]) * 26 + val(word[1])] = Tru... | Solution |
python | run-llama__llama_index | llama-index-integrations/graph_stores/llama-index-graph-stores-tidb/tests/test_property_graph_stores_tidb.py | {
"start": 455,
"end": 2233
} | class ____(TestCase):
@classmethod
def setUp(self) -> None:
try:
get_store()
except Exception:
raise SkipTest("TiDB cluster is not available")
self.e1 = EntityNode(name="e1", properties={"p1": "v1"})
self.e2 = EntityNode(name="e2")
self.r = Relati... | TestTiDBPropertyGraphStore |
python | tensorflow__tensorflow | tensorflow/core/tfrt/mlrt/kernel/testdata/gen_checkpoint.py | {
"start": 1399,
"end": 2589
} | class ____(module.Module):
"""A toy module for testing checkpoing loading."""
def __init__(self):
super().__init__()
self.w = variables.Variable(constant_op.constant([1, 2, 3]), name='w')
self.w1 = variables.Variable(constant_op.constant([4, 5, 6]), name='w1')
self.w2 = variables.Variable(constant_... | ToyModule |
python | pytorch__pytorch | functorch/examples/compilation/linear_train.py | {
"start": 552,
"end": 2156
} | class ____(nn.Module):
def __init__(self, num_layers=3, features=100):
super().__init__()
mods = []
for _ in range(num_layers):
mods.append(nn.Linear(features, features, bias=False))
self.mod = nn.Sequential(*mods)
def forward(self, x):
return (self.mod(x) **... | Foo |
python | django__django | tests/admin_filters/tests.py | {
"start": 8787,
"end": 8897
} | class ____(ModelAdmin):
list_display = ["name", "department"]
list_filter = ["department"]
| EmployeeAdmin |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 15983,
"end": 16177
} | class ____(
Static, can_focus=True, inherit_bindings=False
):
"""A widget that can receive focus but has no bindings and doesn't inherit bindings."""
| FocusableWidgetWithNoBindingsNoInherit |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 12643,
"end": 37202
} | class ____(SocketDummyServerTestCase):
def test_recovery_when_server_closes_connection(self) -> None:
# Does the pool work seamlessly if an open connection in the
# connection pool gets hung up on by the server, then reaches
# the front of the queue again?
done_closing = Event()
... | TestSocketClosing |
python | kamyu104__LeetCode-Solutions | Python/cousins-in-binary-tree.py | {
"start": 191,
"end": 1180
} | class ____(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
def dfs(root, x, depth, parent):
if not root:
return False
if root.val == x:
return... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/cards.py | {
"start": 2225,
"end": 2426
} | class ____(CreditCard):
"""
https://developer.paypal.com/braintree/docs/reference/response/venmo-account
"""
source_description: str
username: str
venmo_user_id: str
| VenmoAccount |
python | hynek__structlog | tests/test_stdlib.py | {
"start": 20496,
"end": 25593
} | class ____:
def test_default(self, stdlib_logger: logging.Logger):
"""
Passes `event` key from `event_dict` in the first positional argument
and handles otherwise empty `event_dict`.
"""
method_name = "debug"
event = "message"
args, kwargs = render_to_log_args... | TestRenderToLogArgsAndKwargs |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/pull_request/organization_pullrequest_comments.py | {
"start": 1140,
"end": 7801
} | class ____(OrganizationEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self, request: Request, organization: Organization, repo_name: str, pr_number: str
) -> Response:
"""
Get GitHub comments for a Pull Re... | OrganizationPrCommentsEndpoint |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 20531,
"end": 22436
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.quant_mode = config.quant_mode
self.layer = nn.ModuleList([IBertLayer(config) for _ in range(config.num_hidden_layers)])
def forward(
self,
hidden_states,
hidd... | IBertEncoder |
python | celery__celery | t/smoke/tests/quorum_queues/test_native_delayed_delivery.py | {
"start": 2944,
"end": 3773
} | class ____:
@pytest.fixture
def default_worker_app(self, default_worker_app: Celery) -> Celery:
app = default_worker_app
app.conf.broker_transport_options = {"confirm_publish": True}
app.conf.task_default_queue_type = "quorum"
app.conf.broker_native_delayed_delivery_queue_type = ... | test_broker_configuration_classic |
python | marshmallow-code__marshmallow | examples/flask_example.py | {
"start": 826,
"end": 1212
} | class ____(db.Model): # type: ignore[name-defined]
id: Mapped[int] = mapped_column(primary_key=True)
content: Mapped[str] = mapped_column(nullable=False)
author_id: Mapped[int] = mapped_column(db.ForeignKey(Author.id))
author: Mapped[Author] = relationship(backref=db.backref("quotes", lazy="dynamic"))
... | Quote |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/llama_index/vector_stores/couchbase/base.py | {
"start": 24922,
"end": 32786
} | class ____(CouchbaseVectorStoreBase):
"""
Couchbase Vector Store using Query Service with vector search capabilities.
This implementation supports both Hyperscale Vector Indexes and Composite Vector
Indexes, which use the Couchbase Query Service with SQL++ and vector search functions.
Hyperscale V... | CouchbaseQueryVectorStore |
python | astropy__astropy | astropy/time/formats.py | {
"start": 80169,
"end": 80314
} | class ____(TimeDeltaNumeric):
"""Time delta in SI seconds."""
name = "sec"
unit = 1.0 / erfa.DAYSEC # for quantity input
| TimeDeltaSec |
python | pytorch__pytorch | test/test_foreach.py | {
"start": 2072,
"end": 3671
} | class ____:
def __init__(self, func):
self.func = func
# Some foreach functions don't have in-place implementations.
self.is_inplace = False if func is None else func.__name__.endswith("_")
def __call__(self, inputs, is_cuda, expect_fastpath, **kwargs):
actual = None
zer... | ForeachFuncWrapper |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 7273,
"end": 8958
} | class ____:
def test_pickle(self):
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
roundtripped = pickle.loads(
pickle.dumps(dispatched_one_arg, protocol=proto))
assert_(roundtripped is dispatched_one_arg)
def test_name_and_docstring(self):
asser... | TestArrayFunctionDispatch |
python | pytorch__pytorch | test/inductor/test_caching.py | {
"start": 43056,
"end": 51984
} | class ____(TestMixin, TestCase):
T = TypeVar("T")
@contextmanager
def executor(self) -> Generator[ThreadPoolExecutor, None, None]:
executor: ThreadPoolExecutor = ThreadPoolExecutor()
try:
yield executor
finally:
executor.shutdown()
def is_lock(self, lock... | LocksTest |
python | walkccc__LeetCode | solutions/3427. Sum of Variable Length Subarrays/3427.py | {
"start": 0,
"end": 225
} | class ____:
def subarraySum(self, nums: list[int]) -> int:
prefix = list(itertools.accumulate(nums, initial=0))
return sum(prefix[i + 1] - prefix[max(0, i - num)]
for i, num in enumerate((nums)))
| Solution |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/softmax_test.py | {
"start": 1475,
"end": 1749
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, N, C, H, W, device, op_func):
self.inputs = {"input": torch.rand(N, C, H, W, device=device)}
self.op_func = op_func()
def forward(self, input):
return self.op_func(input)
| SoftmaxBenchmark |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 47608,
"end": 48919
} | class ____(unittest.TestCase):
def test_sigint(self):
with self.assertRaises(KeyboardInterrupt):
signal.raise_signal(signal.SIGINT)
@unittest.skipIf(sys.platform != "win32", "Windows specific test")
def test_invalid_argument(self):
try:
SIGHUP = 1 # not supported on... | RaiseSignalTest |
python | getsentry__sentry | tests/sentry/runner/commands/test_cleanup.py | {
"start": 958,
"end": 5062
} | class ____(TestCase):
def test_no_filters(self) -> None:
"""Test that without filters, all active projects are included."""
project1 = self.create_project()
project2 = self.create_project()
project3 = self.create_project()
query, _ = prepare_deletes_by_project(is_filtered=la... | PrepareDeletesByProjectTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 23756,
"end": 33926
} | class ____:
def __init__(self, path_prefix: Optional[str]) -> None:
self.path_prefix = path_prefix
self.errors: list[_DgConfigErrorRecord] = []
def validate(self, raw_dict: dict[str, Any]) -> DgConfigValidationResult:
self._normalize_deprecated_settings(raw_dict)
self._validate_... | _DgConfigValidator |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 9933,
"end": 10088
} | class ____(scale_y_continuous):
"""
Continuous y position symmetric logarithm transformed scale
"""
trans: TransUser = "symlog"
| scale_y_symlog |
python | Lightning-AI__lightning | tests/tests_pytorch/core/test_lightning_optimizer.py | {
"start": 9241,
"end": 12560
} | class ____(Optimizer):
def __init__(self, model):
self._fwd_handles = []
self._bwd_handles = []
self.params = []
for _, mod in model.named_modules():
mod_class = mod.__class__.__name__
if mod_class != "Linear":
continue
handle = mo... | OptimizerWithHooks |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 53574,
"end": 55946
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a specific Memcached instance. Instance stops serving and data is deleted.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudMemorystoreMemcachedDeleteInstanceOperator`
:pa... | CloudMemorystoreMemcachedDeleteInstanceOperator |
python | wireservice__csvkit | tests/test_utilities/test_csvlook.py | {
"start": 220,
"end": 4937
} | class ____(CSVKitTestCase, EmptyFileTests):
Utility = CSVLook
def tearDown(self):
config.set_option('truncation_chars', '…')
def test_launch_new_instance(self):
with patch.object(sys, 'argv', [self.Utility.__name__.lower(), 'examples/dummy.csv']):
launch_new_instance()
def... | TestCSVLook |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_with.py | {
"start": 1460,
"end": 1755
} | class ____(object):
def __init__(self):
self.yielded = False
self.stopped = False
@mock_contextmanager
def mock_contextmanager_generator():
mock = MockResource()
try:
mock.yielded = True
yield mock
finally:
mock.stopped = True
| MockResource |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 11540,
"end": 12759
} | class ____(object):
pass
"""
def test_load_auth_module() -> None:
def func(filename: str):
m = bsa.load_auth_module(filename)
assert isinstance(m, ModuleType)
assert [x for x in sorted(dir(m)) if not x.startswith("__")] == ['LoginHandler', 'get_login_url', 'logout_url']
with_file_c... | LoginHandler |
python | getsentry__sentry | src/sentry/models/projectsdk.py | {
"start": 1086,
"end": 7466
} | class ____(DefaultFieldsModel):
__relocation_scope__ = RelocationScope.Organization
date_updated = models.DateTimeField(auto_now=True)
project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE)
event_type = BoundedIntegerField(choices=EventType.as_choices())
sdk_name = models.CharFie... | ProjectSDK |
python | spack__spack | lib/spack/spack/externals.py | {
"start": 17087,
"end": 17212
} | class ____(SpackError):
"""Raised when a dependency on an external package is specified wrongly."""
| ExternalDependencyError |
python | huggingface__transformers | tests/models/bridgetower/test_modeling_bridgetower.py | {
"start": 1601,
"end": 3435
} | class ____:
def __init__(
self,
parent,
hidden_act="gelu",
hidden_size=64,
initializer_factor=1,
layer_norm_eps=1e-05,
num_attention_heads=4,
num_hidden_layers=2,
intermediate_size=128,
tie_word_embeddings=False,
output_hidden_s... | BridgeTowerTextModelTester |
python | walkccc__LeetCode | solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py | {
"start": 0,
"end": 342
} | class ____:
def checkStrings(self, s1: str, s2: str) -> bool:
count = [collections.Counter() for _ in range(2)]
for i, (a, b) in enumerate(zip(s1, s2)):
count[i % 2][a] += 1
count[i % 2][b] -= 1
return (all(freq == 0 for freq in count[0].values()) and
all(freq == 0 for freq in co... | Solution |
python | joblib__joblib | joblib/externals/loky/process_executor.py | {
"start": 5168,
"end": 8443
} | class ____:
"""necessary references to maintain executor states without preventing gc
It permits to keep the information needed by executor_manager_thread
and crash_detection_thread to maintain the pool without preventing the
garbage collection of unreferenced executors.
"""
def __init__(self,... | _ExecutorFlags |
python | pytorch__pytorch | torch/_higher_order_ops/triton_kernel_wrap.py | {
"start": 41930,
"end": 42687
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("triton_kernel_wrapper_mutation", cacheable=True)
def __call__(
self,
kernel_idx: int,
constant_args_idx: int,
grid: list["TritonGridType"],
tma_descriptor_metadata: TMADescriptorMetada... | TritonKernelWrapperMutation |
python | pydata__xarray | xarray/tests/test_conventions.py | {
"start": 687,
"end": 1148
} | class ____:
def test_booltype_array(self) -> None:
x = np.array([1, 0, 1, 1, 0], dtype="i1")
bx = coding.variables.BoolTypeArray(x)
assert bx.dtype == bool
assert_array_equal(bx, np.array([True, False, True, True, False], dtype=bool))
x = np.array([[1, 0, 1], [0, 1, 0]], dty... | TestBoolTypeArray |
python | pytorch__pytorch | torch/distributions/cauchy.py | {
"start": 341,
"end": 3209
} | class ____(Distribution):
r"""
Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of
independent normally distributed random variables with means `0` follows a
Cauchy distribution.
Example::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Cauchy(t... | Cauchy |
python | allegroai__clearml | clearml/binding/frameworks/fastai_bind.py | {
"start": 1102,
"end": 7412
} | class ____(object):
__metrics_names = {}
__gradient_hist_helpers = {}
_current_task = None
__patched = False
@staticmethod
def update_current_task(task: Any, **_: Any) -> None:
PatchFastaiV1._current_task = task
if not task:
return
if not PatchFastaiV1.__patc... | PatchFastaiV1 |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 24203,
"end": 24966
} | class ____(unittest.TestCase):
def setUp(self):
from pyramid.config import Configurator
config = Configurator()
from .pkgs.includeapp1.root import configure
configure(config)
app = config.make_wsgi_app()
self.testapp = TestApp(app)
self.config = config
... | ImperativeIncludeConfigurationTest |
python | pytorch__pytorch | torch/fx/graph_module.py | {
"start": 13310,
"end": 15931
} | class ____:
def __init__(self, cls, cls_call):
self.cls = cls
self.cls_call = cls_call
# Previously, if an error occurred when valid
# symbolically-traced code was run with an invalid input, the
# user would see the source of the error as coming from
# `File "<eval_with_key_N">`, wh... | _WrappedCall |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 2198,
"end": 4214
} | class ____(nn.Module):
"""Relative positional encoding for Parakeet."""
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: ParakeetEncoderConfig, device=None):
super().__init__()
self.max_position_embeddings = config.max_position_embeddings
base ... | ParakeetEncoderRelPositionalEncoding |
python | pydata__xarray | xarray/core/coordinates.py | {
"start": 45724,
"end": 47853
} | class ____(ValueError):
"""Error class for Xarray coordinate validation failures."""
def validate_dataarray_coords(
shape: tuple[int, ...],
coords: Coordinates | Mapping[Hashable, Variable],
dim: tuple[Hashable, ...],
):
"""Validate coordinates ``coords`` to include in a DataArray defined by
`... | CoordinateValidationError |
python | keras-team__keras | keras/src/optimizers/sgd.py | {
"start": 155,
"end": 4396
} | class ____(optimizer.Optimizer):
"""Gradient descent (with momentum) optimizer.
Update rule for parameter `w` with gradient `g` when `momentum` is 0:
```python
w = w - learning_rate * g
```
Update rule when `momentum` is larger than 0:
```python
velocity = momentum * velocity - learn... | SGD |
python | huggingface__transformers | tests/utils/test_activations.py | {
"start": 862,
"end": 2559
} | class ____(unittest.TestCase):
def test_gelu_versions(self):
x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100])
torch_builtin = get_activation("gelu")
torch.testing.assert_close(gelu_python(x), torch_builtin(x))
self.assertFalse(torch.allclose(gelu_python(x), gelu_new(x)))
def... | TestActivations |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 181813,
"end": 183043
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of CreateEnterpriseOrganization"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "login", "profile_name", "billing_email", "admin_logins", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphq... | CreateEnterpriseOrganizationInput |
python | python__mypy | mypy/plugins/singledispatch.py | {
"start": 823,
"end": 8151
} | class ____(NamedTuple):
register_type: Type
singledispatch_obj: Instance
def get_singledispatch_info(typ: Instance) -> SingledispatchTypeVars | None:
if len(typ.args) == 2:
return SingledispatchTypeVars(*typ.args) # type: ignore[arg-type]
return None
T = TypeVar("T")
def get_first_arg(arg... | RegisterCallableInfo |
python | pennersr__django-allauth | allauth/socialaccount/providers/stocktwits/views.py | {
"start": 181,
"end": 1068
} | class ____(OAuth2Adapter):
provider_id = "stocktwits"
access_token_url = "https://api.stocktwits.com/api/2/oauth/token" # nosec
authorize_url = "https://api.stocktwits.com/api/2/oauth/authorize"
profile_url = "https://api.stocktwits.com/api/2/streams/user/{user}.json"
scope_delimiter = ","
def... | StocktwitsOAuth2Adapter |
python | matplotlib__matplotlib | lib/matplotlib/offsetbox.py | {
"start": 15307,
"end": 16418
} | class ____(PackerBase):
"""
HPacker packs its children horizontally, automatically adjusting their
relative positions at draw time.
.. code-block:: none
+-------------------------------+
| Child 1 Child 2 Child 3 |
+-------------------------------+
"""
def _get_bbox... | HPacker |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isin.py | {
"start": 1884,
"end": 4459
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid ISIN (International Securities Identification Number)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
... | ExpectColumnValuesToBeValidIsin |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/query/query_transform/base.py | {
"start": 2848,
"end": 4853
} | class ____(BaseQueryTransform):
"""
Hypothetical Document Embeddings (HyDE) query transform.
It uses an LLM to generate hypothetical answer(s) to a given query,
and use the resulting documents as embedding strings.
As described in `[Precise Zero-Shot Dense Retrieval without Relevance Labels]
(... | HyDEQueryTransform |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 12992,
"end": 13566
} | class ____(nn.Module):
def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
super().__init__()
self.hidden_size = context_dim * (spatial_merge_size**2)
self.ln_q = LayerNorm(context_dim, eps=1e-6)
self.mlp = nn.Sequential(
nn.Linear(self.hi... | PatchMerger |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 145068,
"end": 155580
} | class ____:
# Track the loaded modules so we can remove the on-disk artifacts when
# clearing the cache. Note also that we may load the same path more
# than once, but attach different attributes, i.e., due to different
# constant values.
modules: list[ModuleType] = []
# Modules loaded without ... | PyCodeCache |
python | urllib3__urllib3 | dummyserver/testcase.py | {
"start": 6890,
"end": 7073
} | class ____(HypercornDummyServerTestCase):
scheme = "https"
host = "localhost"
certs = DEFAULT_CERTS
certs_dir = ""
bad_ca_path = ""
| HTTPSHypercornDummyServerTestCase |
python | cython__cython | Cython/Debugger/Tests/TestLibCython.py | {
"start": 7501,
"end": 8392
} | class ____(GdbDebuggerTestCase):
def test_all(self):
if not test_gdb():
return
out, err = self.p.communicate()
out = out.decode('UTF-8')
err = err.decode('UTF-8')
exit_status = self.p.returncode
if exit_status == 1:
sys.stderr.write(out)
... | TestAll |
python | pytorch__pytorch | torch/_guards.py | {
"start": 4603,
"end": 7144
} | class ____(enum.Enum):
LOCAL = 0
GLOBAL = 1
LOCAL_SPECIALIZED_NN_MODULE = 2
GLOBAL_SPECIALIZED_NN_MODULE = 3
CONSTANT = 4
RANDOM_VALUE = 5
SHAPE_ENV = 6
LOCAL_FSDP_MODULE = 7
GLOBAL_FSDP_MODULE = 8
BACKWARD_STATE = 9
EPHEMERAL = 10
SYNTHETIC_LOCAL = 11
LOCAL_UNSPECIAL... | GuardSource |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 1036,
"end": 1201
} | class ____(Protocol):
def method1(self) -> int: ...
# This should generate an error because "method1" is
# not implemented and it is marked final.
@final
| Protocol5 |
python | pytest-dev__pytest-django | tests/test_unittest.py | {
"start": 1197,
"end": 1671
} | class ____(TestCase):
fixtures = ("items",)
def setUp(self) -> None:
assert Item.objects.count() == 1
Item.objects.create(name="Some item")
def test_count(self) -> None:
assert Item.objects.count() == 2
Item.objects.create(name="Some item again")
def test_count_again(s... | TestFixturesWithSetup |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.