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 | pydata__xarray | xarray/tests/test_plot.py | {
"start": 104435,
"end": 111471
} | class ____(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
das = [
DataArray(
np.random.randn(3, 3, 4, 4),
dims=["x", "row", "col", "hue"],
coords=[range(k) for k in [3, 3, 4, 4]],
)
for _ in [1, 2]... | TestDatasetScatterPlots |
python | neetcode-gh__leetcode | python/1845-seat-reservation-manager.py | {
"start": 14,
"end": 285
} | class ____:
def __init__(self, n: int):
self.seats = [i for i in range(1, n + 1)]
def reserve(self) -> int:
return heapq.heappop(self.seats)
def unreserve(self, seatNumber: int) -> None:
heapq.heappush(self.seats, seatNumber) | SeatManager |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 1777,
"end": 1883
} | class ____:
def __init__(self):
self._protected = None
self._protected_two = None
| Parent |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/shell-script-component/pythonic/2-shell-command-empty-no-model-dataclass.py | {
"start": 69,
"end": 381
} | class ____(dg.Component, dg.Resolvable):
"""COMPONENT SUMMARY HERE.
COMPONENT DESCRIPTION HERE.
"""
# Add schema fields here
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions:
# Add definition construction logic here.
return dg.Definitions()
| ShellCommand |
python | django__django | tests/migrations/test_migrations_manual_porting/0004_fourth.py | {
"start": 81,
"end": 590
} | class ____(migrations.Migration):
dependencies = [
("migrations", "0002_second"),
]
replaces = [
("migrations", "0003_third"),
]
operations = [
migrations.AlterUniqueTogether(
name="somemodel",
unique_together={("id", "name")},
),
mig... | Migration |
python | sqlalchemy__sqlalchemy | test/orm/test_dynamic.py | {
"start": 1278,
"end": 4851
} | class ____:
lazy = "dynamic"
@testing.fixture
def user_address_fixture(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
def _user_address_fixture(addresses... | _DynamicFixture |
python | kamyu104__LeetCode-Solutions | Python/merge-in-between-linked-lists.py | {
"start": 151,
"end": 697
} | class ____(object):
def mergeInBetween(self, list1, a, b, list2):
"""
:type list1: ListNode
:type a: int
:type b: int
:type list2: ListNode
:rtype: ListNode
"""
prev_first, last = None, list1
for i in xrange(b):
if i == a-1:
... | Solution |
python | numba__numba | numba/core/ir.py | {
"start": 29458,
"end": 29672
} | class ____(Stmt):
"""Marker statement for a pop block op code"""
def __init__(self, loc):
assert isinstance(loc, Loc)
self.loc = loc
def __str__(self):
return 'pop_block'
| PopBlock |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/dataproc.py | {
"start": 24075,
"end": 27262
} | class ____(DataprocBaseTrigger):
"""
Trigger that periodically polls information on a long running operation from Dataproc API to verify status.
Implementation leverages asynchronous transport.
"""
def __init__(self, name: str, operation_type: str | None = None, **kwargs: Any):
super().__i... | DataprocOperationTrigger |
python | tiangolo__fastapi | docs_src/request_form_models/tutorial001_an.py | {
"start": 124,
"end": 278
} | class ____(BaseModel):
username: str
password: str
@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
return data
| FormData |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 59528,
"end": 78445
} | class ____:
def test_exp_values(self):
with np.errstate(under='raise', over='raise'):
x = [np.nan, np.nan, np.inf, 0.]
y = [np.nan, -np.nan, np.inf, -np.inf]
for dt in ['e', 'f', 'd', 'g']:
xf = np.array(x, dtype=dt)
yf = np.array(y, dtype... | TestSpecialFloats |
python | mwaskom__seaborn | seaborn/_core/typing.py | {
"start": 1481,
"end": 1601
} | class ____:
def __repr__(self):
return "<deprecated>"
default = Default()
deprecated = Deprecated()
| Deprecated |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 152786,
"end": 158140
} | class ____(DataplexCatalogBaseOperator):
"""
Create an Entry resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogCreateEntryOperator`
:param entry_id: Required. Entry identifier. It has to be unique with... | DataplexCatalogCreateEntryOperator |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_events_reader.py | {
"start": 13105,
"end": 14541
} | class ____(BaseDigest):
"""Light-weight digest summarizing top-level execution event.
Use `DebugDataReader.read_execution(execution_digest)` to load the more
detailed data object concerning the execution event (`Execution`).
Properties:
op_type: Type name of the executed op. In the case of the eager execu... | ExecutionDigest |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 54992,
"end": 60613
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | BigBirdPegasusDecoderAttention |
python | pytorch__pytorch | torch/_numpy/_dtypes.py | {
"start": 1059,
"end": 1108
} | class ____(inexact):
name = "floating"
| floating |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/check.py | {
"start": 1834,
"end": 7776
} | class ____(NamedTuple):
object_key: Optional[EnvRegistryKey]
error: "ValidationError"
source_position_tree: ValueAndSourcePositionTree
def check_yaml(
dg_context: DgContext,
resolved_paths: Sequence[Path],
validate_requirements: bool,
) -> bool:
# defer for import performance
from json... | ErrorInput |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 3710,
"end": 5943
} | class ____(fixtures.TestBase):
def test_odict(self):
o = util.OrderedDict()
o["a"] = 1
o["b"] = 2
o["snack"] = "attack"
o["c"] = 3
eq_(list(o.keys()), ["a", "b", "snack", "c"])
eq_(list(o.values()), [1, 2, "attack", 3])
o.pop("snack")
eq_(lis... | OrderedDictTest |
python | Pylons__pyramid | tests/test_util.py | {
"start": 25465,
"end": 26168
} | class ____(unittest.TestCase):
def _callFUT(self, val):
from pyramid.util import get_callable_name
return get_callable_name(val)
def test_valid_ascii_bytes(self):
name = b'hello world'
self.assertEqual(self._callFUT(name), 'hello world')
def test_valid_ascii_string(self):
... | TestCallableName |
python | scipy__scipy | scipy/stats/_odds_ratio.py | {
"start": 5029,
"end": 17005
} | class ____:
"""
Result of `scipy.stats.contingency.odds_ratio`. See the
docstring for `odds_ratio` for more details.
Attributes
----------
statistic : float
The computed odds ratio.
* If `kind` is ``'sample'``, this is sample (or unconditional)
estimate, given by
... | OddsRatioResult |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/auth.py | {
"start": 325,
"end": 629
} | class ____(Exception):
"""Not implemented Auth option error"""
logger = logging.getLogger("airbyte")
def __init__(self, auth_method: str = None):
self.message = f"Not implemented Auth method = {auth_method}"
super().__init__(self.logger.error(self.message))
| NotImplementedAuth |
python | dagster-io__dagster | docs/sphinx/_ext/dagster-sphinx/dagster_sphinx/__init__.py | {
"start": 2796,
"end": 8942
} | class ____(ClassDocumenter):
"""Overrides the default autodoc ClassDocumenter to adds some extra options."""
objtype = "class"
def get_object_members(self, want_all: bool) -> tuple[bool, list[ObjectMember]]:
# the @record transform creates a new outer class, so redirect
# sphinx to target ... | DagsterClassDocumenter |
python | protocolbuffers__protobuf | python/google/protobuf/internal/field_mask_test.py | {
"start": 683,
"end": 19110
} | class ____(unittest.TestCase):
def testStringFormat(self):
mask = field_mask_pb2.FieldMask()
self.assertEqual('', mask.ToJsonString())
mask.paths.append('foo')
self.assertEqual('foo', mask.ToJsonString())
mask.paths.append('bar')
self.assertEqual('foo,bar', mask.ToJsonString())
mask.From... | FieldMaskTest |
python | sympy__sympy | sympy/functions/special/singularity_functions.py | {
"start": 595,
"end": 8346
} | class ____(DefinedFunction):
r"""
Singularity functions are a class of discontinuous functions.
Explanation
===========
Singularity functions take a variable, an offset, and an exponent as
arguments. These functions are represented using Macaulay brackets as:
SingularityFunction(x, a, n) ... | SingularityFunction |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 247564,
"end": 248207
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of LinkProjectV2ToTeam"""
__schema__ = github_schema
__field_names__ = ("project_id", "team_id", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
"""The ID of the project to link to th... | LinkProjectV2ToTeamInput |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 28402,
"end": 28658
} | class ____(graphene.ObjectType):
"""Output indicating that runless asset events were reported."""
assetKey = graphene.NonNull(GrapheneAssetKey)
class Meta:
name = "ReportRunlessAssetEventsSuccess"
| GrapheneReportRunlessAssetEventsSuccess |
python | graphql-python__graphene | graphene/types/definitions.py | {
"start": 742,
"end": 817
} | class ____(GrapheneGraphQLType, GraphQLUnionType):
pass
| GrapheneUnionType |
python | django__django | tests/select_related_regress/models.py | {
"start": 2750,
"end": 2813
} | class ____(Base):
a_field = models.CharField(max_length=10)
| A |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 4730,
"end": 4942
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI Datasets Link."""
name = "Dataset List"
key = "datasets_conf"
format_str = VERTEX_AI_DATASET_LIST_LINK
| VertexAIDatasetListLink |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 53202,
"end": 59158
} | class ____(EvollaPreTrainedModel):
def __init__(self, config: EvollaConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(self.vocab_size, config.hidden_size, self.padding_idx)
self.protei... | EvollaModel |
python | pydata__xarray | xarray/core/accessor_str.py | {
"start": 4530,
"end": 99670
} | class ____(Generic[T_DataArray]):
r"""Vectorized string functions for string-like arrays.
Similar to pandas, fields can be accessed through the `.str` attribute
for applicable DataArrays.
>>> da = xr.DataArray(["some", "text", "in", "an", "array"])
>>> da.str.len()
<xarray.DataArra... | StringAccessor |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py | {
"start": 80818,
"end": 85128
} | class ____:
edges = [
(1, 3),
(2, 3),
(3, 4),
(4, 9),
(4, 5),
(3, 9),
(5, 8),
(5, 7),
(8, 7),
(6, 7),
]
mapped = {
0: "x",
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
6: "f",
... | TestGraphTinoutUpdating |
python | kamyu104__LeetCode-Solutions | Python/three-consecutive-odds.py | {
"start": 29,
"end": 326
} | class ____(object):
def threeConsecutiveOdds(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
count = 0
for x in arr:
count = count+1 if x%2 else 0
if count == 3:
return True
return False
| Solution |
python | huggingface__transformers | src/transformers/models/bert_generation/configuration_bert_generation.py | {
"start": 741,
"end": 5628
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to
instantiate a BertGeneration model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults wi... | BertGenerationConfig |
python | ray-project__ray | rllib/policy/tests/test_sample_batch.py | {
"start": 504,
"end": 20165
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init(num_gpus=1)
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_len_and_size_bytes(self):
s1 = SampleBatch(
{
"a": np.array([1, 2, 3]),
... | TestSampleBatch |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-two-arrays-ii.py | {
"start": 451,
"end": 1459
} | class ____(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
lookup = collections.defaultdict(int)
for i in n... | Solution |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 64530,
"end": 64757
} | class ____(Granularity):
"""
Represents per-tensor granularity in quantization.
This granularity type calculates the quantization parameters
based off the entire tensor.
"""
@dataclass(frozen=True)
| PerTensor |
python | pytorch__pytorch | torch/_inductor/runtime/triton_heuristics.py | {
"start": 80602,
"end": 135595
} | class ____(CachingAutotuner):
def __init__(
self,
*args,
regex_filter="",
with_profiler=False,
with_bandwidth_info=True,
**kwargs,
):
self.regex_filter = regex_filter
self.with_profiler = with_profiler
self.with_bandwidth_info = with_bandwi... | DebugAutotuner |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 883410,
"end": 883822
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("PullRequestTimelineItems"... | PullRequestTimelineItemsEdge |
python | apache__airflow | providers/zendesk/tests/unit/zendesk/hooks/test_zendesk.py | {
"start": 1016,
"end": 3774
} | class ____:
conn_id = "zendesk_conn_id_test"
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=self.conn_id,
conn_type="zendesk",
host="yoursubdomain.... | TestZendeskHook |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 1455,
"end": 2090
} | class ____(models.Model):
name = models.ForeignKey(Name, on_delete=models.CASCADE)
age = models.PositiveIntegerField()
children = models.ManyToManyField("self")
notes = models.ManyToManyField(Note)
personality = models.OneToOneField(
Personality,
null=True,
on_delete=models.C... | Person |
python | tensorflow__tensorflow | tensorflow/python/framework/op_def_library_test.py | {
"start": 55856,
"end": 56535
} | class ____(test_util.TensorFlowTestCase):
def testPybind(self):
x = constant_op.constant(32, dtype=dtypes.float32)
y = constant_op.constant(32, dtype=dtypes.float32)
attrs, inputs, input_types, output_structure = (
op_def_library_pybind.process_inputs("AddV2", 1, {
"x": x,
... | OpDefLibraryPybindTest |
python | django__django | tests/model_fields/models.py | {
"start": 935,
"end": 1115
} | class ____(models.Model):
a = models.CharField(max_length=10)
d = models.DecimalField(max_digits=5, decimal_places=3)
def get_foo():
return Foo.objects.get(id=1).pk
| Foo |
python | pandas-dev__pandas | asv_bench/benchmarks/io/excel.py | {
"start": 1546,
"end": 2486
} | class ____:
params = ["openpyxl", "odf"]
param_names = ["engine"]
fname_excel = "spreadsheet.xlsx"
fname_odf = "spreadsheet.ods"
def _create_odf(self):
doc = OpenDocumentSpreadsheet()
table = Table(name="Table1")
for row in self.df.values:
tr = TableRow()
... | ReadExcel |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 53957,
"end": 54289
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional[bool] = Field(default=None, description="")
| InlineResponse200 |
python | scipy__scipy | scipy/integrate/_odepack_py.py | {
"start": 199,
"end": 11236
} | class ____(Warning):
"""Warning raised during the execution of `odeint`."""
pass
_msgs = {2: "Integration successful.",
1: "Nothing was done; the integration time was 0.",
-1: "Excess work done on this call (perhaps wrong Dfun type).",
-2: "Excess accuracy requested (tolerances too ... | ODEintWarning |
python | django__django | tests/many_to_many/tests.py | {
"start": 25369,
"end": 28091
} | class ____(TestCase):
"""
SQL is optimized to reference the through table without joining against the
related table when using count() and exists() functions on a queryset for
many to many relations. The optimization applies to the case where there
are no filters.
"""
@classmethod
def s... | ManyToManyQueryTests |
python | getsentry__sentry | src/sentry/analytics/events/manual_issue_assignment.py | {
"start": 80,
"end": 308
} | class ____(analytics.Event):
organization_id: int
project_id: int
group_id: int
assigned_by: str | None = None
had_to_deassign: bool | None = None
analytics.register(ManualIssueAssignment)
| ManualIssueAssignment |
python | django__django | django/db/backends/base/validation.py | {
"start": 0,
"end": 1119
} | class ____:
"""Encapsulate backend-specific validation."""
def __init__(self, connection):
self.connection = connection
def __del__(self):
del self.connection
def check(self, **kwargs):
return []
def check_field(self, field, **kwargs):
errors = []
# Backen... | BaseDatabaseValidation |
python | redis__redis-py | redis/commands/cluster.py | {
"start": 24955,
"end": 25807
} | class ____(
ClusterManagementCommands, AsyncManagementCommands
):
"""
A class for Redis Cluster management commands
The class inherits from Redis's core ManagementCommands class and do the
required adjustments to work with cluster mode
"""
async def cluster_delslots(self, *slots: Encodable... | AsyncClusterManagementCommands |
python | pytorch__pytorch | torch/distributed/optim/functional_rprop.py | {
"start": 812,
"end": 3807
} | class ____:
def __init__(
self,
params: list[Tensor],
lr: float = 1e-2,
etas: tuple[float, float] = (0.5, 1.2),
step_sizes: tuple[float, float] = (1e-6, 50),
foreach: bool = False,
maximize: bool = False,
_allow_empty_param_list: bool = False,
):
... | _FunctionalRprop |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 58944,
"end": 59799
} | class ____(MaskedArraySetup):
def test_masked_array_from_masked(self):
"""Check that we can initialize a MaskedArray properly."""
np_ma = np.ma.MaskedArray(self.ma)
assert type(np_ma) is np.ma.MaskedArray
assert type(np_ma.data) is self._data_cls
assert type(np_ma.mask) is np... | TestMaskedArrayInteractionWithNumpyMA |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 13379,
"end": 15277
} | class ____(Binding):
"""
A binding created by an C{__all__} assignment. If the names in the list
can be determined statically, they will be treated as names for export and
additional checking applied to them.
The only recognized C{__all__} assignment via list/tuple concatenation is in the
foll... | ExportBinding |
python | sympy__sympy | sympy/matrices/expressions/factorizations.py | {
"start": 1120,
"end": 1456
} | class ____(Factorization):
@property
def predicates(self):
return (Q.orthogonal,)
def lu(expr):
return LofLU(expr), UofLU(expr)
def qr(expr):
return QofQR(expr), RofQR(expr)
def eig(expr):
return EigenValues(expr), EigenVectors(expr)
def svd(expr):
return UofSVD(expr), SofSVD(expr),... | VofSVD |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 64693,
"end": 67223
} | class ____(CFEncodedBase):
"""Tests for all netCDF3 and netCDF4 backends."""
@pytest.mark.asyncio
@pytest.mark.skip(reason="NetCDF backends don't support async loading")
async def test_load_async(self) -> None:
await super().test_load_async()
@pytest.mark.skipif(
ON_WINDOWS, reason... | NetCDFBase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI012.py | {
"start": 714,
"end": 795
} | class ____:
pass # Y009 Empty body should contain `...`, not `pass`
| EmptyClass |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/cx_oracle.py | {
"start": 22612,
"end": 22713
} | class ____(sqltypes.Uuid):
def get_dbapi_type(self, dbapi):
return dbapi.STRING
| _OracleUUID |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox20.py | {
"start": 315,
"end": 866
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox20.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | cherrypy__cherrypy | cherrypy/lib/profiler.py | {
"start": 1565,
"end": 3936
} | class ____(object):
"""A profiling app."""
def __init__(self, path=None):
"""Prepare the profiling app resources."""
if not path:
path = os.path.join(os.path.dirname(__file__), 'profile')
self.path = path
if not os.path.exists(path):
os.makedirs(path)
... | Profiler |
python | pytorch__pytorch | test/inductor/test_flex_attention.py | {
"start": 181635,
"end": 218819
} | class ____(InductorTestCase):
def setUp(self):
super().setUp()
@supported_platform
def test_block_mask_attributes(self, device):
offset = torch.zeros(8, device=device)
def causal_mask(b, h, q, kv):
return (q + (offset[b] * 128)) >= kv
block_mask = create_block_... | TestBlockMask |
python | pytorch__pytorch | torch/_inductor/compile_fx.py | {
"start": 25565,
"end": 25991
} | class ____(TypedDict, total=False):
cudagraphs: Optional[BoxedBool]
static_input_idxs: Sequence[int]
is_backward: bool
graph_id: Optional[int]
cpp_wrapper: bool
aot_mode: bool
is_inference: bool
layout_opt: Optional[bool]
extern_node_serializer: Optional[Callable[[list[ExternKernelNo... | _CompileFxKwargs |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 24743,
"end": 27679
} | class ____(ModelOutput):
"""
Base class for causal language model (or autoregressive) with mixture of experts outputs.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`... | MoeCausalLMOutputWithPast |
python | numpy__numpy | numpy/f2py/tests/test_crackfortran.py | {
"start": 9939,
"end": 10261
} | class ____(util.F2PyTest):
def test_eval_scalar(self):
eval_scalar = crackfortran._eval_scalar
assert eval_scalar('123', {}) == '123'
assert eval_scalar('12 + 3', {}) == '15'
assert eval_scalar('a + b', {"a": 1, "b": 2}) == '3'
assert eval_scalar('"123"', {}) == "'123'"
| TestEval |
python | openai__openai-python | src/openai/types/realtime/realtime_session_create_response.py | {
"start": 12589,
"end": 13194
} | class ____(BaseModel):
group_id: Optional[str] = None
"""
The group id to attach to this trace to enable filtering and grouping in the
Traces Dashboard.
"""
metadata: Optional[object] = None
"""
The arbitrary metadata to attach to this trace to enable filtering in the Traces
Dashboa... | TracingTracingConfiguration |
python | ansible__ansible | test/lib/ansible_test/_internal/debugging.py | {
"start": 3709,
"end": 7813
} | class ____(DebuggerSettings):
"""Settings for the pydevd debugger."""
package: str | None = None
"""
The Python package to install for debugging.
If `None` then the package will be auto-detected.
If an empty string, then no package will be installed.
"""
module: str | None = None
"... | PydevdSettings |
python | getsentry__sentry | src/sentry/integrations/perforce/integration.py | {
"start": 8697,
"end": 10756
} | class ____(IntegrationProvider):
"""Provider for Perforce integration."""
key = "perforce"
name = "Perforce"
metadata = metadata
integration_cls = PerforceIntegration
features = frozenset(
[
IntegrationFeatures.STACKTRACE_LINK,
IntegrationFeatures.COMMITS,
... | PerforceIntegrationProvider |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py | {
"start": 6906,
"end": 8176
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger for RedshiftDeleteClusterOperator.
:param cluster_identifier: A unique identifier for the cluster.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param aws_conn_id: The Airflow connection used for AWS credentials.
:param wa... | RedshiftDeleteClusterTrigger |
python | redis__redis-py | redis/asyncio/client.py | {
"start": 32218,
"end": 49892
} | class ____:
"""
PubSub provides publish, subscribe and listen support to Redis channels.
After subscribing to one or more channels, the listen() method will block
until a message arrives on one of the subscribed channels. That message
will be returned and it's safe to start listening again.
"""... | PubSub |
python | tiangolo__fastapi | tests/test_security_api_key_query_optional.py | {
"start": 262,
"end": 2061
} | class ____(BaseModel):
username: str
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: Optional[User] = Depends(get_current_user)... | User |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis02.py | {
"start": 315,
"end": 1430
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | keras-team__keras | keras/src/layers/convolutional/conv_transpose_test.py | {
"start": 8998,
"end": 17095
} | class ____(testing.TestCase):
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 2,
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": 1,
"input_shap... | ConvTransposeBasicTest |
python | apache__airflow | providers/celery/src/airflow/providers/celery/executors/celery_kubernetes_executor.py | {
"start": 2000,
"end": 13399
} | class ____(BaseExecutor):
"""
CeleryKubernetesExecutor consists of CeleryExecutor and KubernetesExecutor.
It chooses an executor to use based on the queue defined on the task.
When the queue is the value of ``kubernetes_queue`` in section ``[celery_kubernetes_executor]``
of the configuration (defau... | CeleryKubernetesExecutor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 793,
"end": 1057
} | class ____(str, Enum):
"""The available vector index types in Weaviate.
Attributes:
HNSW: Hierarchical Navigable Small World (HNSW) index.
FLAT: Flat index.
"""
HNSW = "hnsw"
FLAT = "flat"
DYNAMIC = "dynamic"
| VectorIndexType |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 38160,
"end": 38516
} | class ____(PatternEntry):
"""
A pattern that runs a function on the FX graph
"""
handler: Callable[..., Any]
def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None:
with graph.inserting_before(node):
self.handler(match, *match.args, **match.kwargs)
... | GraphPatternEntry |
python | kamyu104__LeetCode-Solutions | Python/equal-row-and-column-pairs.py | {
"start": 84,
"end": 437
} | class ____(object):
def equalPairs(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
cnt1 = collections.Counter(tuple(row) for row in grid)
cnt2 = collections.Counter(tuple(col) for col in itertools.izip(*grid))
return sum(cnt1[k]*cnt2[k] for k in c... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 138289,
"end": 141414
} | class ____(DataplexCatalogBaseOperator):
"""
Get an AspectType resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogGetAspectTypeOperator`
:param aspect_type_id: Required. AspectType identifier.
:para... | DataplexCatalogGetAspectTypeOperator |
python | ansible__ansible | test/units/mock/custom_types.py | {
"start": 998,
"end": 1026
} | class ____(int): ...
| CustomInt |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/job.py | {
"start": 10970,
"end": 43899
} | class ____(
NamedTuple(
"_K8sJobTaskConfig",
[
("job_image", Optional[str]),
("dagster_home", Optional[str]),
("image_pull_policy", str),
("image_pull_secrets", Sequence[Mapping[str, str]]),
("service_account_name", Optional[str]),
... | DagsterK8sJobConfig |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 6180,
"end": 15699
} | class ____(Service):
"""Abstraction layer for all release health related queries"""
__all__ = (
"get_current_and_previous_crash_free_rates",
"get_release_adoption",
"check_has_health_data",
"get_release_sessions_time_bounds",
"check_releases_have_health_data",
"s... | ReleaseHealthBackend |
python | pytest-dev__pytest | testing/code/test_source.py | {
"start": 12966,
"end": 13690
} | class ____:
def setup_class(self) -> None:
self.source = """\
try:
raise ValueError
except Something:
raise IndexError(1)
else:
raise KeyError()
"""
def test_body(self) -> None:
source = getstatement(1, self.source)
assert str(source) == " raise ValueError"
def test_... | TestTry |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 845008,
"end": 846233
} | class ____(sgqlc.types.Type, HovercardContext):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"relevant_teams",
"teams_resource_path",
"teams_url",
"total_team_count",
)
relevant_teams = sgqlc.types.Field(
sgql... | OrganizationTeamsHovercardContext |
python | pypa__warehouse | warehouse/accounts/interfaces.py | {
"start": 7666,
"end": 7861
} | class ____(Interface):
def get_email_breach_count(email: str) -> int | None:
"""
Returns count of times the email appears in verified breaches.
"""
| IEmailBreachedService |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/utils/__init__.py | {
"start": 12869,
"end": 13614
} | class ____:
def format_help(self, context: click.Context, formatter: click.HelpFormatter):
"""Customizes the help to include hierarchical usage."""
from typer.rich_utils import rich_format_help
if not isinstance(self, click.Command):
raise ValueError("This mixin is only intended... | DgClickHelpMixin |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 243976,
"end": 245862
} | class ____(GeneratedAirbyteSource):
class OAuth:
@public
def __init__(self, client_id: str, client_secret: str, refresh_token: str):
self.credentials_title = "OAuth Credentials"
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.st... | HubspotSource |
python | huggingface__transformers | tests/models/llava_next_video/test_modeling_llava_next_video.py | {
"start": 12612,
"end": 19984
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")
image_file = hf_hub_download(
repo_id="raushan-testing-hf/images_test", filename="llava_v1_5_radar.jpg", repo_type="dataset"
)
video_file = hf... | LlavaNextVideoForConditionalGenerationIntegrationTest |
python | joke2k__faker | faker/providers/company/es_MX/__init__.py | {
"start": 45,
"end": 11424
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}}-{{last_name}}",
"{{company_prefix}} {{last_name}}-{{last_name}}",
"{{company_prefix}} {{last_name}} y {{last_name}}",
"{{company_prefix}} {{last_name}}, {{last_name}} y {{last_name}}",... | Provider |
python | scrapy__scrapy | tests/test_feedexport.py | {
"start": 21986,
"end": 22418
} | class ____(BlockingFeedStorage):
def __init__(self, uri, *args, feed_options=None):
self.path = Path(file_uri_to_path(uri))
def _store_in_thread(self, file):
dirname = self.path.parent
if dirname and not dirname.exists():
dirname.mkdir(parents=True)
with self.path.op... | DummyBlockingFeedStorage |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 21641,
"end": 22302
} | class ____(
APIv3Settings,
GenericViewSet,
):
# NOTE: this viewset is only useful for nested URLs required for notifications:
# /api/v3/users/<username>/notifications/
# However, accessing to /api/v3/users/ or /api/v3/users/<username>/ will return 404.
# We can implement these endpoints when we ... | UsersViewSet |
python | rapidsai__cudf | python/cudf/cudf/pandas/module_accelerator.py | {
"start": 2282,
"end": 11089
} | class ____(
importlib.abc.MetaPathFinder, importlib.abc.Loader
):
_instance: ModuleAcceleratorBase | None = None
mod_name: str
fast_lib: str
slow_lib: str
# When walking the module tree and wrapping module attributes,
# we often will come across the same object more than once. We
# don'... | ModuleAcceleratorBase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 44649,
"end": 47711
} | class ____(_PostLoader):
__slots__ = ("join_depth",)
def __init__(self, parent, strategy_key):
super().__init__(parent, strategy_key)
self.join_depth = self.parent_property.join_depth
def init_class_attribute(self, mapper):
self.parent_property._get_strategy(
(("lazy", ... | _ImmediateLoader |
python | huggingface__transformers | tests/models/rembert/test_modeling_rembert.py | {
"start": 1347,
"end": 13362
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
input_embedding_size=18,
output_embeddi... | RemBertModelTester |
python | google__jax | jax/_src/pallas/mosaic/sc_core.py | {
"start": 4313,
"end": 4724
} | class ____(pallas_core.BlockMapping):
indexed_by: int | None = None
indexed_dim: int | None = None
def get_sparse_core_info() -> tpu_info.SparseCoreInfo:
"""Returns the SparseCore information for the current device."""
return tpu_info.get_tpu_info().sparse_core or tpu_info.SparseCoreInfo(
num_cores=0, n... | BlockMapping |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 322553,
"end": 323688
} | class ____(Response):
"""
Response of tasks.make_private endpoint.
:param updated: Number of tasks updated
:type updated: int
"""
_service = "tasks"
_action = "make_private"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"updated": {
... | MakePrivateResponse |
python | pytest-dev__pytest-xdist | testing/test_workermanage.py | {
"start": 1319,
"end": 5221
} | class ____:
def test_popen_no_default_chdir(self, config: pytest.Config) -> None:
gm = NodeManager(config, ["popen"])
assert gm.specs[0].chdir is None
def test_default_chdir(self, config: pytest.Config) -> None:
specs = ["ssh=noco", "socket=xyz"]
for spec in NodeManager(config, ... | TestNodeManagerPopen |
python | ray-project__ray | python/ray/data/_internal/logical/optimizers.py | {
"start": 1674,
"end": 3390
} | class ____(Optimizer):
"""The optimizer for physical operators."""
@property
def rules(self) -> List[Rule]:
return [rule_cls() for rule_cls in get_physical_ruleset()]
def get_plan_conversion_fns() -> List[Callable[[Plan], Plan]]:
"""Get the list of transformation functions to convert a logica... | PhysicalOptimizer |
python | tensorflow__tensorflow | tensorflow/python/tpu/feature_column_test.py | {
"start": 6633,
"end": 13349
} | class ____(test.TestCase):
@test_util.deprecated_graph_mode_only
def test_defaults(self):
categorical_column_a = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=3)
categorical_column_b = fc_lib.categorical_column_with_identity(
key='bbb', num_buckets=3)
embedding_dimensi... | SharedEmbeddingColumnTest |
python | Textualize__textual | tests/snapshot_tests/language_snippets.py | {
"start": 15671,
"end": 19198
} | class ____ implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
// Enums
enum DaysOfWeek {
MOND... | Rectangle |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_iter.py | {
"start": 3511,
"end": 3729
} | class ____:
def __init__(self):
self.i = 0
def __call__(self):
i = self.i
self.i = i + 1
if i > 100:
raise IndexError # Emergency stop
return i
| CallableIterClass |
python | coleifer__peewee | tests/sql.py | {
"start": 72000,
"end": 74554
} | class ____(BaseTestCase):
_data = [(1, 'one'), (2, 'two'), (3, 'three')]
def test_values_list(self):
vl = ValuesList(self._data)
query = vl.select(SQL('*'))
self.assertSQL(query, (
'SELECT * FROM (VALUES (?, ?), (?, ?), (?, ?)) AS "t1"'),
[1, 'one', 2, 'two', 3,... | TestValuesList |
python | PrefectHQ__prefect | src/integrations/prefect-sqlalchemy/tests/test_database.py | {
"start": 2646,
"end": 19488
} | class ____:
async def test_connector_init(self):
credentials_components = SqlAlchemyConnector(
connection_info=ConnectionComponents(
driver=SyncDriver.POSTGRESQL_PSYCOPG2,
username="myusername",
password="mypass",
database="my.db",
... | TestSqlAlchemyConnector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.