language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 3720,
"end": 4519
} | class ____(EmptyIntegerField):
def to_internal_value(self, value):
value = super().to_internal_value(value)
# XXX(epurkhiser): As part of GH-56526 we changed the minimum value
# allowed for the checkin_margin to 1 from 0. Some monitors may still
# be upserting monitors with a 0 for ... | MissedMarginField |
python | dagster-io__dagster | python_modules/libraries/dagster-census/dagster_census/components/census_scaffolder.py | {
"start": 272,
"end": 349
} | class ____(BaseModel):
api_key: Optional[str] = None
| CensusScaffolderParams |
python | zarr-developers__zarr-python | src/zarr/core/indexing.py | {
"start": 11736,
"end": 12192
} | class ____(NamedTuple):
"""A mapping from chunk to output array for a single dimension.
Attributes
----------
dim_chunk_ix
Index of chunk.
dim_chunk_sel
Selection of items from chunk array.
dim_out_sel
Selection of items in target (output) array.
"""
dim_chunk_i... | ChunkDimProjection |
python | matplotlib__matplotlib | lib/matplotlib/tri/_tricontour.py | {
"start": 174,
"end": 10220
} | class ____(ContourSet):
"""
Create and store a set of contour lines or filled regions for
a triangular grid.
This class is typically not instantiated directly by the user but by
`~.Axes.tricontour` and `~.Axes.tricontourf`.
%(contour_set_attributes)s
"""
def __init__(self, ax, *args, *... | TriContourSet |
python | pytorch__pytorch | benchmarks/dynamo/microbenchmarks/operator_inp_utils.py | {
"start": 1380,
"end": 4602
} | class ____:
def __init__(self, call, *args, **kwargs):
self.call = call
self.args = tree_map(truncate_inp, args)
self.kwargs = tree_map(truncate_inp, kwargs) if kwargs is not None else {}
def __repr__(self):
args = ", ".join([repr(arg) for arg in self.args])
kwargs = "".... | FuncCallWrapper |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 23190,
"end": 23664
} | class ____(BaseModel):
"""
Update a task's state.
If a process exits without sending one of these the state will be derived from the exit code:
- 0 = SUCCESS
- anything else = FAILED
"""
state: Literal[
TaskInstanceState.FAILED,
TaskInstanceState.SKIPPED,
TaskInstan... | TaskState |
python | django__django | tests/model_forms/tests.py | {
"start": 89043,
"end": 105053
} | class ____(TestCase):
def setUp(self):
if os.path.exists(temp_storage_dir):
shutil.rmtree(temp_storage_dir)
os.mkdir(temp_storage_dir)
self.addCleanup(shutil.rmtree, temp_storage_dir)
def test_clean_false(self):
"""
If the ``clean`` method on a non-required F... | FileAndImageFieldTests |
python | pytorch__pytorch | torch/distributed/elastic/timer/file_based_local_timer.py | {
"start": 5907,
"end": 16484
} | class ____:
"""
Server that works with ``FileTimerClient``. Clients are expected to be
running on the same host as the process that is running this server.
Each host in the job is expected to start its own timer server locally
and each server instance manages timers for local workers (running on
... | FileTimerServer |
python | walkccc__LeetCode | solutions/1932. Merge BSTs to Create Single BST/1932.py | {
"start": 0,
"end": 1148
} | class ____:
def canMerge(self, trees: list[TreeNode]) -> TreeNode | None:
valToNode = {} # {val: node}
count = collections.Counter() # {val: freq}
for tree in trees:
valToNode[tree.val] = tree
count[tree.val] += 1
if tree.left:
count[tree.left.val] += 1
if tree.right:
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/discord/provider.py | {
"start": 281,
"end": 2767
} | class ____(ProviderAccount):
def validate_descriminator(self, discriminator):
if not isinstance(discriminator, str):
return False
# As of 2023-06-22, Discord returns string literal '0' for users
# with no discriminator
return len(discriminator) == 4 if discriminator.isd... | DiscordAccount |
python | numba__llvmlite | llvmlite/binding/value.py | {
"start": 721,
"end": 854
} | class ____(enum.IntEnum):
# The LLVMVisibility enum from llvm-c/Core.h
default = 0
hidden = 1
protected = 2
| Visibility |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 4100,
"end": 4244
} | class ____(Screen):
"""A screen with a simple alpha key binding."""
BINDINGS = [Binding("a", "a", "a", priority=True)]
| ScreenWithBindings |
python | django__django | tests/auth_tests/test_views.py | {
"start": 29480,
"end": 38472
} | class ____(AuthViewsTestCase):
def test_current_site_in_context_after_login(self):
response = self.client.get(reverse("login"))
self.assertEqual(response.status_code, 200)
if apps.is_installed("django.contrib.sites"):
Site = apps.get_model("sites.Site")
site = Site.ob... | LoginTest |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 879494,
"end": 905489
} | class ____:
'''
We use @staticmethod to avoid the need to create an instance of this class.
'''
def _derotate_matrix(page):
if isinstance(page, mupdf.PdfPage):
return JM_py_from_matrix(JM_derotate_page_matrix(page))
else:
return JM_py_from_matrix(mupdf.FzMatrix()... | TOOLS |
python | kubernetes-client__python | kubernetes/client/api/rbac_authorization_v1_api.py | {
"start": 543,
"end": 417962
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | RbacAuthorizationV1Api |
python | joke2k__faker | faker/providers/internet/th_TH/__init__.py | {
"start": 83,
"end": 670
} | class ____(InternetProvider):
free_email_domains = (
"hotmail.com",
"gmail.com",
"outlook.com",
"yahoo.com",
"ymail.com",
"kon.in.th",
"icloud.com",
"protonmail.com",
)
tlds = OrderedDict(
(
("in.th", 100),
("co... | Provider |
python | pandas-dev__pandas | pandas/tests/computation/test_eval.py | {
"start": 59636,
"end": 63522
} | class ____:
def eval(self, *args, **kwargs):
kwargs["level"] = kwargs.pop("level", 0) + 1
return pd.eval(*args, **kwargs)
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
@pytest.mark.parametrize("fn", _unary_math_ops)
def test_unary_functions(self, fn, engine, parser):
df ... | TestMath |
python | coleifer__peewee | tests/postgres.py | {
"start": 2072,
"end": 4282
} | class ____(ModelTestCase):
database = db
requires = [TZModel]
@skip_if(os.environ.get('CI'), 'running in ci mode, skipping')
def test_tz_field(self):
self.database.set_time_zone('us/eastern')
# Our naive datetime is treated as if it were in US/Eastern.
dt = datetime.datetime(20... | TestTZField |
python | sympy__sympy | sympy/functions/elementary/exponential.py | {
"start": 6306,
"end": 6519
} | class ____(FunctionClass):
def __instancecheck__(cls, instance):
if exp in instance.__class__.__mro__:
return True
return isinstance(instance, Pow) and instance.base is S.Exp1
| ExpMeta |
python | doocs__leetcode | lcof2/剑指 Offer II 079. 所有子集/Solution.py | {
"start": 0,
"end": 373
} | class ____:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(i, n, t):
res.append(t.copy())
if i == n:
return
for j in range(i, n):
t.append(nums[j])
dfs(j + 1, n, t)
t.pop()
... | Solution |
python | pallets__jinja | tests/test_core_tags.py | {
"start": 19913,
"end": 20567
} | class ____:
def test_with(self, env):
tmpl = env.from_string(
"""\
{% with a=42, b=23 -%}
{{ a }} = {{ b }}
{% endwith -%}
{{ a }} = {{ b }}\
"""
)
assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] == [
"42 ... | TestWith |
python | pypa__warehouse | tests/unit/admin/views/test_projects.py | {
"start": 1018,
"end": 2286
} | class ____:
def test_no_query(self, db_request):
projects = sorted(
ProjectFactory.create_batch(30),
key=lambda p: p.normalized_name,
)
result = views.project_list(db_request)
assert result == {"projects": projects[:25], "query": None, "exact_match": None}
... | TestProjectList |
python | nryoung__algorithms | tests/test_data_structures.py | {
"start": 12543,
"end": 15978
} | class ____(unittest.TestCase):
"""
Test Undirected Graph Implementation
"""
def test_directed_graph(self):
# init
self.dg0 = digraph.Digraph()
self.dg1 = digraph.Digraph()
self.dg2 = digraph.Digraph()
self.dg3 = digraph.Digraph()
# populating
sel... | TestDirectedGraph |
python | walkccc__LeetCode | solutions/3264. Final Array State After K Multiplication Operations I/3264.py | {
"start": 0,
"end": 412
} | class ____:
def getFinalState(
self,
nums: list[int],
k: int,
multiplier: int
) -> list[int]:
ans = [0] * len(nums)
minHeap = [(num, i) for i, num in enumerate(nums)]
heapq.heapify(minHeap)
for _ in range(k):
num, i = heapq.heappop(minHeap)
heapq.heappush(minHeap... | Solution |
python | spyder-ide__spyder | spyder/plugins/tours/widgets.py | {
"start": 10562,
"end": 22017
} | class ____(FadingDialog):
"""Dialog that contains the text for each frame in the tour."""
def __init__(self, parent, opacity, duration, easing_curve, tour=None,
color_top=None, color_back=None, combobox_background=None):
super().__init__(parent, opacity, duration, easing_curve)
... | FadingTipBox |
python | pypa__warehouse | tests/unit/admin/views/test_prohibited_project_names.py | {
"start": 13969,
"end": 15828
} | class ____:
def test_no_prohibited_project_name_id(self):
request = pretend.stub(POST={})
with pytest.raises(HTTPBadRequest):
views.remove_prohibited_project_names(request)
def test_prohibited_project_name_id_not_exist(self, db_request):
db_request.POST["prohibited_project_... | TestRemoveProhibitedProjectName |
python | rushter__MLAlgorithms | mla/linear_models.py | {
"start": 218,
"end": 3326
} | class ____(BaseEstimator):
def __init__(
self, lr=0.001, penalty="None", C=0.01, tolerance=0.0001, max_iters=1000
):
"""Basic class for implementing continuous regression estimators which
are trained with gradient descent optimization on their particular loss
function.
P... | BasicRegression |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 36170,
"end": 38274
} | class ____(Operation):
def __init__(self, dtype=None, *, name=None):
super().__init__(name=name)
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
def call(self, x):
return backend.numpy.view(x, dtype=self.dtype)
def compute_output_spec(self, x):
old_... | View |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1407457,
"end": 1407734
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData):
"""Audit log entry for a repo.config.enable_collaborators_only event."""
__schema__ = github_schema
__field_names__ = ()
| RepoConfigEnableCollaboratorsOnlyAuditEntry |
python | huggingface__transformers | src/transformers/models/falcon/modeling_falcon.py | {
"start": 2208,
"end": 4414
} | class ____(nn.Linear):
def forward(self, input: torch.Tensor) -> torch.Tensor:
hidden_states = input @ self.weight.T
if self.bias is None:
return hidden_states
return hidden_states + self.bias
# Copied from transformers.models.llama.modeling_llama.rotate_half
def rotate_half(x)... | FalconLinear |
python | kamyu104__LeetCode-Solutions | Python/super-ugly-number.py | {
"start": 77,
"end": 808
} | class ____(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
heap, uglies, idx, ugly_by_last_prime = [], [0] * n, [0] * len(primes), [0] * n
uglies[0] = 1
for k, p in enumerate(primes):
... | Solution |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_float.py | {
"start": 885,
"end": 2113
} | class ____(_BaseTestFloat):
test_cls = Float16
valid_dtype = (np.dtype(">f2"), np.dtype("<f2"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float32),
)
valid_json_v2 = (
{"name": ">f2", "object_codec_id": None},
{"name": "<f2", "objec... | TestFloat16 |
python | django__django | tests/test_client_regress/tests.py | {
"start": 818,
"end": 1093
} | class ____:
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create_user(username="testclient", password="password")
cls.staff = User.objects.create_user(
username="staff", password="password", is_staff=True
)
| TestDataMixin |
python | apache__airflow | devel-common/src/tests_common/test_utils/logging_command_executor.py | {
"start": 1063,
"end": 2823
} | class ____(LoggingMixin):
"""Logging command executor."""
def execute_cmd(self, cmd, silent=False, cwd=None, env=None):
if silent:
self.log.info("Executing in silent mode: '%s'", " ".join(shlex.quote(c) for c in cmd))
return subprocess.call(
args=cmd, stdout=subp... | LoggingCommandExecutor |
python | astropy__astropy | astropy/convolution/tests/test_kernel_class.py | {
"start": 1466,
"end": 21824
} | class ____:
"""
Test class for the built-in convolution kernels.
"""
@pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy")
@pytest.mark.parametrize("width", WIDTHS_ODD)
def test_scipy_filter_gaussian(self, width):
"""
Test GaussianKernel against SciPy ndimage gaussian filt... | TestKernels |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 2162,
"end": 2289
} | class ____[Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, Cccccccccccccccccccccc]:
pass
| TestTypeParams |
python | getsentry__sentry | src/sentry/deletions/base.py | {
"start": 9343,
"end": 10732
} | class ____(ModelDeletionTask[ModelT]):
"""
An efficient mechanism for deleting larger volumes of rows in one pass,
but will hard fail if the relations have resident foreign relations.
Note: Does NOT support child relations.
"""
DEFAULT_CHUNK_SIZE = 10000
def chunk(self, apply_filter: bool... | BulkModelDeletionTask |
python | readthedocs__readthedocs.org | readthedocs/projects/management/commands/import_project_from_live.py | {
"start": 300,
"end": 3457
} | class ____(BaseCommand):
"""
Import project from production API.
This is a helper to debug issues with projects on the server more easily
locally. It allows you to import projects based on the data that the public
API provides.
"""
help = (
"Retrieves the data of a project from rea... | Command |
python | gevent__gevent | src/gevent/_config.py | {
"start": 8352,
"end": 8554
} | class ____(object):
# Don't do string-to-list conversion.
def _convert(self, value):
if value:
return int(value)
validate = staticmethod(validate_anything)
| IntSettingMixin |
python | pytorch__pytorch | torch/_inductor/cudagraph_trees.py | {
"start": 10405,
"end": 16399
} | class ____:
mark_step_counter = 0
# We need to register this as an object that will be copied over as TLS when new
# threads are created in autograd
torch._C._stash_obj_in_tls("tree_manager_containers", local.tree_manager_containers)
torch._C._stash_obj_in_tls("tree_manager_locks", local.tree_manager_locks)
def... | MarkStepBox |
python | readthedocs__readthedocs.org | readthedocs/core/history.py | {
"start": 4391,
"end": 4951
} | class ____:
"""
Set the change_reason on the model changed through the POST method of this view.
Use this class for views that don't use a form, like ``DeleteView``.
"""
change_reason = None
def get_change_reason(self):
if self.change_reason:
return self.change_reason
... | UpdateChangeReasonPostView |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 282156,
"end": 282595
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "client_mutation_id", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutati... | DisablePullRequestAutoMergePayload |
python | pandas-dev__pandas | pandas/core/resample.py | {
"start": 67576,
"end": 70662
} | class ____(DatetimeIndexResampler):
# error: Incompatible types in assignment (expression has type "PeriodIndex", base
# class "DatetimeIndexResampler" defined the type as "DatetimeIndex")
ax: PeriodIndex # type: ignore[assignment]
@property
def _resampler_for_grouping(self):
return Period... | PeriodIndexResampler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassReplace1.py | {
"start": 188,
"end": 510
} | class ____:
a: int
b: str
c: str = ""
dc1: DC1 = DC1(1, "")
dc1_clone = dc1.__replace__(b="", a=1, c="")
reveal_type(dc1_clone, expected_text="DC1")
dc1.__replace__(c="")
dc1.__replace__(b="2")
# This should generate an error.
dc1.__replace__(b=2)
# This should generate an error.
dc1.__replace__(d="")... | DC1 |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers.py | {
"start": 2836,
"end": 3064
} | class ____(ResolutionError):
def __init__(self, causes):
super(ResolutionImpossible, self).__init__(causes)
# causes is a list of RequirementInformation objects
self.causes = causes
| ResolutionImpossible |
python | MongoEngine__mongoengine | mongoengine/queryset/visitor.py | {
"start": 700,
"end": 1999
} | class ____(QNodeVisitor):
"""Simplifies query trees by combining unnecessary 'and' connection nodes
into a single Q-object.
"""
def visit_combination(self, combination):
if combination.operation == combination.AND:
# The simplification only applies to 'simple' queries
if... | SimplificationVisitor |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 31828,
"end": 40664
} | class ____(Request):
"""
Get all queues
:param name: Get only queues whose name matches this pattern (python regular
expression syntax)
:type name: str
:param id: List of Queue IDs used to filter results
:type id: Sequence[str]
:param tags: User-defined tags list used to filter resu... | GetAllRequest |
python | doocs__leetcode | solution/1900-1999/1982.Find Array Given Subset Sums/Solution.py | {
"start": 0,
"end": 690
} | class ____:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
m = -min(sums)
sl = SortedList(x + m for x in sums)
sl.remove(0)
ans = [sl[0]]
for i in range(1, n):
for j in range(1 << i):
if j >> (i - 1) & 1:
s = sum(... | Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py | {
"start": 9541,
"end": 10892
} | class ____(NonLaunchableGraphQLContextTestMatrix):
def test_permissions_query(self, graphql_context):
result = execute_dagster_graphql(graphql_context, PERMISSIONS_QUERY)
assert result.data
assert result.data["permissions"]
permissions_map = {
permission["permission"]: ... | TestPermissionsQuery |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/schemas.py | {
"start": 40701,
"end": 42528
} | class ____:
"""
Configuration for AOTDispatcher
"""
fw_compiler: Callable
bw_compiler: Callable
partition_fn: Callable
decompositions: dict[OpOverload, Callable]
num_params_buffers: int
aot_id: int
keep_inference_input_mutations: bool
is_export: bool = False
no_tangents:... | AOTConfig |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/single_xla.py | {
"start": 1387,
"end": 4690
} | class ____(SingleDeviceStrategy):
"""Strategy for training on a single XLA device."""
def __init__(
self,
device: _DEVICE,
accelerator: Optional["pl.accelerators.Accelerator"] = None,
checkpoint_io: Optional[Union[XLACheckpointIO, _WrappingCheckpointIO]] = None,
precisio... | SingleDeviceXLAStrategy |
python | boto__boto3 | boto3/dynamodb/conditions.py | {
"start": 6001,
"end": 6129
} | class ____(ConditionBase):
expression_operator = 'attribute_type'
expression_format = '{operator}({0}, {1})'
| AttributeType |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 337359,
"end": 338064
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("EnterpriseServerUserAccountEmailEdge"),
graphql_name="edg... | EnterpriseServerUserAccountEmailConnection |
python | doocs__leetcode | lcof/面试题03. 数组中重复的数字/Solution2.py | {
"start": 0,
"end": 188
} | class ____:
def findRepeatNumber(self, nums: List[int]) -> int:
vis = set()
for v in nums:
if v in vis:
return v
vis.add(v)
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 303496,
"end": 303954
} | class ____(sgqlc.types.Input):
"""Ways in which star connections can be ordered."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(StarOrderField), graphql_name="field")
"""The field in which to order nodes by."""
direction = ... | StarOrder |
python | mlflow__mlflow | mlflow/entities/webhook.py | {
"start": 11428,
"end": 13447
} | class ____:
"""
MLflow entity for WebhookTestResult.
"""
def __init__(
self,
success: bool,
response_status: int | None = None,
response_body: str | None = None,
error_message: str | None = None,
):
"""
Initialize a WebhookTestResult entity.
... | WebhookTestResult |
python | ray-project__ray | python/ray/data/_internal/execution/streaming_executor_state.py | {
"start": 7589,
"end": 32650
} | class ____:
"""The execution state tracked for each PhysicalOperator.
This tracks state to manage input and output buffering for StreamingExecutor and
progress bars, which is separate from execution state internal to the operators.
Note: we use the `deque` data structure here because it is thread-safe... | OpState |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 31091,
"end": 32325
} | class ____(LinalgSquareTestCase, LinalgNonsquareTestCase):
def do(self, a, b, tags):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, False)
x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
if m == 0:
assert_((x == 0).all())
if m <= n:
... | LstsqCases |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/selector.py | {
"start": 7973,
"end": 8944
} | class ____:
location_name: str
repository_name: str
sensor_name: str
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"sensorName": self.sensor_name,
}
@staticmethod
de... | SensorSelector |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 12203,
"end": 12293
} | class ____(nodes.Admonition, nodes.Element):
"""Custom "see also" admonition."""
| seealso |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/streaming/_beta_types.py | {
"start": 1167,
"end": 1344
} | class ____(BaseModel):
type: Literal["thinking"]
thinking: str
"""The thinking delta"""
snapshot: str
"""The accumulated thinking so far"""
| BetaThinkingEvent |
python | PyCQA__pycodestyle | testing/data/E30.py | {
"start": 627,
"end": 2124
} | class ____:
def a(self):
pass
def b(self):
pass
#: E303:5:5
if True:
a = 1
a = 2
#: E304:3:1
@decorator
def function():
pass
#: E303:5:1
#!python
"""This class docstring comes on line 5.
It gives error E303: too many blank lines (3)
"""
#:
#: E305:7:1
def a():
print
... | xyz |
python | huggingface__transformers | tests/models/vit_mae/test_modeling_vit_mae.py | {
"start": 1496,
"end": 6242
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
... | ViTMAEModelTester |
python | django__django | tests/migrations/test_state.py | {
"start": 70904,
"end": 81574
} | class ____(SimpleTestCase):
def setUp(self):
self.apps = Apps(["migrations.related_models_app"])
def create_model(
self, name, foreign_keys=[], bases=(), abstract=False, proxy=False
):
test_name = "related_models_app"
assert not (abstract and proxy)
meta_contents = {... | RelatedModelsTests |
python | kamyu104__LeetCode-Solutions | Python/minimum-addition-to-make-integer-beautiful.py | {
"start": 41,
"end": 566
} | class ____(object):
def makeIntegerBeautiful(self, n, target):
"""
:type n: int
:type target: int
:rtype: int
"""
total, m = 0, n
while m:
total += m%10
m //= 10
m, l = n, 0
while total > target:
while True:
... | Solution |
python | astropy__astropy | astropy/modeling/tests/test_bounding_box.py | {
"start": 71522,
"end": 82426
} | class ____:
def test_create(self):
arguments = _SelectorArguments(
(_SelectorArgument(0, True), _SelectorArgument(1, False))
)
assert isinstance(arguments, _SelectorArguments)
assert arguments == ((0, True), (1, False))
assert arguments._kept_ignore == []
... | Test_SelectorArguments |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/shell_b/package.py | {
"start": 217,
"end": 516
} | class ____(Package):
"""Simple package with no dependencies for shell tests"""
homepage = "http://www.example.com"
url = "http://www.example.com/shell-b-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
version("0.9", md5="abcd456789abcdef0123456789abcdef")
| ShellB |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 154106,
"end": 178177
} | class ____(FieldChannelMixin, core.FacetEncodingFieldDef):
r"""
Facet schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :cl... | Facet |
python | langchain-ai__langchain | libs/langchain/langchain_classic/output_parsers/fix.py | {
"start": 515,
"end": 703
} | class ____(TypedDict, total=False):
"""Input for the retry chain of the OutputFixingParser."""
instructions: str
completion: str
error: str
| OutputFixingParserRetryChainInput |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/uninitializedVariable3.py | {
"start": 216,
"end": 262
} | class ____(NamedTuple):
x: int
y: float
| A |
python | PyCQA__pylint | tests/test_check_parallel.py | {
"start": 5309,
"end": 5513
} | class ____(ParallelTestChecker):
"""A checker that does need to consolidate data across run invocations."""
name = "third-parallel-checker"
test_data = "third-parallel"
| ThirdParallelTestChecker |
python | getsentry__sentry | tests/sentry/data_secrecy/test_cache.py | {
"start": 404,
"end": 7779
} | class ____(TestCase):
def setUp(self) -> None:
self.organization_id = 123
self.cache_key = CACHE_KEY_PATTERN.format(organization_id=self.organization_id)
self.current_time = datetime(2025, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
self.access_start = datetime(2025, 1, 1, 10, 0, 0, tzinfo=... | EffectiveGrantStatusCacheTest |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_typing.py | {
"start": 3545,
"end": 3660
} | class ____:
...
var_a1: A[str] # [unsubscriptable-object]
var_a2: "A[str]" # string annotations aren't checked
| A |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 7464,
"end": 7813
} | class ____(scale_position_continuous):
"""
Continuous y position
"""
_aesthetics = [
"y",
"ymin",
"ymax",
"yend",
"yintercept",
"ymin_final",
"ymax_final",
"lower",
"middle",
"upper",
]
# Transformed scales
@dataclass... | scale_y_continuous |
python | getsentry__sentry | tests/sentry/receivers/test_signals.py | {
"start": 726,
"end": 8439
} | class ____(TestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.now = timezone.now()
self.owner = self.create_user()
self.organization = self.create_organization(owner=self.owner)
self.team = self.create_team(organization=self.organization)
self.pro... | SignalsTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox43.py | {
"start": 315,
"end": 994
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox43.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | has2k1__plotnine | plotnine/themes/elements/element_text.py | {
"start": 329,
"end": 6552
} | class ____(element_base):
"""
Theme element: Text
Parameters
----------
family :
Font family. See [](`~matplotlib.text.Text.set_family`)
for supported values.
style :
Font style
color :
Text color
weight :
Should be one of `normal`, `bold`, `heavy... | element_text |
python | ray-project__ray | python/ray/util/client/server/proxier.py | {
"start": 16196,
"end": 24793
} | class ____(ray_client_pb2_grpc.RayletDriverServicer):
def __init__(self, ray_connect_handler: Callable, proxy_manager: ProxyManager):
self.proxy_manager = proxy_manager
self.ray_connect_handler = ray_connect_handler
def _call_inner_function(
self, request, context, method: str
) -> ... | RayletServicerProxy |
python | getsentry__sentry | src/sentry/hybridcloud/models/externalactorreplica.py | {
"start": 309,
"end": 1355
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
externalactor_id = BoundedPositiveIntegerField()
team_id = HybridCloudForeignKey("sentry.Team", null=True, db_index=True, on_delete="CASCADE")
user = FlexibleForeignKey("sentry.User", null=True, db_index=True, on_delete=models.CASCADE)
... | ExternalActorReplica |
python | huggingface__transformers | src/transformers/models/vjepa2/modeling_vjepa2.py | {
"start": 15080,
"end": 17065
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the original implementation."""
def __init__(
self,
config: VJEPA2Config,
drop_path_rate: float = 0.0,
hidden_size: int = 1024,
num_attention_heads: int = 16,
mlp_ratio: float = 4.0... | VJEPA2Layer |
python | doocs__leetcode | lcof2/剑指 Offer II 014. 字符串中的变位词/Solution2.py | {
"start": 0,
"end": 752
} | class ____:
def checkInclusion(self, s1: str, s2: str) -> bool:
m, n = len(s1), len(s2)
if m > n:
return False
cnt = Counter()
for a, b in zip(s1, s2):
cnt[a] -= 1
cnt[b] += 1
diff = sum(x != 0 for x in cnt.values())
if diff == 0:
... | Solution |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 3772,
"end": 4579
} | class ____:
def bar(self, b: Union[B8, C8], x): # Interval: [1,2]
if x == 1:
return self.baz() # Interval: [1,2] /\ [1,2] = [1,2]
elif x == 2:
# Interval: [1,2]. First, this may return a source because b may
# resolve to B and the intersection between B’s interv... | A8 |
python | pallets__itsdangerous | src/itsdangerous/serializer.py | {
"start": 693,
"end": 1339
} | class ____(t.Protocol[_TSerialized]):
def loads(self, payload: _TSerialized, /) -> t.Any: ...
# A signature with additional arguments is not handled correctly by type
# checkers right now, so an overload is used below for serializers that
# don't match this strict protocol.
def dumps(self, obj: t.An... | _PDataSerializer |
python | sanic-org__sanic | sanic/models/futures.py | {
"start": 940,
"end": 1046
} | class ____(NamedTuple):
handler: ErrorMiddlewareType
exceptions: list[BaseException]
| FutureException |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 23218,
"end": 23406
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("CONTENT_ONLY", "NOTE_ONLY", "REDACTED")
| ProjectCardState |
python | automl__auto-sklearn | autosklearn/evaluation/train_evaluator.py | {
"start": 5436,
"end": 54448
} | class ____(AbstractEvaluator):
def __init__(
self,
backend: Backend,
queue: multiprocessing.Queue,
metrics: Sequence[Scorer],
additional_components: Dict[str, ThirdPartyComponents],
port: Optional[int],
configuration: Optional[Union[int, Configuration]] = None... | TrainEvaluator |
python | great-expectations__great_expectations | great_expectations/execution_engine/sparkdf_execution_engine.py | {
"start": 2999,
"end": 3870
} | class ____(ValueError):
def __init__(self, value: Any) -> None:
super().__init__(f"Invalid row condition type: {type(value)}")
def apply_dateutil_parse(column):
assert len(column.columns) == 1, "Expected DataFrame with 1 column"
col_name = column.columns[0]
_udf = F.udf(parse, pyspark.types.Ti... | InvalidRowConditionException |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/api/test_operations.py | {
"start": 19876,
"end": 24609
} | class ____:
connection_id: str = "test_connection"
conn_type: str = "conn_type"
host: str = "host"
schema_: str = "schema"
login: str = "login"
password: str = "password"
port: int = 1
extra: str = json.dumps({"extra": "extra"})
connection = ConnectionBody(
connection_id=conn... | TestConnectionsOperations |
python | Textualize__rich | examples/attrs.py | {
"start": 257,
"end": 348
} | class ____:
point1: Point3D
point2: Point3D
point3: Point3D
@attr.define
| Triangle |
python | celery__celery | celery/bin/multi.py | {
"start": 5647,
"end": 7213
} | class ____:
splash_text = 'celery multi v{version}'
splash_context = {'version': VERSION_BANNER}
#: Final exit code.
retcode = 0
def setup_terminal(self, stdout, stderr,
nosplash=False, quiet=False, verbose=False,
no_color=False, **kwargs):
se... | TermLogger |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 13105,
"end": 14090
} | class ____(Operation):
def __init__(self, alpha=1.0, *, name=None):
super().__init__(name=name)
self.alpha = alpha
def call(self, x):
return backend.nn.elu(x, alpha=self.alpha)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["ke... | Elu |
python | sympy__sympy | sympy/matrices/expressions/fourier.py | {
"start": 1478,
"end": 2094
} | class ____(DFT):
r"""
Returns an inverse discrete Fourier transform matrix. The matrix is scaled
with :math:`\frac{1}{\sqrt{n}}` so that it is unitary.
Parameters
==========
n : integer or Symbol
Size of the transform
Examples
========
>>> from sympy.matrices.expressions.... | IDFT |
python | wandb__wandb | wandb/vendor/pygments/lexers/int_fiction.py | {
"start": 575,
"end": 20816
} | class ____(RegexLexer):
"""
For `Inform 6 <http://inform-fiction.org/>`_ source code.
.. versionadded:: 2.0
"""
name = 'Inform 6'
aliases = ['inform6', 'i6']
filenames = ['*.inf']
flags = re.MULTILINE | re.DOTALL | re.UNICODE
_name = r'[a-zA-Z_]\w*'
# Inform 7 maps these fou... | Inform6Lexer |
python | openai__openai-python | src/openai/types/responses/response_create_params.py | {
"start": 13330,
"end": 13921
} | class ____(ResponseCreateParamsBase):
stream: Required[Literal[True]]
"""
If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_for... | ResponseCreateParamsStreaming |
python | psf__black | tests/data/cases/docstring_no_string_normalization.py | {
"start": 1814,
"end": 3638
} | class ____:
'''
A multiline class docstring.
'''
def AnEquallyLonelyMethod(self):
'''
A multiline method docstring'''
pass
def one_function():
'''This is a docstring with a single line of text.'''
pass
def shockingly_the_quotes_are_normalized():
'''This is a mult... | ALonelyClass |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2userfunc.py | {
"start": 6350,
"end": 6625
} | class ____(TestEdgeMatch_MultiGraph):
def setup_method(self):
TestEdgeMatch_MultiGraph.setup_method(self)
self.g1 = nx.MultiDiGraph()
self.g2 = nx.MultiDiGraph()
self.GM = iso.MultiDiGraphMatcher
self.build()
| TestEdgeMatch_MultiDiGraph |
python | google__flatbuffers | tests/py_flexbuffers_test.py | {
"start": 36735,
"end": 50405
} | class ____(unittest.TestCase):
"""Tests to check FlexBuffer encoding functions."""
def test_null(self):
def encode_null():
fbb = flexbuffers.Builder()
fbb.Null()
return fbb.Finish()
self.assertIsNone(flexbuffers.Loads(encode_null()))
def test_bool(self):
for value in False, True:
... | EncoderTest |
python | apache__airflow | airflow-core/tests/unit/always/test_secrets_local_filesystem.py | {
"start": 1529,
"end": 3216
} | class ____:
@pytest.mark.parametrize(
("content", "expected_message"),
[
("AA", 'Invalid line format. The line should contain at least one equal sign ("=")'),
("=", "Invalid line format. Key is empty."),
("KEY=", "Invalid line format. Value is empty."),
],... | TestFileParsers |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 155162,
"end": 158240
} | class ____:
def test_manage_project_documentation(self):
request = pretend.stub()
project = pretend.stub()
assert views.manage_project_documentation(project, request) == {
"project": project
}
def test_destroy_project_docs_no_confirm(self):
project = pretend... | TestManageProjectDocumentation |
python | huggingface__transformers | tests/models/clvp/test_processing_clvp.py | {
"start": 866,
"end": 5393
} | class ____(unittest.TestCase):
def setUp(self):
self.checkpoint = "susnato/clvp_dev"
self.tmpdirname = tempfile.mkdtemp()
def tearDown(self):
super().tearDown()
shutil.rmtree(self.tmpdirname)
gc.collect()
# Copied from transformers.tests.models.whisper.test_processi... | ClvpProcessorTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.