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 | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_kueue.py | {
"start": 1590,
"end": 7134
} | class ____:
def setup_method(self):
self.operator = KubernetesInstallKueueOperator(
task_id=TEST_TASK_ID,
kueue_version=KUEUE_VERSION,
kubernetes_conn_id=TEST_K8S_CONN_ID,
)
def test_template_fields(self):
expected_template_fields = {"kueue_version", ... | TestKubernetesInstallKueueOperator |
python | astropy__astropy | astropy/io/ascii/tdat.py | {
"start": 1473,
"end": 1546
} | class ____(AstropyWarning):
"""Tdat Format Warning"""
| TdatFormatWarning |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 60821,
"end": 63278
} | class ____:
"""Test pt_BR address provider methods"""
def test_country(self, faker, num_samples):
for _ in range(num_samples):
country = faker.country()
assert isinstance(country, str)
assert country in PtBrAddressProvider.countries
def test_bairro(self, faker, ... | TestPtBr |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/gce_cluster_resolver.py | {
"start": 1295,
"end": 7660
} | class ____(ClusterResolver):
"""ClusterResolver for Google Compute Engine.
This is an implementation of cluster resolvers for the Google Compute Engine
instance group platform. By specifying a project, zone, and instance group,
this will retrieve the IP address of all the instances within the instance
group ... | GCEClusterResolver |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 2201,
"end": 2309
} | class ____[**P = [T1]]: ...
# This should generate an error because ParamSpec must be a list of types.
| ClassP5 |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/boost/package.py | {
"start": 217,
"end": 2150
} | class ____(Package):
"""Fake boost package."""
homepage = "http://www.boost.org"
url = "http://downloads.sourceforge.net/project/boost/boost/1.63.0/boost_1_63_0.tar.bz2"
version("1.63.0", md5="1c837ecd990bb022d07e7aab32b09847")
default_install_libs = set(
[
"atomic",
... | Boost |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 27484,
"end": 28069
} | class ____(JsProxy):
"""A :py:class:`JsFetchResponse` object represents a :js:data:`Response` to a
:js:func:`fetch` request.
"""
bodyUsed: bool
ok: bool
redirected: bool
status: int
statusText: str
type: str
url: str
headers: Any
def clone(self) -> "JsFetchResponse":
... | JsFetchResponse |
python | PyCQA__isort | isort/exceptions.py | {
"start": 4716,
"end": 5348
} | class ____(ISortError):
"""Raised when isort is told to sort assignments but the format of the assignment section
doesn't match isort's expectation.
"""
def __init__(self, code: str):
super().__init__(
"isort was told to sort a section of assignments, however the given code:\n\n"
... | AssignmentsFormatMismatch |
python | sphinx-doc__sphinx | sphinx/transforms/i18n.py | {
"start": 14656,
"end": 24112
} | class ____(SphinxTransform):
"""Replace translatable nodes with their translated doctree."""
default_priority = 20
def apply(self, **kwargs: Any) -> None:
settings, source = self.document.settings, self.document['source']
msgstr = ''
textdomain = docname_to_domain(
sel... | Locale |
python | aio-libs__aiohttp | aiohttp/helpers.py | {
"start": 25075,
"end": 25952
} | class ____(Protocol):
def set_exception(
self,
exc: type[BaseException] | BaseException,
exc_cause: BaseException = ...,
) -> None: ...
def set_exception(
fut: Union["asyncio.Future[_T]", ErrorableProtocol],
exc: type[BaseException] | BaseException,
exc_cause: BaseException... | ErrorableProtocol |
python | fastai__fastai | fastai/text/models/core.py | {
"start": 3897,
"end": 5918
} | class ____(Module):
"Create an encoder over `module` that can process a full sentence."
def __init__(self,
bptt:int, # Backpropagation through time
module:nn.Module, # A module that can process up to [`bs`, `bptt`] tokens
pad_idx:int=1, # Padding token id
max_len:int=None # Max... | SentenceEncoder |
python | scrapy__scrapy | scrapy/spidermiddlewares/referer.py | {
"start": 11612,
"end": 15111
} | class ____(BaseSpiderMiddleware):
def __init__(self, settings: BaseSettings | None = None): # pylint: disable=super-init-not-called
self.default_policy: type[ReferrerPolicy] = DefaultReferrerPolicy
if settings is not None:
settings_policy = _load_policy_class(settings.get("REFERRER_POLI... | RefererMiddleware |
python | kamyu104__LeetCode-Solutions | Python/number-of-different-integers-in-a-string.py | {
"start": 29,
"end": 500
} | class ____(object):
def numDifferentIntegers(self, word):
"""
:type word: str
:rtype: int
"""
result, num = set(), None
for i in xrange(len(word)+1):
c = word[i] if i < len(word) else ' '
if c.isdigit():
num = 10*num+int(c) if n... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/llms/llm.py | {
"start": 4186,
"end": 30335
} | class ____(BaseLLM):
"""
The LLM class is the main class for interacting with language models.
Attributes:
system_prompt (Optional[str]):
System prompt for LLM calls.
messages_to_prompt (Callable):
Function to convert a list of messages to an LLM prompt.
comp... | LLM |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 11882,
"end": 13094
} | class ____:
"""
Regression test for issue #10232:
Exception in loadarff with quoted nominal attributes.
"""
def setup_method(self):
self.data, self.meta = loadarff(test_quoted_nominal_spaces)
def test_attributes(self):
assert_equal(len(self.meta._attributes), 2)
age, ... | TestQuotedNominalSpaces |
python | getsentry__sentry | src/sentry/search/events/types.py | {
"start": 2752,
"end": 7948
} | class ____:
start: datetime | None = None
end: datetime | None = None
stats_period: str | None = None
query_string: str | None = None
# granularity is used with timeseries requests to specifiy bucket size
granularity_secs: int | None = None
# The None value in this sequence is because the fi... | SnubaParams |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 31408,
"end": 32515
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.feat_out = nn.Linear(config.hidden_size, config.num_mel_bins * config.reduction_factor)
self.prob_out = nn.Linear(config.hidden_size, config.reduction_factor)
self.layers = nn.Mo... | SpeechT5SpeechDecoderPostnet |
python | getsentry__sentry | src/sentry/conf/types/taskworker.py | {
"start": 176,
"end": 665
} | class ____:
"""
crontab schedule value object
Used in configuration to define a task schedule.
:see sentry.taskworker.scheduler.schedules.CrontabSchedule for more details.
"""
minute: str = "*"
hour: str = "*"
day_of_week: str = "*"
day_of_month: str = "*"
month_of_year: str =... | crontab |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 104995,
"end": 106741
} | class ____(SingleODESolver):
r"""
Gives solution of the Airy differential equation
.. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0
in terms of Airy special functions airyai and airybi.
Examples
========
>>> from sympy import dsolve, Function
>>> from sympy.abc import x
>>> f = ... | SecondLinearAiry |
python | ansible__ansible | lib/ansible/plugins/inventory/ini.py | {
"start": 3750,
"end": 19358
} | class ____(BaseFileInventoryPlugin):
"""
Takes an INI-format inventory file and builds a list of groups and subgroups
with their associated hosts and variable settings.
"""
NAME = 'ini'
_COMMENT_MARKERS = frozenset((u';', u'#'))
b_COMMENT_MARKERS = frozenset((b';', b'#'))
# template tru... | InventoryModule |
python | pytorch__pytorch | test/distributed/_shard/sharding_spec/test_sharding_spec.py | {
"start": 19870,
"end": 21822
} | class ____(ShardingSpec):
grid_size: int
placements: list[Union[torch.distributed._remote_device, str]]
def __post_init__(self):
for i, remote_device in enumerate(self.placements):
if not isinstance(remote_device, torch.distributed._remote_device):
self.placements[i] = t... | GridShardingSpec |
python | django__django | tests/foreign_object/models/customers.py | {
"start": 704,
"end": 1046
} | class ____(models.Model):
company_code = models.CharField(max_length=1)
customer_code = models.IntegerField()
customer = models.ForeignObject(
Customer,
models.CASCADE,
related_name="contacts",
to_fields=["customer_id", "company"],
from_fields=["customer_code", "compa... | Contact |
python | conda__conda | conda/plugins/prefix_data_loaders/pypi/pkg_format.py | {
"start": 15087,
"end": 15835
} | class ____(PythonDistribution):
"""
Python distribution installed via distutils.
Notes
-----
- https://www.python.org/dev/peps/pep-0376/
"""
MANIFEST_FILES = ("RECORD",)
REQUIRES_FILES = ()
MANDATORY_FILES = ("METADATA",)
# FIXME: Do this check? Disabled for tests where only ... | PythonInstalledDistribution |
python | kamyu104__LeetCode-Solutions | Python/minimum-total-distance-traveled.py | {
"start": 105,
"end": 1104
} | class ____(object):
def minimumTotalDistance(self, robot, factory):
"""
:type robot: List[int]
:type factory: List[List[int]]
:rtype: int
"""
robot.sort(), factory.sort()
dp = [float("inf")]*(len(robot)+1) # dp[j] at i: min of factory[:i+1] and robot[:j]
... | Solution |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 1684,
"end": 2317
} | class ____(ModelOutput):
r"""
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
"""
image_embeds: Optional[torch.F... | AlignVisionModelOutput |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 684,
"end": 1759
} | class ____:
def __call__(self, req, resp, resource, params):
assert resource
validate_param(req, resp, resource, params, 'limit')
def validate_field(req, resp, resource, params, field_name='test'):
assert resource
try:
params[field_name] = int(params[field_name])
except ValueE... | ResourceAwareValidateParam |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/embeddings/base_sparse.py | {
"start": 2073,
"end": 11323
} | class ____(BaseModel, DispatcherSpanMixin):
"""Base class for embeddings."""
model_config = ConfigDict(
protected_namespaces=("pydantic_model_",), arbitrary_types_allowed=True
)
model_name: str = Field(
default="unknown", description="The name of the embedding model."
)
embed_ba... | BaseSparseEmbedding |
python | scipy__scipy | benchmarks/benchmarks/fft_basic.py | {
"start": 7477,
"end": 8805
} | class ____(Benchmark):
params = [
["100x100", "313x100", "1000x100", "256x256", "512x512"],
['real', 'cmplx'],
['pocketfft', 'pyfftw', 'numpy', 'direct']
]
param_names = ['size', 'type', 'backend']
def setup(self, size, cmplx, backend):
import scipy.fft
size = li... | FftnBackends |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_salesforce_to_s3.py | {
"start": 1915,
"end": 4438
} | class ____:
@mock.patch.object(S3Hook, "load_file")
@mock.patch.object(SalesforceHook, "write_object_to_file")
@mock.patch.object(SalesforceHook, "make_query")
def test_execute(self, mock_make_query, mock_write_object_to_file, mock_load_file):
mock_make_query.return_value = SALESFORCE_RESPONSE
... | TestSalesforceToGcsOperator |
python | google__jax | jax/_src/pallas/mosaic/core.py | {
"start": 7926,
"end": 8646
} | class ____(pallas_core.GridSpec):
num_scalar_prefetch: int
def __init__(
self,
num_scalar_prefetch: int,
grid: pallas_core.Grid = (),
in_specs: pallas_core.BlockSpecTree = no_block_spec,
out_specs: pallas_core.BlockSpecTree = no_block_spec,
scratch_shapes: pallas_core.ScratchSha... | PrefetchScalarGridSpec |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/kw_only.py | {
"start": 165,
"end": 228
} | class ____:
a: int
_: KW_ONLY
b: str
@dataclass
| Test1 |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-visit-a-cell-in-a-grid.py | {
"start": 88,
"end": 1315
} | class ____(object):
def minimumTime(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def dijkstra(start, target):
best = [[float("inf")]*len(grid[0]) for _ in xrange(len(grid))]
best[s... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator1.py | {
"start": 300,
"end": 336
} | class ____:
pass
s = True
| ClassA |
python | getsentry__sentry | tests/sentry/services/nodestore/bigtable/test_backend.py | {
"start": 472,
"end": 3094
} | class ____(BigtableKVStorage):
class Cell:
def __init__(self, value: bytes, timestamp: int) -> None:
self.value = value
self.timestamp = timestamp
class Row:
def __init__(self, table: MockedBigtableKVStorage.Table, row_key: str) -> None:
self.row_key = row_ke... | MockedBigtableKVStorage |
python | ray-project__ray | python/ray/serve/tests/test_fastapi.py | {
"start": 4080,
"end": 4120
} | class ____(BaseModel):
val: int
| Nested |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1009269,
"end": 1009785
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnlinkProjectV2FromRepository"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client perf... | UnlinkProjectV2FromRepositoryPayload |
python | ray-project__ray | python/ray/data/_internal/execution/callbacks/insert_issue_detectors.py | {
"start": 324,
"end": 804
} | class ____(ExecutionCallback):
"""ExecutionCallback that handles issue detection."""
def before_execution_starts(self, executor: "StreamingExecutor"):
# Initialize issue detector in StreamingExecutor
executor._issue_detector_manager = IssueDetectorManager(executor)
def on_execution_step(se... | IssueDetectionExecutionCallback |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 10353,
"end": 11333
} | class ____:
class B:
def foo():
st_error = STError(
f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
" no parent)."
)
def foo():
user_regex = _lazy_re_compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-... | A |
python | TheAlgorithms__Python | data_structures/binary_tree/symmetric_tree.py | {
"start": 268,
"end": 3636
} | class ____:
"""
A Node represents an element of a binary tree, which contains:
Attributes:
data: The value stored in the node (int).
left: Pointer to the left child node (Node or None).
right: Pointer to the right child node (Node or None).
Example:
>>> node = Node(1, Node(2), Node(3))... | Node |
python | pytorch__pytorch | test/quantization/core/test_quantized_op.py | {
"start": 365388,
"end": 368650
} | class ____(TestCase):
@given(batch_size=st.integers(1, 64),
channels=st.integers(1, 64),
width=st.integers(16, 128),
qtype=st.sampled_from(hu._ALL_QINT_TYPES))
def test_reflection_pad1d(self, batch_size, channels, width, qtype):
padding = width // 4
x = torch.ar... | TestPadding |
python | huggingface__transformers | tests/peft_integration/test_peft_integration.py | {
"start": 1324,
"end": 1639
} | class ____:
peft_test_model_ids = ("peft-internal-testing/tiny-OPTForCausalLM-lora",)
transformers_test_model_ids = ("hf-internal-testing/tiny-random-OPTForCausalLM",)
transformers_test_model_classes = (AutoModelForCausalLM, OPTForCausalLM)
# TODO: run it with CI after PEFT release.
@slow
| PeftTesterMixin |
python | anthropics__anthropic-sdk-python | src/anthropic/types/tool_choice_none_param.py | {
"start": 219,
"end": 306
} | class ____(TypedDict, total=False):
type: Required[Literal["none"]]
| ToolChoiceNoneParam |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 11927,
"end": 27671
} | class ____(Base):
"""A non-callable version of `Mock`"""
def __new__(cls, *args, **kw):
# every instance has its own class
# so we can create magic methods on the
# class without stomping on other mocks
new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
instance ... | NonCallableMock |
python | spyder-ide__spyder | spyder/api/shellconnect/main_widget.py | {
"start": 541,
"end": 1392
} | class ____(EmptyMessageWidget):
"""Widget to show when the kernel's shell failed to start."""
def __init__(self, parent, shellwidget):
# Initialize EmptyMessageWidget with the content we want to show for
# errors
super().__init__(
parent,
icon_filename=(
... | _ErroredMessageWidget |
python | walkccc__LeetCode | solutions/1210. Minimum Moves to Reach Target with Rotations/1210.py | {
"start": 81,
"end": 1884
} | class ____:
def minimumMoves(self, grid: list[list[int]]) -> int:
n = len(grid)
ans = 0
# the state of (x, y, pos)
# pos := 0 (horizontal) / 1 (vertical)
q = collections.deque([(0, 0, Pos.HORIZONTAL)])
seen = {(0, 0, Pos.HORIZONTAL)}
def canMoveRight(x: int, y: int, pos: Pos) -> bool:
... | Solution |
python | django__django | tests/gis_tests/geoapp/models.py | {
"start": 1528,
"end": 1684
} | class ____(NamedModel):
geom = models.GeometryField(dim=3)
class Meta:
required_db_features = {"supports_3d_storage"}
| ThreeDimensionalFeature |
python | pytorch__pytorch | torch/_inductor/select_algorithm.py | {
"start": 84698,
"end": 87966
} | class ____(ir.TritonTemplateCallerBase):
def __init__(
self,
name,
input_nodes,
layout,
make_kernel_render,
description,
bmreq,
log_info: Optional[
dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]
] = None,
mutat... | TritonTemplateCaller |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_N.py | {
"start": 2771,
"end": 4094
} | class ____(Benchmark):
r"""
NewFunction02 objective function.
This class defines the NewFunction02 global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{NewFunction02}}(x) = \left | {\sin\left(\sqrt{\lvert{x_{1}^{2}
+ x_{2}}\r... | NewFunction02 |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 1621,
"end": 1755
} | class ____(NotImplementedError):
"""Raised if a SingleODESolver is asked to solve an ODE it does not match"""
pass
| ODEMatchError |
python | pytorch__pytorch | torch/_higher_order_ops/triton_kernel_wrap.py | {
"start": 32853,
"end": 41930
} | class ____:
fn: Callable[..., Any]
cache: dict[tuple[Any], Any]
def __init__(self, fn: Callable[..., Any]) -> None:
self.fn = fn
self.reset()
def __call__(
self,
functions: dict[str, dict[Intermediate, list[Op]]],
fn_name: str,
*args: Any,
) -> list[... | MemoizeWithCycleCheck |
python | walkccc__LeetCode | solutions/206. Reverse Linked List/206-2.py | {
"start": 0,
"end": 231
} | class ____:
def reverseList(self, head: ListNode | None) -> ListNode | None:
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
| Solution |
python | jschneier__django-storages | tests/test_sftp.py | {
"start": 7943,
"end": 8974
} | class ____(TestCase):
def setUp(self):
self.storage = sftpstorage.SFTPStorage(host="foo")
self.file = sftpstorage.SFTPStorageFile("bar", self.storage, "wb")
@patch(
"storages.backends.sftpstorage.SFTPStorage.sftp",
**{
"stat.return_value.st_size": 42,
},
... | SFTPStorageFileTest |
python | doocs__leetcode | solution/0900-0999/0922.Sort Array By Parity II/Solution.py | {
"start": 0,
"end": 304
} | class ____:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
n, j = len(nums), 1
for i in range(0, n, 2):
if nums[i] % 2:
while nums[j] % 2:
j += 2
nums[i], nums[j] = nums[j], nums[i]
return nums
| Solution |
python | PyCQA__pylint | tests/functional/ext/private_import/private_import.py | {
"start": 4303,
"end": 4483
} | class ____:
"""Ensure that an import statement precedes this case."""
def get_example(self):
example: Example = Example().save()
return example
| Regression6624 |
python | google__jax | tests/pallas/tpu_fusible_matmul_test.py | {
"start": 30776,
"end": 35513
} | class ____(jtu.JaxTestCase):
def setUp(self):
if not jtu.is_device_tpu_at_least(4):
self.skipTest('Only works with TPU v4+')
super().setUp()
def test_matmul_bf16_out(self):
if not jtu.is_device_tpu_at_least(4):
self.skipTest('TPU v4+ required')
dtype = jnp.bfloat16
k0, k1 = jax.ran... | ExcessPrecisionTest |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 37422,
"end": 41808
} | class ____:
def mysetup(self, r, method):
self.messages = queue.Queue()
self.pubsub = r.pubsub()
self.state = 0
self.cond = threading.Condition()
if method == "get_message":
self.get_message = self.loop_step_get_message
else:
self.get_message =... | TestPubSubAutoReconnect |
python | readthedocs__readthedocs.org | readthedocs/api/v3/mixins.py | {
"start": 487,
"end": 1565
} | class ____:
"""
Set the change_reason on the model changed through this API view.
The view should inherit one of:
- CreateModelMixin
- UpdateModelMixin
- DestroyModelMixin
Unlike the original methods,
these return the instance that was created/updated,
so they are easy to override... | UpdateChangeReasonMixin |
python | huggingface__transformers | tests/models/t5/test_modeling_t5.py | {
"start": 33619,
"end": 36116
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (T5EncoderModel, T5ForTokenClassification) if is_torch_available() else ()
test_resize_embeddings = False
pipeline_model_mapping = (
{
"token-classification": T5ForTokenClassification,
}
... | T5EncoderOnlyModelTest |
python | pytorch__pytorch | torch/_inductor/select_algorithm.py | {
"start": 4828,
"end": 7573
} | class ____:
"""
Some parts of a template need to be generated at the end, but
inserted into the template at the start. This allows doing a bunch
of replacements after the initial render.
"""
HookFn = Callable[[], str]
def __init__(
self, code: str, replacement_hooks: dict[str, Opt... | PartialRender |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_fastapi/datamodels/test_roles.py | {
"start": 1099,
"end": 5074
} | class ____:
def test_rolebody_accepts_actions_alias_and_maps_to_permissions(self):
data = {
"name": "viewer",
"actions": [
{"action": {"name": "can_read"}, "resource": {"name": "DAG"}},
{"action": {"name": "can_read"}, "resource": {"name": "Connection"... | TestRoleModels |
python | streamlit__streamlit | lib/tests/streamlit/elements/arrow_dataframe_test.py | {
"start": 20207,
"end": 20687
} | class ____(DeltaGeneratorTestCase):
"""Test Public Streamlit Public APIs."""
def test_table(self):
"""Test st.table."""
from streamlit.dataframe_util import convert_arrow_bytes_to_pandas_df
df = pd.DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
st.table(df)
pro... | StArrowTableAPITest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 9391,
"end": 10467
} | class ____(IssueWorklogs, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-worklogs/#api-rest-api-3-issue-issueidorkey-worklog-id-get
"""
def generate(self):
issues_stream = Issues(authenticator=self._session.auth, domain=self._domain)
for... | IssueWorklogsGenerator |
python | h5py__h5py | h5py/tests/test_objects.py | {
"start": 414,
"end": 2792
} | class ____(TestCase):
def test_invalid(self):
# Check for segfault on close
oid = o.ObjectID(0)
del oid
oid = o.ObjectID(1)
del oid
def test_equality(self):
# Identifier-based equality
oid1 = o.ObjectID(42)
oid2 = o.ObjectID(42)
oid3 = o.... | TestObjects |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0141_create_addonsconfig.py | {
"start": 645,
"end": 873
} | class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("projects", "0140_addons_options_base_version"),
]
operations = [
migrations.RunPython(forwards_func),
]
| Migration |
python | modin-project__modin | modin/core/execution/dask/implementations/pandas_on_dask/partitioning/virtual_partition.py | {
"start": 8322,
"end": 10394
} | class ____(PandasOnDaskDataframeVirtualPartition):
axis = 1
def _deploy_dask_func(
deployer,
axis,
f_to_deploy,
f_args,
f_kwargs,
*args,
extract_metadata=True,
**kwargs,
):
"""
Execute a function on an axis partition in a worker process.
This is ALWAYS called on either... | PandasOnDaskDataframeRowPartition |
python | google__jax | jax/_src/state/types.py | {
"start": 6365,
"end": 7452
} | class ____:
permutation: tuple[int, ...] = dataclasses.field(metadata=dict(static=True))
@classmethod
def from_ref_new_permutation(
cls, ref_or_view: Any, *perm: int
) -> RefTransposer:
if len(perm) == 1 and isinstance(perm[0], tuple):
perm = perm[0]
if len(perm) != ref_or_view.ndim:
... | RefTransposer |
python | PrefectHQ__prefect | src/prefect/server/orchestration/core_policy.py | {
"start": 4792,
"end": 6025
} | class ____(TaskRunOrchestrationPolicy):
"""
Orchestration rules that run against task-run-state transitions in priority order,
specifically for clients doing client-side orchestration.
"""
@staticmethod
def priority() -> list[
Union[
type[BaseUniversalTransform[orm_models.Ta... | ClientSideTaskOrchestrationPolicy |
python | kamyu104__LeetCode-Solutions | Python/design-hashset.py | {
"start": 1026,
"end": 1935
} | class ____(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.__data = [LinkedList() for _ in xrange(10000)]
def add(self, key):
"""
:type key: int
:rtype: void
"""
l = self.__data[key % len(self.__data)]
... | MyHashSet |
python | bokeh__bokeh | tests/unit/bokeh/document/test_events__document.py | {
"start": 2102,
"end": 2172
} | class ____(Model):
data = ColumnData(Any, Any, default={})
| OtherModel |
python | palantir__python-language-server | pyls/python_ls.py | {
"start": 644,
"end": 3190
} | class ____(socketserver.StreamRequestHandler, object):
"""A wrapper class that is used to construct a custom handler class."""
delegate = None
def setup(self):
super(_StreamHandlerWrapper, self).setup()
# pylint: disable=no-member
self.delegate = self.DELEGATE_CLASS(self.rfile, sel... | _StreamHandlerWrapper |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 930543,
"end": 931016
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of ReopenDiscussion"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "discussion")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | ReopenDiscussionPayload |
python | django__django | django/templatetags/static.py | {
"start": 225,
"end": 2421
} | class ____(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self, varname=None, name=None):
if name is None:
raise template.TemplateSyntaxError(
"Prefix nodes must be given a name to return."
)
self.varname... | PrefixNode |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property16.py | {
"start": 217,
"end": 337
} | class ____(Generic[T]):
@property
def prop1(self) -> T: ...
@property
def prop2(self) -> Self: ...
| Parent |
python | spack__spack | lib/spack/spack/build_environment.py | {
"start": 49276,
"end": 58411
} | class ____:
"""Class used to manage builds launched by Spack.
Each build is launched in its own child process, and the main Spack process
tracks each child with a ``BuildProcess`` object. ``BuildProcess`` is used to:
- Start and monitor an active child process.
- Clean up its processes and resource... | BuildProcess |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 40784,
"end": 42950
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
"""Test that strided slice's custom gradient produces correct gradients."""
@parameterized.parameters(set((True, context.executing_eagerly())))
@test_util.disable_xla(
"b/210077724: Auto-clustering with where op is... | StridedSliceGradTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py | {
"start": 774,
"end": 962
} | class ____(A):
pass
def func4(a: str | A):
if type(a) == B:
reveal_type(a, expected_text="B")
else:
reveal_type(a, expected_text="str | A")
T = TypeVar("T")
| B |
python | getsentry__sentry | src/sentry/auth/providers/saml2/provider.py | {
"start": 3502,
"end": 5100
} | class ____(BaseView):
@method_decorator(csrf_exempt)
def dispatch(self, request: HttpRequest, organization_slug: str) -> HttpResponseBase:
from sentry.auth.helper import AuthHelper
pipeline = AuthHelper.get_for_request(request)
# SP initiated authentication, request helper is provided
... | SAML2AcceptACSView |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/key_binding/key_processor.py | {
"start": 1935,
"end": 14744
} | class ____:
"""
Statemachine that receives :class:`KeyPress` instances and according to the
key bindings in the given :class:`KeyBindings`, calls the matching handlers.
::
p = KeyProcessor(key_bindings)
# Send keys into the processor.
p.feed(KeyPress(Keys.ControlX, '\x18'))
... | KeyProcessor |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/parentheses/opening_parentheses_comment_value.py | {
"start": 1177,
"end": 1526
} | class ____( # e 9
x): pass
f1 = [ # f 1
x]
[ # f 2
x]
f3 = { # f3
x}
{ # f 4
x}
# Non-empty parentheses: These are not allowed without a value
def f1[ # f1
T
](): pass
f2 = ( # f2
i for i in range(10)
)
f3 = [ # f3
i for i in range(10)
]
f4 = { # f4
i for i in range(10)
}
f5 = { # f5
... | E9 |
python | astropy__astropy | astropy/coordinates/baseframe.py | {
"start": 4224,
"end": 4829
} | class ____(NamedTuple):
"""
This :class:`~typing.NamedTuple` is used with the
``frame_specific_representation_info`` attribute to tell frames what
attribute names (and default units) to use for a particular representation.
``reprname`` and ``framename`` should be strings, while ``defaultunit`` can
... | RepresentationMapping |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance15.py | {
"start": 223,
"end": 837
} | class ____(Operator, Generic[OpType]):
def __init__(
self,
step: OpType,
) -> None:
if isinstance(step, BasePipeline):
reveal_type(step, expected_text="BasePipeline[Unknown]*")
else:
reveal_type(step, expected_text="Operator*")
T1 = TypeVar("T1", int, st... | BasePipeline |
python | Lightning-AI__lightning | examples/pytorch/domain_templates/reinforce_learn_Qnet.py | {
"start": 3580,
"end": 4380
} | class ____(IterableDataset):
"""Iterable Dataset containing the ExperienceBuffer which will be updated with new experiences during training.
>>> RLDataset(ReplayBuffer(5)) # doctest: +ELLIPSIS
<...reinforce_learn_Qnet.RLDataset object at ...>
"""
def __init__(self, buffer: ReplayBuffer, sample_s... | RLDataset |
python | PyCQA__pylint | doc/data/messages/a/arguments-renamed/good.py | {
"start": 147,
"end": 395
} | class ____(Fruit):
def brew(self, ingredient_name: str):
print(f"Brewing an orange with {ingredient_name}")
for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
fruit.brew(ingredient_name=ingredient_name)
| Orange |
python | python-visualization__folium | folium/map.py | {
"start": 2810,
"end": 4113
} | class ____(Evented):
"""An abstract class for everything that is a Layer on the map.
It will be used to define whether an object will be included in
LayerControls.
Parameters
----------
name : string, default None
The name of the Layer, as it will appear in LayerControls
overlay : b... | Layer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 7152,
"end": 10248
} | class ____(graphene.ObjectType):
id = graphene.NonNull(graphene.ID)
name = graphene.NonNull(graphene.String)
locationOrLoadError = graphene.Field(GrapheneRepositoryLocationOrLoadError)
loadStatus = graphene.NonNull(GrapheneRepositoryLocationLoadStatus)
displayMetadata = non_null_list(GrapheneReposit... | GrapheneWorkspaceLocationEntry |
python | apache__airflow | providers/http/src/airflow/providers/http/exceptions.py | {
"start": 871,
"end": 973
} | class ____(AirflowException):
"""Exception raised for HTTP error in Http hook."""
| HttpErrorException |
python | astropy__astropy | astropy/io/registry/tests/test_registries.py | {
"start": 25256,
"end": 38734
} | class ____(TestUnifiedIORegistryBase):
"""Test :class:`astropy.io.registry.UnifiedOutputRegistry`."""
def setup_class(self):
"""Setup class. This is called 1st by pytest."""
self._cls = UnifiedOutputRegistry
# ===========================================
def test_inherited_write_regist... | TestUnifiedOutputRegistry |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 4377,
"end": 6556
} | class ____(RequestHandler): pass
""", func, suffix='.py')
def test_get_user(self) -> None:
def func(filename: str):
am = bsa.AuthModule(filename)
assert am.get_user is not None
assert am.get_user('handler') == 10
with_file_contents("""
def get_user(handl... | LogoutHandler |
python | pytorch__pytorch | torch/distributed/checkpoint/_consolidate_hf_safetensors.py | {
"start": 1537,
"end": 27138
} | class ____:
"""
Dataclass to store information about an input safetensors file.
Attributes:
metadata_size: Size of the metadata section in bytes
metadata: Json metadata from the safetensors file
"""
metadata_size: int = 0
metadata: Any = None
def _parse_input_metadata(
in... | _InputFileData |
python | plotly__plotly.py | plotly/graph_objs/layout/xaxis/title/_font.py | {
"start": 235,
"end": 9890
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.xaxis.title"
_path_str = "layout.xaxis.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Font |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 513591,
"end": 513879
} | class ____(NumBinopNode):
# Binary operation taking integer arguments.
def c_types_okay(self, type1, type2):
#print "IntBinopNode.c_types_okay:", type1, type2 ###
return (type1.is_int or type1.is_enum) \
and (type2.is_int or type2.is_enum)
| IntBinopNode |
python | run-llama__llama_index | llama-index-core/llama_index/core/prompts/base.py | {
"start": 1478,
"end": 4583
} | class ____(BaseModel, ABC): # type: ignore[no-redef]
model_config = ConfigDict(arbitrary_types_allowed=True)
metadata: Dict[str, Any]
template_vars: List[str]
kwargs: Dict[str, str]
output_parser: Optional[BaseOutputParser]
template_var_mappings: Optional[Dict[str, Any]] = Field(
defaul... | BasePromptTemplate |
python | pydantic__pydantic | pydantic/plugin/__init__.py | {
"start": 2608,
"end": 3581
} | class ____(Protocol):
"""Base class for plugin callbacks protocols.
You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
typed `on_error` method.
"""
on_enter: Callable[..., None]
"""`on_enter` is changed to be more specific on all subclasse... | BaseValidateHandlerProtocol |
python | walkccc__LeetCode | solutions/1209. Remove All Adjacent Duplicates in String II/1209.py | {
"start": 0,
"end": 335
} | class ____:
def removeDuplicates(self, s: str, k: int) -> str:
stack = []
for c in s:
if not stack or stack[-1][0] != c:
stack.append([c, 1])
else: # stack[-1][0] == c
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
return ''.join(c * count for c, count... | Solution |
python | langchain-ai__langchain | libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py | {
"start": 682,
"end": 16438
} | class ____(LLM):
"""Hugging Face Endpoint. This works with any model that supports text generation (i.e. text completion) task.
To use this class, you should have installed the `huggingface_hub` package, and
the environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token,
or given as a name... | HuggingFaceEndpoint |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokeh_jinja.py | {
"start": 2102,
"end": 3950
} | class ____(BokehDirective):
has_content = True
required_arguments = 1
option_spec = {
"noindex": lambda x: True, # directives.flag weirdly returns None
}
def run(self):
template_path = self.arguments[0]
module_path, template_name = template_path.rsplit(".", 1)
try... | BokehJinjaDirective |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 259970,
"end": 260645
} | 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("CreatedCommitContributionEdge"), graphql_name="edges"
)
n... | CreatedCommitContributionConnection |
python | PyCQA__isort | isort/parse.py | {
"start": 4121,
"end": 25413
} | class ____(NamedTuple):
in_lines: list[str]
lines_without_imports: list[str]
import_index: int
place_imports: dict[str, list[str]]
import_placements: dict[str, str]
as_map: dict[str, dict[str, list[str]]]
imports: dict[str, dict[str, Any]]
categorized_comments: "CommentsDict"
change_... | ParsedContent |
python | doocs__leetcode | solution/1500-1599/1533.Find the Index of the Large Integer/Solution.py | {
"start": 503,
"end": 1051
} | class ____:
def getIndex(self, reader: 'ArrayReader') -> int:
left, right = 0, reader.length() - 1
while left < right:
t1, t2, t3 = (
left,
left + (right - left) // 3,
left + ((right - left) // 3) * 2 + 1,
)
cmp = re... | Solution |
python | networkx__networkx | networkx/classes/tests/test_multigraph.py | {
"start": 5848,
"end": 14303
} | class ____(BaseMultiGraphTester, _TestGraph):
def setup_method(self):
self.Graph = nx.MultiGraph
# build K3
ed1, ed2, ed3 = ({0: {}}, {0: {}}, {0: {}})
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
self.k3edges = [(0, 1), (0, 2), (1, 2)]
... | TestMultiGraph |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.