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 | PyCQA__pycodestyle | tests/test_parser.py | {
"start": 295,
"end": 1250
} | class ____(unittest.TestCase):
def test_vanilla_ignore_parsing(self):
contents = b"""
[pycodestyle]
ignore = E226,E24
"""
options, args = _process_file(contents)
self.assertEqual(options.ignore, ["E226", "E24"])
def test_multiline_ignore_parsing(self):
contents = b"""
... | ParserTestCase |
python | huggingface__transformers | src/transformers/models/janus/modeling_janus.py | {
"start": 3292,
"end": 4956
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,... | JanusBaseModelOutputWithPast |
python | pymupdf__PyMuPDF | src_classic/utils.py | {
"start": 95635,
"end": 181938
} | class ____(object):
"""Create a new shape."""
@staticmethod
def horizontal_angle(C, P):
"""Return the angle to the horizontal for the connection from C to P.
This uses the arcus sine function and resolves its inherent ambiguity by
looking up in which quadrant vector S = P - C is loc... | Shape |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/evaluator.py | {
"start": 1108,
"end": 1340
} | class ____(operators.ColumnOperators):
def operate(self, *arg, **kw):
return self
def reverse_operate(self, *arg, **kw):
return self
_NO_OBJECT = _NoObject()
_EXPIRED_OBJECT = _ExpiredObject()
| _ExpiredObject |
python | davidhalter__jedi | jedi/inference/recursion.py | {
"start": 1569,
"end": 2791
} | class ____:
def __init__(self):
self.pushed_nodes = []
@contextmanager
def execution_allowed(inference_state, node):
"""
A decorator to detect recursions in statements. In a recursion a statement
at the same place, in the same module may not be executed two times.
"""
pushed_nodes = in... | RecursionDetector |
python | google__jax | jax/_src/lax/lax.py | {
"start": 74494,
"end": 78436
} | class ____(NamedTuple):
"""Specify the algorithm used for computing dot products.
When used to specify the ``precision`` input to :func:`~jax.lax.dot`,
:func:`~jax.lax.dot_general`, and other dot product functions, this data
structure is used for controlling the properties of the algorithm used for
computing... | DotAlgorithm |
python | huggingface__transformers | src/transformers/models/segformer/modeling_segformer.py | {
"start": 8698,
"end": 9113
} | class ____(nn.Module):
def __init__(self, config, hidden_size):
super().__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
... | SegformerSelfOutput |
python | ansible__ansible | test/integration/targets/common_network/test_plugins/is_mac.py | {
"start": 238,
"end": 342
} | class ____(object):
def tests(self):
return {
'is_mac': is_mac,
}
| TestModule |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 6457,
"end": 6659
} | class ____(CtrlNode):
"""Returns the pointwise integral of the input"""
nodeName = 'IntegralFilter'
def processData(self, data):
data[1:] += data[:-1]
return data
| Integral |
python | gevent__gevent | src/greentest/3.14/test_smtplib.py | {
"start": 1313,
"end": 4803
} | class ____:
def setUp(self):
smtplib.socket = mock_socket
self.port = 25
def tearDown(self):
smtplib.socket = socket
# This method is no longer used but is retained for backward compatibility,
# so test to make sure it still works.
def testQuoteData(self):
teststr ... | GeneralTests |
python | davidhalter__jedi | jedi/_compatibility.py | {
"start": 169,
"end": 1491
} | class ____(pickle.Unpickler):
def find_class(self, module: str, name: str) -> Any:
# Python 3.13 moved pathlib implementation out of __init__.py as part of
# generalising its implementation. Ensure that we support loading
# pickles from 3.13 on older version of Python. Since 3.13 maintained ... | Unpickler |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/foundry.py | {
"start": 1404,
"end": 1629
} | class ____(Messages):
@cached_property
@override
def batches(self) -> None: # type: ignore[override]
"""Batches endpoint is not supported for Anthropic Foundry client."""
return None
| MessagesFoundry |
python | python-pillow__Pillow | src/PIL/FontFile.py | {
"start": 702,
"end": 3577
} | class ____:
"""Base class for raster font file handlers."""
bitmap: Image.Image | None = None
def __init__(self) -> None:
self.info: dict[bytes, bytes | int] = {}
self.glyph: list[
tuple[
tuple[int, int],
tuple[int, int, int, int],
... | FontFile |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 19976,
"end": 23029
} | class ____(TestCase):
def setUp(self):
self.css = """
<link rel="stylesheet" href="/static/css/datauri.css" type="text/css">
"""
self.css_node = CssCompressor("css", self.css)
def test_data_uris(self):
datauri_hash = get_hashed_mtime(
os.path.join(settings.CO... | CssDataUriTestCase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 64962,
"end": 67618
} | class ____(SemiIncrementalMixin, GithubStream):
"""
Get all workflow runs for a GitHub repository
API documentation: https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#list-workflow-runs-for-a-repository
"""
# key for accessing slice value from record
record_slice_key =... | WorkflowRuns |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_circulant_test.py | {
"start": 8085,
"end": 10123
} | class ____(object):
"""Common class for circulant tests."""
_atol = {
dtypes.float16: 1e-3,
dtypes.float32: 1e-6,
dtypes.float64: 2e-7,
dtypes.complex64: 1e-6,
dtypes.complex128: 2e-7,
}
_rtol = {
dtypes.float16: 1e-3,
dtypes.float32: 1e-6,
dtypes.float64: 2e-7,
... | LinearOperatorCirculantBaseTest |
python | chroma-core__chroma | chromadb/db/base.py | {
"start": 909,
"end": 1585
} | class ____(ABC, EnforceOverrides):
"""Wrapper class for DBAPI 2.0 Connection objects, with which clients can implement transactions.
Makes two guarantees that basic DBAPI 2.0 connections do not:
- __enter__ returns a Cursor object consistently (instead of a Connection like some do)
- Always re-raises a... | TxWrapper |
python | sqlalchemy__sqlalchemy | test/sql/test_selectable.py | {
"start": 116606,
"end": 117458
} | class ____(fixtures.TestBase):
def test_ensure_repr_elements(self):
for obj in [
elements.Cast(1, Integer()),
elements.TypeClause(String()),
elements.ColumnClause("x"),
elements.BindParameter("q"),
elements.Null(),
elements.True_(),
... | ReprTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/env_vars.py | {
"start": 1730,
"end": 1885
} | class ____(graphene.ObjectType):
class Meta:
name = "LocationDocsJson"
json = graphene.NonNull(graphene.JSONString)
| GrapheneLocationDocsJson |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 7352,
"end": 7470
} | class ____(ShowFieldType, PolymorphicModel):
modelfieldnametest = models.CharField(max_length=30)
| ModelFieldNameTest |
python | tensorflow__tensorflow | tensorflow/python/keras/initializers/initializers_v2.py | {
"start": 29314,
"end": 31143
} | class ____(VarianceScaling):
"""He uniform variance scaling initializer.
Also available via the shortcut function
`tf.keras.initializers.he_uniform`.
Draws samples from a uniform distribution within `[-limit, limit]`, where
`limit = sqrt(6 / fan_in)` (`fan_in` is the number of input units in the
weight t... | HeUniform |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 1482,
"end": 1602
} | class ____(vLLMChatCompletionResponse):
model_config = ConfigDict(arbitrary_types_allowed=True)
| ChatCompletionResponse |
python | walkccc__LeetCode | solutions/2301. Match Substring After Replacement/2301.py | {
"start": 0,
"end": 710
} | class ____:
def matchReplacement(
self,
s: str,
sub: str,
mappings: list[list[str]],
) -> bool:
isMapped = [[False] * 128 for _ in range(128)]
for old, new in mappings:
isMapped[ord(old)][ord(new)] = True
for i in range(len(s)):
if self._canTransform(s, i, sub, isMa... | Solution |
python | ethereum__web3.py | web3/_utils/encoding.py | {
"start": 7487,
"end": 8739
} | class ____(BaseArrayEncoder):
is_dynamic = True
def encode(self, value: Sequence[Any]) -> bytes:
encoded_elements = self.encode_elements(value) # type: ignore[no-untyped-call]
encoded_value = encoded_elements
return encoded_value
# TODO: Replace with eth-abi packed encoder once web... | DynamicArrayPackedEncoder |
python | plotly__plotly.py | plotly/graph_objs/treemap/marker/_colorbar.py | {
"start": 233,
"end": 61634
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap.marker"
_path_str = "treemap.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexpo... | ColorBar |
python | modin-project__modin | modin/pandas/io.py | {
"start": 30834,
"end": 41184
} | class ____(ClassLogger, pandas.ExcelFile): # noqa: PR01, D200
"""
Class for parsing tabular excel sheets into DataFrame objects.
"""
_behave_like_pandas = False
def _set_pandas_mode(self): # noqa
# disable Modin behavior to be able to pass object to `pandas.read_excel`
# otherwis... | ExcelFile |
python | hynek__structlog | tests/test_dev.py | {
"start": 26550,
"end": 33886
} | class ____:
def test_level_styles_roundtrip(self):
"""
The level_styles property can be set and retrieved.
"""
cr = dev.ConsoleRenderer(colors=True)
custom = {"info": "X", "error": "Y"}
cr.level_styles = custom
assert cr.level_styles is custom
assert... | TestConsoleRendererProperties |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axislines.py | {
"start": 6536,
"end": 8756
} | class ____(_FloatingAxisArtistHelperBase):
def __init__(self, axes, nth_coord,
passingthrough_point, axis_direction="bottom"):
super().__init__(nth_coord, passingthrough_point)
self._axis_direction = axis_direction
self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
d... | FloatingAxisArtistHelperRectilinear |
python | google__pytype | pytype/pytd/booleq.py | {
"start": 1865,
"end": 3124
} | class ____(BooleanTerm):
"""Class for representing "FALSE"."""
def simplify(self, assignments):
return self
def __repr__(self):
return "FALSE"
def __str__(self):
return "FALSE"
def extract_pivots(self, assignments):
return {}
def extract_equalities(self):
return ()
TRUE = TrueValu... | FalseValue |
python | getsentry__sentry | fixtures/sudo_testutils.py | {
"start": 496,
"end": 1012
} | class ____(TestCase):
def setUp(self):
self.request = self.get("/foo")
self.request.session = {}
self.setUser(AnonymousUser())
def get(self, *args, **kwargs):
return RequestFactory().get(*args, **kwargs)
def post(self, *args, **kwargs):
return RequestFactory().post(... | BaseTestCase |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 172740,
"end": 173631
} | class ____:
@pytest.mark.parametrize("type_in, type_out", [
('l', 'D'),
('h', 'F'),
('H', 'F'),
('b', 'F'),
('B', 'F'),
('g', 'G'),
])
def test_sort_real(self, type_in, type_out):
# sort_complex() type casting for real input types
a = np.a... | TestSortComplex |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/nios.py | {
"start": 1986,
"end": 2583
} | class ____(CloudEnvironment):
"""NIOS environment plugin. Updates integration test environment after delegation."""
def get_environment_config(self) -> CloudEnvironmentConfig:
"""Return environment configuration for use in the test environment after delegation."""
ansible_vars = dict(
... | NiosEnvironment |
python | kamyu104__LeetCode-Solutions | Python/count-array-pairs-divisible-by-k.py | {
"start": 152,
"end": 888
} | class ____(object):
def countPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(x, y):
while y:
x, y = y, x%y
return x
cnt = collections.Counter()
for x in nums:
... | Solution |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 9192,
"end": 11284
} | class ____(nn.Module):
def __init__(self, config: MllamaVisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.attention_heads
self.head_dim = config.hidden_size // config.attention_heads
self.scaling = self... | MllamaVisionAttention |
python | apache__avro | lang/py/avro/errors.py | {
"start": 2263,
"end": 2391
} | class ____(AvroTypeException):
"""Raised when a default value isn't a suitable type for the schema."""
| InvalidDefaultException |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/window_test.py | {
"start": 10652,
"end": 11241
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self):
dataset = dataset_ops.Dataset.range(42).window(6).interleave(
lambda x: x, cycle_length=2, num_parallel_calls=2)
return dataset
@combinations.generate(
combinatio... | WindowCheckpointTest |
python | mlflow__mlflow | mlflow/tensorflow/__init__.py | {
"start": 31536,
"end": 34406
} | class ____:
"""
Wrapper class that exposes a TensorFlow model for inference via a ``predict`` function such that
``predict(data: pandas.DataFrame) -> pandas.DataFrame``. For TensorFlow versions >= 2.0.0.
"""
def __init__(self, model, infer):
"""
Args:
model: A Tensorflow... | _TF2Wrapper |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes1.py | {
"start": 778,
"end": 973
} | class ____(*args, **kwargs):
pass
def func1(x: type) -> object:
class Y(x):
pass
return Y()
# This should generate an error because a TypeVar can't be used as a base class.
| J |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 74459,
"end": 79130
} | class ____(Request):
"""
Register a worker in the system. Called by the Worker Daemon.
:param worker: Worker id. Must be unique in company.
:type worker: str
:param timeout: Registration timeout in seconds. If timeout seconds have passed
since the worker's last call to register or status_re... | RegisterRequest |
python | kamyu104__LeetCode-Solutions | Python/check-if-every-row-and-column-contains-all-numbers.py | {
"start": 443,
"end": 862
} | class ____(object):
def checkValid(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
return all(reduce(lambda x, y: x^y, (matrix[i][j]^(j+1) for j in xrange(len(matrix[0])))) == 0 for i in xrange(len(matrix))) and \
all(reduce(lambda x, y: x^y, ... | Solution_Wrong |
python | geekcomputers__Python | binary_search_trees/tree_node.py | {
"start": 59,
"end": 227
} | class ____:
def __init__(self, data: int) -> None:
self.data: int = data
self.left: Optional[Node] = None
self.right: Optional[Node] = None
| Node |
python | getsentry__sentry | src/sentry/replays/usecases/ingest/event_logger.py | {
"start": 1748,
"end": 9825
} | class ____(TypedDict):
payload: ReplayActionsEventClickPayload | ReplayActionsEventTapPayload
project_id: int
replay_id: str
retention_days: int
start_time: float
type: Literal["replay_event"]
@sentry_sdk.trace
def emit_tap_events(
tap_events: list[TapEvent],
project_id: int,
repla... | ReplayActionsEvent |
python | django-debug-toolbar__django-debug-toolbar | tests/test_toolbar.py | {
"start": 148,
"end": 557
} | class ____(BaseTestCase):
def test_empty_prefix_errors(self):
with self.assertRaises(ImproperlyConfigured):
debug_toolbar_urls(prefix="")
def test_empty_when_debug_is_false(self):
self.assertEqual(debug_toolbar_urls(), [])
def test_has_path(self):
with self.settings(DEB... | DebugToolbarUrlsTestCase |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_search_view_details_starred.py | {
"start": 1094,
"end": 3060
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
permission_classes = (MemberPermission,)
def post(self, request: Request, organization: Organization, view_id: int) -> Response:
"""
Update the starred statu... | OrganizationGroupSearchViewDetailsStarredEndpoint |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 9841,
"end": 10978
} | class ____(OAuthLibMixin):
"""Mixin for protecting resources with client authentication as mentioned in rfc:`3.2.1`
This involves authenticating with any of: HTTP Basic Auth, Client Credentials and
Access token in that order. Breaks off after first validation.
"""
def dispatch(self, request, *args,... | ClientProtectedResourceMixin |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 43328,
"end": 46324
} | class ____(BaseTestCase):
def test_xls_format_detect(self):
"""Test the XLS format detection."""
in_stream = self.founders.xls
self.assertEqual(detect_format(in_stream), 'xls')
def test_xls_date_import(self):
xls_source = Path(__file__).parent / 'files' / 'dates.xls'
wit... | XLSTests |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 130326,
"end": 131538
} | class ____(Response):
"""
Response of tasks.delete_configuration endpoint.
:param deleted: Indicates if the task was updated successfully
:type deleted: int
"""
_service = "tasks"
_action = "delete_configuration"
_version = "2.9"
_schema = {
"definitions": {},
"prop... | DeleteConfigurationResponse |
python | PyCQA__pylint | tests/regrtest_data/hang/pkg4972/string/__init__.py | {
"start": 62,
"end": 126
} | class ____(string.Formatter):
pass
string.Formatter = Fake
| Fake |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 3292,
"end": 6080
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
global_annotations: List[RawGlobalAnnotation] = dataclasses.field(
metadata=dataclasses_json.config(field_name="globals"), default_factory=list
)
attribute_annotations: List[RawAttributeAnnotation] = dataclasses.field(
metadata=dataclasses... | RawInferOutput |
python | huggingface__transformers | tests/kernels/test_kernels.py | {
"start": 14485,
"end": 16114
} | class ____(TestCasePlus):
@classmethod
def setUpClass(cls):
cls.model_id = "unsloth/Llama-3.2-1B-Instruct"
cls.model = AutoModelForCausalLM.from_pretrained(cls.model_id, use_kernels=False, device_map=torch_device)
@classmethod
def tearDownClass(cls):
# Delete large objects to dr... | TestUseKernelsLifecycle |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 2390,
"end": 4307
} | class ____:
def _test_store_timeout(self, backend, init_method, c2p):
try:
dist.init_process_group(
backend=backend,
init_method=init_method,
world_size=1,
rank=0,
timeout=timedelta(seconds=1),
)
... | AbstractTimeoutTest |
python | pytorch__pytorch | torch/ao/nn/qat/modules/conv.py | {
"start": 3939,
"end": 5753
} | class ____(_ConvNd, nn.Conv1d):
r"""
A Conv1d module attached with FakeQuantize modules for weight,
used for quantization aware training.
We adopt the same interface as :class:`~torch.nn.Conv1d`
Similar to :class:`~torch.nn.Conv2d`, with FakeQuantize modules initialized to
default.
Attrib... | Conv1d |
python | facebookresearch__faiss | tests/test_factory.py | {
"start": 7232,
"end": 7447
} | class ____(unittest.TestCase):
def test_1(self):
self.assertEqual(
factory_tools.get_code_size(50, "IVF32,Flat,Refine(PQ25x12)"),
50 * 4 + (25 * 12 + 7) // 8
)
| TestCodeSize |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 1778,
"end": 2313
} | class ____(pydantic.BaseModel):
column_name: str
sort_ascending: bool = True
method_name: Literal["partition_on_converted_datetime"] = "partition_on_converted_datetime"
date_format_string: str
ColumnPartitioner = Union[
PartitionerColumnValue,
PartitionerMultiColumnValue,
PartitionerDivide... | PartitionerConvertedDatetime |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_emoji.py | {
"start": 1324,
"end": 1895
} | class ____(util.MdCase):
"""Test new style index."""
extension = [
'pymdownx.emoji'
]
extension_configs = {
'pymdownx.emoji': {
'emoji_index': _new_style_index,
'options': {'append_alias': [(':grin:', ":smile:")]}
}
}
def test_new_index(self):
... | TestEmojiNewIndex |
python | getsentry__sentry | src/sentry/relay/config/__init__.py | {
"start": 46260,
"end": 48890
} | class ____(_ConfigBase):
"""
Represents the restricted configuration available to an untrusted
"""
def __init__(self, project: Project, **kwargs: Any) -> None:
object.__setattr__(self, "project", project)
super().__init__(**kwargs)
def _load_filter_settings(flt: _FilterSpec, project:... | ProjectConfig |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 630074,
"end": 630401
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("SponsorsActivity", graphql_name="node")
| SponsorsActivityEdge |
python | doocs__leetcode | solution/0400-0499/0424.Longest Repeating Character Replacement/Solution.py | {
"start": 0,
"end": 324
} | class ____:
def characterReplacement(self, s: str, k: int) -> int:
cnt = Counter()
l = mx = 0
for r, c in enumerate(s):
cnt[c] += 1
mx = max(mx, cnt[c])
if r - l + 1 - mx > k:
cnt[s[l]] -= 1
l += 1
return len(s) - l
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis06.py | {
"start": 315,
"end": 1324
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | openai__gym | gym/error.py | {
"start": 528,
"end": 662
} | class ____(UnregisteredEnv):
"""Raised when the user requests an env from the registry where the name doesn't exist."""
| NameNotFound |
python | kamyu104__LeetCode-Solutions | Python/the-knights-tour.py | {
"start": 75,
"end": 1439
} | class ____(object):
def tourOfKnight(self, m, n, r, c):
"""
:type m: int
:type n: int
:type r: int
:type c: int
:rtype: List[List[int]]
"""
DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2),
(2, 1), (-2, 1), (2, -1), (-2, -1))
... | Solution |
python | django__django | django/contrib/auth/views.py | {
"start": 12545,
"end": 13005
} | class ____(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_complete.html"
title = _("Password reset complete")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["login_url"] = resolve_url(settings.LOGIN_URL)
... | PasswordResetCompleteView |
python | sympy__sympy | sympy/polys/domains/quotientring.py | {
"start": 416,
"end": 2541
} | class ____:
"""
Class representing elements of (commutative) quotient rings.
Attributes:
- ring - containing ring
- data - element of ring.ring (i.e. base ring) representing self
"""
def __init__(self, ring, data):
self.ring = ring
self.data = data
def __str__(self):
... | QuotientRingElement |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 82783,
"end": 84926
} | class ____(SocketDummyServerTestCase):
def test_enforce_content_length_get(self) -> None:
done_event = Event()
def socket_handler(listener: socket.socket) -> None:
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ... | TestBadContentLength |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 34657,
"end": 35404
} | class ____(TestCase):
def test_even(self):
actual = list(mi.interleave_longest([1, 4, 7], [2, 5, 8], [3, 6, 9]))
expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.assertEqual(actual, expected)
def test_short(self):
actual = list(mi.interleave_longest([1, 4], [2, 5, 7], [3, 6, 8]))
... | InterleaveLongestTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 9842,
"end": 9899
} | class ____(BYTEA):
render_bind_cast = True
| AsyncpgByteA |
python | pandas-dev__pandas | pandas/tests/frame/test_cumulative.py | {
"start": 229,
"end": 3278
} | class ____:
# ---------------------------------------------------------------------
# Cumulative Operations - cumsum, cummax, ...
def test_cumulative_ops_smoke(self):
# it works
df = DataFrame({"A": np.arange(20)}, index=np.arange(20))
df.cummax()
df.cummin()
df.cums... | TestDataFrameCumulativeOps |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/base_aws.py | {
"start": 44687,
"end": 46589
} | class ____(AwsGenericHook[Union[boto3.client, boto3.resource]]): # noqa: UP007
"""
Base class for interact with AWS.
This class provide a thin wrapper around the boto3 Python library.
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is None or empty then the defaul... | AwsBaseHook |
python | streamlit__streamlit | lib/tests/streamlit/elements/audio_test.py | {
"start": 1260,
"end": 11918
} | class ____(DeltaGeneratorTestCase):
def test_st_audio_from_bytes(self):
"""Test st.audio using fake audio bytes."""
# Fake audio data: expect the resultant mimetype to be audio default.
fake_audio_data = b"\x11\x22\x33\x44\x55\x66"
st.audio(fake_audio_data)
el = self.get_d... | AudioTest |
python | numpy__numpy | numpy/lib/_utils_impl.py | {
"start": 3487,
"end": 23499
} | class ____:
"""
Decorator class to deprecate old functions.
Refer to `deprecate` for details.
See Also
--------
deprecate
"""
def __init__(self, old_name=None, new_name=None, message=None):
self.old_name = old_name
self.new_name = new_name
self.message = messa... | _Deprecate |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 36943,
"end": 39184
} | class ____(nn.Module):
def __init__(self, config: OwlViTVisionConfig):
super().__init__()
self.config = config
self.embeddings = OwlViTVisionEmbeddings(config)
self.pre_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.encoder = OwlViTEncoder(confi... | OwlViTVisionTransformer |
python | Textualize__rich | tests/test_repr.py | {
"start": 465,
"end": 638
} | class ____:
def __init__(self, foo: str, bar: Optional[int] = None, egg: int = 1):
self.foo = foo
self.bar = bar
self.egg = egg
@rich.repr.auto
| Egg |
python | gevent__gevent | src/gevent/_config.py | {
"start": 13112,
"end": 13807
} | class ____(BoolSettingMixin, Setting):
name = 'track_greenlet_tree'
environment_key = 'GEVENT_TRACK_GREENLET_TREE'
default = True
desc = """\
Should `Greenlet` objects track their spawning tree?
Setting this to a false value will make spawning `Greenlet`
objects and using `spawn_raw` faste... | TrackGreenletTree |
python | ray-project__ray | python/ray/data/tests/unit/test_datatype.py | {
"start": 29988,
"end": 31461
} | class ____:
"""Test that pattern-matching types cannot be converted to concrete Arrow types."""
@pytest.mark.parametrize(
"pattern_type_factory",
[
lambda: DataType.list(),
lambda: DataType.large_list(),
lambda: DataType.struct(),
lambda: DataType... | TestPatternMatchingToArrowDtype |
python | django__django | django/db/utils.py | {
"start": 6515,
"end": 9350
} | class ____:
def __init__(self, routers=None):
"""
If routers is not specified, default to settings.DATABASE_ROUTERS.
"""
self._routers = routers
@cached_property
def routers(self):
if self._routers is None:
self._routers = settings.DATABASE_ROUTERS
... | ConnectionRouter |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_run.py | {
"start": 3031,
"end": 3194
} | class ____(BaseModel):
"""DAG Run Collection serializer for responses."""
dag_runs: Iterable[DAGRunResponse]
total_entries: int
| DAGRunCollectionResponse |
python | python-visualization__folium | folium/plugins/timestamped_geo_json.py | {
"start": 216,
"end": 9135
} | class ____(JSCSSMixin, MacroElement):
"""
Creates a TimestampedGeoJson plugin from timestamped GeoJSONs to append
into a map with Map.add_child.
A geo-json is timestamped if:
* it contains only features of types LineString, MultiPoint, MultiLineString,
Polygon and MultiPolygon.
* each fe... | TimestampedGeoJson |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarmath.py | {
"start": 28973,
"end": 30536
} | class ____(TestCase):
@parametrize("type_code", np.typecodes["AllInteger"])
def test_integer_hashes(self, type_code):
scalar = np.dtype(type_code).type
for i in range(128):
assert hash(i) == hash(scalar(i))
@parametrize("type_code", np.typecodes["AllFloat"])
def test_float_a... | TestHash |
python | ray-project__ray | python/ray/tests/test_memory_scheduling.py | {
"start": 435,
"end": 2153
} | class ____:
def __init__(self):
pass
def ping(self):
return "ok"
def test_memory_request():
try:
ray.init(num_cpus=1, _memory=200 * MB)
# fits first 2
a = Actor.remote()
b = Actor.remote()
ok, _ = ray.wait(
[a.ping.remote(), b.ping.remot... | Actor |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/parallel.py | {
"start": 4203,
"end": 5308
} | class ____(AbstractProgressInfoMatcher):
DOCKER_BUILDX_PROGRESS_MATCHER = re.compile(r"\s*#(\d*) ")
def __init__(self):
self.last_docker_build_lines: dict[str, str] = {}
def get_best_matching_lines(self, output: Output) -> list[str] | None:
last_lines, last_lines_no_colors = get_last_lines... | DockerBuildxProgressMatcher |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 2754,
"end": 2923
} | class ____[**Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]:
pass
| TestTypeParams |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/base.py | {
"start": 1117,
"end": 11122
} | class ____(Conversation, BaseVoiceAgent):
"""
Conversational AI session.
BETA: This API is subject to change without regard to backwards compatibility.
Attributes:
client (BaseElevenLabs): The ElevenLabs client to use for the conversation.
agent_id (str): The ID of the agent to convers... | ElevenLabsVoiceAgent |
python | google__pytype | pytype/rewrite/abstract/containers_test.py | {
"start": 242,
"end": 424
} | class ____(test_utils.ContextfulTestBase):
"""Base class for constant tests."""
def const_var(self, const, name=None):
return self.ctx.consts[const].to_variable(name)
| BaseTest |
python | pypa__warehouse | warehouse/predicates.py | {
"start": 322,
"end": 786
} | class ____:
def __init__(self, val, config):
self.val = val
def text(self):
return f"domain = {self.val!r}"
phash = text
def __call__(self, info, request):
# Support running under the same instance for local development and for
# test.pypi.io which will continue to hos... | DomainPredicate |
python | weaviate__weaviate-python-client | weaviate/collections/classes/cluster.py | {
"start": 221,
"end": 566
} | class ____:
"""The properties of a single shard of a collection."""
collection: str
name: str
node: str
object_count: int
vector_indexing_status: Literal["READONLY", "INDEXING", "READY", "LAZY_LOADING"]
vector_queue_length: int
compressed: bool
loaded: Optional[bool] # not present ... | Shard |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/project_preprod_check_for_updates.py | {
"start": 879,
"end": 1072
} | class ____(BaseModel):
id: str
build_version: str
build_number: int
release_notes: str | None
download_url: str
app_name: str
created_date: str
| InstallableBuildDetails |
python | falconry__falcon | falcon/bench/queues/api.py | {
"start": 1010,
"end": 2600
} | class ____:
def __init__(self, body, headers):
self._body = body
self._headers = headers
def process_response(self, req, resp, resource, req_succeeded):
user_agent = req.user_agent # NOQA
limit = req.get_param('limit') or '10' # NOQA
resp.status = falcon.HTTP_200
... | CannedResponseComponent |
python | keras-team__keras | keras/src/metrics/regression_metrics.py | {
"start": 10365,
"end": 19756
} | class ____(reduction_metrics.Metric):
"""Computes R2 score.
Formula:
```python
sum_squares_residuals = sum((y_true - y_pred) ** 2)
sum_squares = sum((y_true - mean(y_true)) ** 2)
R2 = 1 - sum_squares_residuals / sum_squares
```
This is also called the
[coefficient of determination... | R2Score |
python | sqlalchemy__sqlalchemy | test/sql/test_labels.py | {
"start": 1474,
"end": 16901
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "DefaultDialect"
__sparse_driver_backend__ = True
table1 = table(
"some_large_named_table",
column("this_is_the_primarykey_column"),
column("this_is_the_data_column"),
)
table2 = table(
"table_with_exa... | MaxIdentTest |
python | sympy__sympy | sympy/functions/elementary/hyperbolic.py | {
"start": 36642,
"end": 42137
} | class ____(InverseHyperbolicFunction):
"""
``asinh(x)`` is the inverse hyperbolic sine of ``x``.
The inverse hyperbolic sine function.
Examples
========
>>> from sympy import asinh
>>> from sympy.abc import x
>>> asinh(x).diff(x)
1/sqrt(x**2 + 1)
>>> asinh(1)
log(1 + sqrt(... | asinh |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 64744,
"end": 66078
} | class ____(GestureTool):
''' A base class for all interactive draw tool types.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
default_overrides = Dict(String, AnyRef, default={}, help="""
Padd... | EditTool |
python | scikit-image__scikit-image | tests/skimage/io/test_collection.py | {
"start": 1773,
"end": 5357
} | class ____:
pics = [fetch('data/brick.png'), fetch('data/color.png'), fetch('data/moon.png')]
pattern = pics[:2]
pattern_same_shape = pics[::2]
def setup_method(self):
reset_plugins()
# Generic image collection with images of different shapes.
self.images = ImageCollection(self.... | TestImageCollection |
python | pyparsing__pyparsing | tests/test_unit.py | {
"start": 7129,
"end": 390869
} | class ____(ppt.TestParseResultsAsserts, TestCase):
suite_context = None
save_suite_context = None
def setUp(self):
self.suite_context.restore()
def test000_assert_packrat_status(self):
print("Packrat enabled:", ParserElement._packratEnabled)
self.assertFalse(ParserElement._pack... | Test02_WithoutPackrat |
python | paramiko__paramiko | paramiko/ssh_exception.py | {
"start": 5054,
"end": 6773
} | class ____(socket.error):
"""
Multiple connection attempts were made and no families succeeded.
This exception class wraps multiple "real" underlying connection errors,
all of which represent failed connection attempts. Because these errors are
not guaranteed to all be of the same error type (i.e. ... | NoValidConnectionsError |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/conv_test.py | {
"start": 5386,
"end": 7514
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, IC, OC, stride, N, H, W, G, pad, device):
self.inputs = {"input": torch.rand(N, IC, H, W, device=device)}
# Use 1 as kernel for pointwise convolution
self.conv2d = nn.Conv2d(IC, OC, 1, stride=stride, groups=G, padding=pad).to(
... | Conv2dPointwiseBenchmark |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 579643,
"end": 580027
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("Discussion", graphql_name... | DiscussionEdge |
python | huggingface__transformers | tests/models/sam2/test_modeling_sam2.py | {
"start": 1524,
"end": 4630
} | class ____:
def __init__(
self,
parent,
hidden_size=12,
embed_dim_per_stage=[12, 24, 48, 96],
num_attention_heads_per_stage=[1, 2, 4, 8],
num_channels=3,
image_size=128,
patch_kernel_size=7,
patch_stride=4,
patch_padding=3,
batc... | Sam2VisionModelTester |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 3010,
"end": 3392
} | class ____(Protocol):
def __call__(
self,
ddl: BaseDDLElement,
target: Union[SchemaItem, str],
bind: Optional[Connection],
tables: Optional[List[Table]] = None,
state: Optional[Any] = None,
*,
dialect: Dialect,
compiler: Optional[DDLCompiler] =... | DDLIfCallable |
python | scipy__scipy | scipy/fft/_pocketfft/tests/test_basic.py | {
"start": 28853,
"end": 29136
} | class ____:
def __init__(self, data):
self._data = data
def __array__(self, dtype=None, copy=None):
return self._data
# TODO: Is this test actually valuable? The behavior it's testing shouldn't be
# relied upon by users except for overwrite_x = False
| FakeArray2 |
python | google__pytype | pytype/tests/test_operators3.py | {
"start": 501,
"end": 672
} | class ____(test_base.BaseTest, test_utils.OperatorsTestMixin):
"""Tests for reverse operators."""
def test_div(self):
self.check_reverse("truediv", "/")
| ReverseTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.