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_merge.py | {
"start": 35398,
"end": 38866
} | class ____:
def test_mixed(self) -> None:
tree = xr.DataTree()
ds = xr.Dataset()
with pytest.raises(
TypeError,
match="merge does not support mixed type arguments when one argument is a DataTree",
):
xr.merge([tree, ds]) # type: ignore[list-item]
... | TestMergeDataTree |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/codegen/elemental/concatenate_kernel_emitter_test.py | {
"start": 1087,
"end": 3352
} | class ____(parameterized.TestCase):
@parameterized.product(
cycle_layout=[True, False],
dtype=[
np.dtype(np.uint8),
np.dtype(np.uint16),
np.dtype(np.uint32),
np.dtype(np.uint64),
np.dtype(np.int8),
np.dtype(np.int16),
np.dtype(np.int32... | ConcatenateKernelRunnerTest |
python | sqlalchemy__sqlalchemy | test/orm/test_transaction.py | {
"start": 56076,
"end": 65742
} | class ____(FixtureTest):
run_inserts = None
__sparse_driver_backend__ = True
@testing.requires.savepoints
@engines.close_open_connections
def test_contextmanager_nested_rollback(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, us... | ContextManagerPlusFutureTest |
python | ray-project__ray | python/ray/train/examples/horovod/horovod_tune_example.py | {
"start": 481,
"end": 3946
} | class ____(torch.nn.Module):
def __init__(self, mode="sq"):
super(Net, self).__init__()
if mode == "square":
self.mode = 0
self.param = torch.nn.Parameter(torch.FloatTensor([1.0, -1.0]))
else:
self.mode = 1
self.param = torch.nn.Parameter(torc... | Net |
python | simonw__datasette | datasette/events.py | {
"start": 3031,
"end": 3678
} | class ____(Event):
"""
Event name: ``insert-rows``
Rows were inserted into a table.
:ivar database: The name of the database where the rows were inserted.
:type database: str
:ivar table: The name of the table where the rows were inserted.
:type table: str
:ivar num_rows: The number of... | InsertRowsEvent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/source.py | {
"start": 1195,
"end": 2262
} | class ____(RecordExtractor):
"""
Extractor Template for all BrainTree streams.
"""
@staticmethod
def _extract_as_array(results, attribute):
if attribute not in results:
return []
value = results[attribute]
if not isinstance(value, list):
value = [val... | BraintreeExtractor |
python | getsentry__sentry | src/sentry/integrations/web/organization_integration_setup.py | {
"start": 541,
"end": 2075
} | class ____(ControlSiloOrganizationView):
required_scope = "org:integrations"
csrf_protect = False
def handle(self, request: HttpRequest, organization, provider_id) -> HttpResponseBase:
scope = sentry_sdk.get_current_scope()
scope.set_transaction_name(f"integration.{provider_id}", source=Tr... | OrganizationIntegrationSetupView |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 7287,
"end": 8128
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "GraphNotFoundError"
graph_name = graphene.NonNull(graphene.String)
repository_name = graphene.NonNull(graphene.String)
repository_location_name = graphene.NonNull(graphene.String)
def __init__(self, ... | GrapheneGraphNotFoundError |
python | getsentry__sentry | src/sentry/rules/processing/buffer_processing.py | {
"start": 1737,
"end": 8332
} | class ____(ABC):
buffer_key: ClassVar[str]
buffer_shards: ClassVar[int] = 1 # 1 shard will use the original buffer key
buffer_separator: ClassVar[str] = ":"
option: ClassVar[str | None]
def __init__(self, project_id: int):
self.project_id = project_id
@property
@abstractmethod
... | DelayedProcessingBase |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 218820,
"end": 223558
} | class ____(_fixtures.FixtureTest):
@classmethod
def setup_mappers(cls):
(
users,
Keyword,
items,
order_items,
Order,
Item,
User,
keywords,
item_keywords,
orders,
) = (
... | DeepOptionsTest |
python | modin-project__modin | modin/tests/pandas/native_df_interoperability/test_compiler_caster.py | {
"start": 4354,
"end": 5029
} | class ____(CalculatorTestQc):
"Represents a local network cluster query compiler"
def get_backend(self):
return "Cluster"
@classmethod
def max_cost(cls):
return QCCoercionCost.COST_HIGH
def move_to_cost(self, other_qc_cls, api_cls_name, op, arguments):
return {
... | ClusterQC |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/instrumentation.py | {
"start": 2193,
"end": 2394
} | class ____(Protocol):
def __call__(
self,
state: state.InstanceState[Any],
toload: Set[str],
passive: base.PassiveFlag,
) -> None: ...
| _ExpiredAttributeLoaderProto |
python | django__django | tests/queries/tests.py | {
"start": 100846,
"end": 103125
} | class ____(TestCase):
def test_evaluated_queryset_as_argument(self):
"""
If a queryset is already evaluated, it can still be used as a query
arg.
"""
n = Note(note="Test1", misc="misc")
n.save()
e = ExtraInfo(info="good", note=n)
e.save()
n_li... | CloneTests |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_tls.py | {
"start": 383,
"end": 5274
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1IngressTLS |
python | wandb__wandb | wandb/apis/public/artifacts.py | {
"start": 11183,
"end": 23714
} | class ____:
"""An artifact collection that represents a group of related artifacts.
Args:
client: The client instance to use for querying W&B.
entity: The entity (user or team) that owns the project.
project: The name of the project to query for artifact collections.
name: The n... | ArtifactCollection |
python | rapidsai__cudf | docs/cudf/source/conf.py | {
"start": 22112,
"end": 23964
} | class ____(ClassDocumenter):
objtype = "enum"
directivetype = "attribute"
priority = 10 + ClassDocumenter.priority
option_spec = dict(ClassDocumenter.option_spec)
@classmethod
def can_document_member(
cls, member: Any, membername: str, isattr: bool, parent: Any
) -> bool:
t... | PLCIntEnumDocumenter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/langhelpers.py | {
"start": 54143,
"end": 59634
} | class ____(str):
"""A string subclass that can only be hashed on a maximum amount
of unique values.
This is used for warnings so that we can send out parameterized warnings
without the __warningregistry__ of the module, or the non-overridable
"once" registry within warnings.py, overloading memory,... | _hash_limit_string |
python | astropy__astropy | astropy/io/fits/hdu/compressed/_quantization.py | {
"start": 503,
"end": 3988
} | class ____:
"""
Quantization of floating-point data following the FITS standard.
"""
def __init__(
self, *, row: int, dither_method: int, quantize_level: int, bitpix: int
):
super().__init__()
self.row = row
# TODO: pass dither method as a string instead of int?
... | Quantize |
python | pyqtgraph__pyqtgraph | pyqtgraph/dockarea/Dock.py | {
"start": 142,
"end": 8456
} | class ____(QtWidgets.QWidget):
sigStretchChanged = QtCore.Signal()
sigClosed = QtCore.Signal(object)
def __init__(self, name, area=None, size=(10, 10), widget=None, hideTitle=False, autoOrientation=True, label=None, **kargs):
QtWidgets.QWidget.__init__(self)
self.dockdrop = DockDrop(self)
... | Dock |
python | keras-team__keras | keras/src/layers/core/identity.py | {
"start": 197,
"end": 848
} | class ____(Layer):
"""Identity layer.
This layer should be used as a placeholder when no operation is to be
performed. The layer just returns its `inputs` argument as output.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.supports_masking = True
self._bu... | Identity |
python | giampaolo__psutil | psutil/_common.py | {
"start": 6160,
"end": 6589
} | class ____(Error):
"""Exception raised when a process with a certain PID doesn't
or no longer exists.
"""
__module__ = 'psutil'
def __init__(self, pid, name=None, msg=None):
Error.__init__(self)
self.pid = pid
self.name = name
self.msg = msg or "process no longer ex... | NoSuchProcess |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event_param.py | {
"start": 2666,
"end": 3248
} | class ____(TypedDict, total=False):
group_id: str
"""
The group id to attach to this trace to enable filtering and grouping in the
traces dashboard.
"""
metadata: object
"""
The arbitrary metadata to attach to this trace to enable filtering in the traces
dashboard.
"""
work... | SessionTracingTracingConfiguration |
python | kamyu104__LeetCode-Solutions | Python/maximum-profitable-triplets-with-increasing-prices-i.py | {
"start": 6724,
"end": 9238
} | class ____(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
# Range Maximum Query
class SegmentTree(object):
def __init__(self, N,
... | Solution5 |
python | apache__thrift | test/py/TestSocket.py | {
"start": 915,
"end": 2590
} | class ____(unittest.TestCase):
def setUp(self):
for i in range(50):
try:
# find a port we can use
self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = random.randint(10000, 30000)
self.listen_sock.bind(('... | TimeoutTest |
python | pytorch__pytorch | torch/utils/data/datapipes/datapipe.py | {
"start": 10223,
"end": 15435
} | class ____(Dataset[_T_co], metaclass=_DataPipeMeta):
r"""
Map-style DataPipe.
All datasets that represent a map from keys to data samples should subclass this.
Subclasses should overwrite :meth:`__getitem__`, supporting fetching a
data sample for a given, unique key. Subclasses can also optionally ... | MapDataPipe |
python | modin-project__modin | modin/experimental/core/io/glob/glob_dispatcher.py | {
"start": 1173,
"end": 6302
} | class ____(FileDispatcher):
"""Class implements reading/writing different formats, parallelizing by the number of files."""
@classmethod
def _read(cls, **kwargs):
"""
Read data from `filepath_or_buffer` according to `kwargs` parameters.
Parameters
----------
filepat... | ExperimentalGlobDispatcher |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 96508,
"end": 97477
} | class ____(MeanMetricWrapper):
"""Computes the squared hinge metric between `y_true` and `y_pred`.
`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type ... | SquaredHinge |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 300432,
"end": 303753
} | class ____(TypedDict, total=False):
"""
:class:`altair.ViewConfig` ``TypedDict`` wrapper.
Parameters
----------
clip
Whether the view should be clipped.
continuousHeight
The default height when the plot has a continuous y-field for x or latitude, or has
arc marks.
... | ViewConfigKwds |
python | pandas-dev__pandas | pandas/util/version/__init__.py | {
"start": 3296,
"end": 5691
} | class ____:
_key: tuple[Any, ...]
def __hash__(self) -> int:
return hash(self._key)
# Please keep the duplicated `isinstance` check
# in the six comparisons hereunder
# unless you find a way to avoid adding overhead function calls.
def __lt__(self, other: _BaseVersion) -> bool:
... | _BaseVersion |
python | getsentry__sentry | src/sentry/migrations/0939_rm_eventattachment_fileid_part2.py | {
"start": 239,
"end": 1537
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graphsearch/cycle_undirected_graph/python/cycle_undirected_graph.py | {
"start": 0,
"end": 1291
} | class ____:
def __init__(self):
self.neighbors = {}
def add_vertex(self, v):
if v not in self.neighbors:
self.neighbors[v] = []
def add_edge(self, u, v):
self.neighbors[u].append(v)
# if u == v, do not connect u to itself twice
if u != v:
se... | graph |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 9786,
"end": 9965
} | class ____(Where):
"""Not equal comparison"""
key: str
value: Any
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$ne": self.value}}
@dataclass
| Ne |
python | getsentry__sentry | src/sentry/analytics/events/inapp_request.py | {
"start": 278,
"end": 411
} | class ____(InAppRequestSentEvent, abc.ABC):
invited_member_id: int
@analytics.eventclass("invite_request.sent")
| InviteOrJoinRequest |
python | huggingface__transformers | tests/models/udop/test_modeling_udop.py | {
"start": 15162,
"end": 19570
} | class ____:
def __init__(
self,
parent,
vocab_size=99,
batch_size=13,
seq_length=7,
# For common tests
is_training=False,
use_attention_mask=True,
hidden_size=32,
num_hidden_layers=2,
decoder_layers=2,
num_attention_head... | UdopEncoderOnlyModelTester |
python | doocs__leetcode | solution/0800-0899/0891.Sum of Subsequence Widths/Solution.py | {
"start": 0,
"end": 279
} | class ____:
def sumSubseqWidths(self, nums: List[int]) -> int:
mod = 10**9 + 7
nums.sort()
ans, p = 0, 1
for i, v in enumerate(nums):
ans = (ans + (v - nums[-i - 1]) * p) % mod
p = (p << 1) % mod
return ans
| Solution |
python | OmkarPathak__pygorithm | tests/test_pathing.py | {
"start": 1612,
"end": 1820
} | class ____(SimplePathfindingTestCaseTimed):
def find_path(self, my_graph, v1, v2):
my_pathfinder = dijkstra.Dijkstra()
return my_pathfinder.find_path(my_graph, (0, 0), (3, 0))
| TestDijkstraTimed |
python | PrefectHQ__prefect | src/prefect/_internal/schemas/fields.py | {
"start": 91,
"end": 465
} | class ____(BaseModel):
id: Optional[UUID] = Field(
default=None, description="The id of the creator of the object."
)
type: Optional[str] = Field(
default=None, description="The type of the creator of the object."
)
display_value: Optional[str] = Field(
default=None, descript... | CreatedBy |
python | getsentry__sentry | tests/sentry/api/test_authentication.py | {
"start": 31439,
"end": 35303
} | class ____(TestCase):
def test_system_tokens(self) -> None:
sys_token = SystemToken()
auth_token = AuthenticatedToken.from_token(sys_token)
assert auth_token is not None
assert auth_token.entity_id is None
assert auth_token.user_id is None
assert is_system_auth(sys_t... | TestAuthTokens |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_ops.py | {
"start": 17510,
"end": 26872
} | class ____(TestCase):
__test__ = False
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.__test__ = True
@property
def world_size(self) -> int:
return OP_DB_WORLD_SIZE
def run_opinfo_test(
self, dtype, op, requires_grad=True, sample_inpu... | TestDTensorOps |
python | django__django | tests/auth_tests/models/with_last_login_attr.py | {
"start": 61,
"end": 139
} | class ____(AbstractBaseUser):
last_login = None
| UserWithDisabledLastLoginField |
python | jina-ai__jina | jina/jaml/parsers/deployment/legacy.py | {
"start": 323,
"end": 1922
} | class ____(BaseLegacyParser):
"""Legacy parser for gateway."""
def parse(
self,
cls: Type['Deployment'],
data: Dict,
runtime_args: Optional[Dict[str, Any]] = None,
) -> 'Deployment':
"""
:param cls: target class type to parse into, must be a :class:`JAMLCompa... | DeploymentLegacyParser |
python | python__mypy | mypy/nodes.py | {
"start": 74463,
"end": 74999
} | class ____(Expression):
"""Unary operation"""
__slots__ = ("op", "expr", "method_type")
__match_args__ = ("op", "expr")
op: str # TODO: Enum?
expr: Expression
# Inferred operator method type
method_type: mypy.types.Type | None
def __init__(self, op: str, expr: Expression) -> None:
... | UnaryExpr |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 235171,
"end": 237821
} | class ____(Response):
"""
Response of tasks.enqueue endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param queued: Number of tasks queued (0 or 1)
:type queued: int
"""
_service = "t... | EnqueueResponse |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 645789,
"end": 646450
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("TeamDiscussionCommentEdge"), graphql_name="edges"
)
nodes... | TeamDiscussionCommentConnection |
python | ansible__ansible | lib/ansible/module_utils/errors.py | {
"start": 2734,
"end": 2820
} | class ____(AnsibleValidationError):
"""Missing a required parameter"""
| RequiredError |
python | django__django | django/template/context.py | {
"start": 3763,
"end": 5124
} | class ____(BaseContext):
"A stack container for variable context"
def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None):
self.autoescape = autoescape
self.use_l10n = use_l10n
self.use_tz = use_tz
self.template_name = "unknown"
self.render_context = ... | Context |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_flow_warnings.py | {
"start": 701,
"end": 1319
} | class ____(BoringModel):
def training_step(self, batch, batch_idx):
return self.step(batch[0])
def test_no_depre_without_epoch_end(tmp_path):
"""Tests that only training_step can be used."""
model = TestModel()
trainer = Trainer(
default_root_dir=tmp_path,
limit_train_batches=... | TestModel |
python | scikit-learn__scikit-learn | sklearn/base.py | {
"start": 42284,
"end": 46941
} | class ____:
"""Mark estimators that are non-determinstic on 32bit or PowerPC"""
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.non_deterministic = _IS_32BIT or platform.machine().startswith(
("ppc", "powerpc")
)
return tags
def is_classifier(est... | _UnstableArchMixin |
python | encode__django-rest-framework | rest_framework/generics.py | {
"start": 720,
"end": 6678
} | class ____(views.APIView):
"""
Base class for all other generic views.
"""
# You'll need to either set these attributes,
# or override `get_queryset()`/`get_serializer_class()`.
# If you are overriding a view method, it is important that you call
# `get_queryset()` instead of accessing the `... | GenericAPIView |
python | doocs__leetcode | solution/1100-1199/1140.Stone Game II/Solution2.py | {
"start": 0,
"end": 403
} | class ____:
def stoneGameII(self, piles: List[int]) -> int:
@cache
def dfs(i: int, m: int = 1) -> int:
if i >= len(piles):
return 0
t = inf
for x in range(1, m << 1 | 1):
t = min(t, dfs(i + x, max(m, x)))
return s[-1] - ... | Solution |
python | realpython__materials | python-self-type/accounts_typevar.py | {
"start": 806,
"end": 1843
} | class ____(BankAccount):
interest_rate: float
@classmethod
def from_application(
cls: type[TBankAccount], deposit: float = 0, interest_rate: float = 1
) -> TBankAccount:
# Generate a random seven-digit bank account number
account_number = random.randint(1000000, 9999999)
... | SavingsAccount |
python | fastai__fastai | fastai/callback/comet.py | {
"start": 434,
"end": 3392
} | class ____(Callback):
"Log losses, metrics, model weights, model architecture summary to neptune"
order = Recorder.order + 1
def __init__(self, project_name, log_model_weights=True):
self.log_model_weights = log_model_weights
self.keep_experiment_running = keep_experiment_running
se... | CometCallback |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/reaching_definitions_test.py | {
"start": 1278,
"end": 3059
} | class ____(test.TestCase):
def _parse_and_analyze(self, test_fn):
# TODO(mdan): Use a custom FunctionTransformer here.
node, source = parser.parse_entity(test_fn, future_features=())
entity_info = transformer.EntityInfo(
name=test_fn.__name__,
source_code=source,
source_file=None,... | ReachingDefinitionsAnalyzerTestBase |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/pooling.py | {
"start": 19650,
"end": 23904
} | class ____(Pooling2D):
"""Average pooling operation for spatial data.
Downsamples the input along its spatial dimensions (height and width)
by taking the average value over an input window
(of size defined by `pool_size`) for each channel of the input.
The window is shifted by `strides` along each dimension.... | AveragePooling2D |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/input.py | {
"start": 13618,
"end": 16162
} | class ____(NamedTuple):
"""Defines an input mapping for a graph.
Args:
graph_input_name (str): Name of the input in the graph being mapped from.
mapped_node_name (str): Named of the node (op/graph) that the input is being mapped to.
mapped_node_input_name (str): Name of the input in the... | InputMapping |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_reshape_op_test.py | {
"start": 15279,
"end": 18091
} | class ____(test.TestCase, parameterized.TestCase):
"""Tests for reshaping 0-sized SparseTensors, compared w/ dense tensors."""
def _MakeAndReshapeTensor(self, tensor_class, original_shape, target_shape):
if tensor_class == "sparse":
ind = np.zeros([0, len(original_shape)]).astype(np.int64)
val = np... | EmptySparseTensorReshapeTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC201_numpy.py | {
"start": 346,
"end": 1001
} | class ____:
# OK
def foo(self) -> str:
"""
Do something
Parameters
----------
num : int
A number
Returns
-------
str
A string
"""
return 'test'
# DOC201
def bar(self) -> str:
"""
... | Bar |
python | pypa__warehouse | tests/unit/accounts/test_forms.py | {
"start": 33186,
"end": 36571
} | class ____:
def test_validate(self):
form = forms.ResetPasswordForm(
formdata=MultiDict(
{
"new_password": "MyStr0ng!shPassword",
"password_confirm": "MyStr0ng!shPassword",
"username": "username",
"fu... | TestResetPasswordForm |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 87161,
"end": 87885
} | class ____:
def test_uri(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "ian_uri.pem"),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(
x509.IssuerAlternativeName
)
assert list(ext.value) ... | TestRSAIssuerAlternativeNameExtension |
python | django__django | tests/queries/tests.py | {
"start": 79181,
"end": 80446
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.n1 = Note.objects.create(note="n1", misc="foo", id=1)
cls.e1 = ExtraInfo.objects.create(info="e1", note=cls.n1)
def test_ticket7872(self):
# Another variation on the disjunctive filtering theme.
# For the purpos... | DisjunctiveFilterTests |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session.py | {
"start": 25878,
"end": 27948
} | class ____(SessionCreator):
"""Creates a tf.compat.v1.Session for a chief."""
def __init__(self,
scaffold=None,
master='',
config=None,
checkpoint_dir=None,
checkpoint_filename_with_path=None):
"""Initializes a chief session creator.
... | ChiefSessionCreator |
python | doocs__leetcode | solution/0500-0599/0545.Boundary of Binary Tree/Solution.py | {
"start": 192,
"end": 1436
} | class ____:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
def dfs(nums: List[int], root: Optional[TreeNode], i: int):
if root is None:
return
if i == 0:
if root.left != root.right:
nums.append(root.val)
... | Solution |
python | jazzband__pip-tools | piptools/repositories/pypi.py | {
"start": 1649,
"end": 1731
} | class ____(_t.NamedTuple):
stream: _t.BinaryIO
size: float | None
| FileStream |
python | gawel__pyquery | tests/test_pyquery.py | {
"start": 31485,
"end": 32070
} | class ____(TestCase):
def setUp(self):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
time.sleep(2)
return [b'foobar\n']
self.s = http.StopableWSGIServer.create(app)
self.s.wait()
self.application_url ... | TestWebScrappingTimeouts |
python | mkdocs__mkdocs | mkdocs/contrib/search/search_index.py | {
"start": 446,
"end": 5251
} | class ____:
"""
Search index is a collection of pages and sections (heading
tags and their following content are sections).
"""
def __init__(self, **config) -> None:
self._entries: list[dict] = []
self.config = config
def _find_toc_by_id(self, toc, id_: str | None) -> AnchorLin... | SearchIndex |
python | astropy__astropy | astropy/io/fits/tests/test_convenience.py | {
"start": 532,
"end": 18600
} | class ____(FitsTestCase):
def test_resource_warning(self):
warnings.simplefilter("always", ResourceWarning)
_ = fits.getdata(self.data("test0.fits"))
_ = fits.getheader(self.data("test0.fits"))
def test_fileobj_not_closed(self):
"""
Tests that file-like objects are not c... | TestConvenience |
python | fluentpython__example-code-2e | 14-inheritance/uppermixin.py | {
"start": 2806,
"end": 2878
} | class ____(UpperCaseMixin, collections.UserDict): # <1>
pass
| UpperDict |
python | jazzband__django-oauth-toolkit | oauth2_provider/oauth2_backends.py | {
"start": 376,
"end": 9368
} | class ____:
"""
Wrapper for oauth Server providing django-specific interfaces.
Meant for things like extracting request data and converting
everything to formats more palatable for oauthlib's Server.
"""
def __init__(self, server=None):
"""
:params server: An instance of oauthl... | OAuthLibCore |
python | sympy__sympy | sympy/core/containers.py | {
"start": 606,
"end": 6060
} | class ____(Basic):
"""
Wrapper around the builtin tuple object.
Explanation
===========
The Tuple is a subclass of Basic, so that it works well in the
SymPy framework. The wrapped tuple is available as self.args, but
you can also access elements or slices with [:] syntax.
Parameters
... | Tuple |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py | {
"start": 7158,
"end": 7493
} | class ____(SubsetAutomationCondition):
@property
def name(self) -> str:
return "newly_requested"
def compute_subset(self, context: AutomationContext) -> EntitySubset:
return context.get_previous_requested_subset(context.key) or context.get_empty_subset()
@whitelist_for_serdes
@record
| NewlyRequestedCondition |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/react/base.py | {
"start": 1240,
"end": 2839
} | class ____(Agent):
"""Agent for the ReAct chain."""
output_parser: AgentOutputParser = Field(default_factory=ReActOutputParser)
@classmethod
@override
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
return ReActOutputParser()
@property
def _agent_type(self... | ReActDocstoreAgent |
python | PrefectHQ__prefect | tests/custom_types/test_self_validating_types.py | {
"start": 273,
"end": 1053
} | class ____:
@pytest.mark.parametrize(
"integer_type,valid_value",
[
(PositiveInteger, 1),
(NonNegativeInteger, 0),
],
)
def test_valid_integer(self, integer_type, valid_value):
class Model(BaseModel):
value: integer_type
m = Model(... | TestConstrainedIntegers |
python | kamyu104__LeetCode-Solutions | Python/maximum-elegance-of-a-k-length-subsequence.py | {
"start": 1220,
"end": 3321
} | class ____(object):
def findMaximumElegance(self, items, k):
"""
:type items: List[List[int]]
:type k: int
:rtype: int
"""
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
... | Solution2 |
python | doocs__leetcode | solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution2.py | {
"start": 0,
"end": 340
} | class ____:
def findScore(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * (n + 2)
idx = sorted(range(n), key=lambda i: (nums[i], i))
ans = 0
for i in idx:
if not vis[i + 1]:
ans += nums[i]
vis[i] = vis[i + 2] = True
... | Solution |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 10634,
"end": 11262
} | class ____(FloatType):
"""16-bit floating point type.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
.. warning::
Regular computing platforms do not natively support `Float16` operations,
... | Float16 |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 11429,
"end": 11519
} | class ____(Type):
name = "string"
types: t.ClassVar[t.List[type]] = [str]
| StringType |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_flower.py | {
"start": 18191,
"end": 22514
} | class ____:
"""Tests flower service."""
@pytest.mark.parametrize(
("executor", "flower_enabled", "created"),
[
("CeleryExecutor", False, False),
("CeleryKubernetesExecutor", False, False),
("KubernetesExecutor", False, False),
("CeleryExecutor", T... | TestFlowerService |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/fake_glue.py | {
"start": 344,
"end": 7242
} | class ____:
def __init__(
self,
aws_endpoint_url: str, # usually received from moto
s3_client: boto3.client, # pyright: ignore (reportGeneralTypeIssues)
glue_client: boto3.client, # pyright: ignore (reportGeneralTypeIssues)
pipes_messages_backend: Literal["s3", "cloudwatch... | LocalGlueMockClient |
python | pola-rs__polars | py-polars/tests/unit/io/test_iceberg.py | {
"start": 2170,
"end": 4721
} | class ____:
"""Test coverage for `iceberg` scan ops."""
def test_scan_iceberg_plain(self, iceberg_path: str) -> None:
q = pl.scan_iceberg(iceberg_path)
assert len(q.collect()) == 3
assert q.collect_schema() == {
"id": pl.Int32,
"str": pl.String,
"ts":... | TestIcebergScanIO |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 222780,
"end": 223059
} | class ____(VegaLiteSchema):
"""ConditionalAxisPropertynumbernull schema wrapper."""
_schema = {"$ref": "#/definitions/ConditionalAxisProperty<(number|null)>"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ConditionalAxisPropertynumbernull |
python | getsentry__sentry | src/sentry/issues/endpoints/group_events.py | {
"start": 1838,
"end": 1938
} | class ____(Exception):
pass
@extend_schema(tags=["Events"])
@region_silo_endpoint
| GroupEventsError |
python | redis__redis-py | tests/test_maint_notifications.py | {
"start": 16067,
"end": 18533
} | class ____:
"""Test the MaintNotificationsConfig class."""
def test_init_defaults(self):
"""Test MaintNotificationsConfig initialization with defaults."""
config = MaintNotificationsConfig()
assert config.enabled == "auto"
assert config.proactive_reconnect is True
assert... | TestMaintNotificationsConfig |
python | openai__openai-python | src/openai/resources/fine_tuning/checkpoints/checkpoints.py | {
"start": 2674,
"end": 2980
} | class ____:
def __init__(self, checkpoints: AsyncCheckpoints) -> None:
self._checkpoints = checkpoints
@cached_property
def permissions(self) -> AsyncPermissionsWithRawResponse:
return AsyncPermissionsWithRawResponse(self._checkpoints.permissions)
| AsyncCheckpointsWithRawResponse |
python | django__django | tests/admin_views/admin.py | {
"start": 27419,
"end": 27645
} | class ____(admin.ModelAdmin):
form = FormWithoutHiddenField
fieldsets = (
(
None,
{
"fields": (("first", "second"),),
},
),
)
| EmptyModelVisibleAdmin |
python | huggingface__transformers | tests/models/eomt/test_modeling_eomt.py | {
"start": 1259,
"end": 3741
} | class ____:
def __init__(
self,
parent,
batch_size=2,
is_training=True,
image_size=40,
patch_size=2,
num_queries=5,
num_register_tokens=19,
num_labels=4,
hidden_size=8,
num_attention_heads=2,
num_hidden_layers=2,
):
... | EomtForUniversalSegmentationTester |
python | huggingface__transformers | src/transformers/models/resnet/modeling_resnet.py | {
"start": 7442,
"end": 9036
} | class ____(nn.Module):
def __init__(self, config: ResNetConfig):
super().__init__()
self.stages = nn.ModuleList([])
# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
self.stages.append(
ResNetStage(
... | ResNetEncoder |
python | pytorch__pytorch | torch/_inductor/codegen/mps.py | {
"start": 40276,
"end": 41827
} | class ____(SIMDScheduling):
kernel_type = MetalKernel # type: ignore[assignment]
def __init__(self, scheduler: Optional[Scheduler]) -> None:
super().__init__(scheduler)
wrapper = V.graph.wrapper_code
if wrapper is not None:
if not V.graph.cpp_wrapper:
wrappe... | MetalScheduling |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/failing_build/package.py | {
"start": 217,
"end": 597
} | class ____(Package):
"""This package has a trivial install method that fails."""
homepage = "http://www.example.com/trivial_install"
url = "http://www.unit-test-should-replace-this-url/trivial_install-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
def install(self, spec, prefi... | FailingBuild |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/recompose.py | {
"start": 577,
"end": 793
} | class ____(Horizontal):
progress = reactive(0, recompose=True)
def compose(self) -> ComposeResult:
bar = ProgressBar(100, show_eta=False)
bar.progress = self.progress
yield bar
| Progress |
python | ray-project__ray | python/ray/data/datasource/datasink.py | {
"start": 1209,
"end": 3829
} | class ____(Generic[WriteReturnType]):
"""Interface for defining write-related logic.
If you want to write data to something that isn't built-in, subclass this class
and call :meth:`~ray.data.Dataset.write_datasink`.
"""
def on_write_start(self) -> None:
"""Callback for when a write job sta... | Datasink |
python | gevent__gevent | src/gevent/win32util.py | {
"start": 1292,
"end": 3637
} | class ____(object):
"""
Formatter for Windows error messages.
@ivar winError: A callable which takes one integer error number argument
and returns an L{exceptions.WindowsError} instance for that error (like
L{ctypes.WinError}).
@ivar formatMessage: A callable which takes one integer er... | _ErrorFormatter |
python | jina-ai__jina | jina/clients/base/helper.py | {
"start": 4954,
"end": 8928
} | class ____(AioHttpClientlet):
"""HTTP Client to be used with the streamer"""
UPDATE_EVENT_PREFIX = 14 # the update event has the following format: "event: update: {document_json}"
async def send_message(self, url, request: 'Request'):
"""Sends a POST request to the server
:param url: the... | HTTPClientlet |
python | ray-project__ray | rllib/policy/dynamic_tf_policy.py | {
"start": 1435,
"end": 39922
} | class ____(TFPolicy):
"""A TFPolicy that auto-defines placeholders dynamically at runtime.
Do not sub-class this class directly (neither should you sub-class
TFPolicy), but rather use rllib.policy.tf_policy_template.build_tf_policy
to generate your custom tf (graph-mode or eager) Policy classes.
""... | DynamicTFPolicy |
python | apache__airflow | airflow-core/src/airflow/dag_processing/manager.py | {
"start": 3240,
"end": 3382
} | class ____(NamedTuple):
"""Information on processing progress."""
done: bool
all_files_processed: bool
@attrs.define
| DagParsingStat |
python | django__django | django/tasks/backends/immediate.py | {
"start": 418,
"end": 3377
} | class ____(BaseTaskBackend):
supports_async_task = True
supports_priority = True
def __init__(self, alias, params):
super().__init__(alias, params)
self.worker_id = get_random_string(32)
def _execute_task(self, task_result):
"""
Execute the Task for the given TaskResult... | ImmediateBackend |
python | ray-project__ray | python/ray/dashboard/modules/log/log_agent.py | {
"start": 8096,
"end": 8610
} | class ____(dashboard_utils.DashboardAgentModule):
def __init__(self, dashboard_agent):
super().__init__(dashboard_agent)
log_utils.register_mimetypes()
routes.static("/logs", self._dashboard_agent.log_dir, show_index=True)
async def run(self, server):
pass
@staticmethod
... | LogAgent |
python | django__django | django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py | {
"start": 263,
"end": 4494
} | class ____(BaseCommand):
help = "Deletes stale content types in the database."
def add_arguments(self, parser):
parser.add_argument(
"--noinput",
"--no-input",
action="store_false",
dest="interactive",
help="Tells Django to NOT prompt the user... | Command |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 24383,
"end": 26884
} | class ____(MobileBertPreTrainedModel):
"""
https://huggingface.co/papers/2004.02984
"""
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(conf... | MobileBertModel |
python | kamyu104__LeetCode-Solutions | Python/find-the-peaks.py | {
"start": 37,
"end": 282
} | class ____(object):
def findPeaks(self, mountain):
"""
:type mountain: List[int]
:rtype: List[int]
"""
return [i for i in xrange(1, len(mountain)-1) if mountain[i-1] < mountain[i] > mountain[i+1]]
| Solution |
python | ray-project__ray | python/ray/serve/tests/unit/test_task_consumer.py | {
"start": 1899,
"end": 3618
} | class ____:
"""Test the task_handler decorator."""
def _create_and_test_handler(self, decorator_args=None, expected_name=None):
"""Helper to create and test a task handler."""
mock = MagicMock()
if decorator_args is None:
@task_handler
def test_handler():
... | TestTaskHandlerDecorator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.