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 | pytorch__pytorch | torch/_subclasses/_fake_tensor_utils.py | {
"start": 463,
"end": 2272
} | class ____:
"""
Represents a SymNode without the associated ShapeEnv
"""
# n.b. keep the same protocol as SymNode
_expr: sympy.Expr
pytype: type
_hint: Optional[Union[int, float, bool]]
constant: Optional[Union[int, float, bool]]
fx_node: torch.fx.Node
@staticmethod
def fro... | _DeconstructedSymNode |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 15277,
"end": 15368
} | class ____(AnyUrl):
allowed_schemes = {'amqp', 'amqps'}
host_required = False
| AmqpDsn |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 30264,
"end": 30376
} | class ____(DataType):
"""Type representing DataType values that could not be determined statically."""
| Unknown |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/tools/_beta_functions.py | {
"start": 1053,
"end": 1427
} | class ____(ABC):
@abstractmethod
def to_dict(self) -> BetaToolUnionParam: ...
@abstractmethod
def call(self, input: object) -> BetaFunctionToolResultType: ...
@property
def name(self) -> str:
raw = self.to_dict()
if "mcp_server_name" in raw:
return raw["mcp_server_n... | BetaBuiltinFunctionTool |
python | realpython__materials | python-double-underscore/passenger.py | {
"start": 0,
"end": 165
} | class ____:
def __init__(self, name, class_, seat):
self.name = name
self.class_ = class_
self.seat = seat
# Implementation...
| Passenger |
python | python__mypy | mypy/test/testsemanal.py | {
"start": 1189,
"end": 2547
} | class ____(DataSuite):
files = semanal_files
native_sep = True
def run_case(self, testcase: DataDrivenTestCase) -> None:
test_semanal(testcase)
def test_semanal(testcase: DataDrivenTestCase) -> None:
"""Perform a semantic analysis test case.
The testcase argument contains a description o... | SemAnalSuite |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 11237,
"end": 11300
} | class ____(HTTPServerError):
status_code = 502
| HTTPBadGateway |
python | sanic-org__sanic | sanic/application/constants.py | {
"start": 503,
"end": 594
} | class ____(StrEnum):
"""Server modes."""
PRODUCTION = auto()
DEBUG = auto()
| Mode |
python | ray-project__ray | python/ray/tests/test_failure_4.py | {
"start": 5808,
"end": 24317
} | class ____:
def __init__(self):
self.ref = None
def invoke(self):
self.ref = foo.remote(0)
# Wait for the task to finish before exiting the driver.
ray.get(self.ref)
def get(self):
print("get", self.ref)
return self.ref
if __name__ == "__main__":
ray.i... | Actor |
python | coleifer__peewee | playhouse/reflection.py | {
"start": 12052,
"end": 13754
} | class ____(Metadata):
if FIELD_TYPE is None:
column_map = {}
else:
column_map = {
FIELD_TYPE.BLOB: TextField,
FIELD_TYPE.CHAR: CharField,
FIELD_TYPE.DATE: DateField,
FIELD_TYPE.DATETIME: DateTimeField,
FIELD_TYPE.DECIMAL: DecimalField,
... | MySQLMetadata |
python | openai__openai-python | src/openai/types/beta/realtime/realtime_response_usage.py | {
"start": 566,
"end": 800
} | class ____(BaseModel):
audio_tokens: Optional[int] = None
"""The number of audio tokens used in the Response."""
text_tokens: Optional[int] = None
"""The number of text tokens used in the Response."""
| OutputTokenDetails |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_3des.py | {
"start": 741,
"end": 1773
} | class ____:
test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "CBC"),
[
"TCBCinvperm.rsp",
"TCBCpermop.rsp",
"TCBCsubtab.rsp",
"TCBCvarkey.rsp",
"TCBCvartext.rsp",
],
lambda keys, *... | TestTripleDESModeCBC |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_reflection.py | {
"start": 19674,
"end": 21137
} | class ____(fixtures.TestBase):
"""test that index overflow tables aren't included in
table_names."""
__only_on__ = "oracle"
__sparse_driver_backend__ = True
def setup_test(self):
with testing.db.begin() as conn:
conn.exec_driver_sql(
"""
CREATE TABLE... | DontReflectIOTTest |
python | bokeh__bokeh | tests/unit/bokeh/application/test_application.py | {
"start": 7462,
"end": 7679
} | class ____:
# Public methods ----------------------------------------------------------
def test_abstract(self) -> None:
with pytest.raises(TypeError):
baa.ServerContext()
| Test_ServerContext |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 137882,
"end": 139856
} | class ____(multi_rv_frozen):
r"""Create a frozen Multinomial distribution.
Parameters
----------
n : int
number of trials
p: array_like
probability of a trial falling into each category; should sum to 1
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, op... | multinomial_frozen |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/dtensor_util_test.py | {
"start": 1356,
"end": 3371
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout.Mesh(['batch'], global_ids, local_ids,
test_util.create_device_list((... | DTensorDistributedValueTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 117740,
"end": 119821
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
tb1 = Table(
"tb1",
metadata,
Column("id", Integer),
Column("attr", Integer),
Column("name", sql_types.VARCHAR(20)),
... | CompositeKeyReflectionTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 4698,
"end": 4787
} | class ____:
f: int = 0
def object_target(x):
a = A10()
a.f = x
| A10 |
python | numba__numba | numba/tests/test_extending.py | {
"start": 53063,
"end": 56373
} | class ____(TestCase):
"""Test caching of the use of overload implementations that use
`with objmode`
"""
_numba_parallel_test_ = False
def setUp(self):
warnings.simplefilter("error", errors.NumbaWarning)
def tearDown(self):
warnings.resetwarnings()
def test_caching_overloa... | TestCachingOverloadObjmode |
python | TheAlgorithms__Python | neural_network/convolution_neural_network.py | {
"start": 546,
"end": 14293
} | class ____:
def __init__(
self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2
):
"""
:param conv1_get: [a,c,d], size, number, step of convolution kernel
:param size_p1: pooling size
:param bp_num1: units number of flatten layer
:param bp_nu... | CNN |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 159681,
"end": 160404
} | class ____:
def test_astype(self):
data = [[1, 2], [3, 4]]
actual = np.astype(
np.array(data, dtype=np.int64), np.uint32
)
expected = np.array(data, dtype=np.uint32)
assert_array_equal(actual, expected)
assert_equal(actual.dtype, expected.dtype)
... | TestAsType |
python | openai__openai-python | src/openai/_streaming.py | {
"start": 3923,
"end": 7415
} | class ____(Generic[_T]):
"""Provides the core interface to iterate over an asynchronous stream response."""
response: httpx.Response
_decoder: SSEDecoder | SSEBytesDecoder
def __init__(
self,
*,
cast_to: type[_T],
response: httpx.Response,
client: AsyncOpenAI,
... | AsyncStream |
python | realpython__materials | python-serialize/http-payload/flask-rest-api/main.py | {
"start": 172,
"end": 788
} | class ____:
id: UUID
name: str
created_at: datetime
@classmethod
def create(cls, name):
return cls(uuid4(), name, datetime.now())
users = [
User.create("Alice"),
User.create("Bob"),
]
@app.route("/users", methods=["GET", "POST"])
def view_users():
if request.method == "GET":... | User |
python | automl__auto-sklearn | test/test_evaluation/test_train_evaluator.py | {
"start": 2271,
"end": 2346
} | class ____(object):
def __init__(self):
self.name = "dummy"
| Dummy |
python | openai__openai-python | src/openai/resources/fine_tuning/jobs/checkpoints.py | {
"start": 6476,
"end": 6713
} | class ____:
def __init__(self, checkpoints: Checkpoints) -> None:
self._checkpoints = checkpoints
self.list = _legacy_response.to_raw_response_wrapper(
checkpoints.list,
)
| CheckpointsWithRawResponse |
python | pytorch__pytorch | test/inductor/test_debug_trace.py | {
"start": 3534,
"end": 4572
} | class ____:
var_ranges = {p0: 256}
index0 = p0
def body(self, ops):
get_index = self.get_index('index0')
load = ops.load('arg0_1', get_index)
constant = ops.constant(1.0, torch.float32)
add = ops.add(load, constant)
get_index_1 = self.get_index('index0')
store... | op0_loop_body |
python | ray-project__ray | python/ray/train/v2/_internal/execution/context.py | {
"start": 3530,
"end": 17818
} | class ____:
train_run_context: TrainRunContext
distributed_context: DistributedContext
execution_context: ExecutionContext
storage_context: StorageContext
controller_actor: ActorHandle
dataset_shard_provider: "DatasetShardProvider"
# TODO: consolidate into CheckpointContext
checkpoint:... | TrainContext |
python | pandas-dev__pandas | pandas/tests/extension/base/dim2.py | {
"start": 10723,
"end": 12454
} | class ____(Dim2CompatTests):
# More specific tests for NDArrayBackedExtensionArray subclasses
def test_copy_order(self, data):
# We should be matching numpy semantics for the "order" keyword in 'copy'
arr2d = data.repeat(2).reshape(-1, 2)
assert arr2d._ndarray.flags["C_CONTIGUOUS"]
... | NDArrayBacked2DTests |
python | django__django | tests/admin_changelist/models.py | {
"start": 3440,
"end": 3500
} | class ____(User):
class Meta:
proxy = True
| ProxyUser |
python | keras-team__keras | benchmarks/torch_ctl_benchmark/conv_model_benchmark.py | {
"start": 948,
"end": 2638
} | class ____(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv2d(3, 32, kernel_size=(3, 3))
self.activation = torch.nn.ReLU()
self.max_pool = torch.nn.MaxPool2d((2, 2))
self.flatten = torch.nn.Flatten()
self.dense = torch.nn.LazyLinear(... | TorchModel |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 107855,
"end": 111681
} | class ____(Request):
"""
Get user and system tags used for the models under the specified projects
:param include_system: If set to 'true' then the list of the system tags is
also returned. The default value is 'false'
:type include_system: bool
:param projects: The list of projects under w... | GetModelTagsRequest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1161908,
"end": 1170336
} | class ____(Position2Def):
r"""
SecondaryFieldDef schema wrapper.
A field definition of a secondary channel that shares a scale with another primary channel.
For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``.
Parameters
----------
shorthand : str, dict, Sequenc... | SecondaryFieldDef |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_stateful.py | {
"start": 5494,
"end": 7741
} | class ____(MyStatefulMachine.TestCase):
settings = Settings(derandomize=True, stateful_step_count=5)
def test_multiple_precondition_bug():
# See https://github.com/HypothesisWorks/hypothesis/issues/2861
class MultiplePreconditionMachine(RuleBasedStateMachine):
@rule(x=st.integers())
def go... | TestMyStatefulMachine |
python | sympy__sympy | sympy/polys/polyquinticconst.py | {
"start": 503,
"end": 96035
} | class ____:
"""Special functions for solvable quintics"""
def __init__(self, poly):
_, _, self.p, self.q, self.r, self.s = poly.all_coeffs()
self.zeta1 = Rational(-1, 4) + (sqrt(5)/4) + I*sqrt((sqrt(5)/8) + Rational(5, 8))
self.zeta2 = (-sqrt(5)/4) - Rational(1, 4) + I*sqrt((-sqrt(5)/8) ... | PolyQuintic |
python | ray-project__ray | doc/source/custom_directives.py | {
"start": 16598,
"end": 16962
} | class ____(ExampleEnum):
ML_APPLICATIONS = "ML Applications"
LLM_APPLICATIONS = "LLM Applications"
INTEGRATIONS = "Integrations"
AI_ACCELERATORS = "AI Accelerators"
@classmethod
def formatted_name(cls):
return "Related Technology"
@classmethod
def key(cls: type) -> str:
... | RelatedTechnology |
python | takluyver__flit | flit_core/flit_core/vendor/tomli/_parser.py | {
"start": 1414,
"end": 4123
} | class ____(ValueError):
"""An error raised if a document is not valid TOML."""
def load(fp: BinaryIO, *, parse_float: ParseFloat = float) -> Dict[str, Any]:
"""Parse TOML from a binary file object."""
s_bytes = fp.read()
try:
s = s_bytes.decode()
except AttributeError:
warnings.war... | TOMLDecodeError |
python | plotly__plotly.py | plotly/graph_objs/layout/ternary/caxis/title/_font.py | {
"start": 235,
"end": 9931
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.ternary.caxis.title"
_path_str = "layout.ternary.caxis.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"w... | Font |
python | walkccc__LeetCode | solutions/2657. Find the Prefix Common Array of Two Arrays/2657.py | {
"start": 0,
"end": 385
} | class ____:
def findThePrefixCommonArray(self, A: list[int], B: list[int]) -> list[int]:
n = len(A)
prefixCommon = 0
ans = []
count = [0] * (n + 1)
for a, b in zip(A, B):
count[a] += 1
if count[a] == 2:
prefixCommon += 1
count[b] += 1
if count[b] == 2:
pref... | Solution |
python | keras-team__keras | keras/src/layers/preprocessing/hashing_test.py | {
"start": 268,
"end": 504
} | class ____:
def __init__(self, values):
self.values = values
def __array__(self):
return np.array(self.values)
@pytest.mark.skipif(
backend.backend() == "numpy", reason="Broken with NumPy backend."
)
| ArrayLike |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call_param.py | {
"start": 1631,
"end": 2078
} | class ____(TypedDict, total=False):
path: Required[Iterable[ActionDragPath]]
"""An array of coordinates representing the path of the drag action.
Coordinates will appear as an array of objects, eg
```
[
{ x: 100, y: 200 },
{ x: 200, y: 300 }
]
```
"""
type: Required[Li... | ActionDrag |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/inverted_pendulum_v4.py | {
"start": 201,
"end": 1693
} | class ____(MujocoEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
"rgbd_tuple",
],
"render_fps": 25,
}
def __init__(self, **kwargs):
utils.EzPickle.__init__(self, **kwargs)
obser... | InvertedPendulumEnv |
python | numpy__numpy | numpy/_core/code_generators/genapi.py | {
"start": 10884,
"end": 12259
} | class ____:
def __init__(self, name, index, ptr_cast, api_name, internal_type=None):
self.index = index
self.name = name
self.ptr_cast = ptr_cast
self.api_name = api_name
# The type used internally, if None, same as exported (ptr_cast)
self.internal_type = internal_ty... | TypeApi |
python | getsentry__sentry | src/sentry/integrations/jira/webhooks/installed.py | {
"start": 1159,
"end": 3780
} | class ____(JiraWebhookBase):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
"""
Webhook hit by Jira whenever someone installs the Sentry integration in their Jira instance.
"""
def post(self, request: Request, *args, **kwargs) -> Response:
... | JiraSentryInstalledWebhook |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 3031,
"end": 23052
} | class ____:
# check that non-array arguments to functions wrap them in arrays
def test_choose(self):
choices = [[0, 1, 2],
[3, 4, 5],
[5, 6, 7]]
tgt = [5, 1, 5]
a = [2, 0, 1]
out = np.choose(a, choices)
assert_equal(out, tgt)
de... | TestNonarrayArgs |
python | pytorch__pytorch | torch/autograd/graph.py | {
"start": 12076,
"end": 16608
} | class ____(saved_tensors_hooks):
"""Context manager under which tensors saved by the forward pass will be stored on cpu, then retrieved for backward.
When performing operations within this context manager, intermediary
results saved in the graph during the forward pass will be moved to CPU,
then copied... | save_on_cpu |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 6083,
"end": 6817
} | class ____:
params = [True, False, np.nan]
param_names = ["fill_value"]
def setup(self, fill_value):
N = 1_000_000
d = 1e-5
arr = make_array(N, d, np.nan, np.float64)
self.sp_arr = SparseArray(arr)
b_arr = np.full(shape=N, fill_value=fill_value, dtype=np.bool_)
... | GetItemMask |
python | automl__auto-sklearn | test/test_pipeline/components/regression/test_base.py | {
"start": 493,
"end": 15441
} | class ____(unittest.TestCase):
res = None
module = None
sk_module = None
# Hyperparameter which is increased by iterative_fit
step_hyperparameter = None
# Magic command to not run tests on base class
__test__ = False
def test_default_boston(self):
if self.__class__ == BaseRe... | BaseRegressionComponentTest |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/sqlite_datasource.py | {
"start": 4243,
"end": 4898
} | class ____(SqlQueryAsset):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# update the partitioner map with the Sqlite specific partitioner
self._partitioner_implementation_map[PartitionerConvertedDatetime] = (
SqlitePartitionerConvertedDateTime
)
type: Li... | SqliteQueryAsset |
python | numba__numba | numba/tests/test_mixed_tuple_unroller.py | {
"start": 58255,
"end": 62041
} | class ____(TestCase):
def test_literal_unroll_not_invoked(self):
@njit(pipeline_class=CapturingCompiler)
def foo():
acc = 0
for i in (1, 2, 3):
acc += i
return acc
foo()
cres = foo.overloads[foo.signatures[0]]
self.assertF... | TestLiteralUnrollPassTriggering |
python | pypa__pipenv | pipenv/vendor/importlib_metadata/__init__.py | {
"start": 29968,
"end": 35867
} | class ____(Distribution):
def __init__(self, path: SimplePath) -> None:
"""Construct a distribution.
:param path: SimplePath indicating the metadata directory.
"""
self._path = path
def read_text(self, filename: str | os.PathLike[str]) -> Optional[str]:
with suppress(
... | PathDistribution |
python | viewflow__viewflow | tests/test_middleware.py | {
"start": 203,
"end": 374
} | class ____(Viewset):
app_name = "nested"
page_path = path(
"page/", TemplateView.as_view(template_name="viewflow/base.html"), name="page"
)
| NestedViewset |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 131636,
"end": 132856
} | class ____(Response):
"""
Response of events.get_task_metrics endpoint.
:param metrics: List of task with their metrics
:type metrics: Sequence[dict]
"""
_service = "events"
_action = "get_task_metrics"
_version = "2.23"
_schema = {
"definitions": {},
"properties": ... | GetTaskMetricsResponse |
python | fsspec__filesystem_spec | fsspec/implementations/data.py | {
"start": 98,
"end": 1627
} | class ____(AbstractFileSystem):
"""A handy decoder for data-URLs
Example
-------
>>> with fsspec.open("data:,Hello%2C%20World%21") as f:
... print(f.read())
b"Hello, World!"
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
"""
protocol = "data"
... | DataFileSystem |
python | dateutil__dateutil | src/dateutil/tz/_factories.py | {
"start": 115,
"end": 426
} | class ____(type):
def __init__(cls, *args, **kwargs):
cls.__instance = None
super(_TzSingleton, cls).__init__(*args, **kwargs)
def __call__(cls):
if cls.__instance is None:
cls.__instance = super(_TzSingleton, cls).__call__()
return cls.__instance
| _TzSingleton |
python | apache__airflow | airflow-core/src/airflow/task/priority_strategy.py | {
"start": 2850,
"end": 3134
} | class ____(PriorityWeightStrategy):
"""Priority weight strategy that uses the task's priority weight directly."""
def get_weight(self, ti: TaskInstance):
if TYPE_CHECKING:
assert ti.task
return ti.task.priority_weight
| _AbsolutePriorityWeightStrategy |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/tensor_format.py | {
"start": 1153,
"end": 20279
} | class ____(object):
"""Options for highlighting elements of a tensor."""
def __init__(self,
criterion,
description=None,
font_attr=DEFAULT_TENSOR_ELEMENT_HIGHLIGHT_FONT_ATTR):
"""Constructor of HighlightOptions.
Args:
criterion: (callable) A callable of t... | HighlightOptions |
python | huggingface__transformers | src/transformers/models/timesformer/configuration_timesformer.py | {
"start": 788,
"end": 5568
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`TimesformerModel`]. It is used to instantiate a
TimeSformer model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a simil... | TimesformerConfig |
python | getsentry__sentry | src/sentry/notifications/notification_action/types.py | {
"start": 20071,
"end": 20781
} | class ____(Protocol):
"""Protocol for notification action forms since they have various inheritance layers and but all have the same __init__ signature"""
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def is_valid(self) -> bool: ...
@property
def cleaned_data(self) -> dict[str, Any]:... | NotificationActionForm |
python | streamlit__streamlit | lib/tests/streamlit/watcher/util_test.py | {
"start": 777,
"end": 2650
} | class ____(unittest.TestCase):
def test_md5_calculation_succeeds_with_bytes_input(self):
with patch("streamlit.watcher.util.open", mock_open(read_data=b"hello")):
md5 = util.calc_md5_with_blocking_retries("foo")
assert md5 == "5d41402abc4b2a76b9719d911017c592"
@patch("os.path.is... | UtilTest |
python | buildout__buildout | src/zc/buildout/testing.py | {
"start": 12213,
"end": 12528
} | class ____(HTTPServer):
def __init__(self, tree, *args):
HTTPServer.__init__(self, *args)
self.tree = os.path.abspath(tree)
__run = True
def serve_forever(self):
while self.__run:
self.handle_request()
def handle_error(self, *_):
self.__run = False
| Server |
python | numba__numba | numba/cuda/stubs.py | {
"start": 4105,
"end": 4267
} | class ____(Stub):
'''
syncwarp(mask=0xFFFFFFFF)
Synchronizes a masked subset of threads in a warp.
'''
_description_ = '<warp_sync()>'
| syncwarp |
python | huggingface__transformers | src/transformers/models/starcoder2/modular_starcoder2.py | {
"start": 5630,
"end": 6102
} | class ____(MistralDecoderLayer):
def __init__(self, config: Starcoder2Config, layer_idx: int):
super().__init__(config, layer_idx)
self.self_attn = Starcoder2Attention(config=config, layer_idx=layer_idx)
self.mlp = Starcoder2MLP(config)
self.input_layernorm = nn.LayerNorm(config.hidd... | Starcoder2DecoderLayer |
python | ray-project__ray | python/ray/serve/tests/unit/test_application_state.py | {
"start": 1563,
"end": 1874
} | class ____:
def __init__(self):
self.endpoints = dict()
def update_endpoint(self, endpoint, endpoint_info):
self.endpoints[endpoint] = endpoint_info
def delete_endpoint(self, endpoint):
if endpoint in self.endpoints:
del self.endpoints[endpoint]
| MockEndpointState |
python | gevent__gevent | src/gevent/tests/test__signal.py | {
"start": 102,
"end": 285
} | class ____(Exception):
pass
def raise_Expected():
raise Expected('TestSignal')
@greentest.skipUnless(hasattr(signal, 'SIGALRM'),
"Uses SIGALRM")
| Expected |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 193086,
"end": 194033
} | class ____(Operation):
def __init__(self, axis1, axis2, *, name=None):
super().__init__(name=name)
self.axis1 = axis1
self.axis2 = axis2
def call(self, x):
return backend.numpy.swapaxes(x, self.axis1, self.axis2)
def compute_output_spec(self, x):
x_shape = list(x.s... | Swapaxes |
python | ansible__ansible | lib/ansible/galaxy/collection/gpg.py | {
"start": 4498,
"end": 4667
} | class ____(GpgBaseError):
"""The signature with the keyid has not been verified okay."""
keyid: str
username: str
@dataclass(frozen=True, slots=True)
| GpgBadSig |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchvision_models.py | {
"start": 16348,
"end": 21856
} | class ____(nn.Module):
"""
Demo DETR implementation.
Demo implementation of DETR in minimal number of lines, with the
following differences wrt DETR in the paper:
* learned positional encoding (instead of sine)
* positional encoding is passed at input (instead of attention)
* fc bbox predic... | DETR |
python | openai__openai-python | src/openai/types/vector_store_deleted.py | {
"start": 194,
"end": 307
} | class ____(BaseModel):
id: str
deleted: bool
object: Literal["vector_store.deleted"]
| VectorStoreDeleted |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/pipes/clients/lambda_.py | {
"start": 758,
"end": 4270
} | class ____(PipesClient, TreatAsResourceParam):
"""A pipes client for invoking AWS lambda.
By default context is injected via the lambda input event and messages are parsed out of the
4k tail of logs.
Args:
client (boto3.client): The boto lambda client used to call invoke.
context_injec... | PipesLambdaClient |
python | google__pytype | pytype/abstract/mixin.py | {
"start": 8640,
"end": 10394
} | class ____(metaclass=MixinMeta):
"""Use lazy loading for the attributes of the represented value.
A class that mixes in LazyMembers must:
* pass init_mixin a dict of the raw attribute values. This will be stored as
the `_member_map` attribute.
* Define a `members` attribute to be a name->attribute di... | LazyMembers |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 33198,
"end": 37059
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.is_decoder = config.is_decoder
self.layer = nn.ModuleList()
self.layer.append(
UdopLayerSelfAttention(
... | UdopBlock |
python | pennersr__django-allauth | allauth/headless/socialaccount/inputs.py | {
"start": 1503,
"end": 4727
} | class ____(inputs.Input):
provider = inputs.CharField()
process = inputs.ChoiceField(
choices=[
(AuthProcess.LOGIN, AuthProcess.LOGIN),
(AuthProcess.CONNECT, AuthProcess.CONNECT),
]
)
token = inputs.Field()
def clean(self):
cleaned_data = super().clea... | ProviderTokenInput |
python | Pylons__pyramid | tests/test_session.py | {
"start": 17963,
"end": 19396
} | class ____(unittest.TestCase):
def _makeOne(self, wrapped):
from pyramid.session import manage_accessed
return manage_accessed(wrapped)
def test_accessed_set(self):
request = testing.DummyRequest()
session = DummySessionFactory(request)
session.renewed = 0
wrapp... | Test_manage_accessed |
python | huggingface__transformers | src/transformers/modeling_gguf_pytorch_utils.py | {
"start": 1939,
"end": 3270
} | class ____(TensorProcessor):
def __init__(self, config=None):
super().__init__(config=config)
def process(self, weights, name, **kwargs):
if ".attn_k." in name or ".attn_q." in name:
num_heads = self.config.get("num_attention_heads")
num_kv_heads = self.config.get("num_k... | LlamaTensorProcessor |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 12911,
"end": 14280
} | class ____(ContextWrappingVariable):
"""represents torch.autograd.forward_ad._set_fwd_grad_enabled() to enable/disable fwd grad"""
@staticmethod
def create(
tx: "InstructionTranslator", target_values: Any, **kwargs: Any
) -> "SetFwdGradEnabledContextManager":
return SetFwdGradEnabledCon... | SetFwdGradEnabledContextManager |
python | scikit-learn__scikit-learn | examples/cluster/plot_inductive_clustering.py | {
"start": 1765,
"end": 3953
} | class ____(BaseEstimator):
def __init__(self, clusterer, classifier):
self.clusterer = clusterer
self.classifier = classifier
def fit(self, X, y=None):
self.clusterer_ = clone(self.clusterer)
self.classifier_ = clone(self.classifier)
y = self.clusterer_.fit_predict(X)
... | InductiveClusterer |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 14698,
"end": 15064
} | class ____(WrapperLine):
wrapper: PythonWrapperCodegen
node: ir.Conditional
def codegen(self, code: IndentedBuffer) -> None:
raise NotImplementedError("Only supports FX codegen")
@staticmethod
def codegen_fx(converter: FxConverter) -> FxConversionFunc:
return converter._generate_co... | ConditionalLine |
python | walkccc__LeetCode | solutions/3410. Maximize Subarray Sum After Removing All Occurrences of One Element/3410-2.py | {
"start": 0,
"end": 873
} | class ____:
def maxSubarraySum(self, nums: list[int]) -> int:
ans = max(nums)
prefix = 0
minPrefix = 0
# the minimum prefix sum that can have a negative number removed
modifiedMinPrefix = 0
count = collections.Counter()
# minPrefixPlusRemoval[num] := the minimum prefix sum plus removed `nu... | Solution |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 28913,
"end": 30910
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: GroupViTConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = GroupViTAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = GroupViT... | GroupViTEncoderLayer |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 30514,
"end": 31026
} | class ____(Structure):
_fields_ = (
("module_name", p_uint32),
("iextdefsym", p_uint32),
("nextdefsym", p_uint32),
("irefsym", p_uint32),
("nrefsym", p_uint32),
("ilocalsym", p_uint32),
("nlocalsym", p_uint32),
("iextrel", p_uint32),
("nextrel"... | dylib_module_64 |
python | conda__conda | conda/models/records.py | {
"start": 18809,
"end": 20958
} | class ____(PackageRecord):
"""Representation of a package that has been downloaded or unpacked in the local package cache.
Specialization of :class:`PackageRecord` that adds information for packages that exist in the
local package cache, either as the downloaded package file, or unpacked in its own package... | PackageCacheRecord |
python | pytorch__pytorch | test/dynamo/test_dicts.py | {
"start": 814,
"end": 856
} | class ____(UserDict):
pass
| DummyUserDict |
python | wandb__wandb | wandb/integration/openai/resolver.py | {
"start": 466,
"end": 654
} | class ____:
usage: UsageMetrics = None
stats: wandb.Table = None
trace: trace_tree.WBTraceTree = None
usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())}
| Metrics |
python | kamyu104__LeetCode-Solutions | Python/maximal-score-after-applying-k-operations.py | {
"start": 731,
"end": 1230
} | class ____(object):
def maxKelements(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
result = 0
for i, x in enumerate(nums):
nums[i] = -x
heapq.heapify... | Solution2 |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 82413,
"end": 85756
} | class ____(TestCase):
def test_simple(self):
# Condition is single bool list
x = piecewise([0, 0], [True, False], [1])
assert_array_equal(x, [1, 0])
# List of conditions: single bool list
x = piecewise([0, 0], [[True, False]], [1])
assert_array_equal(x, [1, 0])
... | TestPiecewise |
python | PrefectHQ__prefect | src/prefect/_experimental/sla/client.py | {
"start": 1936,
"end": 3611
} | class ____(BaseAsyncClient):
async def apply_slas_for_deployment(
self, deployment_id: "UUID", slas: "list[SlaTypes]"
) -> "UUID":
"""
Applies service level agreements for a deployment. Performs matching by SLA name. If a SLA with the same name already exists, it will be updated. If a SL... | SlaAsyncClient |
python | has2k1__plotnine | tests/test_geom_smooth.py | {
"start": 3551,
"end": 6025
} | class ____:
p = ggplot(linear_data, aes("x")) + geom_point(aes(y="y_noisy"))
def test_wls(self):
p = self.p + geom_smooth(aes(y="y_noisy"), method="wls")
p.draw_test()
def test_rlm(self):
p = self.p + geom_smooth(aes(y="y_noisy"), method="rlm")
with pytest.warns(PlotnineWar... | TestOther |
python | kamyu104__LeetCode-Solutions | Python/can-i-win.py | {
"start": 30,
"end": 1004
} | class ____(object):
def canIWin(self, maxChoosableInteger, desiredTotal):
"""
:type maxChoosableInteger: int
:type desiredTotal: int
:rtype: bool
"""
def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup):
if visited in lookup:
... | Solution |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_config_command.py | {
"start": 10129,
"end": 11375
} | class ____:
@classmethod
def setup_class(cls):
cls.parser = cli_parser.get_parser()
@conf_vars({("core", "test_key"): "test_value"})
def test_should_display_value(self, stdout_capture):
with stdout_capture as temp_stdout:
config_command.get_value(self.parser.parse_args(["con... | TestCliConfigGetValue |
python | davidhalter__parso | test/test_diff_parser.py | {
"start": 19421,
"end": 34468
} | class ____:
def f():
return node
Some'random text: yeah
for push in plan.dfa_pushes:
def g():
try:
1
except KeyError:
2
''')
differ.initialize(code1)
differ.parse(code2, parsers=2, copies=1, expect_error_leaves=True)
differ.parse(code... | C |
python | euske__pdfminer | pdfminer/converter.py | {
"start": 4270,
"end": 4658
} | class ____(PDFLayoutAnalyzer):
def __init__(self, rsrcmgr, pageno=1, laparams=None):
PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
self.result = None
return
def receive_layout(self, ltpage):
self.result = ltpage
return
def get_result(s... | PDFPageAggregator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-fauna/source_fauna/source.py | {
"start": 812,
"end": 1273
} | class ____:
def __init__(self, conf):
# Domain of Fauna connection (localhost, db.fauna.com).
self.domain = conf["domain"]
# Port of Fauna connection (8443, 443).
self.port = conf["port"]
# Scheme of Fauna connection (https, http).
self.scheme = conf["scheme"]
... | Config |
python | realpython__materials | qt-designer-python/sample_editor/app.py | {
"start": 913,
"end": 1181
} | class ____(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
loadUi("ui/find_replace.ui", self)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec())
| FindReplaceDialog |
python | numpy__numpy | numpy/lib/_polynomial_impl.py | {
"start": 33516,
"end": 44125
} | class ____:
"""
A one-dimensional polynomial class.
.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/rout... | poly1d |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 12665,
"end": 13002
} | class ____(io.IOBase):
def __init__(self, fp, msg, status, reason):
self.fp = fp
self.msg = msg
self.status = status
self.reason = reason
self.code = 200
def read(self):
return ''
def info(self):
return {}
def geturl(self):
return self.u... | MockHTTPResponse |
python | huggingface__transformers | tests/models/d_fine/test_modeling_d_fine.py | {
"start": 1512,
"end": 10980
} | class ____:
def __init__(
self,
parent,
batch_size=3,
is_training=True,
use_labels=True,
n_targets=3,
num_labels=10,
initializer_range=0.02,
layer_norm_eps=1e-5,
batch_norm_eps=1e-5,
# backbone
backbone_config=None,
... | DFineModelTester |
python | tornadoweb__tornado | tornado/test/tcpserver_test.py | {
"start": 363,
"end": 3814
} | class ____(AsyncTestCase):
@gen_test
def test_handle_stream_coroutine_logging(self):
# handle_stream may be a coroutine and any exception in its
# Future will be logged.
class TestServer(TCPServer):
@gen.coroutine
def handle_stream(self, stream, address):
... | TCPServerTest |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/properties/snippets.py | {
"start": 2583,
"end": 2701
} | class ____(messages.Message):
text = messages.StringField(1, required=True)
when = messages.IntegerField(2)
| Note |
python | getsentry__sentry | src/sentry/deletions/defaults/uptime_subscription.py | {
"start": 221,
"end": 1324
} | class ____(ModelDeletionTask[UptimeSubscription]):
def delete_instance(self, instance: UptimeSubscription) -> None:
detector = get_detector(instance)
# XXX: Typically quota updates would be handled by the
# delete_uptime_detector function exposed in the
# uptime.subscriptions.subsc... | UptimeSubscriptionDeletionTask |
python | doocs__leetcode | solution/2600-2699/2653.Sliding Subarray Beauty/Solution.py | {
"start": 0,
"end": 547
} | class ____:
def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]:
def f(x: int) -> int:
s = 0
for i in range(50):
s += cnt[i]
if s >= x:
return i - 50
return 0
cnt = [0] * 101
for v ... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.