language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry | tests/sentry/db/models/fields/test_slug.py | {
"start": 255,
"end": 1049
} | class ____(TestCase):
def setUp(self) -> None:
self.field = SentrySlugField()
def test_combination_of_numeric_and_non_numeric(self) -> None:
# Valid slug value should not raise a ValidationError
self.field.run_validators("49dk20sk5-34fas")
def test_non_numeric(self) -> None:
... | TestSentrySlugField |
python | encode__django-rest-framework | tests/test_validation_error.py | {
"start": 400,
"end": 527
} | class ____(serializers.Serializer):
char = serializers.CharField()
integer = serializers.IntegerField()
| ExampleSerializer |
python | geekcomputers__Python | PongPong_Game/pong/ball.py | {
"start": 82,
"end": 1313
} | class ____(pyglet.shapes.Circle):
def __init__(self, *args, **kwargs):
super(BallObject, self).__init__(*args, **kwargs)
self.color = (255, 180, 0)
self.velocity_x, self.velocity_y = 0.0, 0.0
def update(self, win_size: Tuple, border: Tuple, other_object, dt) -> None:
speed = [
... | BallObject |
python | jazzband__django-formtools | tests/wizard/wizardtests/tests.py | {
"start": 12681,
"end": 13932
} | class ____(TestCase):
wizard_url = '/wiz_other_template/'
wizard_step_1_data = {
'cookie_contact_wizard-current_step': 'form1',
}
wizard_step_data = (
{
'form1-name': 'Pony',
'form1-thirsty': '2',
'cookie_contact_wizard-current_step': 'form1',
... | WizardTestKwargs |
python | modin-project__modin | modin/core/execution/ray/generic/partitioning/partition_manager.py | {
"start": 1041,
"end": 2273
} | class ____(PandasDataframePartitionManager):
"""The class implements the interface in `PandasDataframePartitionManager`."""
@classmethod
def to_numpy(cls, partitions, **kwargs):
"""
Convert `partitions` into a NumPy array.
Parameters
----------
partitions : NumPy ar... | GenericRayDataframePartitionManager |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 10215,
"end": 10275
} | class ____(_GroupsPermission):
pass
| GroupsPermissionOutput |
python | joke2k__faker | faker/providers/credit_card/uk_UA/__init__.py | {
"start": 210,
"end": 2110
} | class ____(CreditCardProvider):
"""Implement credit card provider for ``uk_UA`` locale.
https://blog.ipay.ua/uk/sekrety-bankovskix-kart-kak-identificirovat-bank-po-nomeru-karty/
"""
prefix_visa = ["4"]
prefix_mastercard = ["51", "52", "53", "54"]
prefix_prostir = ["9"]
prefix_maestro = ["67... | Provider |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 18379,
"end": 20239
} | class ____:
"""Descriptor for getting and setting spacing properties (e.g. padding and margin)."""
def __set_name__(self, owner: StylesBase, name: str) -> None:
self.name = name
def __get__(
self, obj: StylesBase, objtype: type[StylesBase] | None = None
) -> Spacing:
"""Get the... | SpacingProperty |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 15539,
"end": 15611
} | class ____(CmpOpIdentity):
pass
@infer_global(operator.is_not)
| CmpOpIs |
python | oauthlib__oauthlib | oauthlib/oauth1/rfc5849/__init__.py | {
"start": 2014,
"end": 16771
} | class ____:
"""A client used to sign OAuth 1.0 RFC 5849 requests."""
SIGNATURE_METHODS = {
SIGNATURE_HMAC_SHA1: signature.sign_hmac_sha1_with_client,
SIGNATURE_HMAC_SHA256: signature.sign_hmac_sha256_with_client,
SIGNATURE_HMAC_SHA512: signature.sign_hmac_sha512_with_client,
SIG... | Client |
python | getsentry__sentry | tests/acceptance/test_performance_summary.py | {
"start": 760,
"end": 8563
} | class ____(AcceptanceTestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(
organization=self.org, name="Mariachi Band", members=[self.user]
)
self.p... | PerformanceSummaryTest |
python | walkccc__LeetCode | solutions/3100. Water Bottles II/3100.py | {
"start": 0,
"end": 248
} | class ____:
def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
numBottles = numBottles - numExchange + 1
numExchange += 1
ans += 1
return ans
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bandit/S602.py | {
"start": 748,
"end": 1208
} | class ____:
def __init__(self):
self.shell_defaults = {}
def fetch_shell_config(self, username):
return {}
def run(self, username):
Popen("true", shell={**self.shell_defaults, **self.fetch_shell_config(username)})
# Additional truthiness cases for generator, lambda, and f-strings
... | ShellConfig |
python | pytorch__pytorch | torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py | {
"start": 461,
"end": 7869
} | class ____(LearnedHeuristicDecision):
def __init__(self) -> None:
self.choices: list[Choice] = []
self.fill_choices()
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
return (
metadata.name == self.get_name()
and metadata.shared_m... | MixedMMH100 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass2.py | {
"start": 313,
"end": 426
} | class ____(InterfaceA):
@abc.abstractmethod
def b(self) -> None:
print("InterfaceAB.b")
| InterfaceAB |
python | allegroai__clearml | examples/frameworks/pytorch/pytorch_matplotlib.py | {
"start": 7434,
"end": 10469
} | class ____(nn.Module):
def __init__(self, target, ):
super(ContentLoss, self).__init__()
# we 'detach' the target content from the tree used
# to dynamically compute the gradient: this is a stated value,
# not a variable. Otherwise the forward method of the criterion
# will ... | ContentLoss |
python | huggingface__transformers | tests/models/clap/test_feature_extraction_clap.py | {
"start": 3706,
"end": 31611
} | class ____(SequenceFeatureExtractionTestMixin, unittest.TestCase):
feature_extraction_class = ClapFeatureExtractor
# Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.setUp with Whisper->Clap
def setUp(self):
self.feat_extract_tester = ClapFeatureExtracti... | ClapFeatureExtractionTest |
python | google__python-fire | fire/console/console_attr.py | {
"start": 3623,
"end": 3977
} | class ____(BoxLineCharacters):
"""ASCII Box/line drawing characters."""
dl = '+'
dr = '+'
h = '-'
hd = '+'
hu = '+'
ul = '+'
ur = '+'
v = '|'
vh = '+'
vl = '+'
vr = '+'
d_dl = '#'
d_dr = '#'
d_h = '='
d_hd = '#'
d_hu = '#'
d_ul = '#'
d_ur = '#'
d_v = '#'
d_vh = '#'
d_vl = '#'... | BoxLineCharactersAscii |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/bedrock.py | {
"start": 2079,
"end": 2697
} | class ____(AwsBaseHook):
"""
Interact with the Amazon Agents for Bedrock API.
Provide thin wrapper around :external+boto3:py:class:`boto3.client("bedrock-agent") <AgentsforBedrock.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBas... | BedrockAgentHook |
python | PyCQA__pylint | tests/functional/r/regression/regression_property_no_member_844.py | {
"start": 135,
"end": 268
} | class ____:
def __init__(self):
self.__thing = 'foo'
@property
def thing(self):
return self.__thing
| Parent |
python | sanic-org__sanic | sanic/cli/executor.py | {
"start": 683,
"end": 2805
} | class ____:
def __init__(self, app: Sanic, kwargs: dict) -> None:
self.app = app
self.kwargs = kwargs
self.commands = self._make_commands()
self.parser = self._make_parser()
def run(self, command: str, args: list[str]) -> None:
if command == "exec":
args = ["... | Executor |
python | openai__openai-python | src/openai/types/beta/realtime/response_audio_transcript_delta_event.py | {
"start": 211,
"end": 773
} | class ____(BaseModel):
content_index: int
"""The index of the content part in the item's content array."""
delta: str
"""The transcript delta."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item."""
output_index: int
"""The index of th... | ResponseAudioTranscriptDeltaEvent |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 119371,
"end": 122473
} | class ____(DataplexCatalogBaseOperator):
"""
Get an EntryType resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogGetEntryTypeOperator`
:param entry_type_id: Required. EntryType identifier.
:param pr... | DataplexCatalogGetEntryTypeOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 13889,
"end": 13988
} | class ____(EventsMixin, RetargetingPartnersReport):
pass
# Source
| RetargetingPartnersEventsReport |
python | allegroai__clearml | clearml/backend_api/utils.py | {
"start": 3027,
"end": 8211
} | class ____(requests.Session):
"""requests.Session with a send timeout for requests with a content length header"""
write_timeout = (300.0, 300.0)
request_size_threshold = 15000
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(SessionWithTimeout, self).__init__(*args, **kwargs)
... | SessionWithTimeout |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/drip/tests.py | {
"start": 236,
"end": 684
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = DripProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"users":[{
"email": "john@acme.com",
"name": "John Doe",
"time_zone": "Amer... | DripTests |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/manifold.py | {
"start": 116,
"end": 820
} | class ____(Estimator, Benchmark):
"""
Benchmarks for t-SNE.
"""
param_names = ["method"]
params = (["exact", "barnes_hut"],)
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
(method,) = params
n_samples = 500 if method == "exact" else None... | TSNEBenchmark |
python | pandas-dev__pandas | pandas/util/version/__init__.py | {
"start": 5691,
"end": 13142
} | class ____(_BaseVersion):
_regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
_key: CmpKey
def __init__(self, version: str) -> None:
# Validate the version and parse it into pieces
match = self._regex.search(version)
if not match:
raise I... | Version |
python | getsentry__sentry | tests/sentry/mail/test_adapter.py | {
"start": 6738,
"end": 7180
} | class ____(BaseMailAdapterTest):
def test_default_prefix(self) -> None:
assert build_subject_prefix(self.project) == "[Sentry]"
def test_project_level_prefix(self) -> None:
prefix = "[Example prefix]"
ProjectOption.objects.set_value(
project=self.project, key="mail:subject_p... | MailAdapterBuildSubjectPrefixTest |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 21555,
"end": 22442
} | class ____(PreTrainedModel):
config: MoonshineConfig
base_model_prefix = "model"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
_no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
_supports_flash_attn = True
_supports... | MoonshinePreTrainedModel |
python | getsentry__sentry | tests/sentry/grouping/seer_similarity/test_get_seer_similar_issues.py | {
"start": 21648,
"end": 50364
} | class ____(TestCase):
@patch("sentry.grouping.ingest.seer.metrics.distribution")
@patch("sentry.grouping.ingest.seer.metrics.incr")
def test_simple(self, mock_incr: MagicMock, mock_distribution: MagicMock) -> None:
existing_event = save_new_event({"message": "Dogs are great!"}, self.project)
... | MultipleParentGroupsFoundTest |
python | walkccc__LeetCode | solutions/3229. Minimum Operations to Make Array Equal to Target/3229.py | {
"start": 0,
"end": 638
} | class ____:
# Similar to 1526. Minimum Number of Increments on Subarrays to Form a Target Array
def minimumOperations(self, nums: list[int], target: list[int]) -> int:
ans = abs(nums[0] - target[0])
for (prevNum, prevTarget), (currNum, currTarget) in (
itertools.pairwise(zip(nums, target))
):
... | Solution |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-siliconflow/llama_index/llms/siliconflow/base.py | {
"start": 5894,
"end": 19848
} | class ____(FunctionCallingLLM):
"""
SiliconFlow LLM.
Visit https://siliconflow.cn/ to get more information about SiliconFlow.
Examples:
`pip install llama-index-llms-siliconflow`
```python
from llama_index.llms.siliconflow import SiliconFlow
llm = SiliconFlow(api_key=... | SiliconFlow |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/some_virtual_mv/package.py | {
"start": 217,
"end": 791
} | class ____(Package):
"""Package providing a virtual dependency and with a multivalued variant."""
homepage = "http://www.example.com"
url = "http://www.example.com/foo-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
provides("somevirtual")
# This multi valued variant is ne... | SomeVirtualMv |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/auto_suggest.py | {
"start": 3746,
"end": 4488
} | class ____(AutoSuggest):
"""
Give suggestions based on the lines in the history.
"""
def get_suggestion(self, buffer: Buffer, document: Document) -> Suggestion | None:
history = buffer.history
# Consider only the last line for the suggestion.
text = document.text.rsplit("\n", 1... | AutoSuggestFromHistory |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 24722,
"end": 26561
} | class ____(IHaveNew):
"""This step input source models being downstream of another unresolved step,
for example indirectly downstream from a step with dynamic output.
"""
unresolved_step_output_handle: UnresolvedStepOutputHandle
# deprecated, preserved for back-compat
node_handle: NodeHandle
... | FromUnresolvedStepOutput |
python | wandb__wandb | wandb/vendor/pygments/lexers/forth.py | {
"start": 432,
"end": 7144
} | class ____(RegexLexer):
"""
Lexer for Forth files.
.. versionadded:: 2.2
"""
name = 'Forth'
aliases = ['forth']
filenames = ['*.frt', '*.fs']
mimetypes = ['application/x-forth']
delimiter = r'\s'
delimiter_end = r'(?=[%s])' % delimiter
valid_name_chars = r'[^%s]' % delimit... | ForthLexer |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 190377,
"end": 192850
} | class ____:
def test_basic(self, xp):
detrended = detrend(xp.asarray([1, 2, 3]))
detrended_exact = xp.asarray([0, 0, 0])
assert_array_almost_equal(detrended, detrended_exact)
@skip_xp_backends("jax.numpy", reason="overwrite_data not implemented")
def test_copy(self, xp):
x ... | TestDetrend |
python | doocs__leetcode | solution/0400-0499/0461.Hamming Distance/Solution.py | {
"start": 0,
"end": 105
} | class ____:
def hammingDistance(self, x: int, y: int) -> int:
return (x ^ y).bit_count()
| Solution |
python | skorch-dev__skorch | skorch/tests/test_probabilistic.py | {
"start": 4024,
"end": 4684
} | class ____(gpytorch.likelihoods.BernoulliLikelihood):
"""This class only exists to add a param to BernoulliLikelihood
BernoulliLikelihood used to have parameters before gpytorch v1.10, but now
it does not have any parameters anymore. This is not an issue per se, but
there are a few things we cannot tes... | MyBernoulliLikelihood |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 13018,
"end": 13291
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
######################################################################
| ulongLongTestCase |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 34730,
"end": 35625
} | class ____(HasherSpec):
"""A structure to specify a key of the strong keyed hash spec.
The strong hash requires a `key`, which is a list of 2 unsigned integer
numbers. These should be non-zero; random numbers generated from random.org
would be a fine choice.
Fields:
key: The key to be used by the keyed ... | StrongHashSpec |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 20614,
"end": 22010
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
... | GitVisionMLP |
python | pytorch__pytorch | test/profiler/test_profiler.py | {
"start": 95688,
"end": 95936
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
return self.fc2(self.fc1(x))
@dataclass(frozen=True)
| SimpleNet |
python | spack__spack | lib/spack/spack/error.py | {
"start": 4879,
"end": 5103
} | class ____(PackageError):
"""Raised when someone tries to build a URL for a package with no URLs."""
def __init__(self, cls):
super().__init__("Package %s has no version with a URL." % cls.__name__)
| NoURLError |
python | PrefectHQ__prefect | tests/blocks/test_core.py | {
"start": 87707,
"end": 87751
} | class ____(Block):
base: int = 0
| BaseBlock |
python | allegroai__clearml | clearml/backend_config/defs.py | {
"start": 1432,
"end": 2136
} | class ____(object):
"""Supported environment names"""
default = "default"
demo = "demo"
local = "local"
CONFIG_FILE_EXTENSION = ".conf"
def is_config_file(path: str) -> bool:
return Path(path).suffix == CONFIG_FILE_EXTENSION
def get_active_config_file() -> Optional[str]:
f = LOCAL_CONFIG_... | Environment |
python | EpistasisLab__tpot | tpot/search_spaces/nodes/estimator_node.py | {
"start": 1773,
"end": 4629
} | class ____(SklearnIndividual):
"""
Note that ConfigurationSpace does not support None as a parameter. Instead, use the special string "<NONE>". TPOT will automatically replace instances of this string with the Python None.
Parameters
----------
method : type
The class of the estimator to b... | EstimatorNodeIndividual |
python | scipy__scipy | scipy/io/_harwell_boeing/hb.py | {
"start": 14964,
"end": 19395
} | class ____:
def __init__(self, file, hb_info=None):
"""Create a HBFile instance.
Parameters
----------
file : file-object
StringIO work as well
hb_info : HBInfo, optional
Should be given as an argument for writing, in which case the file
s... | HBFile |
python | chroma-core__chroma | chromadb/api/collection_configuration.py | {
"start": 6798,
"end": 7934
} | class ____(TypedDict, total=False):
search_nprobe: int
write_nprobe: int
space: Space
ef_construction: int
ef_search: int
max_neighbors: int
reassign_neighbor_count: int
split_threshold: int
merge_threshold: int
def json_to_create_spann_configuration(
json_map: Dict[str, Any]
)... | CreateSpannConfiguration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/unit_tests/salesforce_describe_response_builder.py | {
"start": 153,
"end": 559
} | class ____:
def __init__(self) -> None:
self._fields = []
def field(self, name: str, _type: Optional[str] = None) -> "SalesforceDescribeResponseBuilder":
self._fields.append({"name": name, "type": _type if _type else "string"})
return self
def build(self) -> HttpResponse:
r... | SalesforceDescribeResponseBuilder |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/candidates.py | {
"start": 14324,
"end": 19107
} | class ____(Candidate):
"""A candidate that has 'extras', indicating additional dependencies.
Requirements can be for a project with dependencies, something like
foo[extra]. The extras don't affect the project/version being installed
directly, but indicate that we need additional dependencies. We model... | ExtrasCandidate |
python | apache__airflow | task-sdk/tests/task_sdk/bases/test_sensor.py | {
"start": 1776,
"end": 2034
} | class ____(BaseSensorOperator):
def __init__(self, return_value: bool | None = False, **kwargs):
super().__init__(**kwargs)
self.return_value = return_value
def poke(self, context: Context):
return self.return_value
| DummySensor |
python | bokeh__bokeh | src/bokeh/models/filters.py | {
"start": 3890,
"end": 4148
} | class ____(CompositeFilter):
""" Computes union of indices resulting from other filters. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| UnionFilter |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 2999,
"end": 6779
} | class ____(StepInputSource):
"""Load input value from an asset."""
# deprecated, preserved for back-compat
node_handle: NodeHandle = NodeHandle("", None)
input_name: str = ""
def load_input_object(
self,
step_context: "StepExecutionContext",
input_def: InputDefinition,
... | FromLoadableAsset |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_batch_prediction_job.py | {
"start": 10643,
"end": 15829
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = BatchPredictionJobAsyncHook(gcp_conn_id=TEST_GCP_CONN_ID)
@pytest.mark.asyncio
@mock.patch(BATCH_PREDICTION_JO... | TestBatchPredictionJobAsyncHook |
python | ray-project__ray | rllib/utils/actor_manager.py | {
"start": 2168,
"end": 4674
} | class ____:
"""Represents a list of results from calls to a set of actors.
CallResults provides convenient APIs to iterate over the results
while skipping errors, etc.
.. testcode::
:skipif: True
manager = FaultTolerantActorManager(
actors, max_remote_requests_in_flight_pe... | RemoteCallResults |
python | walkccc__LeetCode | solutions/1186. Maximum Subarray Sum with One Deletion/1186.py | {
"start": 0,
"end": 507
} | class ____:
# Similar to 53. Maximum Subarray
def maximumSum(self, arr: list[int]) -> int:
# dp[0][i] := the maximum sum subarray ending in i (no deletion)
# dp[1][i] := the maximum sum subarray ending in i (at most 1 deletion)
dp = [[0] * len(arr) for _ in range(2)]
dp[0][0] = arr[0]
dp[1][0] ... | Solution |
python | pytorch__pytorch | test/dynamo/test_config.py | {
"start": 224,
"end": 4268
} | class ____(torch._dynamo.test_case.TestCase):
@disable_cache_limit()
def test_no_automatic_dynamic(self):
def fn(a, b):
return a - b * 10
torch._dynamo.reset()
cnt_static = torch._dynamo.testing.CompileCounter()
with torch._dynamo.config.patch(
automatic_... | ConfigTests |
python | pytorch__pytorch | test/test_opaque_obj_v2.py | {
"start": 1637,
"end": 1977
} | class ____:
def __init__(self, start):
self.counter = torch.tensor(start)
def increment_counter(self):
self.counter += 1
register_opaque_type(OpaqueQueue, "_TestOpaqueObject_OpaqueQueue")
register_opaque_type(RNGState, "_TestOpaqueObject_RNGState")
register_opaque_type(Counter, "_TestOpaqueOb... | Counter |
python | pytorch__pytorch | torch/nn/utils/spectral_norm.py | {
"start": 370,
"end": 8237
} | class ____:
# Invariant before and after each forward call:
# u = F.normalize(W @ v)
# NB: At initialization, this invariant is not enforced
_version: int = 1
# At version 1:
# made `W` not a buffer,
# added `v` as a buffer, and
# made eval mode use `W = u @ W_orig @ v` rather ... | SpectralNorm |
python | jazzband__django-model-utils | tests/models.py | {
"start": 4841,
"end": 5153
} | class ____(StatusModel):
"""An abstract status model with a custom manager."""
STATUS = Choices(
("first_choice", _("First choice")),
("second_choice", _("Second choice")),
)
objects = StatusCustomManager()
class Meta:
abstract = True
| AbstractCustomManagerStatusModel |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_flows/client.py | {
"start": 5735,
"end": 10888
} | class ____(BaseAsyncClient):
async def create_flow(self, flow: "FlowObject[Any, Any]") -> "UUID":
"""
Create a flow in the Prefect API.
Args:
flow: a `Flow` object
Raises:
httpx.RequestError: if a flow was not created for any reason
Returns:
... | FlowAsyncClient |
python | tensorflow__tensorflow | tensorflow/compiler/tests/reduce_ops_test.py | {
"start": 1284,
"end": 7471
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
def _testReduction(self,
tf_reduce_fn,
np_reduce_fn,
dtype,
test_inputs,
index_dtype,
rtol=1e-4,
atol=1e-4):
... | ReduceOpsTest |
python | openai__openai-python | src/openai/_extras/pandas_proxy.py | {
"start": 338,
"end": 637
} | class ____(LazyProxy[Any]):
@override
def __load__(self) -> Any:
try:
import pandas
except ImportError as err:
raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err
return pandas
if not TYPE_CHECKING:
pandas = PandasProxy()
| PandasProxy |
python | dask__dask | dask/dataframe/dask_expr/_accessor.py | {
"start": 3233,
"end": 3753
} | class ____(Elemwise):
_parameters = ["frame", "accessor", "attr", "args", "kwargs"]
@functools.cached_property
def _meta(self):
args = [
meta_nonempty(op._meta) if isinstance(op, Expr) else op for op in self._args
]
return make_meta(self.operation(*args, **self._kwargs))... | FunctionMap |
python | python-poetry__poetry | tests/repositories/fixtures/pypi.org/generate.py | {
"start": 3930,
"end": 5982
} | class ____:
def __init__(self, locations: list[Path] | None = None) -> None:
self.locations = locations or [
RELEASE_FILE_LOCATIONS.dist,
RELEASE_FILE_LOCATIONS.stubbed,
]
def filename_exists(self, filename: str) -> bool:
return any(location.joinpath(filename).ex... | _ReleaseFileCollection |
python | scikit-learn__scikit-learn | sklearn/externals/array_api_compat/common/_typing.py | {
"start": 1859,
"end": 2762
} | class ____(Protocol[_T_co]):
@property
def shape(self, /) -> _T_co: ...
# Return type of `__array_namespace_info__.default_dtypes`
Capabilities = TypedDict(
"Capabilities",
{
"boolean indexing": bool,
"data-dependent shapes": bool,
"max dimensions": int,
},
)
# Return type... | HasShape |
python | pennersr__django-allauth | examples/react-spa/backend/backend/drf_demo/views.py | {
"start": 288,
"end": 796
} | class ____(APIView):
authentication_classes = [
authentication.SessionAuthentication,
XSessionTokenAuthentication,
]
permission_classes = [permissions.IsAuthenticated]
def get(self, request):
serializer = AddSerializer(data=request.GET)
serializer.is_valid(raise_exceptio... | AddAPIView |
python | lepture__authlib | authlib/integrations/base_client/errors.py | {
"start": 400,
"end": 484
} | class ____(OAuthError):
error = "unsupported_token_type"
| UnsupportedTokenTypeError |
python | numba__llvmlite | llvmlite/binding/context.py | {
"start": 222,
"end": 417
} | class ____(ffi.ObjectRef):
def __init__(self, context_ptr):
super(ContextRef, self).__init__(context_ptr)
def _dispose(self):
ffi.lib.LLVMPY_ContextDispose(self)
| ContextRef |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-box/llama_index/tools/box/text_extract/base.py | {
"start": 418,
"end": 2419
} | class ____(BaseToolSpec):
"""
Box Text Extraction Tool Specification.
This class provides a specification for extracting text content from Box files
and creating Document objects. It leverages the Box API to retrieve the
text representation (if available) of specified Box files.
Attributes:
... | BoxTextExtractToolSpec |
python | readthedocs__readthedocs.org | readthedocs/settings/proxito/test.py | {
"start": 91,
"end": 371
} | class ____(
CommunityProxitoSettingsMixin, CommunityTestSettings
):
PUBLIC_DOMAIN = "dev.readthedocs.io"
RTD_BUILD_MEDIA_STORAGE = "readthedocs.proxito.tests.storage.BuildMediaStorageTest"
CommunityProxitoTestSettings.load_settings(__name__)
| CommunityProxitoTestSettings |
python | Farama-Foundation__Gymnasium | tests/functional/test_functional.py | {
"start": 169,
"end": 2508
} | class ____(FuncEnv):
"""Generic testing functional environment."""
def __init__(self, options: dict[str, Any] | None = None):
"""Constructor that allows generic options to be set on the environment."""
super().__init__(options)
def initial(self, rng: Any, params=None) -> np.ndarray:
... | GenericTestFuncEnv |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 533,
"end": 679
} | class ____(Sitemap):
lastmod = date.today()
def items(self):
return [object() for x in range(Sitemap.limit + 1)]
| SimplePagedSitemap |
python | PyCQA__pydocstyle | src/tests/test_cases/test.py | {
"start": 257,
"end": 3268
} | class ____:
expect('meta', 'D419: Docstring is empty')
class meta:
""""""
@expect('D102: Missing docstring in public method')
def method(self=None):
pass
def _ok_since_private(self=None):
pass
@overload
def overloaded_method(self, a: int) -> str:
...
... | class_ |
python | huggingface__transformers | src/transformers/models/gpt2/modeling_gpt2.py | {
"start": 34779,
"end": 39424
} | class ____(GPT2PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
def __init__(self, config):
super().__init__(config)
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
#... | GPT2LMHeadModel |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/state.py | {
"start": 300,
"end": 457
} | class ____(BaseModel, extra=Extra.forbid):
strategy: Literal["docker"] = "docker"
python_version: Optional[str] = None
image: str
| DockerBuildOutput |
python | numba__numba | numba/tests/test_tuples.py | {
"start": 2408,
"end": 3069
} | class ____(unittest.TestCase):
'''
issue 4369
raise an error if 'type' is not iterable
'''
def test_namedtuple_types_exception(self):
with self.assertRaises(errors.TypingError) as raises:
types.NamedTuple(types.uint32, 'p')
self.assertIn(
"Argument 'types' is ... | TestTupleTypeNotIterable |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/cfg.py | {
"start": 5315,
"end": 5495
} | class ____(enum.Enum):
FORWARD = 1
REVERSE = 2
# TODO(mdan): Rename to DataFlowAnalyzer.
# TODO(mdan): Consider specializations that use gen/kill/transfer abstractions.
| _WalkMode |
python | huggingface__transformers | tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py | {
"start": 1917,
"end": 5202
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
"""
task_name: str | None = field(
default=None,
... | DataTrainingArguments |
python | scikit-learn__scikit-learn | sklearn/kernel_ridge.py | {
"start": 563,
"end": 9263
} | class ____(MultiOutputMixin, RegressorMixin, BaseEstimator):
"""Kernel ridge regression.
Kernel ridge regression (KRR) combines ridge regression (linear least
squares with l2-norm regularization) with the kernel trick. It thus
learns a linear function in the space induced by the respective kernel and
... | KernelRidge |
python | scikit-learn__scikit-learn | sklearn/exceptions.py | {
"start": 5007,
"end": 6176
} | class ____(UserWarning):
"""Warning raised when an estimator is unpickled with an inconsistent version.
Parameters
----------
estimator_name : str
Estimator name.
current_sklearn_version : str
Current scikit-learn version.
original_sklearn_version : str
Original scikit... | InconsistentVersionWarning |
python | openai__openai-python | src/openai/types/beta/threads/required_action_function_tool_call.py | {
"start": 220,
"end": 395
} | class ____(BaseModel):
arguments: str
"""The arguments that the model expects you to pass to the function."""
name: str
"""The name of the function."""
| Function |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/_typing.py | {
"start": 2774,
"end": 3030
} | class ____(Protocol):
"""protocol for the :class:`.AliasedInsp._orm_adapt_element` method
which is a synonym for :class:`.AliasedInsp._adapt_element`.
"""
def __call__(self, obj: _CE, key: Optional[str] = None) -> _CE: ...
| _ORMAdapterProto |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 648,
"end": 689
} | class ____[T, U,](): ...
# TypeVarTuple
| Test |
python | django__django | django/core/files/storage/handler.py | {
"start": 257,
"end": 1507
} | class ____:
def __init__(self, backends=None):
# backends is an optional dict of storage backend definitions
# (structured like settings.STORAGES).
self._backends = backends
self._storages = {}
@cached_property
def backends(self):
if self._backends is None:
... | StorageHandler |
python | walkccc__LeetCode | solutions/2817. Minimum Absolute Difference Between Elements With Constraint/2817.py | {
"start": 41,
"end": 416
} | class ____:
def minAbsoluteDifference(self, nums: list[int], x: int) -> int:
ans = math.inf
seen = SortedSet()
for i in range(x, len(nums)):
seen.add(nums[i - x])
it = seen.bisect_left(nums[i])
if it != len(seen):
ans = min(ans, seen[it] - nums[i])
if it != 0:
ans ... | Solution |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 32513,
"end": 33464
} | class ____(Blockwise, GroupByBase):
operation = staticmethod(groupby_get_group)
_parameters = ["frame", "get_key", "columns"]
_keyword_only = ["get_key", "columns"]
@property
def _args(self) -> list:
return [self.frame] + self.by
@property
def _kwargs(self) -> dict:
cols = ... | GetGroup |
python | keon__algorithms | tests/test_strings.py | {
"start": 16654,
"end": 16929
} | class ____(unittest.TestCase):
def test_min_distance(self):
self.assertEqual(2, min_distance_dp("sea", "eat"))
self.assertEqual(6, min_distance_dp("abAlgocrithmf", "Algorithmmd"))
self.assertEqual(4, min_distance("acbbd", "aabcd"))
| TestMinDistanceDP |
python | django__django | django/core/exceptions.py | {
"start": 6623,
"end": 6753
} | class ____(Exception):
"""The user tried to call a sync-only function from an async context."""
pass
| SynchronousOnlyOperation |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_uuid.py | {
"start": 2633,
"end": 5975
} | class ____(ColumnMapExpectation):
"""Expect column values to conform to valid UUID format."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_uuids": [
... | ExpectColumnValuesToBeValidUUID |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 1263,
"end": 2271
} | class ____(Completion):
"""Successful argument completion result."""
list_mode: bool
consumed: str
continuation: str
matches: list[str] = dataclasses.field(default_factory=list)
@property
def preserve(self) -> bool:
"""
True if argcomplete should not mangle completion value... | CompletionSuccess |
python | django__django | tests/update/models.py | {
"start": 667,
"end": 732
} | class ____(models.Model):
y = models.IntegerField(default=10)
| C |
python | pytorch__pytorch | torch/_export/db/examples/autograd_function.py | {
"start": 321,
"end": 652
} | class ____(torch.nn.Module):
"""
TorchDynamo does not keep track of backward() on autograd functions. We recommend to
use `allow_in_graph` to mitigate this problem.
"""
def forward(self, x):
return MyAutogradFunction.apply(x)
example_args = (torch.randn(3, 2),)
model = AutogradFunction()
| AutogradFunction |
python | django__django | tests/model_forms/models.py | {
"start": 6943,
"end": 7160
} | class ____(models.Model):
left = models.IntegerField()
middle = models.IntegerField()
right = models.IntegerField()
class Meta:
unique_together = (("left", "middle"), ("middle", "right"))
| Triple |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 28251,
"end": 29971
} | class ____(unittest.TestCase):
"""Tests person in the fr-BE locale"""
def setUp(self):
self.fake = Faker("fr-BE")
self.provider = FrBEProvider
Faker.seed(0)
def test_first_name(self):
# General first name
name = self.fake.first_name()
assert name
sel... | TestFrBE |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_arizona_zip.py | {
"start": 1729,
"end": 4054
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Arizona zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidArizonaZip |
python | neetcode-gh__leetcode | python/0554-brick-wall.py | {
"start": 0,
"end": 395
} | class ____:
def leastBricks(self, wall: List[List[int]]) -> int:
countGap = { 0 : 0 } # { Position : Gap count }
for r in wall:
total = 0 # Position
for b in r[:-1]:
total += b
countGap[total] = 1 + countGap.get(total, 0)
return ... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 13353,
"end": 14011
} | class ____:
def __init__(self):
super().__init__()
self.reuse_pool: dict[ReuseKey, list[FreeIfNotReusedLine]] = (
collections.defaultdict(list)
)
self.total_allocated_buffer_size: int = 0
def __contains__(self, key: ReuseKey) -> bool:
return bool(self.reuse_p... | MemoryPlanningState |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.