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 | tests/sentry/integrations/slack/utils/test_channel.py | {
"start": 10673,
"end": 15762
} | class ____(TestCase):
def setUp(self) -> None:
self.integration = self.create_integration(
organization=self.organization,
external_id="sentry-workspace",
provider="slack",
metadata={"access_token": "abc-123"},
)
self.input_id = "U12345678"
... | ValidateUserIdTest |
python | mahmoud__boltons | boltons/socketutils.py | {
"start": 25066,
"end": 25631
} | class ____(Error):
"""Raised from :meth:`BufferedSocket.recv_until` and
:meth:`BufferedSocket.recv_closed` when more than *maxsize* bytes are
read without encountering the delimiter or a closed connection,
respectively.
"""
def __init__(self, bytes_read=None, delimiter=None):
msg = 'mess... | MessageTooLong |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 11602,
"end": 11874
} | class ____:
def setup(self):
N = 18
self.df = DataFrame({"g": ["a", "b"] * 9, "v": list(range(N))})
def time_defaults(self):
self.df.groupby("g").shift()
def time_fill_value(self):
self.df.groupby("g").shift(fill_value=99)
| Shift |
python | kubernetes-client__python | kubernetes/client/models/v1_daemon_set_list.py | {
"start": 383,
"end": 6856
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1DaemonSetList |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1526056,
"end": 1528593
} | class ____(Transform):
"""
RegressionTransform schema wrapper.
Parameters
----------
on : str, :class:`FieldName`
The data field of the independent variable to use a predictor.
regression : str, :class:`FieldName`
The data field of the dependent variable to predict.
extent :... | RegressionTransform |
python | scipy__scipy | scipy/io/tests/test_idl.py | {
"start": 1186,
"end": 3534
} | class ____:
# Test that scalar values are read in with the correct value and type
def test_byte(self):
s = readsav(path.join(DATA_PATH, 'scalar_byte.sav'), verbose=False)
assert_identical(s.i8u, np.uint8(234))
def test_int16(self):
s = readsav(path.join(DATA_PATH, 'scalar_int16.sav... | TestScalars |
python | getsentry__sentry | tests/sentry/utils/test_snuba.py | {
"start": 20635,
"end": 25107
} | class ____(TestCase):
def setUp(self) -> None:
mock_request = Request(
dataset="events",
app_id="test",
query=Query(
match=Entity("events"),
select=[Function("count", parameters=[], alias="count")],
where=[
... | SnubaQueryRateLimitTest |
python | django__django | tests/indexes/tests.py | {
"start": 493,
"end": 4098
} | class ____(TestCase):
"""
Test index handling by the db.backends.schema infrastructure.
"""
def test_index_name_hash(self):
"""
Index names should be deterministic.
"""
editor = connection.schema_editor()
index_name = editor._create_index_name(
table_... | SchemaIndexesTests |
python | getsentry__sentry | src/sentry/testutils/silo.py | {
"start": 4043,
"end": 5899
} | class ____:
"""Decorate a test case that is expected to work in a given silo mode.
A test marked with a single silo mode runs only in that mode by default. An
`include_monolith_run=True` will add a secondary run in monolith mode.
If a test is marked with both control and region modes, then the primary... | SiloModeTestDecorator |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 15084,
"end": 15821
} | class ____:
def test_1(self, table_types):
t = table_types.Table()
with pytest.raises(KeyError):
t["a"]
def test_2(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name="a", data=[1, 2, 3]))
assert np.all(t["a"] == np.array([1, 2, 3... | TestColumnAccess |
python | getsentry__sentry | tests/apidocs/endpoints/organizations/test_org_stats_v2.py | {
"start": 325,
"end": 3905
} | class ____(APIDocsTestCase, OutcomesSnubaTest):
def setUp(self) -> None:
super().setUp()
self.now = datetime(2021, 3, 14, 12, 27, 28, tzinfo=timezone.utc)
self.login_as(user=self.user)
self.store_outcomes(
{
"org_id": self.organization.id,
... | OrganizationStatsDocs |
python | pytorch__pytorch | test/distributed/test_cupy_as_tensor.py | {
"start": 618,
"end": 1204
} | class ____:
data_ptr: int
size_in_bytes: int
@property
def __cuda_array_interface__(self):
return {
"shape": (self.size_in_bytes,),
"typestr": "|u1",
"data": (self.data_ptr, False),
"version": 3,
}
def from_buffer(
data_ptr: int, siz... | CupyWrapper |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 12872,
"end": 13059
} | class ____:
def setup_cache(self):
s = Series()
return s
def time_lookup_iloc(self, s):
s.iloc
def time_lookup_loc(self, s):
s.loc
| MethodLookup |
python | pytorch__pytorch | test/inductor/test_async_compile.py | {
"start": 778,
"end": 5594
} | class ____(TestCase):
@requires_gpu()
@requires_triton()
@parametrize("method", ("subprocess", "fork", "spawn"))
def test_pool(self, method):
def fn(x, y):
return x + y
x = torch.rand(10).to(GPU_TYPE)
y = torch.rand(10).to(GPU_TYPE)
with config.patch("worker... | TestAsyncCompile |
python | dagster-io__dagster | python_modules/libraries/dagster-docker/dagster_docker/container_context.py | {
"start": 1734,
"end": 6485
} | class ____(
NamedTuple(
"_DockerContainerContext",
[
("registry", Optional[Mapping[str, str]]),
("env_vars", Sequence[str]),
("networks", Sequence[str]),
("container_kwargs", Mapping[str, Any]),
],
)
):
"""Encapsulates the configuration... | DockerContainerContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 10225,
"end": 10278
} | class ____(ShopifyStream):
data_field = "shop"
| Shop |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/d.py | {
"start": 631,
"end": 719
} | class ____(Task.Task):
color = 'BLUE'
run_str = '${D} ${D_HEADER} ${SRC}'
| d_header |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-bedrock-converse/tests/test_bedrock_converse_utils.py | {
"start": 811,
"end": 1944
} | class ____:
def __init__(self) -> None:
self.exceptions = MockExceptions()
async def __aenter__(self) -> "AsyncMockClient":
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
pass
async def converse(self, *args, **kwargs):
return {"output": {"mes... | AsyncMockClient |
python | simonw__datasette | datasette/events.py | {
"start": 4173,
"end": 4611
} | class ____(Event):
"""
Event name: ``update-row``
A row was updated in a table.
:ivar database: The name of the database where the row was updated.
:type database: str
:ivar table: The name of the table where the row was updated.
:type table: str
:ivar pks: The primary key values of th... | UpdateRowEvent |
python | doocs__leetcode | solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/Solution.py | {
"start": 0,
"end": 1269
} | class ____:
def maximumInvitations(self, favorite: List[int]) -> int:
def max_cycle(fa: List[int]) -> int:
n = len(fa)
vis = [False] * n
ans = 0
for i in range(n):
if vis[i]:
continue
cycle = []
... | Solution |
python | numba__numba | numba/core/caching.py | {
"start": 21262,
"end": 25899
} | class ____(_Cache):
"""
A per-function compilation cache. The cache saves data in separate
data files and maintains information in an index file.
There is one index file per function and Python version
("function_name-<lineno>.pyXY.nbi") which contains a mapping of
signatures and architectures... | Cache |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_reflection.py | {
"start": 14057,
"end": 16747
} | class ____:
@logged
def __init__(self, i: int):
pass
@given(st.builds(Bar))
def test_issue_2495_regression(_):
"""See https://github.com/HypothesisWorks/hypothesis/issues/2495"""
@pytest.mark.skipif(
sys.version_info[:2] >= (3, 11),
reason="handled upstream in https://github.com/python/c... | Bar |
python | pytorch__pytorch | torch/_dynamo/package.py | {
"start": 2738,
"end": 4108
} | class ____:
"""
Contains the serializable information associated with a single compilation in dynamo.
To restore an execution of compiled code, we will need to serialize the following data:
- Dynamo bytecode for mapping Python inputs/outputs.
- Dynamo guards.
"""
guards_state: bytes
... | _GuardedCodeCacheEntry |
python | doocs__leetcode | solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/Solution.py | {
"start": 0,
"end": 366
} | class ____:
def minFlips(self, s: str) -> int:
n = len(s)
target = "01"
cnt = sum(c != target[i & 1] for i, c in enumerate(s))
ans = min(cnt, n - cnt)
for i in range(n):
cnt -= s[i] != target[i & 1]
cnt += s[i] != target[(i + n) & 1]
ans = ... | Solution |
python | pydata__xarray | asv_bench/benchmarks/repr.py | {
"start": 663,
"end": 1158
} | class ____:
def setup(self):
# construct a datatree with 500 nodes
number_of_files = 20
number_of_groups = 25
tree_dict = {}
for f in range(number_of_files):
for g in range(number_of_groups):
tree_dict[f"file_{f}/group_{g}"] = xr.Dataset({"g": f * ... | ReprDataTree |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/installation_external_issue_actions.py | {
"start": 1284,
"end": 1593
} | class ____(serializers.Serializer):
groupId = serializers.CharField(required=True, allow_null=False)
action = serializers.CharField(required=True, allow_null=False)
uri = serializers.CharField(required=True, allow_null=False)
@region_silo_endpoint
| SentryAppInstallationExternalIssueActionsSerializer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call9.py | {
"start": 420,
"end": 550
} | class ____:
def __getitem__(self, __key: str) -> str: ...
def keys(self) -> KeysView[str]: ...
T = TypeVar("T")
| StrRecord |
python | spack__spack | .github/workflows/bin/format-rst.py | {
"start": 3523,
"end": 9771
} | class ____:
lineno: int
end_lineno: int
src: str
lines: List[str]
def __init__(self, line: int, src: str) -> None:
self.lineno = line
self.src = src
self.lines = src.splitlines()
self.end_lineno = line + len(self.lines) - 1
def _is_node_in_table(node: nodes.Node) -... | ParagraphInfo |
python | falconry__falcon | tests/asgi/test_request_context_asgi.py | {
"start": 82,
"end": 1652
} | class ____:
def test_default_request_context(
self,
):
req = testing.create_asgi_req()
req.context.hello = 'World'
assert req.context.hello == 'World'
assert req.context['hello'] == 'World'
req.context['note'] = 'Default Request.context_type used to be dict.'
... | TestRequestContext |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | {
"start": 137267,
"end": 138965
} | class ____:
"""Return unicode-decoded values based on type inspection.
Smooth over data type issues (esp. with alpha driver versions) and
normalize strings as Unicode regardless of user-configured driver
encoding settings.
"""
# Some MySQL-python versions can return some columns as
# sets... | _DecodingRow |
python | django__django | tests/fixtures_regress/models.py | {
"start": 4696,
"end": 4901
} | class ____(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle2"]
| Circle1 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec32.py | {
"start": 894,
"end": 1430
} | class ____(Generic[P, T1, T2]):
def __init__(
self, fn: Callable[Concatenate[T1, P], T2], *args: P.args, **kwargs: P.kwargs
) -> None:
self.fn = fn
self.args = args
self.kwargs = kwargs
def __call__(self, value: T1) -> T2:
return self.fn(value, *self.args, **self.kwa... | Class2 |
python | mkdocs__mkdocs | mkdocs/plugins.py | {
"start": 16117,
"end": 17263
} | class ____(Generic[P, T]):
"""
A descriptor that allows defining multiple event handlers and declaring them under one event's name.
Usage example:
```python
@plugins.event_priority(100)
def _on_page_markdown_1(self, markdown: str, **kwargs):
...
@plugins.event_priority(-50)
de... | CombinedEvent |
python | keon__algorithms | tests/test_strings.py | {
"start": 4825,
"end": 5939
} | class ____(unittest.TestCase):
"""[summary]
Test for the file is_palindrome.py
Arguments:
unittest {[type]} -- [description]
"""
def test_is_palindrome(self):
# 'Otto' is a old german name.
self.assertTrue(is_palindrome("Otto"))
self.assertFalse(is_palindrome("house... | TestIsPalindrome |
python | pytorch__pytorch | torch/utils/_strobelight/cli_function_profiler.py | {
"start": 1331,
"end": 11360
} | class ____:
"""
Note: this is a meta only tool.
StrobelightCLIFunctionProfiler can be used to profile a python function and
generate a strobelight link with the results. It works on meta servers but
does not requires an fbcode target.
When stop_at_error is false(default), error during profiling... | StrobelightCLIFunctionProfiler |
python | cython__cython | Cython/Compiler/Optimize.py | {
"start": 3410,
"end": 4850
} | class ____(Visitor.TreeVisitor):
"""
YieldExprNode finder for generator expressions.
"""
def __init__(self):
Visitor.TreeVisitor.__init__(self)
self.yield_stat_nodes = {}
self.yield_nodes = []
visit_Node = Visitor.TreeVisitor.visitchildren
def visit_YieldExprNode(self, ... | _YieldNodeCollector |
python | google__jax | jax/experimental/sparse/bcoo.py | {
"start": 5339,
"end": 117078
} | class ____(Protocol):
@property
def shape(self) -> Shape: ...
@property
def dtype(self) -> Any: ...
def _validate_bcoo(data: Buffer, indices: Buffer, shape: Sequence[int]) -> BCOOProperties:
props = _validate_bcoo_indices(indices, shape)
n_batch, n_sparse, n_dense, nse = props
shape = tuple(shape)
if ... | Buffer |
python | realpython__materials | solid-principles-python/shapes_lsp.py | {
"start": 854,
"end": 989
} | class ____(Shape):
def __init__(self, side):
self.side = side
def calculate_area(self):
return self.side**2
| Square |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_invite_request_details.py | {
"start": 6660,
"end": 12267
} | class ____(InviteRequestBase, HybridCloudTestMixin):
method = "put"
@patch.object(OrganizationMember, "send_invite_email")
def test_owner_can_approve_invite_request(self, mock_invite_email: MagicMock) -> None:
self.login_as(user=self.user)
with outbox_runner():
resp = self.get_r... | OrganizationInviteRequestApproveTest |
python | spack__spack | var/spack/test_repos/spack_repo/builder_test/packages/custom_phases/package.py | {
"start": 541,
"end": 920
} | class ____(generic.GenericBuilder):
phases = ["configure", "install"]
def configure(self, pkg, spec, prefix):
os.environ["CONFIGURE_CALLED"] = "1"
os.environ["LAST_PHASE"] = "CONFIGURE"
def install(self, pkg, spec, prefix):
os.environ["INSTALL_CALLED"] = "1"
os.environ["LAS... | GenericBuilder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataplex.py | {
"start": 3541,
"end": 3808
} | class ____(BaseGoogleLink):
"""Helper class for constructing Dataplex Catalog EntryTypes link."""
name = "Dataplex Catalog EntryTypes"
key = "dataplex_catalog_entry_types_key"
format_str = DATAPLEX_CATALOG_ENTRY_TYPES_LINK
| DataplexCatalogEntryTypesLink |
python | pytorch__pytorch | test/dynamo/test_backward_higher_order_ops.py | {
"start": 9296,
"end": 12475
} | class ____(torch.nn.Module):
def forward(self, L_inputs_ : list, s69: "Sym(s21)", L_sizes_0_: "f32[0, s21]", L_hooks_1_keywords_fn_keywords_obj_counter: "Sym(s45)"):
l_inputs_ = L_inputs_
l_sizes_0_ = L_sizes_0_
l_hooks_1_keywords_fn_keywords_obj_counter = L_hooks_1_keywords_fn_keywords_obj_... | GraphModule |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 3562,
"end": 4360
} | class ____:
''' Mixin class for scal testing '''
def test_simple(self):
x = arange(3., dtype=self.dtype)
real_x = x*3.
x = self.blas_func(3., x)
assert_array_equal(real_x, x)
def test_x_stride(self):
x = arange(6., dtype=self.dtype)
real_x = x.copy()
... | BaseScal |
python | pyparsing__pyparsing | examples/adventureEngine.py | {
"start": 2161,
"end": 3093
} | class ____:
items = {}
def __init__(self, desc):
self.desc = desc
self.isDeadly = False
self.isFragile = False
self.isBroken = False
self.isTakeable = True
self.isVisible = True
self.isOpenable = False
self.useAction = None
self.usableCond... | Item |
python | django__django | tests/gis_tests/geoapp/models.py | {
"start": 580,
"end": 749
} | class ____(City):
county = models.CharField(max_length=30)
founded = models.DateTimeField(null=True)
class Meta:
app_label = "geoapp"
| PennsylvaniaCity |
python | redis__redis-py | redis/_parsers/base.py | {
"start": 5648,
"end": 7913
} | class ____:
"""Protocol defining maintenance push notification parsing functionality"""
@staticmethod
def parse_maintenance_start_msg(response, notification_type):
# Expected message format is: <notification_type> <seq_number> <time>
id = response[1]
ttl = response[2]
return... | MaintenanceNotificationsParser |
python | huggingface__transformers | src/transformers/models/yolos/modeling_yolos.py | {
"start": 19083,
"end": 20707
} | class ____(YolosPreTrainedModel):
def __init__(self, config: YolosConfig, add_pooling_layer: bool = True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self... | YolosModel |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_graph_objs.py | {
"start": 4545,
"end": 5448
} | class ____(TestCase):
def test_warn_on_deprecated_mapbox_traces(self):
# This test will fail if any of the following traces
# fails to emit a DeprecationWarning
for trace_constructor in [
go.Scattermapbox,
go.Densitymapbox,
go.Choroplethmapbox,
]:
... | TestDeprecationWarnings |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 21098,
"end": 27690
} | class ____(_TargetExpr):
"""
Base class for filtering match by node.{target,args,kwargs}
"""
def __init__(
self,
fns: Union[torch.fx.node.Target, str, Sequence[Any]],
*args: Any,
_users: Union[int, Multiple] = 1,
**kwargs: Any,
) -> None:
super().__in... | _TargetArgsExpr |
python | huggingface__transformers | src/transformers/models/jamba/modular_jamba.py | {
"start": 29098,
"end": 33065
} | class ____(JambaPreTrainedModel):
def __init__(self, config: JambaConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
decoder_la... | JambaModel |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/dagster_looker_api_translator.py | {
"start": 589,
"end": 2558
} | class ____:
"""A record representing all content in a Looker instance."""
explores_by_id: dict[str, LookmlModelExplore]
dashboards_by_id: dict[str, Dashboard]
users_by_id: dict[str, User]
def to_state(self, sdk: Looker40SDK) -> Mapping[str, Any]:
return {
"dashboards_by_id": {
... | LookerInstanceData |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 33729,
"end": 40964
} | class ____(Decoder):
"""
JSON streaming decoder optimized for Google Ads API responses.
Uses a fast JSON parse when the full payload fits within max_direct_decode_bytes;
otherwise streams records incrementally from the `results` array.
Ensures truncated or structurally invalid JSON is detected and ... | GoogleAdsStreamingDecoder |
python | getsentry__sentry | tests/sentry/deletions/test_organization.py | {
"start": 2009,
"end": 18946
} | class ____(TransactionTestCase, HybridCloudTestMixin, BaseWorkflowTest):
def test_simple(self) -> None:
org_owner = self.create_user()
org = self.create_organization(name="test", owner=org_owner)
with assume_test_silo_mode(SiloMode.CONTROL):
org_mapping = OrganizationMapping.obje... | DeleteOrganizationTest |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 104886,
"end": 105022
} | class ____:
exprs: list[str]
# A dataclass for storing C++ expressions and helper variables
@dataclass(frozen=True)
| _ShapeGuardsHelper |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/block.py | {
"start": 1783,
"end": 2049
} | class ____(TypedDict, total=False):
size: TextSize
weight: TextWeight
horizontalAlignment: ContentAlignment
spacing: Literal["None"]
isSubtle: bool
height: Literal["stretch"]
wrap: bool
fontType: Literal["Default"]
| _TextBlockNotRequired |
python | bokeh__bokeh | src/bokeh/core/query.py | {
"start": 8284,
"end": 8629
} | class ____(_Operator):
''' Predicate to test if property values are greater than or equal to
some value.
Construct and ``GEQ`` predicate as a dict with ``GEQ`` as the key,
and a value to compare against.
.. code-block:: python
# matches any models with .size >= 10
dict(size={ GEQ:... | GEQ |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 28781,
"end": 31393
} | class ____(unittest.TestCase):
@cached_property
def default_processor(self):
return SpeechT5Processor.from_pretrained("microsoft/speecht5_asr")
def _load_datasamples(self, num_samples):
from datasets import load_dataset
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy",... | SpeechT5ForSpeechToTextIntegrationTests |
python | streamlit__streamlit | lib/tests/streamlit/runtime/pages_manager_test.py | {
"start": 764,
"end": 3324
} | class ____(unittest.TestCase):
def setUp(self):
self.pages_manager = PagesManager("main_script_path")
def test_get_page_script_valid_hash(self):
"""Ensure the page script is provided with valid page hash specified"""
self.pages_manager.set_script_intent("page_hash", "")
self.pa... | PagesManagerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/pyodbc.py | {
"start": 17042,
"end": 17112
} | class ____(_ms_numeric_pyodbc, sqltypes.Float):
pass
| _MSFloat_pyodbc |
python | huggingface__transformers | tests/models/blenderbot_small/test_modeling_blenderbot_small.py | {
"start": 2060,
"end": 7897
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_labels=False,
vocab_size=99,
hidden_size=16,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=4,
hidden_act="gelu",
... | BlenderbotSmallModelTester |
python | doocs__leetcode | solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/Solution.py | {
"start": 192,
"end": 545
} | class ____:
def sumRootToLeaf(self, root: TreeNode) -> int:
def dfs(root, t):
if root is None:
return 0
t = (t << 1) | root.val
if root.left is None and root.right is None:
return t
return dfs(root.left, t) + dfs(root.right, t)
... | Solution |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 17415,
"end": 18244
} | class ____(DefaultFieldsModel):
"""
A model that represents an installable preprod artifact with an expiring URL.
This is created when a user generates a download QR code for a preprod artifact.
"""
__relocation_scope__ = RelocationScope.Excluded
preprod_artifact = FlexibleForeignKey("preprod.... | InstallablePreprodArtifact |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/73_class_generic_defaults.py | {
"start": 0,
"end": 27
} | class ____[T=str]:
x: T
| Foo |
python | pypa__pip | tests/unit/test_operations_prepare.py | {
"start": 3119,
"end": 4650
} | class ____:
def prep(self, tmpdir: Path, data: TestData) -> None:
self.build_dir = os.fspath(tmpdir.joinpath("build"))
self.download_dir = tmpdir.joinpath("download")
os.mkdir(self.build_dir)
os.mkdir(self.download_dir)
self.dist_file = "simple-1.0.tar.gz"
self.dist_f... | Test_unpack_url |
python | arrow-py__arrow | arrow/locales.py | {
"start": 61801,
"end": 62354
} | class ____(ArabicLocale):
names = ["ar-ma"]
month_names = [
"",
"يناير",
"فبراير",
"مارس",
"أبريل",
"ماي",
"يونيو",
"يوليوز",
"غشت",
"شتنبر",
"أكتوبر",
"نونبر",
"دجنبر",
]
month_abbreviations = [
... | MoroccoArabicLocale |
python | ray-project__ray | rllib/examples/envs/classes/multi_agent/footsies/game/footsies_binary.py | {
"start": 1123,
"end": 8071
} | class ____:
def __init__(self, config: EnvContext, port: int):
self._urls = BinaryUrls()
self.config = config
self.port = port
self.binary_to_download = config["binary_to_download"]
if self.binary_to_download == "linux_server":
self.url = self._urls.URL_LINUX_SER... | FootsiesBinary |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/tests/test_new_features.py | {
"start": 12898,
"end": 17303
} | class ____:
"""
Tests the logic for fetching child pages, specifically handling the
difference between cloud and on-premise Confluence instances.
"""
def test_on_prem_folder_call_is_never_made(self):
"""
On-premise mode: Ensures the fix prevents calls for 'folder' children.
... | TestChildPageFetching |
python | huggingface__transformers | src/transformers/integrations/deepspeed.py | {
"start": 3076,
"end": 21059
} | class ____(HfDeepSpeedConfig):
"""
The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
same lifespan as the latter.
"""
def __init__(self, config_file_or_dict):
super().__init__(config_file_or_dict)
self._dtype = None
... | HfTrainerDeepSpeedConfig |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 39203,
"end": 39541
} | class ____(str, Enum):
"""
* `AUTOSCALE`: Automatically resized based on load.
* `USER_REQUEST`: User requested a new size.
* `AUTORECOVERY`: Autorecovery monitor resized the cluster after it lost a node.
"""
autoscale = "AUTOSCALE"
userrequest = "USER_REQUEST"
autorecovery = "AUTOR... | ResizeCause |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 43436,
"end": 44530
} | class ____(TestCase):
def test_extra_kwargs_not_altered(self):
class TestSerializer(serializers.ModelSerializer):
non_model_field = serializers.CharField()
class Meta:
model = OneFieldModel
read_only_fields = ('char_field', 'non_model_field')
... | TestMetaInheritance |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 26744,
"end": 30650
} | class ____:
def test_check_simple(self):
a = np.arange(100).astype('f')
a = np.pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))
b = np.array(
[4.00, 3.84, 3.68, 3.52, 3.36, 3.20, 3.04, 2.88, 2.72, 2.56,
2.40, 2.24, 2.08, 1.92, 1.76, 1.60, 1.44, 1.28, 1.12, 0.96,
... | TestLinearRamp |
python | run-llama__llama_index | llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/augmentation_precision.py | {
"start": 366,
"end": 2005
} | class ____(BaseEvaluator):
"""
Tonic Validate's augmentation precision metric.
The output score is a float between 0.0 and 1.0.
See https://docs.tonic.ai/validate/ for more details.
Args:
openai_service(OpenAIService): The OpenAI service to use. Specifies the chat
completion m... | AugmentationPrecisionEvaluator |
python | PyCQA__pylint | tests/functional/ext/code_style/cs_consider_using_assignment_expr.py | {
"start": 2645,
"end": 2761
} | class ____:
var = 1
A.var = 2
if A.var:
...
i: int
if i: # pylint: disable=used-before-assignment
pass
| A |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 8759,
"end": 9477
} | class ____:
"""§11.6.5 of the 1.7 and 2.0 references."""
TYPE = "/Type" # name, required; must be /XObject
SUBTYPE = "/Subtype" # name, required; must be /Image
NAME = "/Name" # name, required
WIDTH = "/Width" # integer, required
HEIGHT = "/Height" # integer, required
BITS_PER_COMPONEN... | ImageAttributes |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 49414,
"end": 50842
} | class ____(TestCase):
def test_traverse_nullable_fk(self):
"""
A dotted source with nullable elements uses default when any item in the chain is None. #5849.
Similar to model example from test_serializer.py `test_default_for_multiple_dotted_source` method,
but using RelatedField, ra... | TestFieldSource |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-cogniswitch/llama_index/tools/cogniswitch/base.py | {
"start": 120,
"end": 5381
} | class ____(BaseToolSpec):
"""
Cogniswitch Tool Spec.
A toolspec to have store_data and query_knowledge as tools to store the data from a file or a url
and answer questions from the knowledge stored respectively.
"""
spec_functions = ["store_data", "query_knowledge", "knowledge_status"]
def... | CogniswitchToolSpec |
python | sympy__sympy | sympy/polys/domains/old_fractionfield.py | {
"start": 383,
"end": 6226
} | class ____(Field, CompositeDomain):
"""A class for representing rational function fields. """
dtype = DMF
is_FractionField = is_Frac = True
has_assoc_Ring = True
has_assoc_Field = True
def __init__(self, dom, *gens):
if not gens:
raise GeneratorsNeeded("generators not spec... | FractionField |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py | {
"start": 26952,
"end": 29303
} | class ____(
MetadataValue["TableMetadataValue"],
LegacyNamedTupleMixin,
IHaveNew,
):
"""Container class for table metadata entry data.
Args:
records (TableRecord): The data as a list of records (i.e. rows).
schema (Optional[TableSchema]): A schema for the table.
Example:
... | TableMetadataValue |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 346,
"end": 1748
} | class ____(NamedValue, _HasMetadata):
def __init__(self, parent, typ, opname, operands, name='', flags=()):
super(Instruction, self).__init__(parent, typ, name=name)
assert isinstance(parent, Block)
assert isinstance(flags, (tuple, list))
self.opname = opname
self.operands = ... | Instruction |
python | great-expectations__great_expectations | great_expectations/experimental/metric_repository/metrics.py | {
"start": 746,
"end": 1395
} | class ____(str, enum.Enum, metaclass=MetricTypesMeta):
"""Represents Metric types in OSS that are used for ColumnDescriptiveMetrics and MetricRepository.
More Metric types will be added in the future.
""" # noqa: E501 # FIXME CoP
# Table metrics
TABLE_COLUMNS = "table.columns"
TABLE_ROW_COUNT... | MetricTypes |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/nameBinding2.py | {
"start": 143,
"end": 234
} | class ____:
def test(self):
nonlocal missing_symbol
missing_symbol = 4
| Test |
python | jazzband__django-oauth-toolkit | tests/test_rest_framework.py | {
"start": 2331,
"end": 2429
} | class ____(OAuth2View):
permission_classes = [TokenMatchesOASRequirements]
| MethodScopeAltViewBad |
python | getsentry__sentry | tests/sentry/db/models/fields/bitfield/test_bitfield.py | {
"start": 1015,
"end": 4708
} | class ____(unittest.TestCase):
def test_comparison(self) -> None:
bithandler_1 = BitHandler(0, ("FLAG_0", "FLAG_1", "FLAG_2", "FLAG_3"))
bithandler_2 = BitHandler(1, ("FLAG_0", "FLAG_1", "FLAG_2", "FLAG_3"))
bithandler_3 = BitHandler(0, ("FLAG_0", "FLAG_1", "FLAG_2", "FLAG_3"))
asser... | BitHandlerTest |
python | ray-project__ray | rllib/algorithms/dqn/dqn_tf_policy.py | {
"start": 4663,
"end": 17643
} | class ____:
"""Assign the `compute_td_error` method to the DQNTFPolicy
This allows us to prioritize on the worker side.
"""
def __init__(self):
@make_tf_callable(self.get_session(), dynamic_shape=True)
def compute_td_error(
obs_t, act_t, rew_t, obs_tp1, terminateds_mask, im... | ComputeTDErrorMixin |
python | numpy__numpy | numpy/distutils/fcompiler/nag.py | {
"start": 118,
"end": 577
} | class ____(FCompiler):
version_pattern = r'NAG.* Release (?P<version>[^(\s]*)'
def version_match(self, version_string):
m = re.search(self.version_pattern, version_string)
if m:
return m.group('version')
else:
return None
def get_flags_linker_so(self):
... | BaseNAGFCompiler |
python | pydantic__pydantic | pydantic/functional_validators.py | {
"start": 30227,
"end": 31682
} | class ____:
"""A helper class to validate a custom type from a type that is natively supported by Pydantic.
Args:
from_type: The type natively supported by Pydantic to use to perform validation.
instantiation_hook: A callable taking the validated type as an argument, and returning
t... | ValidateAs |
python | wandb__wandb | tests/unit_tests/test_artifacts/test_wandb_artifacts.py | {
"start": 2806,
"end": 17742
} | class ____:
@staticmethod
def _fixture_kwargs_to_kwargs(
artifact_id: str = "my-artifact-id",
artifact_manifest_id: str = "my-artifact-manifest-id",
entry_path: str = "my-path",
entry_digest: str = "my-digest",
entry_local_path: Optional[Path] = None,
preparer: Op... | TestStoreFile |
python | chardet__chardet | chardet/chardistribution.py | {
"start": 6811,
"end": 7633
} | class ____(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER
self._table_size = GB2312_TABLE_SIZE
self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[... | GB2312DistributionAnalysis |
python | gevent__gevent | src/greentest/3.11/test_select.py | {
"start": 267,
"end": 3514
} | class ____(unittest.TestCase):
class Nope:
pass
class Almost:
def fileno(self):
return 'fileno'
def test_error_conditions(self):
self.assertRaises(TypeError, select.select, 1, 2, 3)
self.assertRaises(TypeError, select.select, [self.Nope()], [], [])
self... | SelectTestCase |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 12961,
"end": 13669
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
occurences = helper_functions.get_value("ClassOccurences")
max_value = -1
if len(y.shape) == 2:
for i in range(y.shape[1]):
for num_occurences in occurences[i].values():
i... | ClassProbabilityMax |
python | getsentry__sentry-python | sentry_sdk/integrations/grpc/aio/client.py | {
"start": 2292,
"end": 3327
} | class ____(
ClientInterceptor,
UnaryStreamClientInterceptor, # type: ignore
):
async def intercept_unary_stream(
self,
continuation: Callable[[ClientCallDetails, Message], UnaryStreamCall],
client_call_details: ClientCallDetails,
request: Message,
) -> Union[AsyncIterabl... | SentryUnaryStreamClientInterceptor |
python | walkccc__LeetCode | solutions/2505. Bitwise OR of All Subsequence Sums/2505.py | {
"start": 0,
"end": 181
} | class ____:
def subsequenceSumOr(self, nums: list[int]) -> int:
ans = 0
prefix = 0
for num in nums:
prefix += num
ans |= num | prefix
return ans
| Solution |
python | hyperopt__hyperopt | hyperopt/rdists.py | {
"start": 2283,
"end": 3781
} | class ____:
# -- not inheriting from scipy.stats.rv_discrete
# because I don't understand the design of those rv classes
"""Stats for Y = q * round(X / q) where X ~ U(low, high)."""
def __init__(self, low, high, q):
low, high = list(map(float, (low, high)))
qlow = safe_int_cast(np.ro... | quniform_gen |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py | {
"start": 879,
"end": 986
} | class ____(BaseModel):
"""Base info serializer for responses."""
status: str | None
| BaseInfoResponse |
python | getsentry__sentry | src/sentry/options/store.py | {
"start": 851,
"end": 1029
} | class ____:
# Name of the group of options to include this option in
name: str
# Order of the option within the group
order: int
@dataclasses.dataclass
| GroupingInfo |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 53478,
"end": 53686
} | class ____:
xlDisplayShapes = -4104 # from enum XlDisplayDrawingObjects
xlHide = 3 # from enum XlDisplayDrawingObjects
xlPlaceholders = 2 # from enum XlDisplayDrawingObjects
| DisplayDrawingObjects |
python | pandas-dev__pandas | pandas/tests/indexes/test_any_index.py | {
"start": 2832,
"end": 3352
} | class ____:
def test_pickle_roundtrip(self, index):
result = tm.round_trip_pickle(index)
tm.assert_index_equal(result, index, exact=True)
if result.nlevels > 1:
# GH#8367 round-trip with timezone
assert index.equal_levels(result)
def test_pickle_preserves_name(se... | TestRoundTrips |
python | PrefectHQ__prefect | tests/server/schemas/test_actions.py | {
"start": 11479,
"end": 11746
} | class ____:
def test_updatable_fields(self):
fields = BlockTypeUpdate.updatable_fields()
assert fields == {
"logo_url",
"documentation_url",
"description",
"code_example",
}
| TestBlockTypeUpdate |
python | ray-project__ray | doc/source/tune/doc_code/trainable.py | {
"start": 1367,
"end": 2111
} | class ____(tune.Trainable):
def setup(self, config: dict):
# config (dict): A dict of hyperparameters
self.x = 0
self.a = config["a"]
self.b = config["b"]
def step(self): # This is called iteratively.
score = objective(self.x, self.a, self.b)
self.x += 1
... | Trainable |
python | kamyu104__LeetCode-Solutions | Python/special-array-ii.py | {
"start": 46,
"end": 526
} | class ____(object):
def isArraySpecial(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[bool]
"""
prefix = [0]*len(nums)
for i in xrange(len(nums)-1):
prefix[i+1] = prefix[i]+int(nums[i+1]&1 != nums[i]&1)
... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.