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 | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 6835,
"end": 7664
} | class ____(Token):
""" Represents an implied do loop in Fortran.
Examples
========
>>> from sympy import Symbol, fcode
>>> from sympy.codegen.fnodes import ImpliedDoLoop, ArrayConstructor
>>> i = Symbol('i', integer=True)
>>> idl = ImpliedDoLoop(i**3, i, -3, 3, 2) # -27, -1, 1, 27
>>>... | ImpliedDoLoop |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 13693,
"end": 14019
} | class ____:
def test_phone_number(self, faker, num_samples):
pattern: Pattern = re.compile(r"0(?:55|66|77)\d \d{3} \d{3}")
for _ in range(num_samples):
phone_number = faker.phone_number()
assert isinstance(phone_number, str)
assert pattern.fullmatch(phone_number)
... | TestFrDz |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 97393,
"end": 101266
} | class ____(Request):
"""
Scroll through task events, sorted by timestamp
:param task: Task ID
:type task: str
:param order: 'asc' (default) or 'desc'.
:type order: str
:param scroll_id: Pass this value on next call to get next page
:type scroll_id: str
:param batch_size: Number of e... | GetTaskEventsRequest |
python | ray-project__ray | python/ray/train/_internal/checkpoint_manager.py | {
"start": 1676,
"end": 8074
} | class ____:
"""Checkpoint manager that handles checkpoint book-keeping for a trial.
The main purpose of this abstraction is to keep the top K checkpoints based on
recency/a user-provided metric.
NOTE: This class interacts with `_TrainingResult` objects, which are
(checkpoint, metrics) pairs. This ... | _CheckpointManager |
python | python-openxml__python-docx | src/docx/image/constants.py | {
"start": 2050,
"end": 2161
} | class ____:
"""PNG chunk type names."""
IHDR = "IHDR"
pHYs = "pHYs"
IEND = "IEND"
| PNG_CHUNK_TYPE |
python | django__django | tests/auth_tests/test_models.py | {
"start": 9757,
"end": 13512
} | class ____(TestCase):
def test_email_user(self):
# valid send_mail parameters
kwargs = {
"fail_silently": False,
"auth_user": None,
"auth_password": None,
"connection": None,
"html_message": None,
}
user = User(email="foo@ba... | AbstractUserTestCase |
python | huggingface__transformers | src/transformers/models/persimmon/modeling_persimmon.py | {
"start": 14545,
"end": 18410
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: PersimmonConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = PersimmonAttention(config=config, layer_idx=layer_idx)
self.mlp = PersimmonMLP(config)
self.input_lay... | PersimmonDecoderLayer |
python | getsentry__sentry | src/sentry/hybridcloud/services/replica/impl.py | {
"start": 11805,
"end": 13971
} | class ____(ControlReplicaService):
def upsert_external_actor_replica(self, *, external_actor: RpcExternalActor) -> None:
try:
if external_actor.user_id is not None:
# Validating existence of user
User.objects.get(id=external_actor.user_id)
integration ... | DatabaseBackedControlReplicaService |
python | anthropics__anthropic-sdk-python | src/anthropic/_streaming.py | {
"start": 583,
"end": 1352
} | class ____(abc.ABCMeta):
@override
def __instancecheck__(self, instance: Any) -> bool:
# we override the `isinstance()` check for `Stream`
# as a previous version of the `MessageStream` class
# inherited from `Stream` & without this workaround,
# changing it to not inherit would ... | _SyncStreamMeta |
python | openai__openai-python | src/openai/types/chat/completion_create_params.py | {
"start": 17262,
"end": 18030
} | class ____(CompletionCreateParamsBase):
stream: Required[Literal[True]]
"""
If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_f... | CompletionCreateParamsStreaming |
python | django__django | tests/admin_views/tests.py | {
"start": 205799,
"end": 218309
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.pks = [EmptyModel.objects.create().id for i in range(3)]
def setUp(self):
self.client.fo... | AdminCustomQuerysetTest |
python | pypa__pip | tests/unit/test_utils_unpacking.py | {
"start": 375,
"end": 15976
} | class ____:
"""
test_tar.tgz/test_tar.zip have content as follows engineered to confirm 3
things:
1) confirm that reg files, dirs, and symlinks get unpacked
2) permissions are not preserved (and go by the 022 umask)
3) reg files with *any* execute perms, get chmod +x
file.txt ... | TestUnpackArchives |
python | google__jax | jax/_src/test_warning_util.py | {
"start": 1230,
"end": 4074
} | class ____(threading.local):
"Thread-local state that contains a list of warning handlers."
def __init__(self):
self.handlers = []
_context = _WarningContext()
# Callback that applies the handlers in reverse order. If no handler matches,
# we raise an error.
def _showwarning(message, category, filename, li... | _WarningContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/tickets_response_builder.py | {
"start": 228,
"end": 465
} | class ____(HttpResponseBuilder):
@classmethod
def tickets_response(cls) -> "TicketsResponseBuilder":
return cls(find_template("tickets", __file__), FieldPath("tickets"), CursorBasedPaginationStrategy())
| TicketsResponseBuilder |
python | numpy__numpy | numpy/distutils/tests/test_fcompiler_intel.py | {
"start": 785,
"end": 1058
} | class ____:
def test_64bit_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem')
for vs, version in intel_64bit_version_strings:
v = fc.version_match(vs)
assert_(v == version)
| TestIntelEM64TFCompilerVersions |
python | pytorch__pytorch | torch/utils/_sympy/functions.py | {
"start": 46186,
"end": 46609
} | class ____(sympy.Function):
is_integer = True
@classmethod
def eval(cls, number):
# assert number.is_integer is not True, number
if number in (sympy.oo, int_oo):
return int_oo
if number in (-sympy.oo, -int_oo):
return -int_oo
if isinstance(number, sym... | TruncToInt |
python | neetcode-gh__leetcode | python/0144-binary-tree-preorder-traversal.py | {
"start": 0,
"end": 361
} | class ____:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
cur, stack = root, []
res = []
while cur or stack:
if cur:
res.append(cur.val)
stack.append(cur.right)
cur = cur.left
else:
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/dummy/views.py | {
"start": 945,
"end": 2238
} | class ____(FormView):
form_class = AuthenticateForm
template_name = "dummy/authenticate_form.html"
@method_decorator(login_not_required)
def dispatch(self, request, *args, **kwargs):
self.state_id = request.GET.get("state")
if not self.state_id:
raise PermissionDenied()
... | AuthenticateView |
python | Pylons__pyramid | docs/quick_tutorial/authorization/tutorial/security.py | {
"start": 549,
"end": 1692
} | class ____:
def __init__(self, secret):
self.authtkt = AuthTktCookieHelper(secret=secret)
self.acl = ACLHelper()
def identity(self, request):
identity = self.authtkt.identify(request)
if identity is not None and identity['userid'] in USERS:
return identity
def a... | SecurityPolicy |
python | django-haystack__django-haystack | test_haystack/test_forms.py | {
"start": 464,
"end": 1485
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Stow.
self.old_unified_index = connections["default"]._index
self.ui = UnifiedIndex()
self.bmmsi = BasicMockModelSearchIndex()
self.bammsi = BasicAnotherMockModelSearchIndex()
self.ui.build(indexes=[sel... | SearchFormTestCase |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_test.py | {
"start": 49436,
"end": 54746
} | class ____(parameterized.TestCase):
@parameterized.named_parameters([
('File', lambda: descriptor_pb2.DESCRIPTOR),
('Message', lambda: descriptor_pb2.FeatureSet.DESCRIPTOR),
(
'Enum',
lambda: descriptor_pb2.FeatureSet.FieldPresence.DESCRIPTOR,
),
(
'Field',... | FeaturesTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink05.py | {
"start": 346,
"end": 2038
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | tornadoweb__tornado | tornado/test/iostream_test.py | {
"start": 48313,
"end": 51795
} | class ____(unittest.TestCase):
"""
Unit tests for the private _StreamBuffer class.
"""
def setUp(self):
self.random = random.Random(42)
def to_bytes(self, b):
if isinstance(b, (bytes, bytearray)):
return bytes(b)
elif isinstance(b, memoryview):
retur... | TestStreamBuffer |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 226498,
"end": 230628
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3, 3]"):
l_x_ = L_x_
_jvp_increment_nesting = torch._C._functorch._jvp_increment_nesting(); _jvp_increment_nesting = None
_set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled = None
_enter_... | GraphModule |
python | encode__django-rest-framework | rest_framework/authtoken/apps.py | {
"start": 91,
"end": 198
} | class ____(AppConfig):
name = 'rest_framework.authtoken'
verbose_name = _("Auth Token")
| AuthTokenConfig |
python | crytic__slither | slither/detectors/variables/could_be_constant.py | {
"start": 370,
"end": 2060
} | class ____(AbstractDetector):
"""
State variables that could be declared as constant.
Not all types for constants are implemented in Solidity as of 0.4.25.
The only supported types are value types and strings (ElementaryType).
Reference: https://solidity.readthedocs.io/en/latest/contracts.html#const... | CouldBeConstant |
python | sanic-org__sanic | sanic/errorpages.py | {
"start": 4773,
"end": 7111
} | class ____(BaseRenderer):
"""Render an exception as plain text."""
OUTPUT_TEXT = "{title}\n{bar}\n{text}\n\n{body}"
SPACER = " "
def full(self) -> HTTPResponse:
return text(
self.OUTPUT_TEXT.format(
title=self.title,
text=self.text,
... | TextRenderer |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 8431,
"end": 8939
} | class ____(TestCase):
def test_rcssmin_filter(self):
content = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/
p {
background: rgb(51,102,153) url('../../images/image.gif');
}
"""
output = """/*!
* django-compressor
* Copyrig... | rCssMinTestCase |
python | getsentry__sentry | src/sentry/api/endpoints/project_rules.py | {
"start": 11095,
"end": 25037
} | class ____(serializers.Serializer):
name = serializers.CharField(max_length=256, help_text="The name for the rule.")
environment = serializers.CharField(
required=False, allow_null=True, help_text="The name of the environment to filter by."
)
owner = ActorField(
required=False, allow_nul... | ProjectRulesPostSerializer |
python | realpython__materials | python-property/point_v1.py | {
"start": 0,
"end": 279
} | class ____:
def __init__(self, x, y):
self._x = x
self._y = y
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
def get_y(self):
return self._y
def set_y(self, value):
self._y = value
| Point |
python | numba__numba | numba/core/targetconfig.py | {
"start": 201,
"end": 951
} | class ____:
"""An option to be used in ``TargetConfig``.
"""
__slots__ = "_type", "_default", "_doc"
def __init__(self, type, *, default, doc):
"""
Parameters
----------
type :
Type of the option value. It can be a callable.
The setter always call... | Option |
python | django__django | tests/auth_tests/test_migrations.py | {
"start": 469,
"end": 4731
} | class ____(TransactionTestCase):
available_apps = [
"auth_tests",
"django.contrib.auth",
"django.contrib.contenttypes",
]
def setUp(self):
"""
Create proxy permissions with content_type to the concrete model
rather than the proxy model (as they were before Dj... | ProxyModelWithDifferentAppLabelTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator_test.py | {
"start": 31750,
"end": 32621
} | class ____(ClusterCoordinatorTest):
"""Test basic functionality works with explicit maximum closure queue size.
Execute the same set of test cases as in `ClusterCoordinatorTest`, with an
explicit size limit for the closure queue. Note that even when the queue size
is set to infinite, there is still a maximum p... | LimitedClosureQueueSizeBasicTest |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 6689,
"end": 7726
} | class ____(nn.Module):
r"""
A module that corresponds to the stem module of the original work.
"""
def __init__(self, config: AlignVisionConfig):
super().__init__()
self.out_dim = round_filters(config, 32)
self.padding = nn.ZeroPad2d(padding=(0, 1, 0, 1))
self.convoluti... | AlignVisionEmbeddings |
python | wireservice__csvkit | tests/test_utilities/test_csvformat.py | {
"start": 2716,
"end": 5662
} | class ____(CSVKitTestCase, EmptyFileTests):
Utility = CSVFormat
# New test compared to TestCSVFormat.
def test_locale(self):
self.assertLines(['-U', '2', '--locale', 'de_DE', 'examples/test_locale.csv'], [
'"a","b","c"',
'1.7,200000000,""',
])
def test_launch_ne... | TestCSVFormatQuoteNonNumeric |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-siliconflow/tests/test_llms_siliconflow.py | {
"start": 686,
"end": 3859
} | class ____:
def __init__(self, json_data) -> None:
self._json_data = json_data
def raise_for_status(self) -> None:
pass
async def __aenter__(self) -> "MockAsyncResponse":
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
ex... | MockAsyncResponse |
python | pyca__cryptography | tests/hazmat/primitives/test_aes.py | {
"start": 5103,
"end": 6037
} | class ____:
test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "ECB"),
[
"ECBGFSbox128.rsp",
"ECBGFSbox192.rsp",
"ECBGFSbox256.rsp",
"ECBKeySbox128.rsp",
"ECBKeySbox192.rsp",
"ECBKeySbox2... | TestAESModeECB |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 5036,
"end": 5088
} | class ____:
def f(self):
print("I")
| ParentI |
python | pypa__pipenv | pipenv/vendor/pythonfinder/finders/path_finder.py | {
"start": 380,
"end": 8186
} | class ____(BaseFinder):
"""
Base class for finders that search for Python in filesystem paths.
"""
def __init__(
self,
paths: list[str | Path] | None = None,
only_python: bool = True,
ignore_unsupported: bool = True,
):
"""
Initialize a new PathFinder... | PathFinder |
python | django__django | tests/schema/models.py | {
"start": 3082,
"end": 3295
} | class ____(models.Model):
title = models.CharField(max_length=100, db_index=True)
pub_date = models.DateTimeField()
class Meta:
apps = new_apps
db_table = "schema_book"
| BookWithoutAuthor |
python | ApeWorX__ape | src/ape/managers/converters.py | {
"start": 6047,
"end": 7163
} | class ____(ConverterAPI):
"""
Converts either a string, datetime object, or a timedelta object to a timestamp.
No timezone required, but should be formatted to UTC.
"""
def is_convertible(self, value: Union[str, datetime, timedelta]) -> bool:
if not isinstance(value, (str, datetime, timedel... | TimestampConverter |
python | ray-project__ray | doc/source/serve/doc_code/streaming_tutorial.py | {
"start": 6975,
"end": 10083
} | class ____:
def __init__(self, model_id: str):
self.loop = asyncio.get_running_loop()
self.model_id = model_id
self.model = AutoModelForCausalLM.from_pretrained(self.model_id)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.tokenizer.pad_token = self.token... | Batchbot |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_engine.py | {
"start": 51434,
"end": 53088
} | class ____(fixtures.TestBase):
__requires__ = ("asyncio",)
def test_sync_dbapi_raises(self):
with expect_raises_message(
exc.InvalidRequestError,
"The asyncio extension requires an async driver to be used.",
):
create_async_engine("sqlite:///:memory:")
@... | TextSyncDBAPI |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F821_17.py | {
"start": 1595,
"end": 1884
} | class ____[T](list[T]): ...
T # F821: Undefined name `T` - not accessible after class scope
# Types specified in bounds should exist
type Foo[T: DoesNotExist] = T # F821: Undefined name `DoesNotExist`
def foo[T: DoesNotExist](t: T) -> T: return t # F821: Undefined name `DoesNotExist`
| Foo |
python | astropy__astropy | astropy/extern/ply/lex.py | {
"start": 2229,
"end": 2416
} | class ____(Exception):
def __init__(self, message, s):
self.args = (message,)
self.text = s
# Token class. This class is used to represent the tokens produced.
| LexError |
python | apache__airflow | airflow-core/tests/unit/utils/test_singleton.py | {
"start": 869,
"end": 910
} | class ____(metaclass=Singleton):
pass
| A |
python | astropy__astropy | astropy/coordinates/transformations/function.py | {
"start": 2646,
"end": 10292
} | class ____(FunctionTransform):
r"""Transformation based on functions using finite difference for velocities.
A coordinate transformation that works like a
`~astropy.coordinates.FunctionTransform`, but computes velocity shifts
based on the finite-difference relative to one of the frame attributes.
N... | FunctionTransformWithFiniteDifference |
python | python-pillow__Pillow | src/PIL/EpsImagePlugin.py | {
"start": 5249,
"end": 16552
} | class ____(ImageFile.ImageFile):
"""EPS File Parser for the Python Imaging Library"""
format = "EPS"
format_description = "Encapsulated Postscript"
mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
def _open(self) -> None:
(length, offset) = self._find_offset(self.fp)
# go to of... | EpsImageFile |
python | PyCQA__pylint | tests/functional/m/monkeypatch_method.py | {
"start": 142,
"end": 375
} | class ____:
'test class'
def __init__(self, value):
self.value = value
def func(arg1, arg2):
'function that will be used as a method'
return arg1.value + arg2
Clazz.method = func
VAR = Clazz(1).method(2)
| Clazz |
python | huggingface__transformers | src/transformers/models/got_ocr2/processing_got_ocr2.py | {
"start": 2474,
"end": 12191
} | class ____(ProcessorMixin):
r"""
Constructs a GotOcr2 processor which wraps a [`GotOcr2ImageProcessor`] and
[`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
tokenizer functionalities. See the [`~GotOcr2Processor.__call__`] and [`~GotOcr2Processor.d... | GotOcr2Processor |
python | google__jax | tests/hijax_test.py | {
"start": 1530,
"end": 1645
} | class ____:
arr: jax.Array # int8[m, k]
scale: jax.Array # f32[m]
# Define a type
@dataclass(frozen=True)
| QArray |
python | joke2k__faker | tests/providers/test_enum.py | {
"start": 272,
"end": 1370
} | class ____:
num_samples = 100
def test_enum(self, faker, num_samples):
# (1/3) ** 100 ~ 1.94e-48 probability of this test failing because a specific
# value was not sampled
for _ in range(num_samples):
actual = faker.enum(_TestEnum)
assert actual in (_TestEnum.A,... | TestEnumProvider |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 34943,
"end": 37152
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter task runs. Only task runs matching all criteria will be returned"""
id: Optional[TaskRunFilterId] = Field(
default=None, description="Filter criteria for `TaskRun.id`"
)
name: Optional[TaskRunFilterName] = Field(
default=None, descri... | TaskRunFilter |
python | huggingface__transformers | src/transformers/models/convnext/configuration_convnext.py | {
"start": 910,
"end": 5631
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an
ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults wi... | ConvNextConfig |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_child_process_executor.py | {
"start": 793,
"end": 930
} | class ____(ChildProcessCommand):
def execute(self):
# access inner API to simulate hard crash
os._exit(1)
| CrashyCommand |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/fixed_length_record_dataset_test.py | {
"start": 8240,
"end": 9044
} | class ____(
FixedLengthRecordDatasetTestBase, checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self, num_epochs, compression_type=None):
filenames = self._createFiles()
return readers.FixedLengthRecordDataset(
filenames, self._record_bytes, self._header_byt... | FixedLengthRecordDatasetCheckpointTest |
python | spyder-ide__spyder | spyder/plugins/mainmenu/api.py | {
"start": 3458,
"end": 3559
} | class ____:
Managers = 'managers_section'
Preferences = 'preferences_section'
| ToolsMenuSections |
python | facelessuser__pymdown-extensions | pymdownx/snippets.py | {
"start": 1595,
"end": 16390
} | class ____(Preprocessor):
"""Handle snippets in Markdown content."""
RE_ALL_SNIPPETS = re.compile(
r'''(?x)
^(?P<space>[ \t]*)
(?P<escape>;*)
(?P<all>
(?P<inline_marker>-{1,}8<-{1,}[ \t]+)
(?P<snippet>(?:"(?:\\"|[^"\n\r])+?"|'(?:\\'|[^'\n\r])+?'))(?![ \t]... | SnippetPreprocessor |
python | readthedocs__readthedocs.org | readthedocs/analytics/tests.py | {
"start": 3895,
"end": 10856
} | class ____(TestCase):
def setUp(self):
self.project = get(
Project,
slug="pip",
privacy_level=PUBLIC,
)
self.version = get(Version, slug="1.8", project=self.project)
self.project.versions.all().update(privacy_level=PUBLIC)
self.absolute_uri... | AnalyticsPageViewsTests |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet_identity_block_starter.py | {
"start": 413,
"end": 872
} | class ____:
def __init__(self):
# TODO
pass
def predict(self, X):
# TODO
pass
if __name__ == '__main__':
identity_block = IdentityBlock()
# make a fake image
X = np.random.random((1, 224, 224, 256))
init = tf.global_variables_initializer()
with tf.Session() as session:
identity_... | IdentityBlock |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py | {
"start": 10330,
"end": 11252
} | class ____(Benchmark):
"""
Univariate Problem13 objective function.
This class defines the Univariate Problem13 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\\text{Problem13}}(x) = -x^{2/3} - (1 - x^2)^{1/3}
Bound constraints... | Problem13 |
python | pytorch__pytorch | torchgen/_autoheuristic/pad_mm/test_pad_mm.py | {
"start": 236,
"end": 1061
} | class ____(TestCase):
def test_padmm_a100(self) -> None:
run_bash("get_padmm_dataset.sh")
run_bash("gen_pad_mm_a100.sh")
file_path = "../../../torch/_inductor/autoheuristic/artifacts/_PadMMA100.py"
a100_heuristic_generated_code = read_file_to_string(file_path)
self.assertExp... | TestPadMM |
python | sphinx-doc__sphinx | tests/test_util/test_util_inspect.py | {
"start": 1590,
"end": 33643
} | class ____:
def __call__(self):
pass
def _decorator(f):
@functools.wraps(f)
def wrapper():
return f()
return wrapper
def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # noqa: F821
pass
def forward_reference_in_return() -> Foo: # type: ignore[name-de... | _Callable |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 879894,
"end": 885174
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"database_id",
"fields",
"filter",
"group_by",
"layout",
"name",
"number",
"project",
... | ProjectV2View |
python | facelessuser__soupsieve | tests/test_level4/test_muted.py | {
"start": 50,
"end": 1055
} | class ____(util.TestCase):
"""Test paused selectors."""
MARKUP = """
<!DOCTYPE html>
<html>
<body>
<video id="vid1" width="320" height="240" controls muted>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the v... | TestPaused |
python | matplotlib__matplotlib | lib/matplotlib/backend_bases.py | {
"start": 132356,
"end": 136172
} | class ____:
# A backend can be defined by using the following pattern:
#
# @_Backend.export
# class FooBackend(_Backend):
# # override the attributes and methods documented below.
# `backend_version` may be overridden by the subclass.
backend_version = "unknown"
# The `FigureCanvas... | _Backend |
python | ansible__ansible | test/units/plugins/lookup/test_password.py | {
"start": 22358,
"end": 24395
} | class ____(BaseTestLookupModule):
def setUp(self):
super(TestLookupModuleWithPasslibWrappedAlgo, self).setUp()
self.os_path_exists = password.os.path.exists
def tearDown(self):
super(TestLookupModuleWithPasslibWrappedAlgo, self).tearDown()
password.os.path.exists = self.os_path_... | TestLookupModuleWithPasslibWrappedAlgo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-chat/unit_tests/integration/test_chats.py | {
"start": 3052,
"end": 4485
} | class ____(TestCase):
@HttpMocker()
def test_when_read_then_extract_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
HttpRequest(
f"https://{_SUBDOMAIN}.zendesk.com/api/v2/chat/incremental/chats?fields=chats%28%2A%29&limit=1000&start_time={int(_START_DATETIME.... | ChatsTest |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 80790,
"end": 81102
} | class ____(TestCase):
def setUp(self):
self.model = PollWithManyToManyCustomHistoryID
self.history_model = self.model.history.model
self.place = Place.objects.create(name="Home")
self.poll = self.model.objects.create(question="what's up?", pub_date=today)
| ManyToManyCustomIDTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 11676,
"end": 12113
} | class ____(ConcreteTemplate):
cases = [signature(choose_result_int(op), op) for op in sorted(types.unsigned_domain)]
cases += [signature(choose_result_int(op), op) for op in sorted(types.signed_domain)]
cases += [signature(op, op) for op in sorted(types.real_domain)]
cases += [signature(op, op) for op i... | UnaryOp |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 20069,
"end": 23368
} | class ____(PreTrainedAudioTokenizerBase):
config: DacConfig
base_model_prefix = "dac"
main_input_name = "input_values"
@torch.no_grad()
def _init_weights(self, module):
if isinstance(module, nn.Conv1d):
init.trunc_normal_(module.weight, std=0.02)
init.constant_(modul... | DacPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/transactions.py | {
"start": 1512,
"end": 8617
} | class ____(ContextModel, abc.ABC):
"""
A base model for transaction state.
"""
store: Optional[ResultStore] = None
key: Optional[str] = None
children: list[Self] = Field(default_factory=list)
commit_mode: Optional[CommitMode] = None
isolation_level: Optional[IsolationLevel] = IsolationL... | BaseTransaction |
python | google__jax | jax/_src/xla_metadata.py | {
"start": 2036,
"end": 4865
} | class ____:
__slots__ = ["prev", "updates"]
def __init__(self, updates):
self.updates = updates
def __enter__(self):
if not self.updates:
return
self.prev = config.xla_metadata_context_manager.get_local()
config.xla_metadata_context_manager.set_local(
xla_metadata_lib.update_metad... | XlaMetadataContextManager |
python | dask__distributed | distributed/comm/inproc.py | {
"start": 6934,
"end": 8786
} | class ____(BaseListener):
prefix = "inproc"
def __init__(self, address, comm_handler, deserialize=True):
super().__init__()
self.manager = global_manager
self.address = address or self.manager.new_address()
self.comm_handler = comm_handler
self.deserialize = deserialize
... | InProcListener |
python | huggingface__transformers | tests/models/led/test_modeling_led.py | {
"start": 10658,
"end": 20316
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(LEDModel, LEDForConditionalGeneration, LEDForSequenceClassification, LEDForQuestionAnswering)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
... | LEDModelTest |
python | scipy__scipy | benchmarks/benchmarks/interpolate.py | {
"start": 11036,
"end": 12149
} | class ____(Benchmark):
"""
Benchmark RegularGridInterpolator with method="quintic".
"""
param_names = ['ndim', 'n_samples', 'method']
params = [
[2],
[10, 40],
]
def setup(self, ndim, n_samples):
rng = np.random.default_rng(314159)
self.points = [np.sort(rng... | RGI_Quintic |
python | PrefectHQ__prefect | src/prefect/artifacts.py | {
"start": 9096,
"end": 9341
} | class ____(Artifact):
markdown: str
type: Optional[str] = "markdown"
async def aformat(self) -> str:
return self.markdown
@async_dispatch(aformat)
def format(self) -> str:
return self.markdown
| MarkdownArtifact |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/magic_test.py | {
"start": 779,
"end": 6503
} | class ____(unittest.TestCase):
"""Test for Magic
The test counts the number of substitutions that magic.add_code do for
a few code snippets. The test passes if the expected number of
substitutions have been made.
"""
def _testCode(self, code: str, expected_count: int) -> None:
tree = ma... | MagicTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/tool_text_editor_20250124_param.py | {
"start": 326,
"end": 725
} | class ____(TypedDict, total=False):
name: Required[Literal["str_replace_editor"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["text_editor_20250124"]]
cache_control: Optional[CacheControlEphemeralParam]
"""Crea... | ToolTextEditor20250124Param |
python | pandas-dev__pandas | pandas/tests/io/formats/test_format.py | {
"start": 48803,
"end": 66944
} | class ____:
def test_freq_name_separation(self):
s = Series(
np.random.default_rng(2).standard_normal(10),
index=date_range("1/1/2000", periods=10),
name=0,
)
result = repr(s)
assert "Freq: D, Name: 0" in result
def test_unicode_name_in_foote... | TestSeriesFormatting |
python | huggingface__transformers | src/transformers/quantizers/quantizer_aqlm.py | {
"start": 1086,
"end": 3490
} | class ____(HfQuantizer):
"""
Quantizer of the AQLM method. Enables the loading of prequantized models.
"""
requires_calibration = True
required_packages = ["aqlm"]
optimum_quantizer = None
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
super().__init__(... | AqlmHfQuantizer |
python | keras-team__keras | keras/src/layers/rnn/conv_lstm_test.py | {
"start": 1367,
"end": 2275
} | class ____(testing.TestCase):
def test_correctness(self):
x = np.arange(450).reshape((2, 3, 5, 5, 3)).astype("float32") / 100
s1 = np.arange(200).reshape((2, 5, 5, 4)).astype("float32") / 100
s2 = np.arange(200).reshape((2, 5, 5, 4)).astype("float32") / 100
if backend.config.image_d... | ConvLSTMTest |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 28536,
"end": 28906
} | class ____:
"""Class level constant, raises when trying to set the attribute"""
__slots__ = ["value"]
def __init__(self, value):
self.value = value
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
raise TypeError(f"Const value does... | Const |
python | scrapy__scrapy | tests/test_pipelines.py | {
"start": 11142,
"end": 16866
} | class ____:
"""Tests for the deprecated spider arg handling in MiddlewareManager.
Here because MiddlewareManager doesn't have methods that could take a spider arg."""
@pytest.fixture
def crawler(self) -> Crawler:
return get_crawler(Spider)
@deferred_f_from_coro_f
async def test_deprec... | TestMiddlewareManagerSpider |
python | walkccc__LeetCode | solutions/2359. Find Closest Node to Given Two Nodes/2359.py | {
"start": 0,
"end": 631
} | class ____:
def closestMeetingNode(self, edges: list[int], node1: int, node2: int) -> int:
MAX = 10000
dist1 = self._getDist(edges, node1)
dist2 = self._getDist(edges, node2)
minDist = MAX
ans = -1
for i, (d1, d2) in enumerate(zip(dist1, dist2)):
if min(d1, d2) >= 0:
maxDist = m... | Solution |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_class_instantiated.py | {
"start": 564,
"end": 676
} | class ____(metaclass=abc.ABCMeta):
@abc.abstractmethod
def test(self):
""" do nothing. """
| BadClass |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/views.py | {
"start": 4743,
"end": 6148
} | class ____(View):
provider_class = OpenIDProvider
def get(self, request):
provider = self.provider = self.provider_class(request)
endpoint = request.GET.get("openid.op_endpoint", "")
client = self.get_client(provider, endpoint)
response = self.get_openid_response(client)
... | OpenIDCallbackView |
python | numba__numba | numba/tests/test_sets.py | {
"start": 15026,
"end": 15317
} | class ____(TestSets):
"""
Test sets with floating-point keys.
"""
# Only a few basic tests here, as the sanity of most operations doesn't
# depend on the key type.
def _range(self, stop):
return np.arange(stop, dtype=np.float32) * np.float32(0.1)
| TestFloatSets |
python | run-llama__llama_index | llama-index-core/tests/output_parsers/test_pydantic.py | {
"start": 311,
"end": 2029
} | class ____(BaseModel):
__test__ = False
title: str
attr_dict: AttrDict
def test_pydantic() -> None:
"""Test pydantic output parser."""
output = """\
Here is the valid JSON:
{
"title": "TestModel",
"attr_dict": {
"test_attr": "test_attr",
"foo": 2
... | TestModel |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 69590,
"end": 71767
} | class ____(unittest.TestCase):
def setUp(self):
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb
)
factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb
)
db = L... | FallBackDBTest |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 5599,
"end": 6459
} | class ____(UsageError):
"""Raised if click attempted to handle an option that does not
exist.
.. versionadded:: 4.0
"""
def __init__(self, option_name, message=None, possibilities=None, ctx=None):
if message is None:
message = "no such option: {}".format(option_name)
Us... | NoSuchOption |
python | aio-libs__aiohttp | aiohttp/http_exceptions.py | {
"start": 1538,
"end": 1626
} | class ____(PayloadEncodingError):
"""transfer encoding error."""
| TransferEncodingError |
python | scikit-learn__scikit-learn | sklearn/ensemble/_weight_boosting.py | {
"start": 28532,
"end": 39704
} | class ____(_RoutingNotSupportedMixin, RegressorMixin, BaseWeightBoosting):
"""An AdaBoost regressor.
An AdaBoost [1] regressor is a meta-estimator that begins by fitting a
regressor on the original dataset and then fits additional copies of the
regressor on the same dataset but where the weights of ins... | AdaBoostRegressor |
python | huggingface__transformers | src/transformers/models/qwen2_audio/modeling_qwen2_audio.py | {
"start": 10579,
"end": 11156
} | class ____(PreTrainedModel):
config: Qwen2AudioConfig
base_model_prefix = "model"
input_modalities = ("audio", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen2AudioAttention"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_... | Qwen2AudioPreTrainedModel |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 16396,
"end": 17677
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.flattop(6, sym=False, xp=xp),
xp.asarray([-0.000421051, -0.051263156, 0.19821053, 1.0,
0.19821053, -0.051263156], dtype=xp.float64))
xp_assert_close(windows.flattop(7, sym=Fals... | TestFlatTop |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/return_in_init.py | {
"start": 49,
"end": 99
} | class ____:
def __init__(self):
return
| A |
python | pola-rs__polars | py-polars/tests/unit/constructors/test_constructors.py | {
"start": 1563,
"end": 1646
} | class ____:
a: str
b: int
c: _TestBazDC
@dataclasses.dataclass
| _TestBarDC |
python | plotly__plotly.py | plotly/graph_objs/scattermapbox/hoverlabel/_font.py | {
"start": 233,
"end": 17174
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermapbox.hoverlabel"
_path_str = "scattermapbox.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc"... | Font |
python | has2k1__plotnine | plotnine/geoms/annotation_logticks.py | {
"start": 7178,
"end": 8969
} | class ____(annotate):
"""
Marginal log ticks.
If added to a plot that does not have a log10 axis
on the respective side, a warning will be issued.
Parameters
----------
sides :
Sides onto which to draw the marks. Any combination
chosen from the characters `btlr`, for *botto... | annotation_logticks |
python | python__mypy | mypy/test/teststubtest.py | {
"start": 6317,
"end": 8208
} | class ____:
def __init__(self, stub: str, runtime: str, error: str | None) -> None:
self.stub = stub
self.runtime = runtime
self.error = error
def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:
"""run_stubtest used to be slow, so we used this decorator to comb... | Case |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.