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 | doocs__leetcode | lcof2/剑指 Offer II 030. 插入、删除和随机访问都是 O(1) 的容器/Solution.py | {
"start": 0,
"end": 1188
} | class ____:
def __init__(self):
"""
Initialize your data structure here.
"""
self.a = []
self.m = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
... | RandomizedSet |
python | scipy__scipy | scipy/interpolate/tests/test_fitpack2.py | {
"start": 23257,
"end": 28604
} | class ____:
def test_linear_constant(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1)
for t in lut.get_knots():
assert_array_almost_equal(t, [1, 1, 3, 3])
assert_array_almost_equal... | TestSmoothBivariateSpline |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/PColorMeshItem.py | {
"start": 479,
"end": 594
} | class ____(enum.Flag):
XY = enum.auto()
Z = enum.auto()
LUT = enum.auto()
DIM = enum.auto()
| DirtyFlag |
python | crytic__slither | slither/core/source_mapping/source_mapping.py | {
"start": 683,
"end": 7276
} | class ____:
def __init__(self, compilation_unit: "SlitherCompilationUnit") -> None:
self.start: int = 0
self.length: int = 0
self.filename: Filename = Filename("", "", "", "")
self.is_dependency: bool = False
self.lines: List[int] = []
self.starting_column: int = 0
... | Source |
python | kevin1024__vcrpy | vcr/cassette.py | {
"start": 587,
"end": 5786
} | class ____:
"""Context manager/decorator that handles installing the cassette and
removing cassettes.
This class defers the creation of a new cassette instance until
the point at which it is installed by context manager or
decorator. The fact that a new cassette is used with each
application pr... | CassetteContextDecorator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_annotations/allow_overload.py | {
"start": 245,
"end": 558
} | class ____:
def bar(i):
return i
# TODO(charlie): This third case should raise an error (as in Mypy), because we have a
# statement between the interfaces and implementation.
@overload
def baz(i: int) -> "int":
...
@overload
def baz(i: "str") -> "str":
...
x = 1
def baz(i):
return i
| X |
python | apache__thrift | lib/py/src/transport/TTransport.py | {
"start": 3211,
"end": 3352
} | class ____(object):
"""Base class for a Transport Factory"""
def getTransport(self, trans):
return trans
| TTransportFactoryBase |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 205899,
"end": 206664
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("assignees",)
assignees = sgqlc.types.Field(
sgqlc.types.non_null("UserConnection"),
graphql_name="assignees",
args=sgqlc.types.ArgDict(
(... | Assignable |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modular_instructblipvideo.py | {
"start": 6749,
"end": 6823
} | class ____(InstructBlipQFormerModel):
pass
| InstructBlipVideoQFormerModel |
python | run-llama__llama_index | llama-index-core/tests/tools/test_eval_query_engine_tool.py | {
"start": 1005,
"end": 1190
} | class ____(CustomQueryEngine):
"""Custom query engine."""
def custom_query(self, query_str: str) -> str:
"""Query."""
return "custom_" + query_str
| MockQueryEngine |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_calendar.py | {
"start": 1201,
"end": 7083
} | class ____:
DAG_NAME = "test_dag1"
@pytest.fixture(autouse=True)
@provide_session
def setup_dag_runs(self, dag_maker, session=None) -> None:
clear_db_runs()
clear_db_dags()
with dag_maker(
self.DAG_NAME,
schedule="0 0,1 * * *",
start_date=date... | TestCalendar |
python | PyCQA__pylint | pylint/checkers/variables.py | {
"start": 1977,
"end": 17967
} | class ____(Enum):
"""Reported by _check_consumer() and its sub-methods to determine the
subsequent action to take in _undefined_and_used_before_checker().
Continue -> continue loop to next consumer
Return -> return and thereby break the loop
"""
CONTINUE = 0
RETURN = 1
def _is_from_futur... | VariableVisitConsumerAction |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax.py | {
"start": 1533,
"end": 1602
} | class ____:
my_var: int | str
@dataclasses.dataclass
| CustomDataClass |
python | django__django | django/core/management/commands/dbshell.py | {
"start": 139,
"end": 1762
} | class ____(BaseCommand):
help = (
"Runs the command-line client for specified database, or the "
"default database if none is provided."
)
requires_system_checks = []
def add_arguments(self, parser):
parser.add_argument(
"--database",
default=DEFAULT_DB_... | Command |
python | apache__airflow | providers/snowflake/tests/unit/snowflake/operators/test_snowflake.py | {
"start": 4554,
"end": 5149
} | class ____:
@mock.patch("airflow.providers.common.sql.operators.sql.SQLCheckOperator.get_db_hook")
def test_get_db_hook(
self,
mock_get_db_hook,
):
operator = SnowflakeCheckOperator(
task_id="snowflake_check",
snowflake_conn_id="snowflake_default",
... | TestSnowflakeCheckOperator |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 10241,
"end": 10551
} | class ____(models.Model):
name = models.CharField(max_length=100)
history = HistoricalRecords()
def save(self, *args, **kwargs):
if hasattr(self, "skip_history_when_saving"):
raise RuntimeError("error while saving")
else:
super().save(*args, **kwargs)
| Person |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 87226,
"end": 87463
} | class ____(openblas_ilp64_info):
# ILP64 Openblas, with default symbol suffix
section = 'openblas64_'
dir_env_var = 'OPENBLAS64_'
_lib_names = ['openblas64_']
symbol_suffix = '64_'
symbol_prefix = ''
| openblas64__info |
python | pypa__pip | src/pip/_vendor/platformdirs/macos.py | {
"start": 193,
"end": 6322
} | class ____(PlatformDirsABC):
"""
Platform directories for the macOS operating system.
Follows the guidance from
`Apple documentation <https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html>`_.
Makes use... | MacOS |
python | Netflix__metaflow | metaflow/package/__init__.py | {
"start": 796,
"end": 1384
} | class ____(MetaflowException):
headline = "Non-unique file path for a file name included in code package"
def __init__(self, filename, file_paths, lineno=None):
msg = (
"Filename %s included in the code package includes multiple different "
"paths for the same name : %s.\n"
... | NonUniqueFileNameToFilePathMappingException |
python | python-markdown__markdown | tests/test_apis.py | {
"start": 16926,
"end": 22761
} | class ____(unittest.TestCase):
""" Test the html and xhtml serializers. """
def testHtml(self):
""" Test HTML serialization. """
el = etree.Element('div')
el.set('id', 'foo<&">')
p = etree.SubElement(el, 'p')
p.text = 'foo <&escaped>'
p.set('hidden', 'hidden')
... | testSerializers |
python | ray-project__ray | python/ray/tune/utils/mock.py | {
"start": 254,
"end": 2197
} | class ____(Callback):
"""Adds random failure injection to the TrialExecutor."""
def __init__(
self,
config_path="~/ray_bootstrap_config.yaml",
probability=0.1,
time_between_checks=0,
disable=False,
):
self.probability = probability
self.config_path = ... | FailureInjectorCallback |
python | wandb__wandb | wandb/vendor/pygments/lexers/grammar_notation.py | {
"start": 1799,
"end": 3686
} | class ____(RegexLexer):
"""
Lexer for `IETF 7405 ABNF
<http://www.ietf.org/rfc/rfc7405.txt>`_
(Updates `5234 <http://www.ietf.org/rfc/rfc5234.txt>`_)
grammars.
.. versionadded:: 2.1
"""
name = 'ABNF'
aliases = ['abnf']
filenames = ['*.abnf']
mimetypes = ['text/x-abnf']
... | AbnfLexer |
python | huggingface__transformers | tests/models/mask2former/test_image_processing_mask2former.py | {
"start": 6289,
"end": 29654
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = Mask2FormerImageProcessor if (is_vision_available() and is_torch_available()) else None
fast_image_processing_class = (
Mask2FormerImageProcessorFast if (is_vision_available() and is_torchvision_available()) else None
... | Mask2FormerImageProcessingTest |
python | PrefectHQ__prefect | src/prefect/server/schemas/sorting.py | {
"start": 546,
"end": 2101
} | class ____(AutoEnum):
"""Defines flow run sorting options."""
ID_DESC = AutoEnum.auto()
START_TIME_ASC = AutoEnum.auto()
START_TIME_DESC = AutoEnum.auto()
EXPECTED_START_TIME_ASC = AutoEnum.auto()
EXPECTED_START_TIME_DESC = AutoEnum.auto()
NAME_ASC = AutoEnum.auto()
NAME_DESC = AutoEnum... | FlowRunSort |
python | neetcode-gh__leetcode | python/0540-single-element-in-a-sorted-array.py | {
"start": 0,
"end": 829
} | class ____:
def singleNonDuplicate(self, nums: List[int]) -> int:
def is_non_duplicate(i):
is_left_different = i == 0 or nums[i-1] != nums[i]
is_right_different = i == len(nums)-1 or nums[i+1] != nums[i]
return is_left_different and is_right_different
if len(nums... | Solution |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 26677,
"end": 28586
} | class ____(BaseDataset):
"""
Feature: Datasets created with a compression code
"""
@pytest.mark.thread_unsafe(reason="monkey-patch")
def test_compression_number(self):
""" Create with compression number of gzip (h5py.h5z.FILTER_DEFLATE) and a compression level of 7"""
original_c... | TestCreateCompressionNumber |
python | huggingface__transformers | tests/generation/test_fsdp.py | {
"start": 4552,
"end": 5702
} | class ____(TestCasePlus):
@require_torch_multi_accelerator
def test_fsdp_generate(self):
device_count = backend_device_count(torch_device)
distributed_args = f"""--nproc_per_node={device_count}
--master_port={get_torch_dist_unique_port()}
{self.test_file_dir}/test_fsdp.py... | TestFSDPGeneration |
python | streamlit__streamlit | lib/tests/streamlit/elements/button_group_test.py | {
"start": 7348,
"end": 13366
} | class ____(DeltaGeneratorTestCase):
"""Tests that are specific for the feedback command."""
@parameterized.expand(
[
("thumbs", list(_THUMB_ICONS)),
("faces", list(_FACES_ICONS)),
("stars", list([_STAR_ICON] * 5)),
]
)
def test_call_feedback_with_all_... | TestFeedbackCommand |
python | pytorch__pytorch | torch/testing/_internal/distributed/distributed_test.py | {
"start": 7469,
"end": 7710
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc = nn.Linear(10, 50, bias=True)
self.fc.bias.requires_grad = False
def forward(self, x):
x = self.fc(x)
return x
| _FC2 |
python | nedbat__coveragepy | tests/test_files.py | {
"start": 30081,
"end": 30316
} | class ____(CoverageTest):
"""Windows-specific tests of file name handling."""
run_in_temp_dir = False
def test_actual_path(self) -> None:
assert actual_path(r"c:\Windows") == actual_path(r"C:\wINDOWS")
| WindowsFileTest |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/xcom_arg.py | {
"start": 16948,
"end": 18463
} | class ____(XComArg):
"""
An XCom reference with ``zip()`` applied.
This is constructed from multiple XComArg instances, and presents an
iterable that "zips" them together like the built-in ``zip()`` (and
``itertools.zip_longest()`` if ``fillvalue`` is provided).
"""
args: Sequence[XComArg]... | ZipXComArg |
python | realpython__materials | duck-typing-python/vehicles_abc.py | {
"start": 711,
"end": 913
} | class ____(Vehicle):
def start(self):
print("The truck is starting")
def stop(self):
print("The truck is stopping")
def drive(self):
print("The truck is driving")
| Truck |
python | walkccc__LeetCode | solutions/3194. Minimum Average of Smallest and Largest Elements/3194.py | {
"start": 0,
"end": 177
} | class ____:
def minimumAverage(self, nums: list[int]) -> float:
nums.sort()
return min((nums[i] + nums[~i]) / 2
for i in range(len(nums) // 2 + 1))
| Solution |
python | pytorch__pytorch | torch/onnx/ops/_symbolic_impl.py | {
"start": 889,
"end": 11765
} | class ____:
"""Class to encode attributes from dictionary into lists of FX compatible attributes.
Since FX does not support dictionaries, we need to encode the attributes into
lists. This class provides a way to encode and decode the attributes.
Attributes:
attr_keys: List of attribute keys.
... | EncodedAttrs |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 12298,
"end": 13899
} | class ____(LossFunctionWrapper):
"""Computes the logarithm of the hyperbolic cosine of the prediction error.
Formula:
```python
error = y_pred - y_true
logcosh = mean(log((exp(error) + exp(-error))/2), axis=-1)`
```
where x is the error `y_pred - y_true`.
Args:
reduction: Type... | LogCosh |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 18989,
"end": 19871
} | class ____(nn.Module):
def __init__(self, config):
"""
Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
up training throughput.
"""
super().__init__()
self.input_dim = config.adapter_attn_dim
self.hi... | HubertAttnAdapterLayer |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 229156,
"end": 230333
} | class ____(multi_rv_frozen):
def __init__(self, alpha, n, seed=None):
alpha, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
self.alpha = alpha
self.n = n
self._dist = dirichlet_multinomial_gen(seed)
def logpmf(self, x):
return self._dist.logpmf(x, self.alpha, ... | dirichlet_multinomial_frozen |
python | huggingface__transformers | tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py | {
"start": 1367,
"end": 1655
} | class ____(ConfigTester):
def create_and_test_config_common_properties(self):
config = self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(config, "tf_padding"))
self.parent.assertTrue(hasattr(config, "depth_multiplier"))
| MobileNetV1ConfigTester |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_member_invite_details.py | {
"start": 1063,
"end": 1332
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-member-invite-details"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
@with_feature("organizations:new-organization-member-invite")
| OrganizationMemberInviteTestBase |
python | redis__redis-py | tests/test_asyncio/test_pubsub.py | {
"start": 22502,
"end": 22777
} | class ____:
async def test_channel_subscribe(self, r: redis.Redis):
r = redis.Redis(host="localhost", port=6390)
p = r.pubsub()
with pytest.raises(ConnectionError):
await p.subscribe("foo")
@pytest.mark.onlynoncluster
| TestPubSubRedisDown |
python | walkccc__LeetCode | solutions/1622. Fancy Sequence/1622.py | {
"start": 0,
"end": 1162
} | class ____:
def __init__(self):
self.MOD = 1_000_000_007
# For each `val` in `vals`, it actually represents a * val + b.
self.vals = []
self.a = 1
self.b = 0
# To undo a * val + b and get the original value, we append (val - b) // a.
# By Fermat's little theorem:
# a^(p - 1) ≡ 1 (mod p)
... | Fancy |
python | jina-ai__jina | jina/proto/serializer.py | {
"start": 6931,
"end": 7917
} | class ____:
"""Placeholder that delegates the serialization and deserialization to the internal protobuf"""
@staticmethod
def SerializeToString(x: 'SingleDocumentRequest'):
"""
# noqa: DAR101
# noqa: DAR102
# noqa: DAR201
"""
if not x.is_decompressed:
... | SingleDocumentRequestProto |
python | huggingface__transformers | src/transformers/models/segformer/image_processing_segformer_fast.py | {
"start": 1781,
"end": 9225
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"height": 512, "width": 512}
default_to_square = True
crop_size = None
do_resize = True
do_center_crop = None
do_rescale = True
d... | SegformerImageProcessorFast |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 894,
"end": 1201
} | class ____(MultibandFilter):
filterargs: tuple[Any, ...]
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
if image.mode == "P":
msg = "cannot filter palette images"
raise ValueError(msg)
return image.filter(*self.filterargs)
| BuiltinFilter |
python | pytorch__pytorch | torch/autograd/profiler_legacy.py | {
"start": 684,
"end": 12210
} | class ____:
"""DEPRECATED: use torch.profiler instead."""
def __init__(
self,
enabled=True,
*,
use_cuda=False,
record_shapes=False,
with_flops=False,
profile_memory=False,
with_stack=False,
with_modules=False,
):
self.enabled: ... | profile |
python | getsentry__sentry | tests/sentry/sentry_metrics/test_base_indexer.py | {
"start": 7419,
"end": 15045
} | class ____(TestCase):
def test_basic(self) -> None:
use_case_key_results = UseCaseKeyResults()
assert use_case_key_results.results == {}
assert use_case_key_results.get_mapped_results() == {}
assert use_case_key_results.get_mapped_strings_to_ints() == {}
use_case_collection... | UseCaseResultsTest |
python | getsentry__sentry | src/sentry/api/helpers/group_index/validators/inbox_details.py | {
"start": 67,
"end": 172
} | class ____(serializers.Serializer[Never]):
# Support undo / snooze reasons
pass
| InboxDetailsValidator |
python | pytorch__pytorch | torch/distributed/checkpoint/_experimental/barriers.py | {
"start": 5214,
"end": 9137
} | class ____(Barrier):
"""
A barrier implementation using PyTorch's TCPStore for synchronization.
This barrier uses a TCP-based distributed key-value store to coordinate
synchronization across multiple processes. It uses a single TCP store
for all barrier operations, with different prefixes to distin... | TCPStoreBarrier |
python | huggingface__transformers | src/transformers/models/edgetam_video/modular_edgetam_video.py | {
"start": 31171,
"end": 31239
} | class ____(Sam2VideoMemoryEncoder):
pass
| EdgeTamVideoMemoryEncoder |
python | getsentry__sentry | src/sentry/auth/access.py | {
"start": 25484,
"end": 26084
} | class ____(OrganizationGlobalAccess):
"""Access to all an organization's teams and projects with simulated membership."""
@property
def team_ids_with_membership(self) -> frozenset[int]:
return self.accessible_team_ids
@property
def project_ids_with_team_membership(self) -> frozenset[int]:
... | OrganizationGlobalMembership |
python | keon__algorithms | algorithms/maths/polynomial.py | {
"start": 10324,
"end": 22052
} | class ____:
"""
A simple implementation
of a polynomial class that
records the details about two polynomials
that are potentially comprised of multiple
variables.
"""
def __init__(self, monomials: Iterable[Union[int, float, Fraction, Monomial]]) -> None:
'''
Create a poly... | Polynomial |
python | doocs__leetcode | solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution.py | {
"start": 192,
"end": 681
} | class ____:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
if n <= 0:
return None
v = preorder[i]
k = d[v]
l = dfs(i + 1, j, k - j)
r = dfs(... | Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_glue_crawler.py | {
"start": 1069,
"end": 3633
} | class ____:
def setup_method(self):
self.sensor = GlueCrawlerSensor(
task_id="test_glue_crawler_sensor",
crawler_name="aws_test_glue_crawler",
poke_interval=1,
timeout=5,
aws_conn_id="aws_default",
)
@mock.patch.object(GlueCrawlerHook,... | TestGlueCrawlerSensor |
python | getsentry__sentry | tests/sentry/middleware/test_devtoolbar.py | {
"start": 597,
"end": 6876
} | class ____(TestCase):
middleware = cached_property(DevToolbarAnalyticsMiddleware)
analytics_event_name = DevToolbarApiRequestEvent.type
@cached_property
def factory(self):
return RequestFactory()
def setUp(self) -> None:
# Allows changing the get_response mock for each test.
... | DevToolbarAnalyticsMiddlewareUnitTest |
python | kubernetes-client__python | kubernetes/client/models/v1_device_class_spec.py | {
"start": 383,
"end": 7192
} | 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... | V1DeviceClassSpec |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_management_test.py | {
"start": 5192,
"end": 10892
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def testAbsPath(self):
save_dir = self._get_test_dir("abs_paths")
abs_path = os.path.join(save_dir, "model-0")
ckpt = checkpoint_manag... | CheckpointStateTest |
python | facebookresearch__faiss | tests/torch_test_neural_net.py | {
"start": 8931,
"end": 9979
} | class ____(unittest.TestCase):
@torch.no_grad()
def test_decode(self):
torch.manual_seed(123)
qinco = QINCo(d=16, K=20, L=2, M=3, h=8)
codes = torch.randint(0, 20, (10, 3))
x_ref = qinco.decode(codes)
qinco2 = faiss.QINCo(qinco)
codes2 = faiss.Int32Tensor2D(code... | TestQINCo |
python | doocs__leetcode | solution/3600-3699/3627.Maximum Median Sum of Subsequences of Size 3/Solution.py | {
"start": 0,
"end": 138
} | class ____:
def maximumMedianSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[len(nums) // 3 :: 2])
| Solution |
python | psf__black | tests/data/cases/class_blank_parentheses.py | {
"start": 737,
"end": 978
} | class ____(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc:
pass
| ClassWithEmptyFunc |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 79269,
"end": 80034
} | class ____(TestCase):
def setUp(self):
super().setUp()
assert requests.post(settings.SENTRY_SNUBA + "/tests/outcomes/drop").status_code == 200
def store_outcomes(self, outcome, num_times=1):
outcomes = []
for _ in range(num_times):
outcome_copy = outcome.copy()
... | OutcomesSnubaTest |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 11377,
"end": 14190
} | class ____(nn.Module):
def __init__(self, config, index, dim, focal_factor=2, bias=True, projection_dropout=0.0):
super().__init__()
self.dim = dim
self.focal_window = config.focal_windows[index]
self.focal_level = config.focal_levels[index]
self.focal_factor = focal_factor
... | FocalNetModulation |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 6385,
"end": 11909
} | class ____:
def setup_method(self):
with mock.patch(
MODULE_NAME + ".GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.instance = hook.GoogleBaseHook(gcp_conn_id="google-cloud-default")
def test_provide_gcp_credential_file_decorator... | TestProvideGcpCredentialFile |
python | celery__celery | t/unit/utils/test_time.py | {
"start": 9229,
"end": 11850
} | class ____:
def test_standard_tz(self):
class tzz(tzinfo):
def utcoffset(self, dt):
return None # Mock no utcoffset specified
tz = tzz()
assert localize(make_aware(datetime.now(_timezone.utc), tz), tz)
@patch('dateutil.tz.datetime_ambiguous')
def test... | test_localize |
python | bokeh__bokeh | src/bokeh/application/handlers/server_request_handler.py | {
"start": 1748,
"end": 4387
} | class ____(RequestHandler):
''' Load a script which contains server request handler callbacks.
'''
_module: ModuleType
def __init__(self, *, filename: PathLike, argv: list[str] = [], package: ModuleType | None = None) -> None:
'''
Keyword Args:
filename (str) : path to a ... | ServerRequestHandler |
python | walkccc__LeetCode | solutions/1863. Sum of All Subset XOR Totals/1863-2.py | {
"start": 0,
"end": 131
} | class ____:
def subsetXORSum(self, nums: list[int]) -> int:
return functools.reduce(operator.or_, nums) << len(nums) - 1
| Solution |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/configurable.py | {
"start": 15347,
"end": 24053
} | class ____(DynamicRunnable[Input, Output]):
"""`Runnable` that can be dynamically configured.
A `RunnableConfigurableAlternatives` should be initiated using the
`configurable_alternatives` method of a `Runnable` or can be
initiated directly as well.
Here is an example of using a `RunnableConfigura... | RunnableConfigurableAlternatives |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/glue_databrew.py | {
"start": 978,
"end": 2593
} | class ____(AwsBaseWaiterTrigger):
"""
Watches for a Glue DataBrew job, triggers when it finishes.
:param job_name: Glue DataBrew job name
:param run_id: the ID of the specific run to watch for that job
:param waiter_delay: Number of seconds to wait between two checks. Default is 30 seconds.
:pa... | GlueDataBrewJobCompleteTrigger |
python | walkccc__LeetCode | solutions/57. Insert Interval/57.py | {
"start": 0,
"end": 596
} | class ____:
def insert(self, intervals: list[list[int]],
newInterval: list[int]) -> list[list[int]]:
n = len(intervals)
ans = []
i = 0
while i < n and intervals[i][1] < newInterval[0]:
ans.append(intervals[i])
i += 1
# Merge overlapping intervals.
while i < n and int... | Solution |
python | django__django | tests/m2m_multiple/models.py | {
"start": 471,
"end": 908
} | class ____(models.Model):
headline = models.CharField(max_length=50)
pub_date = models.DateTimeField()
primary_categories = models.ManyToManyField(
Category, related_name="primary_article_set"
)
secondary_categories = models.ManyToManyField(
Category, related_name="secondary_article_... | Article |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py | {
"start": 3248,
"end": 8088
} | class ____:
def test_K4_normalized(self):
"Approximate current-flow betweenness centrality: K4 normalized"
G = nx.complete_graph(4)
b = nx.current_flow_betweenness_centrality(G, normalized=True)
epsilon = 0.1
ba = approximate_cfbc(G, normalized=True, epsilon=0.5 * epsilon)
... | TestApproximateFlowBetweennessCentrality |
python | doocs__leetcode | solution/1400-1499/1401.Circle and Rectangle Overlapping/Solution.py | {
"start": 0,
"end": 455
} | class ____:
def checkOverlap(
self,
radius: int,
xCenter: int,
yCenter: int,
x1: int,
y1: int,
x2: int,
y2: int,
) -> bool:
def f(i: int, j: int, k: int) -> int:
if i <= k <= j:
return 0
return i - k ... | Solution |
python | redis__redis-py | redis/exceptions.py | {
"start": 2078,
"end": 2242
} | class ____(RedisError):
"""
Cluster errors occurred multiple times, resulting in an exhaustion of the
command execution TTL
"""
pass
| ClusterError |
python | pytorch__pytorch | test/quantization/fx/test_quantize_fx.py | {
"start": 380569,
"end": 404006
} | class ____(QuantizationTestCase):
@skipIfNoFBGEMM
@unittest.skipIf(not TEST_CUDA, "gpu is not available.")
def test_static_gpu_convert_basic(self):
class Net(nn.Module):
def __init__(self) -> None:
super().__init__()
self.relu1 = nn.ReLU()
... | TestQuantizeFxModels |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 1401,
"end": 4073
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.E... | NystromformerEmbeddings |
python | pola-rs__polars | py-polars/src/polars/series/series.py | {
"start": 4599,
"end": 273868
} | class ____:
"""
A Series represents a single column in a Polars DataFrame.
Parameters
----------
name : str, default None
Name of the Series. Will be used as a column name when used in a DataFrame.
When not specified, name is set to an empty string.
values : ArrayLike, default N... | Series |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/gcp.py | {
"start": 404,
"end": 967
} | class ____(CloudProvider):
"""GCP cloud provider plugin. Sets up cloud resources before delegation."""
def __init__(self, args: IntegrationConfig) -> None:
super().__init__(args)
self.uses_config = True
def setup(self) -> None:
"""Setup the cloud resource before delegation and reg... | GcpCloudProvider |
python | pytorch__pytorch | test/onnx/ops/test_ops.py | {
"start": 2672,
"end": 15957
} | class ____(common_utils.TestCase):
def test_symbolic_accepts_valid_inputs(self):
output = torch.onnx.ops.symbolic(
"custom_domain::CustomOp",
(torch.tensor(1),),
dict(
int_key=1,
float_key=1.0,
str_key="attr",
... | SymbolicOpsTest |
python | catalyst-team__catalyst | catalyst/callbacks/misc.py | {
"start": 4607,
"end": 8454
} | class ____(Callback):
"""Logs pipeline execution time.
.. code-block:: python
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
# data
num_samples, num_features = int(1e4), int(1e1)
X, y = torch.rand(num_samples, num_fe... | TimerCallback |
python | ray-project__ray | doc/source/serve/doc_code/streaming_tutorial.py | {
"start": 3109,
"end": 6345
} | 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)
# __chatbot_constructor_end__
# __c... | Chatbot |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 31572,
"end": 34936
} | class ____(YosoPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.yoso = YosoModel(config)
self.classifier = YosoClassificationHead(config)
# Initialize weights and apply final processing
self.post_init()
... | YosoForSequenceClassification |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/installation_details.py | {
"start": 1208,
"end": 4243
} | class ____(SentryAppInstallationBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"DELETE": ApiPublishStatus.UNKNOWN,
"GET": ApiPublishStatus.UNKNOWN,
"PUT": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, installation) -> Response:
return Respo... | SentryAppInstallationDetailsEndpoint |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 32975,
"end": 34414
} | class ____(rv_continuous):
r"""A Bradford continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `bradford` is:
.. math::
f(x, c) = \frac{c}{\log(1+c) (1+cx)}
for :math:`0 <= x <= 1` and :math:`c > 0`.
`bradford` takes ``c`` as a shape... | bradford_gen |
python | pytorch__pytorch | torch/_inductor/exc.py | {
"start": 2228,
"end": 2460
} | class ____(RuntimeError):
def __init__(self) -> None:
from . import config
super().__init__(
f"No working C++ compiler found in {config.__name__}.cpp.cxx: {config.cpp.cxx}"
)
| InvalidCxxCompiler |
python | getsentry__sentry | tests/sentry/incidents/subscription_processor/test_subscription_processor_base.py | {
"start": 1186,
"end": 8110
} | class ____(TestCase, SpanTestCase, SnubaTestCase):
@pytest.fixture(autouse=True)
def _setup_metrics_patch(self):
with mock.patch("sentry.incidents.subscription_processor.metrics") as self.metrics:
yield
def setUp(self) -> None:
super().setUp()
self._run_tasks = self.task... | ProcessUpdateBaseClass |
python | tiangolo__fastapi | docs_src/body_updates/tutorial001_py39.py | {
"start": 150,
"end": 900
} | class ____(BaseModel):
name: Union[str, None] = None
description: Union[str, None] = None
price: Union[float, None] = None
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.... | Item |
python | keon__algorithms | tests/test_strings.py | {
"start": 2941,
"end": 3245
} | class ____(unittest.TestCase):
"""[summary]
Test for the file delete_reoccurring.py
Arguments:
unittest {[type]} -- [description]
"""
def test_delete_reoccurring_characters(self):
self.assertEqual("abc", delete_reoccurring_characters("aaabcccc"))
| TestDeleteReoccurring |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 83658,
"end": 84157
} | class ____(PrefectFilterBaseModel):
"""Filter by `Variable.id`."""
any_: Optional[list[UUID]] = Field(
default=None, description="A list of variable ids to include"
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
filt... | VariableFilterId |
python | mlflow__mlflow | tests/store/tracking/test_plugin_validation.py | {
"start": 1588,
"end": 2902
} | class ____(SqlAlchemyStore):
pass
"""
subprocess.check_call([sys.executable, "-c", code], timeout=20)
def test_plugin_can_create_dataset_without_name_error(tmp_path):
"""
Regression test for plugin runtime usage (https://github.com/mlflow/mlflow/issues/18386).
Store plugins that inherit from Sq... | CustomTrackingStore |
python | huggingface__transformers | tests/models/deberta_v2/test_modeling_deberta_v2.py | {
"start": 12095,
"end": 12947
} | class ____(unittest.TestCase):
@unittest.skip(reason="Model not available yet")
def test_inference_masked_lm(self):
pass
@slow
def test_inference_no_head(self):
model = DebertaV2Model.from_pretrained("microsoft/deberta-v2-xlarge")
input_ids = torch.tensor([[0, 31414, 232, 328, ... | DebertaV2ModelIntegrationTest |
python | cython__cython | docs/examples/tutorial/cdef_classes/math_function.py | {
"start": 0,
"end": 202
} | class ____(object):
def __init__(self, name, operator):
self.name = name
self.operator = operator
def __call__(self, *operands):
return self.operator(*operands)
| MathFunction |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_system_message_param.py | {
"start": 466,
"end": 1226
} | class ____(TypedDict, total=False):
content: Required[Iterable[Content]]
"""The content of the message."""
role: Required[Literal["system"]]
"""The role of the message sender. Always `system`."""
type: Required[Literal["message"]]
"""The type of the item. Always `message`."""
id: str
... | RealtimeConversationItemSystemMessageParam |
python | django-import-export__django-import-export | tests/core/tests/test_forms.py | {
"start": 312,
"end": 408
} | class ____(resources.ModelResource):
class Meta:
name = "My super resource"
| MyResource |
python | huggingface__transformers | src/transformers/models/blt/modeling_blt.py | {
"start": 16404,
"end": 19426
} | class ____(nn.Module):
"""Cross-attention module for Blt, following transformers style"""
def __init__(self, config: BltConfig, layer_idx: int, hidden_size: Optional[int] = None):
super().__init__()
self.config = config
self.num_heads = self.config.num_attention_heads
self.num_k... | BltCrossAttention |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 335978,
"end": 336329
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("EnterpriseServerInstallation", graphql_name="node")... | EnterpriseServerInstallationEdge |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 508,
"end": 761
} | class ____:
env = {}
help = ''
called = False
dummy_attr = 1
def __call__(self, env, help):
self.env = env
self.help = help
self.called = True
self.env['request'].dummy_attr = self.dummy_attr
| DummyShell |
python | pandas-dev__pandas | pandas/tests/extension/date/array.py | {
"start": 1222,
"end": 6023
} | class ____(ExtensionArray):
def __init__(
self,
dates: (
dt.date
| Sequence[dt.date]
| tuple[np.ndarray, np.ndarray, np.ndarray]
| np.ndarray
),
) -> None:
if isinstance(dates, dt.date):
self._year = np.array([dates.year... | DateArray |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0012_add-predefined-match-arg-field.py | {
"start": 150,
"end": 2025
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0011_version-media-availability"),
]
operations = [
migrations.AddField(
model_name="versionautomationrule",
name="predefined_match_arg",
field=models.CharField(... | Migration |
python | getsentry__sentry | tests/sentry/api/test_client.py | {
"start": 163,
"end": 1405
} | class ____(TestCase):
@patch("sentry.api.client.resolve")
def test_mixed_parameters_in_query_string(self, mock_resolve):
mock_view = Mock(return_value=JsonResponse({"success": True}))
mock_resolve.return_value = (mock_view, (), {})
mock_auth = Mock()
mock_auth.organization_id =... | ClientParameterHandlingTest |
python | pytorch__pytorch | torch/nn/modules/loss.py | {
"start": 1147,
"end": 1489
} | class ____(_Loss):
def __init__(
self,
weight: Optional[Tensor] = None,
size_average=None,
reduce=None,
reduction: str = "mean",
) -> None:
super().__init__(size_average, reduce, reduction)
self.register_buffer("weight", weight)
self.weight: Option... | _WeightedLoss |
python | huggingface__transformers | src/transformers/models/lightglue/modular_lightglue.py | {
"start": 11200,
"end": 11586
} | class ____(SuperGlueImageProcessorFast):
def post_process_keypoint_matching(
self,
outputs: "LightGlueKeypointMatchingOutput",
target_sizes: Union[TensorType, list[tuple]],
threshold: float = 0.0,
) -> list[dict[str, torch.Tensor]]:
return super().post_process_keypoint_ma... | LightGlueImageProcessorFast |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.