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 | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 182714,
"end": 183443
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"item_id",
"field_id",
"value",
"client_mutation_id",
)
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphq... | UpdateProjectV2ItemFieldValueInput |
python | ray-project__ray | python/ray/dag/dag_operation_future.py | {
"start": 1174,
"end": 4961
} | class ____(DAGOperationFuture[Any]):
"""
A future for a GPU event on a CUDA stream.
This future wraps a buffer, and records an event on the given stream
when it is created. When the future is waited on, it makes the current
CUDA stream wait on the event, then returns the buffer.
The buffer mus... | GPUFuture |
python | PyCQA__pylint | tests/functional/n/non/non_iterator_returned.py | {
"start": 776,
"end": 899
} | class ____:
""" __iter__ returns iter(...) """
def __iter__(self):
return iter(range(10))
| FourthGoodIterator |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datacatalog.py | {
"start": 29381,
"end": 30628
} | class ____:
@mock.patch(
"airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook",
**{"return_value.lookup_entry.return_value": TEST_ENTRY},
)
def test_assert_valid_hook_call(self, mock_hook) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
... | TestCloudDataCatalogLookupEntryOperator |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_sentinels.py | {
"start": 157,
"end": 1018
} | class ____:
"""Create a unique sentinel object."""
__slots__ = ('_name',)
_name: str
def __new__(cls, name: str, /) -> Self:
sentinel = super().__new__(cls)
object.__setattr__(sentinel, '_name', str(name))
return sentinel
def __repr__(self) -> str:
return self._na... | _Sentinel |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 1963,
"end": 2459
} | class ____(View):
def post(self, request, *args, **kwargs):
default_user = CustomUser.objects.create_superuser(
"test_user", "test_user@example.com", "pass"
)
polls = Poll.objects.all()
for i, poll in enumerate(polls):
poll.question = str(i)
bulk_upda... | PollBulkUpdateWithDefaultUserView |
python | great-expectations__great_expectations | great_expectations/data_context/templates.py | {
"start": 212,
"end": 5293
} | class ____(YAML):
"""
Get yaml dump as a string: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string
"""
def dump(self, data, stream=None, **kw): # type: ignore[explicit-override] # FIXME
inefficient = False
if not stream:
inefficient = True
... | YAMLToString |
python | keon__algorithms | algorithms/queues/queue.py | {
"start": 655,
"end": 1084
} | class ____(metaclass=ABCMeta):
def __init__(self):
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
@abstractmethod
def enqueue(self, value):
pass
@abstractmethod
def dequeue(self):
pass
@abstract... | AbstractQueue |
python | pytorch__pytorch | test/quantization/jit/test_ondevice_quantization.py | {
"start": 10214,
"end": 22318
} | class ____(TestCase):
def _validate_packed_params(self, model, num_nodes, per_channel=0):
quantize_forward_graph = model.quantize_forward.graph
quantize_per_tensor = quantize_per_channel = 0
linear_prepack = 0
linear_prepack_uses = 0
for n in quantize_forward_graph.nodes():
... | TestOnDeviceDynamicPTQFinalize |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py | {
"start": 1308,
"end": 1854
} | class ____:
table_name: str
stream_prefix: Optional[str]
stream_name: str
json_schema: Mapping[str, Any]
connection_id: str
connection_name: str
destination_type: Optional[str]
database: Optional[str]
schema: Optional[str]
@property
def fully_qualified_table_name(self) -> Op... | AirbyteConnectionTableProps |
python | django-haystack__django-haystack | haystack/query.py | {
"start": 23711,
"end": 24415
} | class ____(ValuesListSearchQuerySet):
"""
A ``SearchQuerySet`` which returns a list of dictionaries, each containing
the key/value pairs for the result, exactly like Django's
``ValuesQuerySet``.
"""
def _fill_cache(self, start, end):
query_fields = set(self._internal_fields)
que... | ValuesSearchQuerySet |
python | doocs__leetcode | solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py | {
"start": 127,
"end": 660
} | class ____:
def __init__(self):
self.good = []
self.bad = []
def add(self, name: str, score: int) -> None:
score, node = heappushpop(self.good, (score, Node(name)))
heappush(self.bad, (-score, node.s))
def get(self) -> str:
score, name = heappop(self.bad)
h... | SORTracker |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_xbins.py | {
"start": 233,
"end": 7476
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.xbins"
_valid_props = {"end", "size", "start"}
@property
def end(self):
"""
Sets the end value for the x axis bins. The last bin may not
end exactly at this value, we increment the... | XBins |
python | getsentry__sentry | tests/sentry/seer/similarity/test_utils.py | {
"start": 39804,
"end": 40116
} | class ____(TestCase):
def test_filter_null_from_string(self) -> None:
string_with_null = 'String with null \x00, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" is null'
assert filter_null_from_string(string_with_null) == 'String with null , "" is null'
| SeerUtilsTest |
python | aimacode__aima-python | search.py | {
"start": 53162,
"end": 55316
} | class ____(Problem):
"""Delegates to a problem, and keeps statistics."""
def __init__(self, problem):
self.problem = problem
self.succs = self.goal_tests = self.states = 0
self.found = None
def actions(self, state):
self.succs += 1
return self.problem.actions(state)... | InstrumentedProblem |
python | mahmoud__glom | glom/core.py | {
"start": 27027,
"end": 28618
} | class ____:
"""Spec objects serve three purposes, here they are, roughly ordered
by utility:
1. As a form of compiled or "curried" glom call, similar to
Python's built-in :func:`re.compile`.
2. A marker as an object as representing a spec rather than a
literal value in certain cas... | Spec |
python | zarr-developers__zarr-python | src/zarr/codecs/sharding.py | {
"start": 2594,
"end": 3122
} | class ____(_ShardingByteGetter, ByteSetter):
shard_dict: ShardMutableMapping
async def set(self, value: Buffer, byte_range: ByteRequest | None = None) -> None:
assert byte_range is None, "byte_range is not supported within shards"
self.shard_dict[self.chunk_coords] = value
async def delete... | _ShardingByteSetter |
python | weaviate__weaviate-python-client | weaviate/users/sync.py | {
"start": 296,
"end": 384
} | class ____(_UsersOIDCExecutor[ConnectionSync]):
pass
@executor.wrap("sync")
| _UsersOIDC |
python | getsentry__sentry | tests/sentry/receivers/test_data_forwarding.py | {
"start": 240,
"end": 6226
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
def test_auto_enrollment_when_enroll_new_projects_enabled(self) -> None:
data_forwarder = DataForwarde... | DataForwardingReceiverTest |
python | tensorflow__tensorflow | tensorflow/python/training/adadelta_test.py | {
"start": 1224,
"end": 7973
} | class ____(test.TestCase):
def doTestBasic(self, use_resource=False, use_callable_params=False):
num_updates = 4 # number of ADADELTA steps to perform
for dtype in [dtypes.half, dtypes.float32]:
for grad in [0.2, 0.1, 0.01]:
for lr in [1.0, 0.5, 0.1]:
var0_init = [1.0, 2.0]
... | AdadeltaOptimizerTest |
python | doocs__leetcode | solution/2500-2599/2549.Count Distinct Numbers on Board/Solution.py | {
"start": 0,
"end": 92
} | class ____:
def distinctIntegers(self, n: int) -> int:
return max(1, n - 1)
| Solution |
python | django__django | tests/admin_views/admin.py | {
"start": 16899,
"end": 16969
} | class ____(admin.ModelAdmin):
search_fields = ("name",)
| StudentAdmin |
python | bokeh__bokeh | src/bokeh/core/validation/issue.py | {
"start": 2077,
"end": 2945
} | class ____(Issue):
_code_map: ClassVar[dict[int, Error]] = {}
_name_map: ClassVar[dict[str, Error]] = {}
def __post_init__(self) -> None:
Error._code_map[self.code] = self
Error._name_map[self.name] = self
@classmethod
def get_by_code(cls, code: int) -> Error:
return cls._c... | Error |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 72514,
"end": 75564
} | class ____(_LazyConvXdMixin, ConvTranspose2d): # type: ignore[misc]
r"""A :class:`torch.nn.ConvTranspose2d` module with lazy initialization of the ``in_channels`` argument.
The ``in_channels`` argument of the :class:`ConvTranspose2d` is inferred from
the ``input.size(1)``.
The attributes that will be ... | LazyConvTranspose2d |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_cli_integration.py | {
"start": 3761,
"end": 5823
} | class ____:
"""
Integration version of job CLI test that ensures interaction with the
following components are working as expected:
1) Ray client: use of RAY_ADDRESS and ray.init() in job_head.py
2) Ray dashboard: `ray start --head`
"""
def test_empty_ray_address(self, ray_start_stop):
... | TestRayAddress |
python | TheAlgorithms__Python | divide_and_conquer/convex_hull.py | {
"start": 675,
"end": 16233
} | class ____:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
... | Point |
python | walkccc__LeetCode | solutions/351. Android Unlock Patterns/351.py | {
"start": 0,
"end": 911
} | class ____:
def numberOfPatterns(self, m: int, n: int) -> int:
seen = set()
accross = [[0] * 10 for _ in range(10)]
accross[1][3] = accross[3][1] = 2
accross[1][7] = accross[7][1] = 4
accross[3][9] = accross[9][3] = 6
accross[7][9] = accross[9][7] = 8
accross[1][9] = accross[9][1] = accro... | Solution |
python | getsentry__sentry | src/sentry/sentry_apps/logic.py | {
"start": 15421,
"end": 23227
} | class ____:
name: str
author: str
organization_id: int
is_internal: bool
scopes: list[str] = dataclasses.field(default_factory=list)
events: list[str] = dataclasses.field(default_factory=list)
webhook_url: str | None = None
redirect_url: str | None = None
is_alertable: bool = False
... | SentryAppCreator |
python | getsentry__sentry | src/sentry/spans/consumers/process_segments/types.py | {
"start": 732,
"end": 1298
} | class ____(SpanEvent, total=True):
"""A span that has the same fields as a kafka span, plus shimming for logic shared with the event pipeline.
This type will be removed eventually."""
exclusive_time: float
op: str
sentry_tags: dict[str, str]
# Added by `SpanGroupingResults.write_to_spans` in ... | CompatibleSpan |
python | spack__spack | lib/spack/spack/operating_systems/freebsd.py | {
"start": 235,
"end": 404
} | class ____(OperatingSystem):
def __init__(self):
release = py_platform.release().split("-", 1)[0]
super().__init__("freebsd", Version(release))
| FreeBSDOs |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/complex.py | {
"start": 11812,
"end": 12928
} | class ____(BaseComplex[np.dtypes.Complex128DType, np.complex128], HasEndianness):
"""
A Zarr data type for arrays containing 64 bit complex floats.
Wraps the [`np.dtypes.Complex128DType`][numpy.dtypes.Complex128DType] data type. Scalars for this data type
are instances of [`np.complex128`][numpy.comple... | Complex128 |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 69524,
"end": 71669
} | class ____(FunctionPass):
"""Implement the literal_unroll semantics"""
_name = "literal_unroll"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
# Determine whether to even attempt this pass... if there's no
# `literal_unroll` as a global or as a freev... | LiteralUnroll |
python | scrapy__scrapy | tests/test_http_request.py | {
"start": 58373,
"end": 64728
} | class ____(TestRequest):
request_class = JsonRequest
default_method = "GET"
default_headers = {
b"Content-Type": [b"application/json"],
b"Accept": [b"application/json, text/javascript, */*; q=0.01"],
}
def test_data(self):
r1 = self.request_class(url="http://www.example.com/... | TestJsonRequest |
python | lepture__authlib | authlib/oidc/core/errors.py | {
"start": 2572,
"end": 2731
} | class ____(OAuth2Error):
"""The OP does not support use of the request_uri parameter."""
error = "request_uri_not_supported"
| RequestURINotSupportedError |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 546,
"end": 1533
} | class ____(views.Feed):
title = "My blog"
description = "A more thorough description of my blog."
link = "/blog/"
feed_guid = "/foo/bar/1234"
author_name = "Sally Smith"
author_email = "test@example.com"
author_link = "http://www.example.com/"
categories = ("python", "django")
feed_c... | TestRss2Feed |
python | pydata__xarray | xarray/tests/test_sparse.py | {
"start": 28020,
"end": 29458
} | class ____:
@pytest.mark.xfail(reason="Coercion of coords to dense")
def test_sparse_coords(self):
xr.DataArray(
sparse.COO.from_numpy(np.arange(4)),
dims=["x"],
coords={"x": sparse.COO.from_numpy([1, 2, 3, 4])},
)
@requires_dask
def test_chunk():
s = sp... | TestSparseCoords |
python | wandb__wandb | wandb/sdk/lib/printer.py | {
"start": 12062,
"end": 12284
} | class ____(DynamicText):
def __init__(self, handle: term.DynamicBlock) -> None:
self._handle = handle
@override
def set_text(self, text: str) -> None:
self._handle.set_text(text)
| _DynamicTermText |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 4777,
"end": 7736
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.k.
question_answering_score (`torch.FloatTensor` of shap... | LxmertForQuestionAnsweringOutput |
python | kamyu104__LeetCode-Solutions | Python/find-the-last-marked-nodes-in-tree.py | {
"start": 35,
"end": 1016
} | class ____(object):
def lastMarkedNodes(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
def bfs(root):
new_root = -1
dist = [-1]*len(adj)
dist[root] = 0
q = [root]
while q:
new_ro... | Solution |
python | getsentry__sentry | src/sentry/models/files/control_fileblobindex.py | {
"start": 278,
"end": 667
} | class ____(AbstractFileBlobIndex):
__relocation_scope__ = RelocationScope.Excluded
file = FlexibleForeignKey("sentry.ControlFile")
blob = FlexibleForeignKey("sentry.ControlFileBlob", on_delete=models.PROTECT)
class Meta:
app_label = "sentry"
db_table = "sentry_controlfileblobindex"
... | ControlFileBlobIndex |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 139084,
"end": 142853
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[4, 3]"):
l_x_ = L_x_
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors_ho... | GraphModule |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 5402,
"end": 5657
} | class ____(TypedDict):
"""A dictionary representing on object on the AST."""
name: str
module: str
type: str
ast_type: str
src: str
op: "VyperAstNode"
value: Dict
test: Dict
VyperAstJson = List[VyperAstNode]
| VyperAstNode |
python | ray-project__ray | python/ray/tests/test_get_or_create_actor.py | {
"start": 1530,
"end": 3085
} | class ____:
def ping(self):
return "ok"
@ray.remote
def getter(name):
actor = Actor.options(
name="foo", lifetime="detached", namespace="n", get_if_exists=True).remote()
ray.get(actor.ping.remote())
def do_run(name):
name = "actor_" + str(name)
tasks = [getter.remote(name) for i ... | Actor |
python | FactoryBoy__factory_boy | factory/enums.py | {
"start": 278,
"end": 557
} | class ____:
#: During attribute resolution/computation
ATTRIBUTE_RESOLUTION = 'attributes'
#: Once the target object has been built
POST_INSTANTIATION = 'post_instance'
def get_builder_phase(obj):
return getattr(obj, 'FACTORY_BUILDER_PHASE', None)
| BuilderPhase |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_tags.py | {
"start": 1837,
"end": 4790
} | class ____:
"""Common class for /dags related unit tests."""
@staticmethod
def _clear_db():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
clear_db_serialized_dags()
def _create_deactivated_paused_dag(self, session=None):
dag_model = DagModel(
... | TestDagEndpoint |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/testpkg-compatmodule/pkg/api2.py | {
"start": 147,
"end": 180
} | class ____ (object):
pass
| MyClass |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1055711,
"end": 1056691
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (
AddedToProjectEvent,
AssignedEvent,
ClosedEvent,
CommentDeletedEvent,
ConnectedEvent,
ConvertedNoteToIssueEvent,
ConvertedToDiscuss... | IssueTimelineItems |
python | django__django | tests/admin_views/models.py | {
"start": 16861,
"end": 17010
} | class ____(models.Model):
owner = models.ForeignKey(User, models.SET_NULL, null=True, blank=True)
title = models.CharField(max_length=30)
| Album |
python | pytorch__pytorch | test/functorch/test_control_flow.py | {
"start": 347375,
"end": 355856
} | class ____(torch.nn.Module):
def forward(self, primals_2: "f32[3, 3]", primals_3: "f32[3]", cat: "f32[u2, 3, 3]", tangents_1: "f32[3, 3]"):
zeros: "i64[]" = torch.ops.aten.zeros.default([], dtype = torch.int64, device = device(type='cpu'), pin_memory = False)
zeros_like: "f32[3]" = torch.ops.aten.ze... | GraphModule |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 5576,
"end": 5802
} | class ____(torch.Tensor):
x: int = 10
size: int = 10
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
return super().__torch_function__(func, types, args, kwargs)
| AttrSubclass |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_generic_transfer.py | {
"start": 5270,
"end": 7629
} | class ____:
def teardown_method(self):
tables_to_drop = ["test_postgres_to_postgres", "test_airflow"]
with PostgresHook().get_conn() as conn:
with conn.cursor() as cur:
for table in tables_to_drop:
cur.execute(f"DROP TABLE IF EXISTS {table}")
def ... | TestPostgres |
python | kamyu104__LeetCode-Solutions | Python/delete-leaves-with-a-given-value.py | {
"start": 191,
"end": 611
} | class ____(object):
def removeLeafNodes(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: TreeNode
"""
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root... | Solution |
python | pallets__werkzeug | src/werkzeug/routing/rules.py | {
"start": 9885,
"end": 32538
} | class ____(RuleFactory):
"""A Rule represents one URL pattern. There are some options for `Rule`
that change the way it behaves and are passed to the `Rule` constructor.
Note that besides the rule-string all arguments *must* be keyword arguments
in order to not break the application on Werkzeug upgrade... | Rule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/utils.py | {
"start": 4378,
"end": 7182
} | class ____:
"""
A basic builder that constructs a URL with placeholder parameters like:
{{client_id_param}}
{{redirect_uri_param}}
etc.
These placeholders will be replaced later during Oauth flow.
"""
def __init__(self):
self._scheme = "https"
self._host = ""
... | PlaceholderUrlBuilder |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 5977,
"end": 7016
} | class ____(TestCase):
"""Smoke test of functions (array_like) -> scalar or python object."""
@parametrize("func, np_func", one_arg_scalar_funcs)
def test_toscalar_tensor(self, func, np_func):
t = torch.Tensor([[1, 2, 3], [4, 5, 6]])
ta = func(t)
tn = np_func(_np.asarray(t))
... | TestOneArrToScalar |
python | numba__numba | numba/tests/test_indexing.py | {
"start": 23539,
"end": 35390
} | class ____(TestCase):
"""
Test basic indexed store into an array.
Note fancy indexing is tested in test_fancy_indexing.
"""
def test_conversion_setitem(self, flags=enable_pyobj_flags):
""" this used to work, and was used in one of the tutorials """
from numba import jit
def... | TestSetItem |
python | kamyu104__LeetCode-Solutions | Python/diagonal-traverse-ii.py | {
"start": 688,
"end": 1120
} | class ____(object):
def findDiagonalOrder(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
result = []
for r, row in enumerate(nums):
for c, num in enumerate(row):
if len(result) <= r+c:
result.append([... | Solution2 |
python | openai__openai-python | src/openai/types/beta/threads/runs/code_interpreter_tool_call.py | {
"start": 1102,
"end": 1473
} | class ____(BaseModel):
input: str
"""The input to the Code Interpreter tool call."""
outputs: List[CodeInterpreterOutput]
"""The outputs from the Code Interpreter tool call.
Code Interpreter can output one or more items, including text (`logs`) or images
(`image`). Each of these are represente... | CodeInterpreter |
python | google__jax | jax/_src/custom_derivatives.py | {
"start": 3355,
"end": 16584
} | class ____(Generic[ReturnValue]):
"""Set up a JAX-transformable function for a custom JVP rule definition.
This class is meant to be used as a function decorator. Instances are
callables that behave similarly to the underlying function to which the
decorator was applied, except when a differentiation transform... | custom_jvp |
python | sphinx-doc__sphinx | sphinx/ext/doctest.py | {
"start": 1620,
"end": 5291
} | class ____(SphinxDirective):
"""Base class for doctest-related directives."""
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
def run(self) -> list[Node]:
# use ordinary docutils nodes for test code: they get special attributes
... | TestDirective |
python | joblib__joblib | joblib/externals/cloudpickle/cloudpickle.py | {
"start": 19482,
"end": 43594
} | class ____:
"""Sentinel for empty closures."""
@classmethod
def __reduce__(cls):
return cls.__name__
def _make_function(code, globals, name, argdefs, closure):
# Setting __builtins__ in globals is needed for nogil CPython.
globals["__builtins__"] = __builtins__
return types.FunctionTy... | _empty_cell_value |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 5127,
"end": 5660
} | class ____(HasOptions, Generic[R, T0, T1, T2]):
def __init__(self, function: Callable[[T0, T1, T2], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2]]",
) -> "ObjectRef[R]":
... | RemoteFunction2 |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 5140,
"end": 10192
} | class ____:
_values: collections.defaultdict[str, int] = collections.defaultdict(int)
# Track sizes of known not re-inplaced tensors (exclude dynamic shapes).
@classmethod
def add_missed_bytes(cls, trigger: ReInplaceTrigger, bytes: int) -> None:
if bytes != 0:
cls._values[f"missed_b... | ReinplaceCounters |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 16409,
"end": 16489
} | class ____(PaliGemmaCausalLMOutputWithPast):
pass
| Gemma3CausalLMOutputWithPast |
python | tensorflow__tensorflow | tensorflow/python/saved_model/registration/registration_test.py | {
"start": 4587,
"end": 7640
} | class ____(test.TestCase):
def test_invalid_registration(self):
with self.assertRaisesRegex(TypeError, "must be string"):
registration.register_checkpoint_saver(
package=None,
name="test",
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=lambda: Non... | CheckpointSaverRegistrationTest |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_whoosh_backend.py | {
"start": 1840,
"end": 2300
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr="author", indexed=False)
pub_date = indexes.DateTimeField(model_attr="pub_date")
sites = indexes.MultiValueField()
seen_count = indexes.IntegerField(inde... | AllTypesWhooshMockSearchIndex |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 40995,
"end": 41709
} | class ____(FieldValues):
"""
Check that empty string ('', ' ') is acceptable value for the DecimalField
if allow_null=True and there are max/min validators
"""
valid_inputs = {
None: None,
'': None,
' ': None,
' ': None,
5: Decimal('5'),
'0': Decimal(... | TestAllowEmptyStrDecimalFieldWithValidators |
python | pytorch__pytorch | test/dynamo/test_logging.py | {
"start": 3029,
"end": 34028
} | class ____(LoggingTestCase):
test_bytecode = multi_record_test(2, bytecode=True)
test_output_code = multi_record_test(3, output_code=True)
test_aot_graphs = multi_record_test(3, aot_graphs=True)
@requires_gpu
@make_logging_test(schedule=True)
def test_schedule(self, records):
fn_opt = t... | LoggingTests |
python | pennersr__django-allauth | allauth/headless/internal/restkit/response.py | {
"start": 262,
"end": 1267
} | class ____(JsonResponse):
def __init__(
self,
request,
errors=None,
data=None,
meta: Optional[Dict] = None,
status: int = HTTPStatus.OK,
):
d: Dict[str, Any] = {"status": status}
if data is not None:
d["data"] = data
meta = self... | APIResponse |
python | getsentry__sentry | tests/sentry/seer/autofix/test_issue_summary.py | {
"start": 36379,
"end": 38491
} | class ____:
@patch("sentry.seer.autofix.issue_summary.sign_with_seer_secret", return_value={})
@patch("sentry.seer.autofix.issue_summary.requests.post")
def test_fetch_user_preference_success(self, mock_post, mock_sign):
mock_response = Mock()
mock_response.json.return_value = {
... | TestFetchUserPreference |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 230696,
"end": 241334
} | class ____(Request):
"""
Save frames into a draft version. Frame IDs, if sent, will be ignored, and every frame will be assigned a new ID.
:param version: Draft version ID
:type version: str
:param frames: Frames to save
:type frames: Sequence[Frame]
"""
_service = "datasets"
_acti... | SaveFramesRequest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/test_utils.py | {
"start": 13271,
"end": 14139
} | class ____(RunCoordinator, ConfigurableClass):
def __init__(self, inst_data: Optional[ConfigurableClassData] = None):
self._inst_data = inst_data
self._queue = []
super().__init__()
def submit_run(self, context: SubmitRunContext):
dagster_run = context.dagster_run
check... | MockedRunCoordinator |
python | walkccc__LeetCode | solutions/3162. Find the Number of Good Pairs I/3162.py | {
"start": 0,
"end": 199
} | class ____:
def numberOfPairs(self, nums1: list[int], nums2: list[int], k: int) -> int:
return sum(num1 % (num2 * k) == 0
for num1 in nums1
for num2 in nums2)
| Solution |
python | walkccc__LeetCode | solutions/258. Add Digits/258.py | {
"start": 0,
"end": 104
} | class ____:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else 1 + (num - 1) % 9
| Solution |
python | joke2k__faker | faker/providers/automotive/tl_PH/__init__.py | {
"start": 57,
"end": 237
} | class ____(EnPhAutomotiveProvider):
"""Implement automotive provider for ``tl_PH`` locale.
There is no difference from the ``en_PH`` implementation.
"""
pass
| Provider |
python | walkccc__LeetCode | solutions/701. Insert into a Binary Search Tree/701.py | {
"start": 0,
"end": 296
} | class ____:
def insertIntoBST(self, root: TreeNode | None, val: int) -> TreeNode | None:
if not root:
return TreeNode(val)
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
| Solution |
python | getsentry__sentry | src/sentry/preprod/api/models/project_preprod_build_details_models.py | {
"start": 1371,
"end": 1541
} | class ____(BaseModel):
metrics_artifact_type: PreprodArtifactSizeMetrics.MetricsArtifactType
install_size_bytes: int
download_size_bytes: int
| SizeInfoSizeMetric |
python | pydantic__pydantic | pydantic/mypy.py | {
"start": 14985,
"end": 15625
} | class ____:
"""Based on mypy.plugins.dataclasses.DataclassAttribute.
ClassVars are ignored by subclasses.
Attributes:
name: the ClassVar name
"""
def __init__(self, name):
self.name = name
@classmethod
def deserialize(cls, data: JsonDict) -> PydanticModelClassVar:
... | PydanticModelClassVar |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 22458,
"end": 39929
} | class ____:
exit_stack = None
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = self.exit_stack.__doc__
obj = self.exit_stack()
self.assertEqual(obj.__doc__, cm_docstring)
def t... | _TestBaseExitStack |
python | realpython__materials | python-pydantic/settings_management.py | {
"start": 101,
"end": 453
} | class ____(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=True,
extra="forbid",
)
database_host: HttpUrl
database_user: str = Field(min_length=5)
database_password: str = Field(min_length=10)
api_key: ... | AppConfig |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/tests/test_rl_trainer.py | {
"start": 865,
"end": 8459
} | class ____(RLTrainer):
def set_is_policy_updating(self, is_updating):
self.update_policy = is_updating
def get_policy(self, name_behavior_id):
return mock.Mock()
def _is_ready_update(self):
return True
def _update_policy(self):
return self.update_policy
def add_po... | FakeTrainer |
python | eth-brownie__brownie | brownie/network/contract.py | {
"start": 5046,
"end": 18720
} | class ____(_ContractBase):
"""List-like container class that holds all Contract instances of the same
type, and is used to deploy new instances of that contract.
Attributes:
abi: Complete contract ABI.
bytecode: Bytecode used to deploy the contract.
signatures: Dictionary of {'funct... | ContractContainer |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 20541,
"end": 22980
} | class ____(AdminTestMixin, TestCase):
"""Test export ok when column name is defined in fields list (issue 1828)."""
def setUp(self):
super().setUp()
self.author = Author.objects.create(id=11, name="Ian Fleming")
self.book = Book.objects.create(
name="Moonraker", author=self.... | CustomColumnNameExportTest |
python | graphql-python__graphene | graphene/types/definitions.py | {
"start": 817,
"end": 894
} | class ____(GrapheneGraphQLType, GraphQLObjectType):
pass
| GrapheneObjectType |
python | getsentry__sentry | src/sentry/notifications/notification_action/types.py | {
"start": 2011,
"end": 2111
} | class ____(TypedDict):
actions: list[dict[str, Any]]
legacy_rule_id: NotRequired[int]
| RuleData |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataflow.py | {
"start": 20993,
"end": 28039
} | class ____:
@pytest.mark.parametrize(
("job_current_state", "fail_on_terminal_state"),
[
(DataflowJobStatus.JOB_STATE_RUNNING, True),
(DataflowJobStatus.JOB_STATE_RUNNING, False),
(DataflowJobStatus.JOB_STATE_DONE, False),
],
)
@mock.patch("airflow... | TestDataflowJobAutoScalingEventsSensor |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 50790,
"end": 53943
} | class ____(RobertaPreLayerNormPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roberta_prelayernorm = RobertaPreLayerNormModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout... | RobertaPreLayerNormForTokenClassification |
python | tensorflow__tensorflow | tensorflow/python/ops/tensor_array_ops.py | {
"start": 2231,
"end": 15973
} | class ____:
"""Graph-mode implementation of TensorArray."""
def __init__(self,
dtype,
size=None,
dynamic_size=None,
clear_after_read=None,
tensor_array_name=None,
handle=None,
flow=None,
infer_sh... | _GraphTensorArray |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_run.py | {
"start": 18424,
"end": 23268
} | class ____(distribute_lib.ReplicaContext):
"""ReplicaContext for synchronized replica."""
def _merge_call(self, fn, args, kwargs):
"""`merge_call()` implementation for synchronized replica.
This pauses the current replica thread and passes `fn` and its arguments to
the main thread. The main thread wil... | _MirroredReplicaContext |
python | MongoEngine__mongoengine | tests/document/test_timeseries_collection.py | {
"start": 285,
"end": 6679
} | class ____(unittest.TestCase):
def setUp(self):
connect(db="mongoenginetest")
self.db = get_db()
class SensorData(Document):
timestamp = DateTimeField(required=True)
temperature = FloatField()
meta = {
"timeseries": {
... | TestTimeSeriesCollections |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 6434,
"end": 6634
} | class ____(graphene.ObjectType):
entries = non_null_list(GrapheneWorkspaceLocationStatusEntry)
class Meta:
name = "WorkspaceLocationStatusEntries"
| GrapheneWorkspaceLocationStatusEntries |
python | palantir__python-language-server | pyls/python_ls.py | {
"start": 3190,
"end": 18671
} | class ____(MethodDispatcher):
""" Implementation of the Microsoft VSCode Language Server Protocol
https://github.com/Microsoft/language-server-protocol/blob/master/versions/protocol-1-x.md
"""
# pylint: disable=too-many-public-methods,redefined-builtin
def __init__(self, rx, tx, check_parent_proce... | PythonLanguageServer |
python | Pylons__pyramid | tests/test_config/test_assets.py | {
"start": 142,
"end": 11831
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.config import Configurator
config = Configurator(*arg, **kw)
return config
def test_override_asset_samename(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
... | TestAssetsConfiguratorMixin |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 8859,
"end": 9053
} | class ____(object):
"A unique, named, sentinel object."
def __init__(self, name):
self.name = name
def __repr__(self):
return 'sentinel.%s' % self.name
| _SentinelObject |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 20625,
"end": 21253
} | class ____(nn.Module):
"""Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
This rescales diagonally the residual outputs close to 0, with a learnt scale.
"""
def __init__(self, config):
super().__init__()
channels = config.hidden_size
initial_sca... | MimiLayerScale |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/mapping/last.py | {
"start": 674,
"end": 3115
} | class ____(PartitionMapping, NamedTuple("_LastPartitionMapping", [])):
"""Maps all dependencies to the last partition in the upstream asset.
Commonly used in the case when the downstream asset is not partitioned, in which the entire
downstream asset depends on the last partition of the upstream asset.
... | LastPartitionMapping |
python | PyCQA__pylint | doc/data/messages/s/single-string-used-for-slots/bad.py | {
"start": 0,
"end": 126
} | class ____: # [single-string-used-for-slots]
__slots__ = "name"
def __init__(self, name):
self.name = name
| Fruit |
python | celery__celery | celery/backends/gcs.py | {
"start": 5266,
"end": 12563
} | class ____(GCSBackendBase):
"""Google Cloud Storage task result backend.
Uses Firestore for chord ref count.
"""
implements_incr = True
supports_native_join = True
# Firestore parameters
_collection_name = 'celery'
_field_count = 'chord_count'
_field_expires = 'expires_at'
de... | GCSBackend |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 3808,
"end": 4018
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {
"$ref": create_definition_ref("io.k8s.api.core.v1.LocalObjectReference")
},
}
| SecretRef |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 126634,
"end": 136915
} | class ____(ScopedExprNode):
# Used as part of for statement implementation.
#
# Implements result = iter(sequence)
#
# sequence ExprNode
type = py_object_type
iter_func_ptr = None
counter_cname = None
reversed = False # currently only used for list/tuple types (see Optimiz... | IteratorNode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.