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 | walkccc__LeetCode | solutions/1654. Minimum Jumps to Reach Home/1654.py | {
"start": 24,
"end": 78
} | class ____(Enum):
FORWARD = 0
BACKWARD = 1
| Direction |
python | ray-project__ray | doc/source/serve/doc_code/monitoring/logging_config.py | {
"start": 1171,
"end": 1415
} | class ____:
def __call__(self) -> int:
return "hello world"
# __logs_dir_end__
# __enable_access_log_start__
import requests
import logging
from ray import serve
@serve.deployment(logging_config={"enable_access_log": False})
| Model |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 9936,
"end": 10026
} | class ____(VyperException):
"""Interface is not fully implemented."""
| InterfaceViolation |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 25413,
"end": 29378
} | class ____(nn.Module):
def __init__(self, config: DabDetrConfig, is_first: bool = False):
super().__init__()
hidden_size = config.hidden_size
self.cross_attn_query_content_proj = nn.Linear(hidden_size, hidden_size)
self.cross_attn_query_pos_proj = nn.Linear(hidden_size, hidden_size)
... | DabDetrDecoderLayerCrossAttention |
python | kamyu104__LeetCode-Solutions | Python/maximum-possible-number-by-binary-concatenation.py | {
"start": 54,
"end": 391
} | class ____(object):
def maxGoodNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return int("".join(sorted(map(lambda x: bin(x)[2:], nums), cmp=lambda x, y: (x+y > y+x)-(x+y < y+x), reverse=True)), 2)
# Time: O(n! * nlogr)
# Space: O(nlogr)
import itertools
#... | Solution |
python | sqlalchemy__sqlalchemy | test/ext/test_hybrid.py | {
"start": 60399,
"end": 68261
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
"""tests against hybrids that return a non-ClauseElement.
use cases derived from the example at
https://techspot.zzzeek.org/2011/10/21/hybrids-and-value-agnostic-types/
"""
__dialect__ = "default"
@classmethod
def setup_test_class(cls):
... | SpecialObjectTest |
python | facebook__pyre-check | client/log/log.py | {
"start": 9722,
"end": 12387
} | class ____:
_should_stop_reading_stream = False
_current_section: Optional[str]
_server_log_pattern: Pattern[str] = re.compile(
r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (\w+)(.*)"
)
def __init__(self, stream: Iterable[str]) -> None:
self._reader = threading.Thread(target=self._read_st... | StreamLogger |
python | django__django | django/contrib/postgres/search.py | {
"start": 10021,
"end": 11957
} | class ____(Func):
function = "ts_headline"
template = "%(function)s(%(expressions)s%(options)s)"
output_field = TextField()
def __init__(
self,
expression,
query,
*,
config=None,
start_sel=None,
stop_sel=None,
max_words=None,
min_w... | SearchHeadline |
python | gevent__gevent | src/gevent/tests/test__pool.py | {
"start": 15301,
"end": 15561
} | class ____(gevent.testing.timing.AbstractGenericWaitTestCase):
def wait(self, timeout):
p = gevent.pool.Pool()
g = p.spawn(gevent.sleep, 10)
try:
p.join(timeout=timeout)
finally:
g.kill()
| TestJoinSleep |
python | sympy__sympy | sympy/physics/mechanics/inertia.py | {
"start": 2554,
"end": 6172
} | class ____(namedtuple('Inertia', ['dyadic', 'point'])):
"""Inertia object consisting of a Dyadic and a Point of reference.
Explanation
===========
This is a simple class to store the Point and Dyadic, belonging to an
inertia.
Attributes
==========
dyadic : Dyadic
The dyadic o... | Inertia |
python | pexpect__pexpect | tests/test_socket_pexpect.py | {
"start": 1286,
"end": 2539
} | class ____(PexpectTestCase.PexpectTestCase):
def setUp(self):
print(self.id())
PexpectTestCase.PexpectTestCase.setUp(self)
def test_socket (self):
socket = open_file_socket('TESTDATA.txt')
s = socket_pexpect.SocketSpawn(socket)
s.expect(b'This is the end of test data:')
... | ExpectTestCase |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 40048,
"end": 41898
} | class ____(PreTrainedModel):
config: BridgeTowerConfig
base_model_prefix = "bridgetower"
input_modalities = ("image", "text")
supports_gradient_checkpointing = False
_no_split_modules = ["BridgeTowerSelfAttention", "BridgeTowerResidualAttention"]
_skip_keys_device_placement = "past_key_values"
... | BridgeTowerPreTrainedModel |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-vertex/tests/test_embeddings_vertex.py | {
"start": 626,
"end": 4500
} | class ____(unittest.TestCase):
@patch("vertexai.init")
@patch("vertexai.language_models.TextEmbeddingModel.from_pretrained")
def test_init(self, model_mock: Mock, mock_init: Mock):
mock_cred = Mock(return_value="mock_credentials_instance")
embedding = VertexTextEmbedding(
model_n... | VertexTextEmbeddingTest |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/ghostwriter/test_ghostwriter.py | {
"start": 8719,
"end": 16621
} | class ____(UnicodeDecodeError):
pass
@pytest.mark.parametrize(
"exceptions,output",
[
# Discard subclasses of other exceptions to catch, including non-builtins,
# and replace OSError aliases with OSError.
((Exception, UnicodeError), "Exception"),
((UnicodeError, MyError), "... | MyError |
python | mitmproxy__pdoc | test/testdata/typed_dict.py | {
"start": 100,
"end": 283
} | class ____(Foo, total=False):
"""A TypedDict subclass. Before 3.12, TypedDict botches __mro__."""
b: int
"""Second attribute."""
c: str
# undocumented attribute
| Bar |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 10950,
"end": 12009
} | class ____(UnaryPredicate):
"""The callable() function."""
_NAME = "callable"
def _call_predicate(self, node, obj):
return self._is_callable(node, obj)
def _is_callable(self, node, obj):
"""Check if the object is callable.
Args:
node: The given node.
obj: A BaseValue, the arg of a ca... | IsCallable |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_method.py | {
"start": 128,
"end": 365
} | class ____:
def aaaa(self):
"""should be overridden in concrete class"""
raise NotImplementedError()
def bbbb(self):
"""should be overridden in concrete class"""
raise NotImplementedError()
| Abstract |
python | sphinx-doc__sphinx | sphinx/util/inventory.py | {
"start": 8281,
"end": 9383
} | class ____:
"""Inventory data in memory."""
__slots__ = ('data',)
data: dict[str, dict[str, _InventoryItem]]
def __init__(self, data: dict[str, dict[str, _InventoryItem]], /) -> None:
# type -> name -> _InventoryItem
self.data: dict[str, dict[str, _InventoryItem]] = data
def __re... | _Inventory |
python | marshmallow-code__marshmallow | tests/test_decorators.py | {
"start": 30090,
"end": 34392
} | class ____:
def __init__(self, nested):
self.nested = nested
example = Example(nested=[Nested(x) for x in range(1)])
@pytest.mark.parametrize(
("data", "expected_data", "expected_original_data"),
([example, {"foo": 0}, example.nested[0]],),
)
def test_decorator_post_dump_with_nested_original_and... | Example |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/deep_learning/optimizers.py | {
"start": 3306,
"end": 3982
} | class ____():
def __init__(self, learning_rate=0.01, rho=0.9):
self.learning_rate = learning_rate
self.Eg = None # Running average of the square gradients at w
self.eps = 1e-8
self.rho = rho
def update(self, w, grad_wrt_w):
# If not initialized
if self.Eg is None... | RMSprop |
python | huggingface__transformers | src/transformers/models/switch_transformers/modeling_switch_transformers.py | {
"start": 9557,
"end": 10979
} | class ____(nn.Module):
r"""
Switch Transformers Feed Forward layer module. This is a wrapper around the Mixture of Experts module.
Parameters:
config : ([`SwitchTransformersConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does no... | SwitchTransformersLayerFF |
python | kamyu104__LeetCode-Solutions | Python/create-components-with-same-value.py | {
"start": 2543,
"end": 3299
} | class ____(object):
def componentValue(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def dfs(u, p, target):
total = nums[u]
for v in adj[u]:
if v == p:
continue
... | Solution3 |
python | weaviate__weaviate-python-client | weaviate/cluster/models.py | {
"start": 2704,
"end": 2814
} | class ____(TypedDict):
shardingState: _ReplicationShardingState
@dataclass
| _ReplicationShardingStateResponse |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/since_operator.py | {
"start": 1076,
"end": 3386
} | class ____:
"""Convenience class for manipulating metadata relevant to historical SinceCondition evaluations.
Tracks the previous evaluation id and timestamp of the last evaluation where the trigger condition
and reset conditions were true.
"""
trigger_evaluation_id: Optional[int]
trigger_times... | SinceConditionData |
python | fabric__fabric | tests/group.py | {
"start": 731,
"end": 4167
} | class ____:
class init:
"__init__"
def may_be_empty(self):
assert len(Group()) == 0
def takes_splat_arg_of_host_strings(self):
g = Group("foo", "bar")
assert g[0].host == "foo"
assert g[1].host == "bar"
def takes_splat_kwargs_and_pas... | Group_ |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/advanced_activations.py | {
"start": 1278,
"end": 2810
} | class ____(Layer):
"""Leaky version of a Rectified Linear Unit.
It allows a small gradient when the unit is not active:
```
f(x) = alpha * x if x < 0
f(x) = x if x >= 0
```
Usage:
>>> layer = tf.keras.layers.LeakyReLU()
>>> output = layer([-3.0, -1.0, 0.0, 2.0])
>>> list(output.numpy())
[-... | LeakyReLU |
python | django__django | tests/prefetch_related/models.py | {
"start": 1901,
"end": 2113
} | class ____(models.Model):
author = models.OneToOneField(
Author,
models.CASCADE,
primary_key=True,
to_field="name",
)
books = models.ManyToManyField(Book, blank=True)
| Bio |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ScatterPlotItem.py | {
"start": 4847,
"end": 10646
} | class ____(object):
"""
Used to efficiently construct a single QPixmap containing all rendered symbols
for a ScatterPlotItem. This is required for fragment rendering.
Use example:
atlas = SymbolAtlas()
sc1 = atlas[[('o', 5, QPen(..), QBrush(..))]]
sc2 = atlas[[('t', 10, QPen(..)... | SymbolAtlas |
python | kamyu104__LeetCode-Solutions | Python/decode-xored-array.py | {
"start": 29,
"end": 312
} | class ____(object):
def decode(self, encoded, first):
"""
:type encoded: List[int]
:type first: int
:rtype: List[int]
"""
result = [first]
for x in encoded:
result.append(result[-1]^x)
return result
| Solution |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 11308,
"end": 12011
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_OPENAI, frozen=True, exclude=True
)
baseURL: Optional[AnyHttpUrl]
dimensions: Optional[int]
model: Optional[str]
modelVersion: Optional[str]
type_: Optional[OpenAIT... | _Text2VecOpenAIConfig |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_test.py | {
"start": 140297,
"end": 160320
} | class ____(test.TestCase):
def setUp(self):
super(VocabularyFileCategoricalColumnTest, self).setUp()
# Contains ints, Golden State Warriors jersey numbers: 30, 35, 11, 23, 22
self._warriors_vocabulary_file_name = test.test_src_dir_path(
'python/feature_column/testdata/warriors_vocabulary.txt')
... | VocabularyFileCategoricalColumnTest |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/patchelf/package.py | {
"start": 228,
"end": 944
} | class ____(AutotoolsPackage):
"""PatchELF is a small utility to modify the dynamic linker and RPATH of
ELF executables."""
homepage = "https://nixos.org/patchelf.html"
url = "https://nixos.org/releases/patchelf/patchelf-0.10/patchelf-0.10.tar.gz"
list_url = "https://nixos.org/releases/patchelf/"
... | Patchelf |
python | kevin1024__vcrpy | vcr/stubs/aiohttp_stubs.py | {
"start": 556,
"end": 639
} | class ____(asyncio.StreamReader, streams.AsyncStreamReaderMixin):
pass
| MockStream |
python | pytorch__pytorch | test/functorch/test_aot_joint_with_descriptors.py | {
"start": 24140,
"end": 54202
} | class ____(torch.nn.Module):
def forward(
self,
primals,
tangents,
):
primals_1: "f32[2, 3]" # ParamAOTInput(target='linear1.weight')
primals_2: "f32[2]" # ParamAOTInput(target='linear1.bias')
primals_3: "f32[4, 3]" # ParamAOTInput(target='linear2.weight')
... | inner_f |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 22629,
"end": 24770
} | class ____(TestCase):
def setUp(self):
self.patterns = [
path('api/v1/example/', views.ExampleListView.as_view()),
path('api/v1/example/<int:pk>/', views.ExampleDetailView.as_view()),
path('api/v1/example/<int:pk>/sub/', views.ExampleDetailView.as_view()),
]
... | TestSchemaGeneratorNotAtRoot |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/help.py | {
"start": 2711,
"end": 4839
} | class ____(BlockSlackMessageBuilder):
def __init__(self, command: str | None = None, integration_id: int | None = None) -> None:
super().__init__()
self.command = command
self.integration_id = integration_id
def get_header_blocks(self) -> Sequence[SlackBlock]:
blocks = []
... | SlackHelpMessageBuilder |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/dropout.py | {
"start": 66,
"end": 806
} | class ____(torch.nn.Dropout):
r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
And this is a placeholder to enable models where fp32 tensors
had dropout to work with quantized tensors in train and eval mode.
Args:
p: probability of an element to be zeroed
inpl... | Dropout |
python | getsentry__sentry | src/sentry/web/frontend/disabled_member_view.py | {
"start": 338,
"end": 1302
} | class ____(ReactPageView):
def is_member_disabled_from_limit(self, request: object, organization) -> bool:
return False
def handle(self, request: HttpRequest, organization, **kwargs) -> HttpResponse:
user = request.user
# if org member is not restricted, redirect user out of the disable... | DisabledMemberView |
python | pandas-dev__pandas | pandas/tests/indexes/test_old_base.py | {
"start": 720,
"end": 32541
} | class ____:
@pytest.fixture(
params=[
RangeIndex(start=0, stop=20, step=2),
Index(np.arange(5, dtype=np.float64)),
Index(np.arange(5, dtype=np.float32)),
Index(np.arange(5, dtype=np.uint64)),
Index(range(0, 20, 2), dtype=np.int64),
Inde... | TestBase |
python | jazzband__prettytable | src/prettytable/prettytable.py | {
"start": 106207,
"end": 111735
} | class ____(HTMLParser):
def __init__(self, **kwargs) -> None:
HTMLParser.__init__(self)
self.kwargs = kwargs
self.tables: list[PrettyTable] = []
self.last_row: list[str] = []
self.rows: list[tuple[list[str], bool]] = []
self.max_row_width = 0
self.active: str ... | TableHandler |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 19127,
"end": 19769
} | class ____(_BaseAddress):
__slots__ = ()
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
field_schema.update(type='string', format='ipvanyinterface')
@classmethod
def __get_validators__(cls) -> 'CallableGenerator':
yield cls.validate
@classmethod... | IPvAnyInterface |
python | tensorflow__tensorflow | tensorflow/python/tpu/profiler/profiler_analysis_pb2_grpc.py | {
"start": 2823,
"end": 5789
} | class ____(object):
"""//////////////////////////////////////////////////////////////////////////////
ProfileAnalysis service provide entry point for profiling TPU and for
serving profiled data to Tensorboard through GRPC
//////////////////////////////////////////////////////////////////////////////
"""
d... | ProfileAnalysisServicer |
python | astropy__astropy | astropy/coordinates/builtin_frames/skyoffset.py | {
"start": 3825,
"end": 8120
} | class ____(BaseCoordinateFrame):
"""
A frame which is relative to some specific position and oriented to match
its frame.
SkyOffsetFrames always have component names for spherical coordinates
of ``lon``/``lat``, *not* the component names for the frame of ``origin``.
This is useful for calculat... | SkyOffsetFrame |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_tool_execution_error_param.py | {
"start": 234,
"end": 380
} | class ____(TypedDict, total=False):
message: Required[str]
type: Required[Literal["tool_execution_error"]]
| RealtimeMcpToolExecutionErrorParam |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/datatable_hot_reloading.py | {
"start": 732,
"end": 1260
} | class ____(App[None]):
CSS_PATH = CSS_PATH
def compose(self) -> ComposeResult:
yield DataTable(zebra_stripes=True, cursor_type="row")
def on_mount(self) -> None:
dt = self.query_one(DataTable)
dt.add_column("A", width=10)
self.c = dt.add_column("B")
dt.fixed_columns... | DataTableHotReloadingApp |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/markers.py | {
"start": 1141,
"end": 5164
} | class ____(object):
"""
This class is used to evaluate marker expressions.
"""
operations = {
'==': lambda x, y: x == y,
'===': lambda x, y: x == y,
'~=': lambda x, y: x == y or x > y,
'!=': lambda x, y: x != y,
'<': lambda x, y: x < y,
'<=': lambda x, y:... | Evaluator |
python | conda__conda | conda/models/match_spec.py | {
"start": 39129,
"end": 39241
} | class ____(GlobStrMatch):
def __init__(self, value):
super().__init__(value.lower())
| GlobLowerStrMatch |
python | huggingface__transformers | examples/modular-transformers/image_processing_new_imgproc_model.py | {
"start": 1265,
"end": 14909
} | class ____(BaseImageProcessor):
r"""
Constructs a IMGPROC_MODEL image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
`do_resize` parameter in the ... | ImgprocModelImageProcessor |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 3921,
"end": 5444
} | class ____(ast.NodeVisitor):
"""Check if a name is a local dict."""
def __init__(self, name: str, keys: set[str]) -> None:
"""Initialize the visitor.
Args:
name: The name to check.
keys: The keys to populate.
"""
self.name = name
self.keys = keys... | IsLocalDict |
python | pytorch__pytorch | torch/utils/data/sampler.py | {
"start": 7519,
"end": 9995
} | class ____(Sampler[int]):
r"""Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).
Args:
weights (sequence) : a sequence of weights, not necessary summing up to one
num_samples (int): number of samples to draw
replacement (bool): if ``True``, samples are... | WeightedRandomSampler |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/testlib/elemental_kernel_emitter_test.py | {
"start": 8863,
"end": 13004
} | class ____(parameterized.TestCase):
def test_map(self, input_dimensions, dtype):
scalar_shape = xla_extension.Shape.scalar_shape(dtype)
shape = xla_extension.Shape.array_shape(dtype, input_dimensions)
# Please note the double curly braces is to escape the python string
# formatting.
hlo = """
... | HloModuleKernelRunnerTest |
python | apache__airflow | scripts/ci/prek/check_deferrable_default.py | {
"start": 2553,
"end": 5278
} | class ____(cst.CSTTransformer):
def leave_Param(self, original_node: cst.Param, updated_node: cst.Param) -> cst.Param:
if original_node.name.value == "deferrable":
expected_default_cst = cst.parse_expression(
'conf.getboolean("operators", "default_deferrable", fallback=False)'
... | DefaultDeferrableTransformer |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 24847,
"end": 24966
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Linaro'
strategy_class = FileStrategy
| LinaroHostname |
python | sympy__sympy | sympy/physics/quantum/state.py | {
"start": 18796,
"end": 18915
} | class ____(State):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
| OrthogonalState |
python | mwaskom__seaborn | seaborn/_marks/line.py | {
"start": 8301,
"end": 8845
} | class ____(Paths):
"""
A line mark drawn as an oriented segment for each datapoint.
Examples
--------
.. include:: ../docstrings/objects.Dash.rst
"""
width: MappableFloat = Mappable(.8, grouping=False)
def _setup_segments(self, data, orient):
ori = ["x", "y"].index(orient)
... | Dash |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/keyfunc_dict.py | {
"start": 638,
"end": 1110
} | class ____(Base):
__tablename__ = "note"
id: Mapped[int] = mapped_column(primary_key=True)
item_id: Mapped[int] = mapped_column(ForeignKey("item.id"))
keyword: Mapped[str]
text: Mapped[Optional[str]]
def __init__(self, keyword: str, text: str):
self.keyword = keyword
self.text ... | Note |
python | huggingface__transformers | src/transformers/models/olmo3/modeling_olmo3.py | {
"start": 15353,
"end": 15894
} | class ____(PreTrainedModel):
config: Olmo3Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Olmo3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
... | Olmo3PreTrainedModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1253207,
"end": 1253476
} | class ____(sgqlc.types.Type, Node, AuditEntry, OauthApplicationAuditEntryData, OrganizationAuditEntryData):
"""Audit log entry for a org.oauth_app_access_requested event."""
__schema__ = github_schema
__field_names__ = ()
| OrgOauthAppAccessRequestedAuditEntry |
python | spack__spack | lib/spack/spack/vendor/attr/exceptions.py | {
"start": 1549,
"end": 1915
} | class ____(TypeError):
"""
A ``attr.ib()`` requiring a callable has been set with a value
that is not callable.
.. versionadded:: 19.2.0
"""
def __init__(self, msg, value):
super(TypeError, self).__init__(msg, value)
self.msg = msg
self.value = value
def __str__(se... | NotCallableError |
python | huggingface__transformers | src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py | {
"start": 8638,
"end": 8918
} | class ____(PreTrainedModel):
config: MobileNetV2Config
base_model_prefix = "mobilenet_v2"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = False
_no_split_modules = []
@auto_docstring
| MobileNetV2PreTrainedModel |
python | fastapi__sqlmodel | docs_src/tutorial/connect/select/tutorial002.py | {
"start": 254,
"end": 2174
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqli... | Hero |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/helpers/latest_releases.py | {
"start": 1173,
"end": 1866
} | class ____:
"""
Class that represents a boosted release fetched from Redis.
"""
id: int
timestamp: float
environment: str | None
# We also store the cache key corresponding to this boosted release entry, in order to remove it efficiently.
cache_key: str
def extend(self, release: Re... | BoostedRelease |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 331592,
"end": 332240
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateDiscussionComment"""
__schema__ = github_schema
__field_names__ = ("comment_id", "body", "client_mutation_id")
comment_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="commentId")
"""The Node ID of the discussion comm... | UpdateDiscussionCommentInput |
python | spyder-ide__spyder | spyder/widgets/tests/test_collectioneditor.py | {
"start": 2155,
"end": 45933
} | class ____(QWidget):
def __init__(self):
QWidget.__init__(self)
self.proxy_model = None
# =============================================================================
# Pytest Fixtures
# =============================================================================
@pytest.fixture
def nonsettable... | MockParent |
python | pytorch__pytorch | test/distributed/checkpoint/e2e/test_fsdp_ep.py | {
"start": 1719,
"end": 4128
} | class ____(DTensorTestBase, VerifyStateDictMixin):
@property
def world_size(self) -> int:
return min(8, torch.accelerator.device_count())
@with_comms
@skip_if_lt_x_gpu(8)
@with_temp_dir
def test_e2e(self):
model = TopModel(self.rank).to(self.device_type)
mesh_fsdp_tp = ... | TestFSDPWithEP |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 973296,
"end": 973690
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("SponsorableItem", graphql... | SponsorableItemEdge |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_remote_logging.py | {
"start": 8843,
"end": 14354
} | class ____:
"""Tests opensearch configuration behaviors."""
def test_should_not_generate_secret_document_if_opensearch_disabled(self):
docs = render_chart(
values={"opensearch": {"enabled": False}},
show_only=[OS_SECRET_TEMPLATE],
)
assert len(docs) == 0
de... | TestOpenSearchConfig |
python | pypa__pip | src/pip/_vendor/pygments/lexer.py | {
"start": 15957,
"end": 16252
} | class ____:
"""
Indicates a state or state action (e.g. #pop) to apply.
For example default('#pop') is equivalent to ('', Token, '#pop')
Note that state tuples may be used as well.
.. versionadded:: 2.0
"""
def __init__(self, state):
self.state = state
| default |
python | scikit-learn__scikit-learn | sklearn/linear_model/tests/test_sgd.py | {
"start": 2173,
"end": 72779
} | class ____(linear_model.SGDOneClassSVM):
def fit(self, X, *args, **kw):
X = sp.csr_matrix(X)
return linear_model.SGDOneClassSVM.fit(self, X, *args, **kw)
def partial_fit(self, X, *args, **kw):
X = sp.csr_matrix(X)
return linear_model.SGDOneClassSVM.partial_fit(self, X, *args, **... | _SparseSGDOneClassSVM |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 119789,
"end": 130009
} | class ____(GroundingDinoPreTrainedModel):
# When using clones, all layers > 0 will be clones, but layer 0 *is* required
# the bbox_embed in the decoder are all clones though
_tied_weights_keys = {
r"bbox_embed.(?![0])\d+": "bbox_embed.0",
"model.decoder.bbox_embed": "bbox_embed",
}
... | GroundingDinoForObjectDetection |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataplex.py | {
"start": 9151,
"end": 10041
} | class ____:
@mock.patch(HOOK_STR)
def test_execute(self, hook_mock):
op = DataplexDeleteLakeOperator(
project_id=PROJECT_ID,
region=REGION,
lake_id=LAKE_ID,
task_id="delete_dataplex_lake",
api_version=API_VERSION,
gcp_conn_id=GCP_CO... | TestDataplexDeleteLakeOperator |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 819156,
"end": 819348
} | class ____(VegaLiteSchema):
"""Orientation schema wrapper."""
_schema = {"$ref": "#/definitions/Orientation"}
def __init__(self, *args):
super().__init__(*args)
| Orientation |
python | astropy__astropy | astropy/visualization/wcsaxes/frame.py | {
"start": 10754,
"end": 11324
} | class ____(BaseFrame):
"""
A classic rectangular frame.
"""
spine_names = "brtl"
_spine_auto_position_order = "bltr"
def update_spines(self):
xmin, xmax = self.parent_axes.get_xlim()
ymin, ymax = self.parent_axes.get_ylim()
self["b"].data = np.array(([xmin, ymin], [xma... | RectangularFrame |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/retrieval/base.py | {
"start": 968,
"end": 2417
} | class ____(BaseModel):
"""
Retrieval eval result.
NOTE: this abstraction might change in the future.
Attributes:
query (str): Query string
expected_ids (List[str]): Expected ids
retrieved_ids (List[str]): Retrieved ids
metric_dict (Dict[str, BaseRetrievalMetric]): \
... | RetrievalEvalResult |
python | Netflix__metaflow | test/test_config/config_corner_cases.py | {
"start": 1649,
"end": 2828
} | class ____(FlowSpec):
trigger_param = Parameter(
"trigger_param",
default="",
external_trigger=True,
external_artifact=trigger_name_func,
)
cfg = Config("cfg", default="config_simple.json")
cfg_default_value = Config(
"cfg_default_value",
default_value=de... | ConfigSimple |
python | google__jax | jax/experimental/mosaic/gpu/core.py | {
"start": 9780,
"end": 10277
} | class ____:
addr_ref: ir.Value
num_cols: int
collective: bool
def alloc(self) -> int:
"""Allocates TMEM and returns the number of columns allocated."""
_, cols = tcgen05.tmem_alloc(
self.addr_ref, self.num_cols, collective=self.collective, exact=False
)
return cols
def dealloc(self):... | _TMEMAlloc |
python | kamyu104__LeetCode-Solutions | Python/minimize-maximum-pair-sum-in-array.py | {
"start": 33,
"end": 252
} | class ____(object):
def minPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return max(nums[i]+nums[-1-i] for i in xrange(len(nums)//2))
| Solution |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 772,
"end": 992
} | class ____(BaseModel, from_attributes=True):
x: float
y: str
kwargs_model = KwargsModel(x=1, y='y')
KwargsModel(x=1, y='y', z='z')
kwargs_model.x = 2
kwargs_model.model_validate(kwargs_model.__dict__)
| KwargsModel |
python | pandas-dev__pandas | pandas/core/indexing.py | {
"start": 52602,
"end": 88270
} | class ____(_LocationIndexer):
_valid_types = (
"integer, integer slice (START point is INCLUDED, END "
"point is EXCLUDED), listlike of integers, boolean array"
)
_takeable = True
# -------------------------------------------------------------------
# Key Checks
def _validate_k... | _iLocIndexer |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cli/configs/base.py | {
"start": 9107,
"end": 13502
} | class ____(DbtConfigs):
"""
Global configs control things like the visual output
of logs, the manner in which dbt parses your project,
and what to do when dbt finds a version mismatch
or a failing model. Docs can be found [here](
https://docs.getdbt.com/reference/global-configs).
Attributes... | GlobalConfigs |
python | getsentry__sentry | src/sentry/incidents/grouptype.py | {
"start": 2361,
"end": 2440
} | class ____(EvidenceData[MetricResult]):
alert_id: int
| MetricIssueEvidenceData |
python | huggingface__transformers | src/transformers/models/oneformer/convert_to_hf_oneformer.py | {
"start": 3575,
"end": 7733
} | class ____:
def __call__(self, original_config: object, is_swin: bool) -> OneFormerConfig:
model = original_config.MODEL
dataset_catalog = MetadataCatalog.get(original_config.DATASETS.TEST_PANOPTIC[0])
id2label = dict(enumerate(dataset_catalog.stuff_classes))
label2id = {label: idx ... | OriginalOneFormerConfigToOursConverter |
python | huggingface__transformers | src/transformers/models/video_llama_3/modular_video_llama_3.py | {
"start": 2686,
"end": 5674
} | class ____(SiglipVisionConfig):
"""
This is the configuration class to store the configuration of a [`VideoLlama3VisionModel`]. It is used to instantiate a
VideoLLaMA3 vision encoder model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defau... | VideoLlama3VisionConfig |
python | huggingface__transformers | src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py | {
"start": 3101,
"end": 5087
} | class ____(nn.Module):
"""
This class turns `input_values` into the initial `hidden_states` (patch embeddings) of shape `(batch_size,
seq_length, hidden_size)` to be consumed by a Transformer.
"""
def __init__(self, config: ASTConfig):
super().__init__()
patch_size = config.patch_s... | ASTPatchEmbeddings |
python | walkccc__LeetCode | solutions/1290. Convert Binary Number in a Linked List to Integer/1290.py | {
"start": 0,
"end": 167
} | class ____:
def getDecimalValue(self, head: ListNode) -> int:
ans = 0
while head:
ans = ans * 2 + head.val
head = head.next
return ans
| Solution |
python | ansible__ansible | test/units/plugins/lookup/test_password.py | {
"start": 16204,
"end": 17037
} | class ____(unittest.TestCase):
def setUp(self):
self.fake_loader = DictDataLoader({'/path/to/somewhere': 'sdfsdf'})
self.password_lookup = lookup_loader.get('password')
self.password_lookup._loader = self.fake_loader
self.os_path_exists = password.os.path.exists
self.os_open ... | BaseTestLookupModule |
python | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 8068,
"end": 8819
} | class ____(TypedDict, total=False):
call_id: Required[str]
"""The unique ID of the function shell tool call generated by the model."""
output: Required[Iterable[ResponseFunctionShellCallOutputContentParam]]
"""
Captured chunks of stdout and stderr output, along with their associated
outcomes.
... | ShellCallOutput |
python | kamyu104__LeetCode-Solutions | Python/find-all-people-with-secret.py | {
"start": 54,
"end": 1087
} | class ____(object):
def findAllPeople(self, n, meetings, firstPerson):
"""
:type n: int
:type meetings: List[List[int]]
:type firstPerson: int
:rtype: List[int]
"""
meetings.sort(key=lambda x: x[2])
result = {0, firstPerson}
adj = collections.d... | Solution |
python | astropy__astropy | astropy/constants/codata2022.py | {
"start": 354,
"end": 477
} | class ____(Constant):
default_reference = "CODATA 2022"
_registry = {}
_has_incompatible_units = set()
| CODATA2022 |
python | openai__gym | gym/wrappers/filter_observation.py | {
"start": 146,
"end": 3435
} | class ____(gym.ObservationWrapper):
"""Filter Dict observation space by the keys.
Example:
>>> import gym
>>> env = gym.wrappers.TransformObservation(
... gym.make('CartPole-v1'), lambda obs: {'obs': obs, 'time': 0}
... )
>>> env.observation_space = gym.spaces.Dict(o... | FilterObservation |
python | pyodide__pyodide | tools/create_lockfile_diff.py | {
"start": 534,
"end": 2747
} | class ____:
name: str
old_version: str | None
new_version: str | None
def is_normal_python_package(pkg: PackageSpec) -> bool:
return pkg.package_type == "package" and pkg.file_name.endswith(".whl")
def calculate_diff(
old_lockfile_path: Path, new_lockfile_path: Path
) -> tuple[list[PackageDiff],... | PackageDiff |
python | keras-team__keras | keras/src/ops/numpy_test.py | {
"start": 64584,
"end": 85599
} | class ____(testing.TestCase):
def test_mean(self):
x = KerasTensor((2, 3))
self.assertEqual(knp.mean(x).shape, ())
def test_all(self):
x = KerasTensor((2, 3))
self.assertEqual(knp.all(x).shape, ())
def test_any(self):
x = KerasTensor((2, 3))
self.assertEqual... | NumpyOneInputOpsStaticShapeTest |
python | django__django | tests/foreign_object/models/article.py | {
"start": 152,
"end": 652
} | class ____(ForwardManyToOneDescriptor):
"""
The set of articletranslation should not set any local fields.
"""
def __set__(self, instance, value):
if instance is None:
raise AttributeError("%s must be accessed via instance" % self.field.name)
self.field.set_cached_value(inst... | ArticleTranslationDescriptor |
python | encode__django-rest-framework | tests/test_throttling.py | {
"start": 864,
"end": 953
} | class ____(UserRateThrottle):
rate = '6/min'
scope = 'minutes'
| User6MinRateThrottle |
python | wandb__wandb | tests/unit_tests/test_lib/test_fsm.py | {
"start": 203,
"end": 463
} | class ____(TrackCalls):
def __init__(self, calls):
super().__init__(calls)
def on_state(self, inputs) -> None:
self._calls.append("A:on_state")
def to_b(self, inputs) -> bool:
self._calls.append("to_b")
return True
| A |
python | kamyu104__LeetCode-Solutions | Python/missing-ranges.py | {
"start": 29,
"end": 749
} | class ____(object):
def findMissingRanges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
def getRange(lower, upper):
if lower == upper:
return "{}".format(lower)
... | Solution |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 8998,
"end": 9196
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
value_set: List[DiagnosticTag] = dataclasses.field(default_factory=list)
@dataclasses.dataclass(frozen=True)
| PublishDiagnosticsClientTagSupport |
python | pytorch__pytorch | test/distributed/tensor/test_random_ops.py | {
"start": 12154,
"end": 26999
} | class ____(DTensorTestBase):
@with_comms
@skip_unless_torch_gpu
def test_rng_tracker_init(self):
torch.manual_seed(self.rank)
seed_local = (
torch.zeros_like(torch.empty(1), device=self.device_type)
+ torch.initial_seed()
)
torch.distributed.broadcast(... | DistTensorRandomOpTest |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/commands/test_link_team.py | {
"start": 676,
"end": 1301
} | class ____(SlackCommandsTest):
def setUp(self) -> None:
super().setUp()
self.link_user()
responses.add(
method=responses.POST,
url="https://slack.com/api/chat.postMessage",
body='{"ok": true}',
status=status.HTTP_200_OK,
content_typ... | SlackCommandsLinkTeamTestBase |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 1131,
"end": 3418
} | class ____(IntFlag):
"""
Table 3.20 User access permissions.
Table 22 of the 2.0 manual.
"""
R1 = 1
R2 = 2
PRINT = 4
MODIFY = 8
EXTRACT = 16
ADD_OR_MODIFY = 32
R7 = 64
R8 = 128
FILL_FORM_FIELDS = 256
EXTRACT_TEXT_AND_GRAPHICS = 512
ASSEMBLE_DOC = 1024
PRI... | UserAccessPermissions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.