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 | mkdocs__mkdocs | mkdocs/tests/config/config_options_legacy_tests.py | {
"start": 38766,
"end": 39007
} | class ____(TestCase):
def test_defined(self):
class Schema:
option = c.Private()
with self.expect_error(option="For internal use only."):
self.get_config(Schema, {'option': 'somevalue'})
| PrivateTest |
python | allegroai__clearml | clearml/automation/optimization.py | {
"start": 46087,
"end": 49447
} | class ____(SearchStrategy):
"""
Grid search strategy controller. Full grid sampling of every hyperparameter combination.
"""
def __init__(
self,
base_task_id: str,
hyper_parameters: Sequence[Parameter],
objective_metric: Objective,
execution_queue: str,
n... | GridSearch |
python | getsentry__sentry | src/sentry/hybridcloud/models/outbox.py | {
"start": 1774,
"end": 16531
} | class ____(Model):
sharding_columns: Iterable[str]
coalesced_columns: Iterable[str]
def should_skip_shard(self) -> bool:
if self.shard_scope == OutboxScope.ORGANIZATION_SCOPE:
return self.shard_identifier in options.get(
"hybrid_cloud.authentication.disabled_organization... | OutboxBase |
python | marshmallow-code__marshmallow | tests/test_deserialization.py | {
"start": 60254,
"end": 80619
} | class ____:
def test_deserialize_to_dict(self):
user_dict = {"name": "Monty", "age": "42.3"}
result = SimpleUserSchema().load(user_dict)
assert result["name"] == "Monty"
assert math.isclose(result["age"], 42.3)
def test_deserialize_with_missing_values(self):
user_dict = ... | TestSchemaDeserialization |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py | {
"start": 26032,
"end": 26898
} | class ____(nn.Module):
def __init__(self, config: Phi4MultimodalAudioConfig):
super().__init__()
self.layer_norm = nn.LayerNorm(config.hidden_size)
self.act_fn = ACT2FN[config.activation]
self.gate_up_proj = nn.Linear(config.hidden_size, config.intermediate_size * 2)
self.dow... | Phi4MultimodalAudioMLP |
python | sphinx-doc__sphinx | sphinx/domains/citation.py | {
"start": 726,
"end": 4156
} | class ____(Domain):
"""Domain for citations."""
name = 'citation'
label = 'citation'
dangling_warnings = {
'ref': 'citation not found: %(target)s',
}
@property
def citations(self) -> dict[str, tuple[str, str, int]]:
return self.data.setdefault('citations', {})
@proper... | CitationDomain |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/random_poisson_test.py | {
"start": 1411,
"end": 7089
} | class ____(test.TestCase):
"""This is a large test due to the moments computation taking some time."""
def _Sampler(self, num, lam, dtype, use_gpu, seed=None):
def func():
with self.session(use_gpu=use_gpu, graph=ops.Graph()) as sess:
rng = random_ops.random_poisson(lam, [num], dtype=dtype, seed... | RandomPoissonTest |
python | tensorflow__tensorflow | tensorflow/python/saved_model/nested_structure_coder.py | {
"start": 3687,
"end": 4778
} | class ____:
"""Codec for lists."""
def can_encode(self, pyobj):
return isinstance(pyobj, list)
def do_encode(self, list_value, encode_fn):
encoded_list = struct_pb2.StructuredValue()
encoded_list.list_value.CopyFrom(struct_pb2.ListValue())
for element in list_value:
encoded_list.list_value... | _ListCodec |
python | django__django | django/db/models/functions/text.py | {
"start": 5769,
"end": 6122
} | class ____(Transform):
"""Return the number of characters in the expression."""
function = "LENGTH"
lookup_name = "length"
output_field = IntegerField()
def as_mysql(self, compiler, connection, **extra_context):
return super().as_sql(
compiler, connection, function="CHAR_LENGTH... | Length |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_not_null_app/migrations/0003_delete.py | {
"start": 190,
"end": 525
} | class ____(CheckedMigration):
dependencies = [
("good_flow_delete_field_pending_with_not_null_app", "0002_remove_not_null_and_pending"),
]
operations = [
SafeRemoveField(
model_name="testtable",
name="field",
deletion_action=DeletionAction.DELETE,
... | Migration |
python | great-expectations__great_expectations | great_expectations/core/util.py | {
"start": 5907,
"end": 8478
} | class ____:
"""
Parses an Azure Blob Storage URL into its separate components.
Formats:
WASBS (for Spark): "wasbs://<CONTAINER>@<ACCOUNT_NAME>.blob.core.windows.net/<BLOB>"
HTTP(S) (for Pandas) "<ACCOUNT_NAME>.blob.core.windows.net/<CONTAINER>/<BLOB>"
Reference: WASBS -- Windows Azu... | AzureUrl |
python | spack__spack | lib/spack/spack/variant.py | {
"start": 952,
"end": 1343
} | class ____(enum.IntEnum):
"""Enum representing the three concrete variant types."""
BOOL = 1
SINGLE = 2
MULTI = 3
@property
def string(self) -> str:
"""Convert the variant type to a string."""
if self == VariantType.BOOL:
return "bool"
elif self == VariantTy... | VariantType |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/request_validator.py | {
"start": 144,
"end": 28848
} | class ____:
def client_authentication_required(self, request, *args, **kwargs):
"""Determine if client authentication is required for current request.
According to the rfc6749, client authentication is required in the following cases:
- Resource Owner Password Credentials Grant, when C... | RequestValidator |
python | fluentpython__example-code | 13-op-overloading/vector_v7.py | {
"start": 6246,
"end": 9539
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-kyriba/source_kyriba/source.py | {
"start": 7434,
"end": 8539
} | class ____(AccountSubStream):
def stream_slices(
self, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None, **kwargs
) -> Iterable[Optional[Mapping[str, Any]]]:
slices = []
account_uuids = self.get_account_uuids()
# bank balances require the date to be specifie... | BankBalancesStream |
python | ethereum__web3.py | web3/_utils/module_testing/go_ethereum_admin_module.py | {
"start": 1958,
"end": 3435
} | class ____:
@pytest.mark.asyncio
async def test_async_datadir(self, async_w3: "AsyncWeb3[Any]") -> None:
datadir = await async_w3.geth.admin.datadir()
assert isinstance(datadir, str)
@pytest.mark.asyncio
async def test_async_node_info(self, async_w3: "AsyncWeb3[Any]") -> None:
n... | GoEthereumAsyncAdminModuleTest |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 42274,
"end": 45895
} | class ____:
"""Hackly distilling info from reference ops decorated with elementwise type promotion rule.
The goal is to retrieve the decorator
```python
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=type_promotion_kind,
)
... | ElementwiseTypePromotionRuleSetGenerator |
python | walkccc__LeetCode | solutions/2548. Maximum Price to Fill a Bag/2548.py | {
"start": 0,
"end": 370
} | class ____:
def maxPrice(self, items: list[list[int]], capacity: int) -> float:
ans = 0
# Sort items based on price//weight.
for price, weight in sorted(items, key=lambda x: -x[0] / x[1]):
# The bag is filled.
if capacity <= weight:
return ans + price * capacity / weight
ans += ... | Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/javascript.py | {
"start": 17034,
"end": 21444
} | class ____(RegexLexer):
"""
For `TypeScript <http://typescriptlang.org/>`_ source code.
.. versionadded:: 1.6
"""
name = 'TypeScript'
aliases = ['ts', 'typescript']
filenames = ['*.ts', '*.tsx']
mimetypes = ['text/x-typescript']
flags = re.DOTALL | re.MULTILINE
tokens = {
... | TypeScriptLexer |
python | ansible__ansible | test/lib/ansible_test/_internal/util_common.py | {
"start": 4126,
"end": 17814
} | class ____:
"""Configuration common to all commands."""
def __init__(self, args: t.Any, command: str) -> None:
self.command = command
self.interactive = False
self.check_layout = True
self.success: t.Optional[bool] = None
self.color: bool = args.color
self.expla... | CommonConfig |
python | huggingface__transformers | examples/pytorch/object-detection/run_object_detection.py | {
"start": 2065,
"end": 8970
} | class ____:
logits: torch.Tensor
pred_boxes: torch.Tensor
def format_image_annotations_as_coco(
image_id: str, categories: list[int], areas: list[float], bboxes: list[tuple[float]]
) -> dict:
"""Format one set of image annotations to the COCO format
Args:
image_id (str): image id. e.g. "0... | ModelOutput |
python | huggingface__transformers | src/transformers/generation/candidate_generator.py | {
"start": 1239,
"end": 3334
} | class ____:
"""Abstract base class for all candidate generators that can be applied during assisted generation."""
def get_candidates(self, input_ids: torch.LongTensor) -> tuple[torch.LongTensor, torch.FloatTensor | None]:
"""
Fetches the candidates to be tried for the current input.
A... | CandidateGenerator |
python | conda__conda | conda/core/package_cache_data.py | {
"start": 21496,
"end": 23293
} | class ____:
# this is a class to manage urls.txt
# it should basically be thought of as a sequence
# in this class I'm breaking the rule that all disk access goes through conda.gateways
def __init__(self, pkgs_dir):
self.pkgs_dir = pkgs_dir
self.urls_txt_path = urls_txt_path = join(pkgs... | UrlsData |
python | ray-project__ray | rllib/utils/exploration/epsilon_greedy.py | {
"start": 789,
"end": 9429
} | class ____(Exploration):
"""Epsilon-greedy Exploration class that produces exploration actions.
When given a Model's output and a current epsilon value (based on some
Schedule), it produces a random action (if rand(1) < eps) or
uses the model-computed one (if rand(1) >= eps).
"""
def __init__(... | EpsilonGreedy |
python | wandb__wandb | wandb/automations/_generated/delete_automation.py | {
"start": 153,
"end": 225
} | class ____(GQLResult):
result: DeleteAutomationResult
| DeleteAutomation |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_leap_year.py | {
"start": 1629,
"end": 3865
} | class ____(ColumnMapExpectation):
"""Expect column values to be a valid leap year."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_leap_year": [
... | ExpectColumnValuesToBeValidLeapYear |
python | google__python-fire | fire/console/platforms.py | {
"start": 1595,
"end": 4934
} | class ____(object):
"""An enum representing the operating system you are running on."""
class _OS(object):
"""A single operating system."""
# pylint: disable=redefined-builtin
def __init__(self, id, name, file_name):
self.id = id
self.name = name
self.file_name = file_name
def _... | OperatingSystem |
python | boto__boto3 | boto3/resources/model.py | {
"start": 2415,
"end": 3108
} | class ____:
"""
An item which has parameters exposed via the ``params`` property.
A request has an operation and parameters, while a waiter has
a name, a low-level waiter name and parameters.
:type definition: dict
:param definition: The JSON definition
"""
def __init__(self, definitio... | DefinitionWithParams |
python | getsentry__sentry | src/sentry/migrations/0913_split_discover_dataset_dashboards_self_hosted.py | {
"start": 1544,
"end": 2481
} | class ____(Enum):
"""
Ambiguous queries that haven't been or couldn't be categorized into a
specific dataset.
"""
UNKNOWN = 0
"""
Dataset inferred by either running the query or using heuristics.
"""
INFERRED = 1
"""
Canonical dataset, user explicitly selected it.
"""
... | DatasetSourcesTypes |
python | getsentry__sentry | src/sentry/models/groupopenperiodactivity.py | {
"start": 256,
"end": 575
} | class ____(IntEnum):
OPENED = 1
STATUS_CHANGE = 2
CLOSED = 3
def to_str(self) -> str:
"""
Return the string representation of the activity type.
"""
return self.name.lower()
def generate_random_uuid() -> UUID:
return uuid4()
@region_silo_model
| OpenPeriodActivityType |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 30750,
"end": 31551
} | class ____(Instruction):
def __init__(self, parent, typ, name='', cleanup=False):
super(LandingPadInstr, self).__init__(parent, typ, "landingpad", [],
name=name)
self.cleanup = cleanup
self.clauses = []
def add_clause(self, clause):
... | LandingPadInstr |
python | mlflow__mlflow | mlflow/utils/file_utils.py | {
"start": 31634,
"end": 32672
} | class ____:
"""
Exclusive file lock (only works on Unix system)
"""
def __init__(self, path: str):
if os.name == "nt":
raise MlflowException("ExclusiveFileLock class does not support Windows system.")
self.path = path
self.fd = None
def __enter__(self) -> None:
... | ExclusiveFileLock |
python | numba__llvmlite | llvmlite/tests/test_binding.py | {
"start": 63205,
"end": 72996
} | class ____(BaseTest):
def test_str(self):
mod = self.module()
glob = mod.get_global_variable("glob")
self.assertEqual(str(glob.global_value_type), "i32")
glob_struct_type = mod.get_struct_type("struct.glob_type")
self.assertEqual(str(glob_struct_type),
... | TestTypeRef |
python | sanic-org__sanic | sanic/models/futures.py | {
"start": 1414,
"end": 1568
} | class ____(NamedTuple):
handler: SignalHandler
event: str
condition: Optional[dict[str, str]]
exclusive: bool
priority: int
| FutureSignal |
python | PyCQA__pylint | tests/functional/u/use/use_implicit_booleaness_not_comparison.py | {
"start": 2902,
"end": 4845
} | class ____:
lst = []
@staticmethod
def test(b=1):
print(b)
return []
if A.lst == []: # [use-implicit-booleaness-not-comparison]
pass
if [] == A.lst: # [use-implicit-booleaness-not-comparison]
pass
if A.test("b") == []: # [use-implicit-booleaness-not-comparison]
pass
d... | A |
python | google__flatbuffers | tests/monster_test_generated.py | {
"start": 16809,
"end": 17709
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 20
# StructOfStructsOfStructs
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# StructOfStructsOfStructs
def A(self, obj):
obj.Init(self._tab.Bytes, self._tab.Pos ... | StructOfStructsOfStructs |
python | tensorflow__tensorflow | tensorflow/lite/python/metrics/metrics_portable.py | {
"start": 1827,
"end": 2048
} | class ____(TFLiteMetrics):
"""Similar to TFLiteMetrics but specialized for converter."""
def __del__(self):
pass
def set_export_required(self):
pass
def export_metrics(self):
pass
| TFLiteConverterMetrics |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/test_imports.py | {
"start": 16725,
"end": 17752
} | class ____ (unittest.TestCase):
if not hasattr(unittest.TestCase, 'assertIsInstance'):
def assertIsInstance(self, value, types):
if not isinstance(value, types):
self.fail("%r is not an instance of %r"%(value, types))
def setUp(self):
root = os.path.join(
... | TestRegression4 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 9263,
"end": 9367
} | class ____(IncrementalShopifyGraphQlBulkStream):
bulk_query: DiscountCode = DiscountCode
| DiscountCodes |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_plugin_details.py | {
"start": 2056,
"end": 2742
} | class ____(ProjectPluginDetailsTestBase):
method = "put"
def test_simple(self) -> None:
with outbox_runner():
self.get_success_response(
self.project.organization.slug,
self.project.slug,
"webhooks",
**{"urls": "http://example.... | UpdateProjectPluginTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 56384,
"end": 57485
} | class ____(Request):
"""
Clear an open Scroll ID
:param scroll_id: Scroll ID as returned by previous events service calls
:type scroll_id: str
"""
_service = "events"
_action = "clear_scroll"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
... | ClearScrollRequest |
python | sqlalchemy__sqlalchemy | test/orm/test_validators.py | {
"start": 551,
"end": 15081
} | class ____(_fixtures.FixtureTest):
def test_scalar(self):
users = self.tables.users
canary = Mock()
class User(ComparableEntity):
@validates("name")
def validate_name(self, key, name):
canary(key, name)
ne_(name, "fred")
... | ValidatorTest |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 74212,
"end": 78130
} | class ____:
def test_isel_siblings(self) -> None:
tree = DataTree.from_dict(
{
"/first": xr.Dataset({"a": ("x", [1, 2])}),
"/second": xr.Dataset({"b": ("x", [1, 2, 3])}),
}
)
expected = DataTree.from_dict(
{
... | TestIndexing |
python | python__mypy | mypy/plugins/attrs.py | {
"start": 39102,
"end": 46406
} | class ____:
"""Helper to add methods to a TypeInfo.
ctx: The ClassDefCtx we are using on which we will add methods.
"""
# TODO: Combine this with the code build_namedtuple_typeinfo to support both.
def __init__(self, ctx: mypy.plugin.ClassDefContext) -> None:
self.ctx = ctx
self.s... | MethodAdder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess10.py | {
"start": 894,
"end": 1126
} | class ____:
@FlagValue
def suppress(self):
return 2
flags = Flags()
def func1(new: Any):
flags.suppress = new
def func2(new: int):
flags.suppress = new
def func3(new: bool):
flags.suppress = new
| Flags |
python | great-expectations__great_expectations | contrib/cli/great_expectations_contrib/package.py | {
"start": 676,
"end": 836
} | class ____(SerializableDictDot):
concept_only: int
experimental: int
beta: int
production: int
total: int
@dataclass
| PackageCompletenessStatus |
python | urllib3__urllib3 | dummyserver/testcase.py | {
"start": 1025,
"end": 5497
} | class ____:
"""
A simple socket-based server is created for this class that is good for
exactly one request.
"""
scheme = "http"
host = "localhost"
server_thread: typing.ClassVar[SocketServerThread]
port: typing.ClassVar[int]
tmpdir: typing.ClassVar[str]
ca_path: typing.ClassV... | SocketDummyServerTestCase |
python | sqlalchemy__sqlalchemy | examples/inheritance/single.py | {
"start": 1211,
"end": 1680
} | class ____(Base):
__tablename__ = "person"
__table__: FromClause
id: Mapped[intpk]
company_id: Mapped[int] = mapped_column(ForeignKey("company.id"))
name: Mapped[str50]
type: Mapped[str50]
company: Mapped[Company] = relationship(back_populates="employees")
__mapper_args__ = {
... | Person |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 24693,
"end": 27138
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that performs top-k, i.e. restricting to the k highest probability elements. Often used
together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].
Args:
top_k (`int`):
The number of highest probability vocabulary tokens ... | TopKLogitsWarper |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-two-arrays.py | {
"start": 1826,
"end": 2448
} | class ____(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort()
res = []
it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if n... | Solution3 |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/pod.py | {
"start": 4305,
"end": 63330
} | class ____(BaseOperator):
"""
Execute a task in a Kubernetes Pod.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:KubernetesPodOperator`
.. note::
If you use `Google Kubernetes Engine <https://cloud.google.com/kubern... | KubernetesPodOperator |
python | gevent__gevent | src/greentest/3.10/test_asyncore.py | {
"start": 25702,
"end": 25927
} | class ____(BaseTestAPI):
if HAS_UNIX_SOCKETS:
family = socket.AF_UNIX
addr = os_helper.TESTFN
def tearDown(self):
os_helper.unlink(self.addr)
BaseTestAPI.tearDown(self)
| TestAPI_UseUnixSockets |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/foundry.py | {
"start": 1862,
"end": 2129
} | class ____(Beta):
@cached_property
@override
def messages(self) -> BetaMessages: # type: ignore[override]
"""Return beta messages resource instance with excluded unsupported endpoints."""
return BetaFoundryMessages(self._client)
| BetaFoundry |
python | huggingface__transformers | tests/models/vipllava/test_modeling_vipllava.py | {
"start": 10928,
"end": 12188
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@slow
@require_bitsandbytes
def test_small_model_integration_test(self):
model_id = "llava-h... | VipLlavaForConditionalGenerationIntegrationTest |
python | joke2k__faker | faker/providers/color/cs_CZ/__init__.py | {
"start": 43,
"end": 449
} | class ____(ColorProvider):
"""Implement color provider for ``cs_CZ`` locale."""
safe_colors = (
"černá",
"kaštanová",
"zelená",
"námořnická",
"olivová",
"fialová",
"zelenomodrá",
"limetková",
"modrá",
"stříbrná",
"šedá",
... | Provider |
python | PrefectHQ__prefect | tests/results/test_flow_results.py | {
"start": 692,
"end": 14033
} | class ____(Serializer):
"""
Custom serializer for test coverage of user-defined serializers
"""
type: str = "int-custom"
def dumps(self, obj: int):
return obj.to_bytes(8, byteorder="little")
def loads(self, blob):
return int.from_bytes(blob, byteorder="little")
async def tes... | MyIntSerializer |
python | pytorch__pytorch | torch/nn/modules/activation.py | {
"start": 25300,
"end": 25933
} | class ____(Module):
r"""Applies the Logsigmoid function element-wise.
.. math::
\text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)
Shape:
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
- Output: :math:`(*)`, same shape as the input.
.. ima... | LogSigmoid |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 118970,
"end": 119462
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
def get(self):
# remote_ip is optional, although it's set by
# both HTTPServer and WSGIAdapter.
# Clobber it to make sure it doesn't break logging.
self.request.remote_ip = None
self... | RequestSummaryTest |
python | pytorch__pytorch | test/distributions/test_distributions.py | {
"start": 185119,
"end": 197192
} | class ____(DistributionsTestCase):
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def test_gamma(self):
num_samples = 100
for alpha in [1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4]:
alphas = torch.tensor(
[alpha] * num_samples, dtype=torch.float, requires_grad=True
... | TestRsample |
python | ansible__ansible | lib/ansible/module_utils/compat/version.py | {
"start": 1399,
"end": 3429
} | class ____:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
seem to be the same for all version numbering classes; and route
rich comparisons to _cmp.
"""
def __init__(self, vstring=None):
if vstring:
... | Version |
python | kubernetes-client__python | kubernetes/client/models/v1_stateful_set_persistent_volume_claim_retention_policy.py | {
"start": 383,
"end": 5817
} | 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... | V1StatefulSetPersistentVolumeClaimRetentionPolicy |
python | pytorch__pytorch | torch/export/graph_signature.py | {
"start": 1587,
"end": 2525
} | class ____:
kind: InputKind
arg: ArgumentSpec
target: Optional[str]
persistent: Optional[bool] = None
def __post_init__(self):
if self.kind == InputKind.BUFFER:
assert self.persistent is not None, (
"Failed to specify persistent flag on BUFFER."
)
... | InputSpec |
python | scikit-learn__scikit-learn | sklearn/externals/_arff.py | {
"start": 15224,
"end": 15791
} | class ____:
def __init__(self, values):
self.values = set(values)
self.zero_value = values[0]
def __call__(self, value):
if value not in self.values:
if value == 0:
# Sparse decode
# See issue #52: nominals should take their first value when
... | NominalConversor |
python | django__django | tests/admin_views/admin.py | {
"start": 30793,
"end": 30879
} | class ____(admin.ModelAdmin):
autocomplete_fields = ["living_country"]
| TravelerAdmin |
python | python-openxml__python-docx | src/docx/types.py | {
"start": 256,
"end": 510
} | class ____(Protocol):
"""An object that provides access to the StoryPart.
This type is for objects that have a story part like document or header as their
root part.
"""
@property
def part(self) -> StoryPart: ...
| ProvidesStoryPart |
python | huggingface__transformers | src/transformers/models/starcoder2/configuration_starcoder2.py | {
"start": 878,
"end": 8144
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Starcoder2Model`]. It is used to instantiate a
Starcoder2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar... | Starcoder2Config |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py | {
"start": 1654,
"end": 1696
} | class ____(Generic[_T1]):
x: _T1
| ParentD |
python | astropy__astropy | astropy/table/tests/test_init_table.py | {
"start": 910,
"end": 2054
} | class ____:
def test_init(self):
"""Test initialisation with lists, tuples, dicts of arrays
rather than Columns [regression test for #2647]"""
x1 = np.arange(10.0)
x2 = np.arange(5.0)
x3 = np.arange(7.0)
col_list = [("x1", x1), ("x2", x2), ("x3", x3)]
tc_list ... | TestTableColumnsInit |
python | ray-project__ray | python/ray/llm/_internal/serve/config_generator/utils/prompt.py | {
"start": 251,
"end": 465
} | class ____(IntPrompt):
@classmethod
def ask(cls, prompt: str, **kwargs):
# Automatically apply bold style to the BoldPrompt
return IntPrompt.ask(f"[bold]{prompt}[/bold]", **kwargs)
| BoldIntPrompt |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 53884,
"end": 58475
} | class ____(SinglePatternODESolver):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that... | HomogeneousCoeffSubsIndepDivDep |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1054193,
"end": 1054419
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (CreatedRepositoryContribution, RestrictedContribution)
| CreatedRepositoryOrRestrictedContribution |
python | huggingface__transformers | src/transformers/models/sew/modular_sew.py | {
"start": 1650,
"end": 1718
} | class ____(Wav2Vec2GroupNormConvLayer):
pass
| SEWGroupNormConvLayer |
python | streamlit__streamlit | lib/tests/streamlit/elements/time_input_test.py | {
"start": 1164,
"end": 11559
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall time_input protos."""
def test_just_label(self):
"""Test that it can be called with no value."""
st.time_input("the label")
c = self.get_delta_from_queue().new_element.time_input
assert c.label == "the label"
... | TimeInputTest |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 8078,
"end": 10682
} | class ____(HTTPException):
"""*401* ``Unauthorized``
Raise if the user is not authorized to access a resource.
The ``www_authenticate`` argument should be used to set the
``WWW-Authenticate`` header. This is used for HTTP basic auth and
other schemes. Use :class:`~werkzeug.datastructures.WWWAuthen... | Unauthorized |
python | crytic__slither | slither/printers/inheritance/inheritance.py | {
"start": 225,
"end": 2998
} | class ____(AbstractPrinter):
ARGUMENT = "inheritance"
HELP = "Print the inheritance relations between contracts"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#inheritance"
def _get_child_contracts(self, base):
# Generate function to get all child contracts of a base... | PrinterInheritance |
python | getsentry__responses | responses/tests/test_registries.py | {
"start": 3132,
"end": 5811
} | class ____:
def test_invocation_index(self):
@responses.activate(registry=OrderedRegistry)
def run():
responses.add(
responses.GET,
"http://twitter.com/api/1/foobar",
status=666,
)
responses.add(
resp... | TestOrderedRegistry |
python | walkccc__LeetCode | solutions/235. Lowest Common Ancestor of a Binary Search Tree/235.py | {
"start": 0,
"end": 344
} | class ____:
def lowestCommonAncestor(
self,
root: 'TreeNode',
p: 'TreeNode',
q: 'TreeNode',
) -> 'TreeNode':
if root.val > max(p.val, q.val):
return self.lowestCommonAncestor(root.left, p, q)
if root.val < min(p.val, q.val):
return self.lowestCommonAncestor(root.right, p,... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 43810,
"end": 45030
} | class ____(NonStrictDataModel):
"""
:param entries: List of view entries. All tasks must have at least one view.
:type entries: Sequence[ViewEntry]
"""
_schema = {
"properties": {
"entries": {
"description": "List of view entries. All tasks must have at least one... | View |
python | ray-project__ray | rllib/examples/algorithms/ppo/benchmark_ppo_mujoco.py | {
"start": 2025,
"end": 4330
} | class ____(Stopper):
def __init__(self, benchmark_envs):
self.benchmark_envs = benchmark_envs
def __call__(self, trial_id, result):
# Stop training if the mean reward is reached.
if (
result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
>= self.benchmark_envs[result["... | BenchmarkStopper |
python | pydantic__pydantic | tests/test_type_adapter.py | {
"start": 26010,
"end": 26734
} | class ____:
x: int
@pytest.mark.parametrize('type_,repr_', [(int, 'int'), (list[int], 'list[int]'), (SimpleDataclass, 'SimpleDataclass')])
def test_ta_repr(type_: Any, repr_: str) -> None:
ta = TypeAdapter(type_)
assert repr(ta) == f'TypeAdapter({repr_})'
def test_correct_frame_used_parametrized(create_... | SimpleDataclass |
python | openai__openai-python | src/openai/types/realtime/realtime_transcription_session_audio_input_turn_detection.py | {
"start": 2401,
"end": 3489
} | class ____(BaseModel):
type: Literal["semantic_vad"]
"""Type of turn detection, `semantic_vad` to turn on Semantic VAD."""
create_response: Optional[bool] = None
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
eagerness: Optional[Literal["low",... | SemanticVad |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-microsoft-outlook/llama_index/readers/microsoft_outlook/base.py | {
"start": 880,
"end": 3948
} | class ____(BaseReader):
"""
Outlook local calendar reader for Windows.
Reads events from local copy of Outlook calendar.
"""
def load_data(
self,
number_of_results: Optional[int] = 100,
start_date: Optional[Union[str, datetime.date]] = None,
end_date: Optional[Union[... | OutlookLocalCalendarReader |
python | great-expectations__great_expectations | tests/expectations/fixtures/expect_column_values_to_equal_three.py | {
"start": 1098,
"end": 1346
} | class ____(ColumnMapExpectation):
map_metric = "column_values.equal_three"
success_keys = ("mostly",)
def validate_configuration(self, configuration) -> None:
pass # no-op to make test setup easier
| ExpectColumnValuesToEqualThree |
python | PrefectHQ__prefect | tests/server/services/test_scheduler.py | {
"start": 18031,
"end": 22110
} | class ____:
async def test_tight_loop_by_default(self):
assert RecentDeploymentsScheduler().loop_seconds == 5
async def test_tight_loop_can_be_configured(self):
assert RecentDeploymentsScheduler(loop_seconds=1).loop_seconds == 1
with temporary_settings(
{PREFECT_SERVER_SERV... | TestRecentDeploymentsScheduler |
python | walkccc__LeetCode | solutions/2782. Number of Unique Categories/2782.py | {
"start": 130,
"end": 407
} | class ____:
def numberOfCategories(
self,
n: int,
categoryHandler: Optional['CategoryHandler'],
) -> int:
ans = 0
for i in range(n):
if not any(categoryHandler.haveSameCategory(i, j) for j in range(i)):
ans += 1
return ans
| Solution |
python | automl__auto-sklearn | autosklearn/pipeline/base.py | {
"start": 667,
"end": 22448
} | class ____(Pipeline):
"""Base class for all pipeline objects.
Notes
-----
This class should not be instantiated, only subclassed."""
__metaclass__ = ABCMeta
def __init__(
self,
config=None,
feat_type: Optional[FEAT_TYPE_TYPE] = None,
steps=None,
dataset... | BasePipeline |
python | huggingface__transformers | src/transformers/models/dia/modeling_dia.py | {
"start": 4626,
"end": 5345
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
DiaRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_dt... | DiaRMSNorm |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_crossing01.py | {
"start": 315,
"end": 1441
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_crossing01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 29076,
"end": 29798
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.h... | CaninePredictionHeadTransform |
python | doocs__leetcode | solution/1000-1099/1095.Find in Mountain Array/Solution.py | {
"start": 216,
"end": 972
} | class ____:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
def search(l: int, r: int, k: int) -> int:
while l < r:
mid = (l + r) >> 1
if k * mountain_arr.get(mid) >= k * target:
r = mid
else:
... | Solution |
python | lepture__mistune | src/mistune/markdown.py | {
"start": 231,
"end": 4019
} | class ____:
"""Markdown instance to convert markdown text into HTML or other formats.
Here is an example with the HTMLRenderer::
from mistune import HTMLRenderer
md = Markdown(renderer=HTMLRenderer(escape=False))
md('hello **world**')
:param renderer: a renderer to convert parsed ... | Markdown |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_class_spec.py | {
"start": 383,
"end": 5087
} | 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... | V1IngressClassSpec |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 74392,
"end": 75221
} | class ____(TestCase):
"""Tests for divide()"""
def test_invalid_n(self):
self.assertRaises(ValueError, lambda: mi.divide(-1, [1, 2, 3]))
self.assertRaises(ValueError, lambda: mi.divide(0, [1, 2, 3]))
def test_basic(self):
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n, e... | DivideTest |
python | huggingface__transformers | tests/models/whisper/test_tokenization_whisper.py | {
"start": 1089,
"end": 14932
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "openai/whisper-tiny"
tokenizer_class = WhisperTokenizer
rust_tokenizer_class = WhisperTokenizer
test_rust_tokenizer = True # We only have one tokenizer now
test_slow_tokenizer = False # No slow tokenizer
test_sentencepi... | WhisperTokenizerTest |
python | wandb__wandb | wandb/_pydantic/base.py | {
"start": 1754,
"end": 4495
} | class ____(CompatBaseModel, ABC):
# Base class with sensible defaults for converting to and from JSON.
#
# Automatically parse or serialize "raw" API data (e.g. convert to and from
# camelCase keys):
# - `.model_{dump,dump_json}()` should return JSON-ready dicts or JSON
# strings.
# - `.mo... | JsonableModel |
python | scipy__scipy | scipy/signal/tests/test_ltisys.py | {
"start": 31674,
"end": 32581
} | class ____:
def test_initialization(self):
# Check that all initializations work
TransferFunction(1, 1)
TransferFunction([1], [2])
TransferFunction(np.array([1]), np.array([2]))
def test_conversion(self):
# Check the conversion functions
s = TransferFunction([1, ... | TestTransferFunction |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 36530,
"end": 36772
} | class ____(_SizedIntType):
""" Represents an unsigned integer type. """
__slots__ = ()
@property
def min(self):
return 0
@property
def max(self):
return 2**self.nbits - 1
two = Integer(2)
| UnsignedIntType |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 56018,
"end": 57281
} | class ____(object):
"""Implementation of GPU IPC using CUDA driver API.
This requires the devices to be peer accessible.
"""
def __init__(self, parent):
self.base = parent.base
self.handle = parent.handle
self.size = parent.size
self.offset = parent.offset
# remem... | _CudaIpcImpl |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 13984,
"end": 15205
} | class ____(TestCase):
def test_init(self):
try:
foo = DateTimeField(model_attr="foo")
except:
self.fail()
def test_convert(self):
pub_date = DateTimeField()
self.assertEqual(
pub_date.convert("2016-02-16T10:02:03"),
datetime.datet... | DateTimeFieldTestCase |
python | getsentry__sentry | tests/sentry/integrations/models/deletions/test_organizationintegration.py | {
"start": 1192,
"end": 7772
} | class ____(TransactionTestCase, HybridCloudTestMixin):
def test_simple(self) -> None:
org = self.create_organization()
integration, organization_integration = self.create_provider_integration_for(
org, self.user, provider="example", name="Example"
)
with assume_test_silo... | DeleteOrganizationIntegrationTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.