language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry-python | sentry_sdk/integrations/redis/__init__.py | {
"start": 553,
"end": 1659
} | class ____(Integration):
identifier = "redis"
def __init__(self, max_data_size=_DEFAULT_MAX_DATA_SIZE, cache_prefixes=None):
# type: (Optional[int], Optional[list[str]]) -> None
self.max_data_size = max_data_size
self.cache_prefixes = cache_prefixes if cache_prefixes is not None else []... | RedisIntegration |
python | huggingface__transformers | src/transformers/models/biogpt/tokenization_biogpt.py | {
"start": 1274,
"end": 12158
} | class ____(PreTrainedTokenizer):
"""
Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those me... | BioGptTokenizer |
python | pallets__werkzeug | src/werkzeug/datastructures/structures.py | {
"start": 33677,
"end": 34895
} | class ____( # type: ignore[misc]
ImmutableMultiDictMixin[K, V], _OrderedMultiDict[K, V]
):
"""An immutable :class:`OrderedMultiDict`.
.. deprecated:: 3.1
Will be removed in Werkzeug 3.2. Use ``ImmutableMultiDict`` instead.
.. versionadded:: 0.6
"""
def __init__(
self,
... | _ImmutableOrderedMultiDict |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 113410,
"end": 117179
} | class ____(_RelationshipErrors, fixtures.MappedTest):
"""'viewonly' mappings with a complex join condition."""
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=... | ViewOnlyComplexJoin |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/regression.py | {
"start": 143,
"end": 418
} | class ____():
""" Regularization for Lasso Regression """
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, w):
return self.alpha * np.linalg.norm(w)
def grad(self, w):
return self.alpha * np.sign(w)
| l1_regularization |
python | bottlepy__bottle | test/test_securecookies.py | {
"start": 101,
"end": 1304
} | class ____(unittest.TestCase):
def setUp(self):
self.data = touni('υηι¢σ∂є')
self.secret = tob('secret')
bottle.app.push()
bottle.response.bind()
def tear_down(self):
bottle.app.pop()
def get_pairs(self):
for k, v in bottle.response.headerlist:
i... | TestSignedCookies |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 12586,
"end": 12717
} | class ____(_TestIDCTBase):
def setup_method(self):
self.rdt = int
self.dec = 5
self.type = 4
| TestIDCTIVInt |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1174933,
"end": 1192808
} | class ____:
def encode(
self,
*args: Any,
angle: Optional[str | AnyAngle | IntoCondition | Map] = Undefined,
color: Optional[str | AnyColor | IntoCondition | Map] = Undefined,
column: Optional[str | Column | IntoCondition | Map] = Undefined,
description: Optional[str ... | _EncodingMixin |
python | ipython__ipython | tests/test_io.py | {
"start": 1066,
"end": 1409
} | class ____(unittest.TestCase):
def test_capture_output(self):
"""capture_output() context works"""
with capture_output() as io:
print("hi, stdout")
print("hi, stderr", file=sys.stderr)
self.assertEqual(io.stdout, "hi, stdout\n")
self.assertEqual(io.stderr, "... | TestIOStream |
python | jazzband__django-oauth-toolkit | oauth2_provider/management/commands/createapplication.py | {
"start": 203,
"end": 4372
} | class ____(BaseCommand):
help = "Shortcut to create a new application in a programmatic way"
def add_arguments(self, parser):
parser.add_argument(
"client_type",
type=str,
help="The client type, one of: %s" % ", ".join([ctype[0] for ctype in Application.CLIENT_TYPES]... | Command |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cli/configs/base.py | {
"start": 4028,
"end": 5084
} | class ____(DbtConfigs, abc.ABC):
type: str = Field(default=..., description="The name of the database warehouse.")
schema_: str = Field(
alias="schema",
description=(
"The schema that dbt will build objects into; "
"in BigQuery, a schema is actually a dataset."
),... | BaseTargetConfigs |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 31008,
"end": 31728
} | class ____(themeable):
"""
y-axis line
Parameters
----------
theme_element : element_line
"""
position = "left"
_omit = ["solid_capstyle"]
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
properties = self.properties
# MPL has a default zorder of 2.5 for ... | axis_line_y |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 343837,
"end": 361910
} | class ____(VegaLiteSchema):
r"""
FacetEncodingFieldDef schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggr... | FacetEncodingFieldDef |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-vertex/tests/test_tool_required.py | {
"start": 681,
"end": 9272
} | class ____:
"""Test suite for Vertex AI tool_required functionality."""
@patch("llama_index.llms.vertex.gemini_utils.create_gemini_client")
def test_to_function_calling_config_tool_required_true(self, mock_create_client):
"""Test that _to_function_calling_config correctly sets mode to ANY when tool... | TestVertexToolRequired |
python | ethereum__web3.py | web3/types.py | {
"start": 7007,
"end": 7518
} | class ____(TypedDict, total=False):
error: RPCError
id: RPCId
jsonrpc: Literal["2.0"]
result: Any
# eth_subscribe
method: Literal["eth_subscription"]
params: EthSubscriptionParams
EthSubscriptionResult = Union[
BlockData, # newHeads
TxData, # newPendingTransactions, full_transac... | RPCResponse |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py | {
"start": 18114,
"end": 18236
} | class ____(Qwen3VLCausalLMOutputWithPast):
aux_loss: Optional[torch.FloatTensor] = None
| Qwen3VLMoeCausalLMOutputWithPast |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 7964,
"end": 8397
} | class ____(TestModelMixin, TestBase):
def testSetComment(self):
with reversion.create_revision():
reversion.set_comment("comment v1")
obj = TestModel.objects.create()
self.assertSingleRevision((obj,), comment="comment v1")
def testSetCommentNoBlock(self):
with s... | SetCommentTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 4559,
"end": 5443
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_create_dlp_job(self, mock_hook):
mock_hook.return_value.create_dlp_job.return_value = DlpJob(
name=DLP_JOB_PATH, state=DlpJob.JobState.PENDING
)
operator = CloudDLPCreateDLPJobOperat... | TestCloudDLPCreateDLPJobOperator |
python | PrefectHQ__prefect | src/prefect/server/schemas/sorting.py | {
"start": 4443,
"end": 5166
} | class ____(AutoEnum):
"""Defines deployment sorting options."""
CREATED_DESC = AutoEnum.auto()
UPDATED_DESC = AutoEnum.auto()
NAME_ASC = AutoEnum.auto()
NAME_DESC = AutoEnum.auto()
@db_injector
def as_sql_sort(self, db: "PrefectDBInterface") -> Iterable[sa.ColumnElement[Any]]:
"""R... | DeploymentSort |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/utils/external_token_supplier.py | {
"start": 4006,
"end": 7129
} | class ____(CacheTokenSupplier):
"""
Class that retrieves an OIDC token from an external IdP using OAuth2.0 Client Credentials Grant flow.
This class implements the ``SubjectTokenSupplier`` interface class used by ``google.auth.identity_pool.Credentials``
:params oidc_issuer_url: URL of the IdP that pe... | ClientCredentialsGrantFlowTokenSupplier |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 345424,
"end": 345775
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("platform", "url")
platform = sgqlc.types.Field(
sgqlc.types.non_null(FundingPlatform), graphql_name="platform"
)
url = sgqlc.types.Field(sgqlc.types.non_null(URI)... | FundingLink |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 15350,
"end": 22663
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "keyword_performance_report_hourly"
report_file = "keyword_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "keyword_performance_report_hourly_incremental"
repor... | TestKeywordPerformanceReportHourlyStream |
python | django__django | django/db/models/functions/datetime.py | {
"start": 7367,
"end": 12021
} | class ____(TimezoneMixin, Transform):
kind = None
tzinfo = None
def __init__(
self,
expression,
output_field=None,
tzinfo=None,
**extra,
):
self.tzinfo = tzinfo
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self,... | TruncBase |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/incident_groupopenperiod_serializer.py | {
"start": 418,
"end": 909
} | class ____(Serializer):
def serialize(
self, obj: IncidentGroupOpenPeriod, attrs: Mapping[str, Any], user, **kwargs
) -> IncidentGroupOpenPeriodSerializerResponse:
return {
"incidentId": str(obj.incident_id) if obj.incident_id else None,
"incidentIdentifier": obj.incident... | IncidentGroupOpenPeriodSerializer |
python | weaviate__weaviate-python-client | profiling/test_refs.py | {
"start": 1310,
"end": 1416
} | class ____:
properties: Dict[str, Any]
class_name: str
uuid: uuid_lib.UUID
@dataclass
| DataObject |
python | aio-libs__aiohttp | tests/test_tracing.py | {
"start": 2973,
"end": 5313
} | class ____:
@pytest.mark.parametrize(
"signal,params,param_obj",
[
("request_start", (Mock(), Mock(), Mock()), TraceRequestStartParams),
(
"request_chunk_sent",
(Mock(), Mock(), Mock()),
TraceRequestChunkSentParams,
... | TestTrace |
python | sqlalchemy__sqlalchemy | test/sql/test_compiler.py | {
"start": 269839,
"end": 271878
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = default.DefaultDialect(supports_native_boolean=True)
def _fixture(self):
m = MetaData()
return Table("foo", m, Column("id", Integer))
bool_table = table("t", column("x", Boolean))
def test_coerce_bool_where(self):
... | CoercionTest |
python | getsentry__sentry | tests/sentry/middleware/integrations/test_classifications.py | {
"start": 2447,
"end": 5057
} | class ____(BaseClassificationTestCase):
get_response = MagicMock()
integration_cls = IntegrationClassification(response_handler=get_response)
prefix = IntegrationClassification.integration_prefix
@override_settings(SILO_MODE=SiloMode.CONTROL)
@patch.object(
IntegrationClassification,
... | IntegrationClassificationTest |
python | getsentry__sentry | src/sentry/snuba/query_subscriptions/run.py | {
"start": 780,
"end": 4132
} | class ____(ProcessingStrategyFactory[KafkaPayload]):
def __init__(
self,
dataset: str,
max_batch_size: int,
max_batch_time: int,
num_processes: int,
input_block_size: int | None,
output_block_size: int | None,
multi_proc: bool = True,
topic_ove... | QuerySubscriptionStrategyFactory |
python | pikepdf__pikepdf | src/pikepdf/models/image.py | {
"start": 1255,
"end": 1359
} | class ____(Exception):
"""Indicates that an image cannot be directly extracted."""
| NotExtractableError |
python | boto__boto3 | tests/integration/test_s3.py | {
"start": 3598,
"end": 5469
} | class ____:
def __init__(self):
self.rootdir = tempfile.mkdtemp()
def remove_all(self):
shutil.rmtree(self.rootdir)
def create_file(self, filename, contents, mode='w'):
"""Creates a file in a tmpdir
``filename`` should be a relative path, e.g. "foo/bar/baz.txt"
It ... | FileCreator |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-events-that-can-be-attended.py | {
"start": 84,
"end": 704
} | class ____(object):
def maxEvents(self, events):
"""
:type events: List[List[int]]
:rtype: int
"""
events.sort(reverse=True)
min_heap = []
result = 0
for d in xrange(1, max(events, key=lambda x:x[1])[1]+1):
while events and events[-1][0] ==... | Solution |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 16983,
"end": 17891
} | class ____(nn.Module):
"""
Scaled positional encoding, see §3.2 in https://huggingface.co/papers/1809.08895
"""
def __init__(self, dropout, dim, max_len=5000):
pe = torch.zeros(max_len, dim)
position = torch.arange(0, max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, di... | SpeechT5ScaledPositionalEncoding |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 20576,
"end": 20952
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
basic_auth: Optional[DockerBasicAuth] = Field(
None, description="Basic authentication information for Docker repository."
)
url: Optional[str] = Field(... | DockerImage |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/views/roles_list.py | {
"start": 941,
"end": 1512
} | class ____(RoleModelView):
"""Customize permission names for FAB's builtin RoleModelView."""
class_permission_name = permissions.RESOURCE_ROLE
method_permission_name = {
"delete": "delete",
"download": "read",
"show": "read",
"list": "read",
"edit": "edit",
"... | CustomRoleModelView |
python | fluentpython__example-code-2e | 17-it-generator/sentence_iter2.py | {
"start": 501,
"end": 749
} | class ____:
def __init__(self, word_iter):
self.word_iter = word_iter # <3>
def __next__(self):
match = next(self.word_iter) # <4>
return match.group() # <5>
def __iter__(self):
return self
| SentenceIter |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/connectors/test_signal_connector.py | {
"start": 5712,
"end": 6867
} | class ____:
def signal_handler(self):
pass
@pytest.mark.parametrize(
("handler", "expected_return"),
[
(None, False),
(signal.Handlers.SIG_IGN, True),
(signal.Handlers.SIG_DFL, False),
(signal_handler, True),
(SignalHandlers().signal_handler, True),
],
)... | SignalHandlers |
python | apache__airflow | providers/apache/hive/tests/unit/apache/hive/transfers/test_mssql_to_hive.py | {
"start": 980,
"end": 5475
} | class ____:
def setup_method(self):
self.kwargs = dict(sql="sql", hive_table="table", task_id="test_mssql_to_hive", dag=None)
def test_type_map_binary(self):
mapped_type = MsSqlToHiveOperator(**self.kwargs).type_map(pymssql.BINARY.value)
assert mapped_type == "INT"
def test_type_m... | TestMsSqlToHiveTransfer |
python | ansible__ansible | test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py | {
"start": 1895,
"end": 2003
} | class ____(BaseFileCacheModule):
"""
A caching module backed by json files.
"""
pass
| CacheModule |
python | simonw__datasette | tests/test_base_view.py | {
"start": 142,
"end": 394
} | class ____(View):
async def get(self, request, datasette):
return Response.json(
{
"absolute_url": datasette.absolute_url(request, "/"),
"request_path": request.path,
}
)
| GetView |
python | pytorch__pytorch | test/dynamo/test_functions.py | {
"start": 87218,
"end": 117542
} | class ____(torch.nn.Module):
def forward(self, s77: "Sym(s77)", L_x_: "f32[s77, s77]"):
l_x_ = L_x_
mul: "f32[s77, s77]" = l_x_ * 4
mul_1: "f32[s77, s77]" = mul * l_x_; mul = None
mul_2: "f32[s77, s77]" = 20 * l_x_; l_x_ = None
mul_3: "f32[s77, s77]" = torch.mul(mul_1, mu... | GraphModule |
python | huggingface__transformers | src/transformers/models/layoutlm/modeling_layoutlm.py | {
"start": 16861,
"end": 17260
} | class ____(PreTrainedModel):
config: LayoutLMConfig
base_model_prefix = "layoutlm"
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
super()._init_weights(module)
if isinstance(module, LayoutLMLMPredictionHe... | LayoutLMPreTrainedModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/session.py | {
"start": 27598,
"end": 28201
} | class ____(Enum):
"""indicates the origin of a :class:`.SessionTransaction`.
This enumeration is present on the
:attr:`.SessionTransaction.origin` attribute of any
:class:`.SessionTransaction` object.
.. versionadded:: 2.0
"""
AUTOBEGIN = 0
"""transaction were started by autobegin"""... | SessionTransactionOrigin |
python | langchain-ai__langchain | libs/core/tests/unit_tests/test_messages.py | {
"start": 30235,
"end": 44769
} | class ____:
pass
def test_tool_message_ser_non_serializable() -> None:
bad_obj = BadObject()
message = ToolMessage("foo", artifact=bad_obj, tool_call_id="1")
ser_message = {
"lc": 1,
"type": "constructor",
"id": ["langchain", "schema", "messages", "ToolMessage"],
"kwarg... | BadObject |
python | streamlit__streamlit | lib/streamlit/runtime/state/query_params_proxy.py | {
"start": 967,
"end": 7730
} | class ____(MutableMapping[str, str]):
"""
A stateless singleton that proxies ``st.query_params`` interactions
to the current script thread's QueryParams instance.
"""
def __iter__(self) -> Iterator[str]:
with get_session_state().query_params() as qp:
return iter(qp)
def __l... | QueryParamsProxy |
python | google__jax | jax/_src/mesh.py | {
"start": 15337,
"end": 15567
} | class ____:
device_kind: str
num_cores: int | None
def __repr__(self):
return (f"AbstractDevice({self._repr()})")
def _repr(self):
return f"device_kind={self.device_kind}, num_cores={self.num_cores}"
| AbstractDevice |
python | Textualize__textual | src/textual/containers.py | {
"start": 418,
"end": 655
} | class ____(Widget):
"""Simple container widget, with vertical layout."""
DEFAULT_CSS = """
Container {
width: 1fr;
height: 1fr;
layout: vertical;
overflow: hidden hidden;
}
"""
| Container |
python | huggingface__transformers | src/transformers/pipelines/depth_estimation.py | {
"start": 547,
"end": 6115
} | class ____(Pipeline):
"""
Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
Example:
```python
>>> from transformers import pipeline
>>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")... | DepthEstimationPipeline |
python | tensorflow__tensorflow | tensorflow/python/trackable/data_structures.py | {
"start": 5671,
"end": 6083
} | class ____(ValueError):
def __init__(self, value): # pylint: disable=super-init-not-called
self._value = value
def __str__(self):
return ("Only trackable objects (such as Layers or Optimizers) may be "
f"stored in a List object. Got {self._value}, which does not "
"inherit from Tr... | _UntrackableError |
python | scipy__scipy | scipy/fft/_pocketfft/tests/test_basic.py | {
"start": 4272,
"end": 4399
} | class ____(_TestFFTBase):
def setup_method(self):
self.cdt = np.complex64
self.rdt = np.float32
| TestSingleFFT |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 17195,
"end": 18094
} | class ____(Node):
__slots__ = ('loc', 'name', 'arguments',)
_fields = ('name', 'arguments',)
def __init__(self, name, arguments=None, loc=None):
self.loc = loc
self.name = name
self.arguments = arguments
def __eq__(self, other):
return (
self is other or (
... | Directive |
python | pypa__pip | src/pip/_vendor/packaging/specifiers.py | {
"start": 878,
"end": 1186
} | class ____(ValueError):
"""
Raised when attempting to create a :class:`Specifier` with a specifier
string that is invalid.
>>> Specifier("lolwat")
Traceback (most recent call last):
...
packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
"""
| InvalidSpecifier |
python | Pylons__pyramid | tests/test_events.py | {
"start": 5622,
"end": 8822
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _makeOne(self, *ifaces, **predicates):
from pyramid.events import subscriber
return subscriber(*ifaces, **predicates)
def test_register_single(self... | TestSubscriber |
python | pallets__click | src/click/exceptions.py | {
"start": 4484,
"end": 6944
} | class ____(BadParameter):
"""Raised if click required an option or argument but it was not
provided when invoking the script.
.. versionadded:: 4.0
:param param_type: a string that indicates the type of the parameter.
The default is to inherit the parameter type from
... | MissingParameter |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 679,
"end": 855
} | class ____(Sitemap):
changefreq = "never"
priority = 0.5
i18n = True
def items(self):
return I18nTestModel.objects.order_by("pk").all()
| SimpleI18nSitemap |
python | huggingface__transformers | src/transformers/models/levit/image_processing_levit.py | {
"start": 1457,
"end": 16477
} | class ____(BaseImageProcessor):
r"""
Constructs a LeViT image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Wwhether to resize the shortest edge of the input to int(256/224 *`size`). Can be overridden by the
`do_resize` parameter in the `preprocess` me... | LevitImageProcessor |
python | doocs__leetcode | solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/Solution.py | {
"start": 0,
"end": 412
} | class ____:
def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
ans, n = 0, len(nums)
for l in range(n):
if nums[l] % 2 == 0 and nums[l] <= threshold:
r = l + 1
while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= thresho... | Solution |
python | spack__spack | lib/spack/spack/error.py | {
"start": 5476,
"end": 5567
} | class ____(SpackError):
"""Superclass for all Spack config related errors."""
| ConfigError |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_engine/condense_plus_context.py | {
"start": 2784,
"end": 16522
} | class ____(BaseChatEngine):
"""
Condensed Conversation & Context Chat Engine.
First condense a conversation and latest user message to a standalone question
Then build a context for the standalone question from a retriever,
Then pass the context along with prompt and user message to LLM to generate... | CondensePlusContextChatEngine |
python | huggingface__transformers | src/transformers/models/apertus/modeling_apertus.py | {
"start": 15345,
"end": 18484
} | class ____(ApertusPreTrainedModel):
def __init__(self, config: ApertusConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.l... | ApertusModel |
python | Textualize__textual | docs/examples/guide/styles/outline01.py | {
"start": 401,
"end": 773
} | class ____(App):
def compose(self) -> ComposeResult:
self.widget = Static(TEXT)
yield self.widget
def on_mount(self) -> None:
self.widget.styles.background = "darkblue"
self.widget.styles.width = "50%"
self.widget.styles.outline = ("heavy", "yellow")
if __name__ == "__... | OutlineApp |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 38277,
"end": 38532
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": False,
"return_mm_token_type_ids": False,
},
"videos_kwargs": {"return_metadata": True},
}
| Qwen2_5_VLProcessorKwargs |
python | walkccc__LeetCode | solutions/216. Combination Sum III/216.py | {
"start": 0,
"end": 377
} | class ____:
def combinationSum3(self, k: int, n: int) -> list[list[int]]:
ans = []
def dfs(k: int, n: int, s: int, path: list[int]) -> None:
if k == 0 and n == 0:
ans.append(path)
return
if k == 0 or n < 0:
return
for i in range(s, 10):
dfs(k - 1, n - i, i +... | Solution |
python | google__jax | tests/tree_util_test.py | {
"start": 3603,
"end": 4548
} | class ____:
def __init__(self, structured, *, leaves=None, treedef=None):
if treedef is None:
leaves, treedef = tree_util.tree_flatten(structured)
self._structured = structured
self.treedef = treedef
self.leaves = leaves
def __hash__(self):
return hash(self.structured)
def __eq__(self,... | FlatCache |
python | huggingface__transformers | src/transformers/models/mlcd/modeling_mlcd.py | {
"start": 17451,
"end": 19777
} | class ____(PreTrainedModel):
config: MLCDVisionConfig
base_model_prefix = "mlcd"
supports_gradient_checkpointing = True
accepts_loss_kwargs = False
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs = {
... | MLCDPreTrainedModel |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 11932,
"end": 13970
} | class ____(nn.Module):
"""
CvtLayer composed by attention layers, normalization and multi-layer perceptrons (mlps).
"""
def __init__(
self,
num_heads,
embed_dim,
kernel_size,
padding_q,
padding_kv,
stride_q,
stride_kv,
qkv_projecti... | CvtLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1007384,
"end": 1007858
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnarchiveProjectV2Item"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "item")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | UnarchiveProjectV2ItemPayload |
python | huggingface__transformers | tests/models/hubert/test_modeling_hubert.py | {
"start": 11516,
"end": 16372
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (HubertForCTC, HubertForSequenceClassification, HubertModel) if is_torch_available() else ()
pipeline_model_mapping = (
{
"audio-classification": HubertForSequenceClassification,
"automatic-... | HubertModelTest |
python | pydata__xarray | asv_bench/benchmarks/indexing.py | {
"start": 4253,
"end": 5081
} | class ____(Base):
@parameterized(["key"], [list(basic_indexes.keys())])
def time_assignment_basic(self, key):
ind = basic_indexes[key]
val = basic_assignment_values[key]
self.ds["var1"][ind.get("x", slice(None)), ind.get("y", slice(None))] = val
@parameterized(["key"], [list(outer_i... | Assignment |
python | catalyst-team__catalyst | catalyst/callbacks/metrics/recsys.py | {
"start": 8183,
"end": 12141
} | class ____(BatchMetricCallback):
"""MRR metric callback.
Computes MRR@topk for the specified values of `topk`.
Args:
input_key: input key to use for metric calculation, specifies our `y_pred`
target_key: output key to use for metric calculation, specifies our `y_true`
prefix: key f... | MRRCallback |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 50784,
"end": 50934
} | class ____:
xlDataBarBorderNone = 0 # from enum XlDataBarBorderType
xlDataBarBorderSolid = 1 # from enum XlDataBarBorderType
| DataBarBorderType |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 46185,
"end": 47117
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
... | MultiplePathTest |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-two-arrays.py | {
"start": 41,
"end": 812
} | class ____(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersection(nums2, nums1)
lookup = set()
for i in nums1:
... | Solution |
python | ethereum__web3.py | web3/utils/subscriptions.py | {
"start": 7876,
"end": 8722
} | class ____(EthSubscription[Union[HexBytes, TxData]]):
def __init__(
self,
full_transactions: bool = False,
label: str | None = None,
handler: PendingTxSubscriptionHandler | None = None,
handler_context: dict[str, Any] | None = None,
parallelize: bool | None = None,
... | PendingTxSubscription |
python | walkccc__LeetCode | solutions/2585. Number of Ways to Earn Points/2585.py | {
"start": 0,
"end": 596
} | class ____:
def waysToReachTarget(self, target: int, types: list[list[int]]) -> int:
MOD = 1_000_000_007
# dp[i][j] := the number of ways to earn j points with the first i types
dp = [[0] * (target + 1) for _ in range(len(types) + 1)]
dp[0][0] = 1
for i in range(1, len(types) + 1):
count = ... | Solution |
python | openai__openai-python | src/openai/types/evals/runs/output_item_list_response.py | {
"start": 404,
"end": 1457
} | class ____(BaseModel):
name: str
"""The name of the grader."""
passed: bool
"""Whether the grader considered the output a pass."""
score: float
"""The numeric score produced by the grader."""
sample: Optional[Dict[str, object]] = None
"""Optional sample or intermediate data produced b... | Result |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 157884,
"end": 160792
} | class ____(Request):
"""
Indicates that task is closed
:param force: Allows forcing state change even if transition is not supported
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: ... | CloseRequest |
python | kamyu104__LeetCode-Solutions | Python/rearrange-string-k-distance-apart.py | {
"start": 973,
"end": 1930
} | class ____(object):
def rearrangeString(self, s, k):
"""
:type str: str
:type k: int
:rtype: str
"""
if not k:
return s
cnts = collections.Counter(s)
bucket_cnt = (len(s)+k-1)//k
if not (max(cnts.itervalues()) <= bucket_cnt and cnts... | Solution2 |
python | getsentry__sentry | tests/sentry/models/test_organizationaccessrequest.py | {
"start": 349,
"end": 3230
} | class ____(TestCase):
def test_sends_email_to_everyone(self) -> None:
owner = self.create_user("owner@example.com")
team_admin = self.create_user("team-admin@example.com")
non_team_admin = self.create_user("non-team-admin@example.com")
random_member = self.create_user("member@example... | SendRequestEmailTest |
python | google__jax | jax/_src/interpreters/ad.py | {
"start": 21211,
"end": 25131
} | class ____:
__slots__ = ['aval']
def __init__(self, aval):
self.aval = aval
def __repr__(self):
return f'UndefinedPrimal({self.aval})'
def is_undefined_primal(x):
return type(x) is UndefinedPrimal
register_pytree_node(UndefinedPrimal,
lambda z: ((), z.aval),
l... | UndefinedPrimal |
python | getsentry__sentry | src/sentry/integrations/pagerduty/utils.py | {
"start": 1166,
"end": 8320
} | class ____(TypedDict):
integration_id: int
integration_key: str
service_name: str
id: int
@control_silo_function
def add_service(
organization_integration: OrganizationIntegration, integration_key: str, service_name: str
) -> PagerDutyServiceDict:
with transaction.atomic(router.db_for_write(Or... | PagerDutyServiceDict |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_data_condition_index.py | {
"start": 362,
"end": 3163
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-data-condition-index"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.registry = Registry[type[DataConditionHandler[dict[str, Any]]]](
enable_reverse_lookup=False
)
sel... | OrganizationDataConditionAPITestCase |
python | pytorch__pytorch | torch/utils/_cxx_pytree.py | {
"start": 34574,
"end": 39486
} | class ____(TreeSpec, metaclass=LeafSpecMeta): # type: ignore[misc,final]
def __new__(cls) -> Self:
return treespec_leaf() # type: ignore[return-value]
def tree_flatten_with_path(
tree: PyTree,
is_leaf: Callable[[PyTree], bool] | None = None,
) -> tuple[list[tuple[KeyPath, Any]], TreeSpec]:
"... | LeafSpec |
python | pytorch__pytorch | test/torch_np/test_random.py | {
"start": 3191,
"end": 3619
} | class ____(TestCase):
@parametrize("use_numpy", [True, False])
def test_choice(self, use_numpy):
kwds = dict(size=3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
with control_stream(use_numpy):
tnp.random.seed(12345)
x = tnp.random.choice(5, **kwds)
tnp.random.seed... | TestChoice |
python | jazzband__django-oauth-toolkit | tests/test_commands.py | {
"start": 428,
"end": 4944
} | class ____(TestCase):
def test_command_creates_application(self):
output = StringIO()
self.assertEqual(Application.objects.count(), 0)
call_command(
"createapplication",
"confidential",
"authorization-code",
"--redirect-uris=http://example.com ... | CreateApplicationTest |
python | crytic__slither | slither/detectors/operations/missing_events_access_control.py | {
"start": 801,
"end": 4493
} | class ____(AbstractDetector):
"""
Missing events for critical contract parameters set by owners and used in access control
"""
ARGUMENT = "events-access"
HELP = "Missing Events Access Control"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https:... | MissingEventsAccessControl |
python | pandas-dev__pandas | pandas/tests/indexes/ranges/test_constructors.py | {
"start": 158,
"end": 5328
} | class ____:
@pytest.mark.parametrize("name", [None, "foo"])
@pytest.mark.parametrize(
"args, kwargs, start, stop, step",
[
((5,), {}, 0, 5, 1),
((1, 5), {}, 1, 5, 1),
((1, 5, 2), {}, 1, 5, 2),
((0,), {}, 0, 0, 1),
((0, 0), {}, 0, 0, 1),... | TestRangeIndexConstructors |
python | huggingface__transformers | src/transformers/models/dpt/image_processing_dpt.py | {
"start": 4183,
"end": 32454
} | class ____(BaseImageProcessor):
r"""
Constructs a DPT image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions. Can be overridden by `do_resize` in `preprocess`.
size (`dict[str, int]` *optional*, default... | DPTImageProcessor |
python | pytorch__pytorch | torch/_inductor/cudagraph_trees.py | {
"start": 73979,
"end": 74076
} | class ____(Enum):
FORWARD = auto()
BACKWARD = auto()
INFERENCE = auto()
| CompilationMode |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 62324,
"end": 68573
} | class ____(Visitor):
"""Visitor for verifying containers.
Every container (except typing.Generic) must inherit from typing.Generic and
have an explicitly parameterized base that is also a container. The
parameters on typing.Generic must all be TypeVar instances. A container must
have at most as many paramete... | VerifyContainers |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/all.py | {
"start": 124,
"end": 196
} | class ____:
pass
__all__ = ("public_func", "PublicClass")
| PrivateClass |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/trainer/on_policy_trainer.py | {
"start": 680,
"end": 5851
} | class ____(RLTrainer):
"""The PPOTrainer is an implementation of the PPO algorithm."""
def __init__(
self,
behavior_name: str,
reward_buff_cap: int,
trainer_settings: TrainerSettings,
training: bool,
load: bool,
seed: int,
artifact_path: str,
... | OnPolicyTrainer |
python | walkccc__LeetCode | solutions/332. Reconstruct Itinerary/332.py | {
"start": 0,
"end": 358
} | class ____:
def findItinerary(self, tickets: list[list[str]]) -> list[str]:
ans = []
graph = collections.defaultdict(list)
for a, b in reversed(sorted(tickets)):
graph[a].append(b)
def dfs(u: str) -> None:
while u in graph and graph[u]:
dfs(graph[u].pop())
ans.append(u)
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/longest-subsequence-repeated-k-times.py | {
"start": 59,
"end": 1373
} | class ____(object):
def longestSubsequenceRepeatedK(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def check(s, k, curr):
if not curr:
return True
i = 0
for c in s:
if c != curr[i]:
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/leaf-similar-trees.py | {
"start": 210,
"end": 760
} | class ____(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
def dfs(node):
if not node:
return
if not node.left and not node.right:
yield node.val
... | Solution |
python | Pylons__pyramid | tests/test_util.py | {
"start": 27929,
"end": 28840
} | class ____(unittest.TestCase):
def _callFUT(self, *args, **kw):
from pyramid.util import is_same_domain
return is_same_domain(*args, **kw)
def test_it(self):
self.assertTrue(self._callFUT("example.com", "example.com"))
self.assertFalse(self._callFUT("evil.com", "example.com"))
... | Test_is_same_domain |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 15988,
"end": 16293
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
ptr, idx = args
if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer):
return signature(ptr.dtype, ptr, normalize_1d_index(idx))
@infer_global(operator.setitem)
| GetItemCPointer |
python | pikepdf__pikepdf | tests/test_page.py | {
"start": 1973,
"end": 9390
} | class ____:
def _make_simple_dict(self):
return Dictionary(Type=Name.XObject, Subtype=Name.Image, Width=1, Height=1)
def test_basic(self, graph_page):
d = self._make_simple_dict()
with pytest.raises(ValueError, match="already exists"):
graph_page.add_resource(d, Name.XObjec... | TestAddResource |
python | keras-team__keras | keras/src/layers/core/lambda_layer_test.py | {
"start": 121,
"end": 3259
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_lambda_basics(self):
self.run_layer_test(
layers.Lambda,
init_kwargs={
"function": ops.square,
},
input_shape=(2, 3),
expected_output_shape=(2, 3),
... | LambdaTest |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/protocol.py | {
"start": 993,
"end": 1108
} | class ____(typing.TypedDict):
url: str
token: str
default_kernel_spec: str | None
| JupyterHubClientOptions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.