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 | run-llama__llama_index | llama-index-core/llama_index/core/llms/mock.py | {
"start": 2945,
"end": 3151
} | class ____(MockLLM):
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
yield from []
| MockLLMWithNonyieldingChatStream |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/model_summary/model_summary.py | {
"start": 1460,
"end": 4957
} | class ____:
"""Summary class for a single layer in a :class:`~lightning.pytorch.core.LightningModule`. It collects the
following information:
- Type of the layer (e.g. Linear, BatchNorm1d, ...)
- Input shape
- Output shape
- Number of parameters
The input and output shapes are only known a... | LayerSummary |
python | numba__numba | numba/tests/test_gdb_bindings.py | {
"start": 3918,
"end": 6897
} | class ____(TestCase):
"""
This test class is used to generate tests which will run the test cases
defined in TestGdbBindImpls in isolated subprocesses, this is for safety
in case something goes awry.
"""
# test mutates env
_numba_parallel_test_ = False
_DEBUG = True
def run_cmd(se... | TestGdbBinding |
python | huggingface__transformers | src/transformers/models/rwkv/modeling_rwkv.py | {
"start": 18145,
"end": 18826
} | class ____(ModelOutput):
r"""
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
avoid providing the old `input_ids`.
"""
last_hidden... | RwkvOutput |
python | spyder-ide__spyder | spyder/utils/syntaxhighlighters.py | {
"start": 72178,
"end": 73899
} | class ____(BaseWebSH):
"""HTML Syntax Highlighter"""
PROG = re.compile(make_html_patterns(), re.S)
# =============================================================================
# Markdown highlighter
# =============================================================================
def make_md_patterns():
... | HtmlSH |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 9100,
"end": 10949
} | class ____(Warning):
"""
Warning raised when reading different dtypes in a column from a file.
Raised for a dtype incompatibility. This can happen whenever `read_csv`
or `read_table` encounter non-uniform dtypes in a column(s) of a given
CSV file.
See Also
--------
read_csv : Read CSV ... | DtypeWarning |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 76725,
"end": 77763
} | class ____(object):
def __init__(self):
self.root = None ### current root of tree
self.child = None ### current child to which siblings are added
### Make sure that child is the last sibling */
def advanceChildToEnd(self):
if self.child:
while self.child... | ASTPair |
python | django__django | tests/one_to_one/models.py | {
"start": 378,
"end": 674
} | class ____(models.Model):
place = models.OneToOneField(Place, models.CASCADE, primary_key=True)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self):
return "%s the restaurant" % self.place.name
| Restaurant |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/ghostwriter/test_ghostwriter.py | {
"start": 2828,
"end": 3546
} | class ____(enum.Enum):
a = "value of AnEnum.a"
b = "value of AnEnum.b"
def takes_enum(foo=AnEnum.a):
# This can only fail if we use the default argument to guess
# that any instance of that enum type should be allowed.
assert foo != AnEnum.b
def test_ghostwriter_exploits_arguments_with_enum_defa... | AnEnum |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_sql.py | {
"start": 79975,
"end": 82880
} | class ____:
@pytest.mark.asyncio
@mock.patch(HOOK_STR.format("CloudSQLAsyncHook._get_conn"))
async def test_async_get_operation_name_should_execute_successfully(self, mocked_conn, hook_async):
await hook_async.get_operation_name(
operation_name=OPERATION_NAME,
project_id=PROJ... | TestCloudSQLAsyncHook |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams1.py | {
"start": 101,
"end": 158
} | class ____[T1]: ...
def func1[T1](): ...
T2: str
| ClassA |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-opea/llama_index/llms/opea/base.py | {
"start": 176,
"end": 730
} | class ____(OpenAILike):
"""
Adapter for a OPEA LLM.
Examples:
`pip install llama-index-llms-opea`
```python
from llama_index.llms.opea import OPEA
llm = OPEA(
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
api_base="http://localhost:8080/v1",
... | OPEA |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 8135,
"end": 8783
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | FNetIntermediate |
python | doocs__leetcode | solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.py | {
"start": 0,
"end": 237
} | class ____:
def countKDifference(self, nums: List[int], k: int) -> int:
ans = 0
cnt = Counter()
for num in nums:
ans += cnt[num - k] + cnt[num + k]
cnt[num] += 1
return ans
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 140226,
"end": 140811
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("user_id", "limit", "expiry", "client_mutation_id")
user_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="userId")
limit = sgqlc.types.Field(
sgqlc.type... | SetUserInteractionLimitInput |
python | huggingface__transformers | tests/models/git/test_processing_git.py | {
"start": 876,
"end": 1269
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = GitProcessor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
return tokenizer_class.from_pretrained(
"hf-internal-testing/tiny-random-BertModel",... | GitProcessorTest |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_artifact_lookup.py | {
"start": 2254,
"end": 26737
} | class ____(APITestCase):
def assert_download_matches_file(self, url: str, file_contents: bytes) -> None:
response = self.client.get(url)
file = BytesIO(file_contents)
for chunk in response:
assert file.read(len(chunk)) == chunk
def create_archive(self, fields, files, dist=No... | ArtifactLookupTest |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 18024,
"end": 20125
} | class ____:
"""Test en_BD address provider methods"""
def test_administrative_unit(self, faker, num_samples):
for _ in range(num_samples):
administrative_unit = faker.administrative_unit()
assert isinstance(administrative_unit, str)
assert administrative_unit in EnBd... | TestEnBd |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py | {
"start": 2214,
"end": 2955
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
HunYuanDenseV1RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
... | HunYuanDenseV1RMSNorm |
python | walkccc__LeetCode | solutions/256. Paint House/256.py | {
"start": 0,
"end": 319
} | class ____:
def minCost(self, costs: list[list[int]]) -> list[list[int]]:
for i in range(1, len(costs)):
costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
return min(costs[-1])
| Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_planner.py | {
"start": 26129,
"end": 27934
} | class ____(TestCase):
@with_temp_dir
def test_strict(self):
original_module = nn.Linear(2, 2)
dcp.save(state_dict={"module": original_module}, checkpoint_id=self.temp_dir)
new_module = nn.Linear(2, 2)
new_module.extra_param = nn.Parameter(torch.randn(2, 2))
dcp.load(
... | TestLoadPlanner |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 1144,
"end": 1192
} | class ____:
# comment
"""Docstring"""
| Test |
python | ansible__ansible | test/lib/ansible_test/_internal/completion.py | {
"start": 4472,
"end": 4966
} | class ____(PythonCompletionConfig):
"""Configuration for a POSIX host reachable over SSH."""
def __init__(self, user: str, host: str) -> None:
super().__init__(
name=f'{user}@{host}',
python=','.join(SUPPORTED_PYTHON_VERSIONS),
)
@property
def is_default(self) -... | PosixSshCompletionConfig |
python | huggingface__transformers | src/transformers/models/vit/modeling_vit.py | {
"start": 10575,
"end": 11212
} | class ____(nn.Module):
"""
The residual connection is defined in ViTLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config: ViTConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, conf... | ViTSelfOutput |
python | joblib__joblib | benchmarks/bench_compression.py | {
"start": 2359,
"end": 8935
} | class ____:
"""Protect the underlying fileobj against numerous calls to write
This is achieved by internally keeping a list of small chunks and
only flushing to the backing fileobj if passed a large chunk or
after a threshold on the number of small chunks.
"""
def __init__(self, fileobj, max_bu... | PickleBufferedReader |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/fastapi/FAST003.py | {
"start": 4390,
"end": 4440
} | class ____(BaseModel):
my_id: int
| PydanticParams |
python | lxml__lxml | src/lxml/html/soupparser.py | {
"start": 3094,
"end": 10197
} | class ____:
# Minimal imitation of BeautifulSoup.Tag
def __init__(self, contents):
self.name = 'html'
self.attrs = []
self.contents = contents
def __iter__(self):
return self.contents.__iter__()
def _convert_tree(beautiful_soup_tree, makeelement):
if makeelement is Non... | _PseudoTag |
python | getsentry__sentry | src/sentry/sentry_apps/utils/webhooks.py | {
"start": 52,
"end": 99
} | class ____(StrEnum):
pass
| SentryAppActionType |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_set_column09.py | {
"start": 315,
"end": 1011
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/pop2piano/modeling_pop2piano.py | {
"start": 17100,
"end": 18506
} | class ____(nn.Module):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.SelfAttention = Pop2PianoAttention(
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
)
self.l... | Pop2PianoLayerSelfAttention |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 63178,
"end": 66196
} | class ____:
# survival function reference values were computed with mpmath
# from mpmath import mp
# mp.dps = 50
# def sf_mpmath(x):
# x = mp.mpf(x)
# return float(mp.mpf(2.)/(mp.exp(x) + mp.one))
@pytest.mark.parametrize('x, ref', [(100, 7.440151952041672e-44),
... | TestHalfLogistic |
python | google__pytype | pytype/rewrite/operators_test.py | {
"start": 176,
"end": 503
} | class ____(test_utils.ContextfulTestBase):
def test_call_binary(self):
a = self.ctx.consts[1].to_variable()
b = self.ctx.consts[2].to_variable()
ret = operators.call_binary(self.ctx, '__add__', a, b)
self.assertIsInstance(ret, variables.Variable)
if __name__ == '__main__':
unittest.main()
| BinaryOperatorTest |
python | walkccc__LeetCode | solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py | {
"start": 0,
"end": 221
} | class ____:
def areSimilar(self, mat: list[list[int]], k: int) -> bool:
n = len(mat[0])
for row in mat:
for j in range(n):
if row[j] != row[(j + k) % n]:
return False
return True
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 267194,
"end": 268831
} | class ____(sgqlc.types.Input):
"""Require all commits be made to a non-target branch and submitted
via a pull request before they can be merged.
"""
__schema__ = github_schema
__field_names__ = (
"dismiss_stale_reviews_on_push",
"require_code_owner_review",
"require_last_pus... | PullRequestParametersInput |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 5417,
"end": 6239
} | class ____(np.ma.core.MaskedConstant):
"""A trivial extension of numpy.ma.masked.
We want to be able to put the generic term ``masked`` into a dictionary.
The constant ``numpy.ma.masked`` is not hashable (see
https://github.com/numpy/numpy/issues/4660), so we need to extend it
here with a hash valu... | MaskedConstant |
python | keras-team__keras | keras/src/backend/tensorflow/trainer.py | {
"start": 705,
"end": 27517
} | class ____(base_trainer.Trainer):
def __init__(self):
super().__init__()
self.train_function = None
self.test_function = None
self.predict_function = None
# Specifies how many steps of the step_per_execution loop to unroll.
# Increasing this value can reduce kernel l... | TensorFlowTrainer |
python | apache__airflow | providers/tableau/src/airflow/providers/tableau/hooks/tableau.py | {
"start": 1968,
"end": 7623
} | class ____(BaseHook):
"""
Connects to the Tableau Server Instance and allows to communicate with it.
Can be used as a context manager: automatically authenticates the connection
when opened and signs out when closed.
.. seealso:: https://tableau.github.io/server-client-python/docs/
:param sit... | TableauHook |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 59317,
"end": 60336
} | class ____(SpeechT5PreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when used in combination with
[`SpeechT5Model`].
"""
def __init__(self, config: SpeechT5Config):
super().__init__(config)
self.wrapped_encoder = SpeechT5Encoder(con... | SpeechT5EncoderWithoutPrenet |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/string.py | {
"start": 12241,
"end": 13279
} | class ____(DTypeConfig_V2[Literal["|O"], Literal["vlen-utf8"]]):
"""
A wrapper around the JSON representation of the ``VariableLengthUTF8`` data type in Zarr V2.
The ``name`` field of this class contains the value that would appear under the
``dtype`` field in Zarr V2 array metadata. The ``object_codec... | VariableLengthUTF8JSON_V2 |
python | Farama-Foundation__Gymnasium | tests/test_core.py | {
"start": 7391,
"end": 8883
} | class ____:
@staticmethod
def test_nonempty_seed_retrieved_when_not_set(example_env):
assert example_env.np_random_seed is not None
assert isinstance(example_env.np_random_seed, int)
@staticmethod
def test_seed_set_at_reset_and_retrieved(example_env):
seed = 42
example_e... | TestRandomSeeding |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/wrap_unwrap_test.py | {
"start": 1131,
"end": 3157
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
# TODO(b/182414964): After making options persistent across tf.function is
# enabled, the ModelDatasetOp and MaxIntraParallelismOp are no longer present
# in Python. As a result, the Fin... | WrapUnwrapTest |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-jina/llama_index/tools/jina/base.py | {
"start": 226,
"end": 1678
} | class ____(BaseToolSpec):
"""
Jina tool spec.
"""
spec_functions = ["jina_search"]
def _make_request(self, params: Dict) -> requests.Response:
"""
Make a request to the Jina Search API.
Args:
params (dict): The parameters to be passed to the API.
Retur... | JinaToolSpec |
python | rapidsai__cudf | python/cudf/cudf/pandas/fast_slow_proxy.py | {
"start": 33643,
"end": 33754
} | class ____(FallbackError):
"""Raises when cuDF produces an AttributeError"""
pass
| AttributeFallbackError |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/pooling.py | {
"start": 12473,
"end": 15652
} | class ____(keras_layers.AveragePooling3D, base.Layer):
"""Average pooling layer for 3D inputs (e.g. volumes).
Args:
pool_size: An integer or tuple/list of 3 integers:
(pool_depth, pool_height, pool_width)
specifying the size of the pooling window.
Can be a single integer to specify the same v... | AveragePooling3D |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 29146,
"end": 29723
} | class ____(forms.Form):
code = forms.CharField(
label=_("Code"),
widget=forms.TextInput(
attrs={"placeholder": _("Code"), "autocomplete": "one-time-code"},
),
)
def __init__(self, *args, **kwargs):
self.code = kwargs.pop("code", None)
super().__init__(*ar... | BaseConfirmCodeForm |
python | django__django | tests/migrations/test_executor.py | {
"start": 35183,
"end": 39380
} | class ____(SimpleTestCase):
"""(More) isolated unit tests for executor methods."""
def test_minimize_rollbacks(self):
"""
Minimize unnecessary rollbacks in connected apps.
When you say "./manage.py migrate appA 0001", rather than migrating to
just after appA-0001 in the lineari... | ExecutorUnitTests |
python | getsentry__sentry | src/sentry/search/events/builder/base.py | {
"start": 2314,
"end": 70048
} | class ____:
requires_organization_condition: bool = False
organization_column: str = "organization.id"
function_alias_prefix: str | None = None
spans_metrics_builder = False
entity: Entity | None = None
config_class: type[DatasetConfig] | None = None
duration_fields: set[str] = set()
siz... | BaseQueryBuilder |
python | google__flatbuffers | python/flatbuffers/flexbuffers.py | {
"start": 1097,
"end": 4770
} | class ____(enum.IntEnum):
"""Supported bit widths of value types.
These are used in the lower 2 bits of a type field to determine the size of
the elements (and or size field) of the item pointed to (e.g. vector).
"""
W8 = 0 # 2^0 = 1 byte
W16 = 1 # 2^1 = 2 bytes
W32 = 2 # 2^2 = 4 bytes
W64 = 3 # 2... | BitWidth |
python | numpy__numpy | numpy/matrixlib/defmatrix.py | {
"start": 1626,
"end": 30875
} | class ____(N.ndarray):
"""
matrix(data, dtype=None, copy=True)
Returns a matrix from an array-like object, or from a string of data.
A matrix is a specialized 2-D array that retains its 2-D nature
through operations. It has certain special operators, such as ``*``
(matrix multiplication) and ... | matrix |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_config.py | {
"start": 378,
"end": 1178
} | class ____:
def __init__(self):
self._handlers = set()
def __iadd__(self, handler):
if not callable(handler):
raise ValueError('handler must be callable')
self._handlers.add(handler)
return self
def __isub__(self, handler):
try:
self._handler... | _EventSource |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/output/win32.py | {
"start": 17362,
"end": 17597
} | class ____:
BLACK = 0x0000
BLUE = 0x0001
GREEN = 0x0002
CYAN = 0x0003
RED = 0x0004
MAGENTA = 0x0005
YELLOW = 0x0006
GRAY = 0x0007
INTENSITY = 0x0008 # Foreground color is intensified.
| FOREGROUND_COLOR |
python | django__django | tests/model_indexes/tests.py | {
"start": 11649,
"end": 14735
} | class ____(TestCase):
@skipUnlessDBFeature("supports_tablespaces")
def test_db_tablespace(self):
editor = connection.schema_editor()
# Index with db_tablespace attribute.
for fields in [
# Field with db_tablespace specified on model.
["shortcut"],
# Fi... | IndexesTests |
python | scrapy__scrapy | scrapy/resolver.py | {
"start": 764,
"end": 2380
} | class ____(ThreadedResolver):
"""
Default caching resolver. IPv4 only, supports setting a timeout value for DNS requests.
"""
def __init__(self, reactor: ReactorBase, cache_size: int, timeout: float):
super().__init__(reactor)
dnscache.limit = cache_size
self.timeout = timeout
... | CachingThreadedResolver |
python | astropy__astropy | astropy/samp/tests/test_standard_profile.py | {
"start": 468,
"end": 8894
} | class ____:
@property
def hub_init_kwargs(self):
return {}
@property
def client_init_kwargs(self):
return {}
@property
def client_connect_kwargs(self):
return {}
@pytest.fixture(autouse=True)
def setup_method(self, tmp_path):
self.tmpdir = str(tmp_path)... | TestStandardProfile |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py | {
"start": 92752,
"end": 93066
} | class ____(Qwen2VLRotaryEmbedding):
def __init__(self, config: Qwen2_5OmniThinkerConfig, device=None):
super().__init__(config, device)
# It's same as `Qwen2_5_VLAttention`, but talker model's hidden_size isn't divisible by num_heads.
# Removes the value error as a workaround.
| Qwen2_5OmniRotaryEmbedding |
python | google__jax | jax/_src/interpreters/batching.py | {
"start": 4560,
"end": 15182
} | class ____:
stacked_axis: int
# For each axis, we store its index and the corresponding segment lengths.
# For example, the jumble i:(Fin 3) => f32[lens1.i, 7, lens2.i]
# would be represented with ragged_axes = [(1, lens1), (3, lens2)]
ragged_axes: tuple[tuple[int, Any], ...]
@property
def size(self):
... | RaggedAxis |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-valid-strings-to-form-target-i.py | {
"start": 1139,
"end": 1362
} | class ____(object):
def __init__(self):
self.children = collections.defaultdict(AhoNode)
# self.indices = []
self.suffix = None
# self.output = None
self.length = 0 # added
| AhoNode |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 5821,
"end": 6671
} | class ____(PandasPendingDeprecationWarning):
"""
Warning raised for an upcoming change that will be enforced in pandas 5.0.
See Also
--------
errors.PandasChangeWarning: Class for deprecations that will raise any warning.
errors.PandasPendingDeprecationWarning : Class for deprecations that will... | Pandas5Warning |
python | sqlalchemy__sqlalchemy | test/orm/test_rel_fn.py | {
"start": 987,
"end": 25440
} | class ____:
@classmethod
def setup_test_class(cls):
m = MetaData()
cls.left = Table(
"lft",
m,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
cls.right = Table(
"rgt",... | _JoinFixtures |
python | pezy__LeetCode | 001. Add Two Numbers/solution.py | {
"start": 49,
"end": 140
} | class ____:
def __init__(self, x):
self.val = x
self.next = None
| ListNode |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_sheet_views6.py | {
"start": 301,
"end": 3142
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_sheet_views() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_sheet_views1(self):
"""Test the _write_sheet_views() met... | TestWriteSheetViews |
python | jazzband__django-waffle | waffle/admin.py | {
"start": 4190,
"end": 4416
} | class ____(BaseAdmin):
actions = [enable_switches, disable_switches, delete_individually]
list_display = ('name', 'active', 'note', 'created', 'modified')
list_filter = ('active',)
ordering = ('-id',)
| SwitchAdmin |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/add_breadcrumb_to_state.py | {
"start": 1400,
"end": 1775
} | class ____:
def __init__(self):
pass
# Annotated with `@AddBreadcrumbToState(Via[add_breadcrumb_to_state])`
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return
def test_add_breadcrumb_context_manager():
x = _test_source()
with B... | BreadcrumbOnEnter |
python | scrapy__scrapy | scrapy/spiderloader.py | {
"start": 4579,
"end": 5037
} | class ____:
"""A dummy spider loader that does not load any spiders."""
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
return cls()
def load(self, spider_name: str) -> type[Spider]:
raise KeyError("DummySpiderLoader doesn't load any spiders")
def list(self) -... | DummySpiderLoader |
python | plotly__plotly.py | plotly/graph_objs/scatter/selected/_textfont.py | {
"start": 233,
"end": 2420
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.selected"
_path_str = "scatter.selected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and may be specified as:
... | Textfont |
python | doocs__leetcode | solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py | {
"start": 0,
"end": 321
} | class ____:
def minimumDeletions(self, s: str) -> int:
n = len(s)
f = [0] * (n + 1)
b = 0
for i, c in enumerate(s, 1):
if c == 'b':
f[i] = f[i - 1]
b += 1
else:
f[i] = min(f[i - 1] + 1, b)
return f[n]
| Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/client/utils.py | {
"start": 214,
"end": 561
} | class ____(Enum):
"""This enum describes the status of a GraphQL mutation to reload a Dagster repository location.
Args:
Enum (str): can be either `ReloadRepositoryLocationStatus.SUCCESS`
or `ReloadRepositoryLocationStatus.FAILURE`.
"""
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
... | ReloadRepositoryLocationStatus |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_datastore.py | {
"start": 1137,
"end": 16478
} | class ____:
def setup_method(self):
with patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_init
):
self.datastore_hook = DatastoreHook()
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook._authorize")
@patc... | TestDatastoreHook |
python | pennersr__django-allauth | allauth/headless/base/response.py | {
"start": 705,
"end": 4267
} | class ____(APIResponse):
def __init__(self, request, user=None, status=None):
data = {}
if user and user.is_authenticated:
adapter = get_adapter()
data["user"] = adapter.serialize_user(user)
data["methods"] = get_authentication_records(request)
status ... | BaseAuthenticationResponse |
python | python__mypy | mypy/stubdoc.py | {
"start": 977,
"end": 2088
} | class ____:
"""Signature info for a single argument."""
def __init__(
self,
name: str,
type: str | None = None,
*,
default: bool = False,
default_value: str = "...",
) -> None:
self.name = name
self.type = type
# Does this argument hav... | ArgSig |
python | RaRe-Technologies__gensim | docs/src/auto_examples/core/run_corpora_and_vector_spaces.py | {
"start": 6097,
"end": 14275
} | class ____:
def __iter__(self):
for line in open('https://radimrehurek.com/mycorpus.txt'):
# assume there's one document per line, tokens separated by whitespace
yield dictionary.doc2bow(line.lower().split())
##########################################################################... | MyCorpus |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/trace_type_builder.py | {
"start": 1134,
"end": 2198
} | class ____(trace.TracingContext):
"""Container for variables and flags shared across TraceType generation."""
def __init__(self, is_legacy_signature: bool = False):
self._global_to_local_id = {}
self._alias_id_to_placeholder = {}
self._is_legacy_signature = is_legacy_signature
def alias_global_id(se... | InternalTracingContext |
python | has2k1__plotnine | plotnine/positions/position_nudge.py | {
"start": 169,
"end": 949
} | class ____(position):
"""
Nudge points
Useful to nudge labels away from the points
being labels.
Parameters
----------
x :
Horizontal nudge
y :
Vertical nudge
"""
def __init__(self, x: float = 0, y: float = 0):
self.params = {"x": x, "y": y}
@class... | position_nudge |
python | pypa__pip | src/pip/_vendor/rich/styled.py | {
"start": 225,
"end": 1258
} | class ____:
"""Apply a style to a renderable.
Args:
renderable (RenderableType): Any renderable.
style (StyleType): A style to apply across the entire renderable.
"""
def __init__(self, renderable: "RenderableType", style: "StyleType") -> None:
self.renderable = renderable
... | Styled |
python | PrefectHQ__prefect | src/prefect/filesystems.py | {
"start": 858,
"end": 1157
} | class ____(Block, abc.ABC):
_block_schema_capabilities = ["read-path", "write-path"]
@abc.abstractmethod
async def read_path(self, path: str) -> bytes:
pass
@abc.abstractmethod
async def write_path(self, path: str, content: bytes) -> None:
pass
| WritableFileSystem |
python | pallets__werkzeug | examples/plnt/database.py | {
"start": 1623,
"end": 1872
} | class ____:
query = session.query_property()
def __repr__(self):
return f"<{type(self).__name__} {self.guid!r}>"
mapper(Entry, entry_table)
mapper(Blog, blog_table, properties=dict(entries=dynamic_loader(Entry, backref="blog")))
| Entry |
python | weaviate__weaviate-python-client | weaviate/collections/classes/filters.py | {
"start": 4709,
"end": 5273
} | class ____:
_target: Optional[_TargetRefs] = None
_property: Union[str, _CountRef]
def _target_path(self) -> _FilterTargets:
if self._target is None:
return self._property
# get last element in chain
target = self._target
while target.target is not None:
... | _FilterBase |
python | pandas-dev__pandas | pandas/core/groupby/ops.py | {
"start": 39500,
"end": 40491
} | class ____(Generic[NDFrameT]):
def __init__(
self,
data: NDFrameT,
ngroups: int,
*,
sort_idx: npt.NDArray[np.intp],
sorted_ids: npt.NDArray[np.intp],
) -> None:
self.data = data
self.ngroups = ngroups
self._slabels = sorted_ids
sel... | DataSplitter |
python | great-expectations__great_expectations | tests/integration/metrics/query/test_row_count.py | {
"start": 990,
"end": 2087
} | class ____:
@parameterize_batch_for_data_sources(
data_source_configs=SPARK_DATA_SOURCES,
data=DATA_FRAME,
)
def test_success_spark(self, batch_for_datasource) -> None:
batch = batch_for_datasource
metric = QueryRowCount(query="SELECT * FROM {batch} WHERE id > 0")
met... | TestQueryRowCount |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 46467,
"end": 49902
} | class ____(GoogleCloudBaseOperator):
"""
Will update current set of Parameters to the set of specified nodes of the Memcached Instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudMemorystoreMemcachedApplyParametersOpera... | CloudMemorystoreMemcachedApplyParametersOperator |
python | python__mypy | mypyc/test-data/fixtures/ir.py | {
"start": 14000,
"end": 14048
} | class ____(Exception):
value: Any
| StopIteration |
python | redis__redis-py | redis/cluster.py | {
"start": 78953,
"end": 88599
} | class ____(PubSub):
"""
Wrapper for PubSub class.
IMPORTANT: before using ClusterPubSub, read about the known limitations
with pubsub in Cluster mode and learn how to workaround them:
https://redis-py-cluster.readthedocs.io/en/stable/pubsub.html
"""
def __init__(
self,
redi... | ClusterPubSub |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 67537,
"end": 67940
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
# Copied from transforme... | BigBirdOnlyNSPHead |
python | pypa__setuptools | setuptools/_vendor/typeguard/_importhook.py | {
"start": 3061,
"end": 4575
} | class ____(MetaPathFinder):
"""
Wraps another path finder and instruments the module with
:func:`@typechecked <typeguard.typechecked>` if :meth:`should_instrument` returns
``True``.
Should not be used directly, but rather via :func:`~.install_import_hook`.
.. versionadded:: 2.6
"""
de... | TypeguardFinder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/unit_tests/integration/test_bulk_stream.py | {
"start": 9363,
"end": 30729
} | class ____(TestCase):
def setUp(self) -> None:
self._http_mocker = HttpMocker()
self._http_mocker.__enter__()
set_up_shop(self._http_mocker, _SHOP_NAME)
grant_all_scopes(self._http_mocker, _SHOP_NAME)
def tearDown(self) -> None:
self._http_mocker.__exit__(None, None, No... | GraphQlBulkStreamIncrementalTest |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ViewBox/ViewBox.py | {
"start": 2230,
"end": 75813
} | class ____(GraphicsWidget):
"""
**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
Box that allows internal scaling/panning of children by mouse drag.
This class is usually created automatically as part of a :class:`PlotItem <pyqtgraph.PlotItem>` or with :func:`GraphicsLayout.addViewBox() <p... | ViewBox |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/hooks.py | {
"start": 8323,
"end": 11438
} | class ____(session_run_hook.SessionRunHook):
"""A hook that streams debugger-related events to any grpc_debug_server.
For example, the debugger data server is a grpc_debug_server. The debugger
data server writes debugger-related events it receives via GRPC to logdir.
This enables debugging features in Tensorbo... | GrpcDebugHook |
python | django__django | tests/admin_views/models.py | {
"start": 30050,
"end": 30250
} | class ____(models.Model):
m2m = models.ManyToManyField(CamelCaseModel, related_name="m2m")
fk = models.ForeignKey(CamelCaseModel, on_delete=models.CASCADE, related_name="fk")
| CamelCaseRelatedModel |
python | numba__numba | numba/np/polynomial/polynomial_core.py | {
"start": 490,
"end": 9003
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('coef', fe_type.coef),
('domain', fe_type.domain),
('window', fe_type.window)
# Introduced in NumPy 1.24, maybe leave it out for now
# ('symbol', types.string)
]... | PolynomialModel |
python | redis__redis-py | redis/commands/bf/info.py | {
"start": 34,
"end": 716
} | class ____:
capacity = None
size = None
filterNum = None
insertedNum = None
expansionRate = None
def __init__(self, args):
response = dict(zip(map(nativestr, args[::2]), args[1::2]))
self.capacity = response["Capacity"]
self.size = response["Size"]
self.filterNum... | BFInfo |
python | psf__black | src/black/handle_ipynb_magics.py | {
"start": 10944,
"end": 11952
} | class ____(ast.NodeVisitor):
r"""Find cell magics.
Note that the source of the abstract syntax tree
will already have been processed by IPython's
TransformerManager().transform_cell.
For example,
%%time\n
foo()
would have been transformed to
get_ipython().run_cell_ma... | CellMagicFinder |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 185642,
"end": 187608
} | class ____(TestCase):
def test_basic(self):
for iterable, expected in [
([], []),
([1, 2, 3], []),
([1, 1], [1]),
([1, 2, 1, 2], [1, 2]),
([1, 2, 3, '1'], []),
]:
with self.subTest(args=(iterable,)):
self.assertE... | DuplicatesEverSeenTests |
python | dagster-io__dagster | .buildkite/buildkite-shared/buildkite_shared/python_packages.py | {
"start": 940,
"end": 3618
} | class ____:
def __init__(self, setup_path: Path):
self.directory = setup_path
if (setup_path / "setup.py").exists():
# run_setup stores state in a global variable. Reload the module
# each time we use it - otherwise we'll get the previous invocation's
# distribut... | PythonPackage |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 118854,
"end": 128910
} | class ____(MMGroundingDinoPreTrainedModel):
_tied_weights_keys = {
r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
r"class_embed.(?![0])\d+": r"^class_embed.0",
"model.decoder.bbox_embed": "bbox_embed",
"model.decoder.class_embed": "class_embed",
}
def __init__(self, config: MMGr... | MMGroundingDinoForObjectDetection |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/scheduler.py | {
"start": 380,
"end": 548
} | class ____(BaseModel, extra="forbid"):
daemonScheduler: Optional[DaemonSchedulerConfig] = None
customScheduler: Optional[ConfigurableClass] = None
| SchedulerConfig |
python | pytest-dev__pluggy | docs/examples/toy-example.py | {
"start": 110,
"end": 278
} | class ____:
"""A hook specification namespace."""
@hookspec
def myhook(self, arg1, arg2):
"""My special little hook that you can customize."""
| MySpec |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/relu_op_test.py | {
"start": 9986,
"end": 14568
} | class ____(test.TestCase):
def _npLeakyRelu(self, np_features, alpha=0.1):
return np.maximum(np_features, alpha * np_features)
def testNpLeakyRelu(self):
self.assertAllClose(
np.array([[-0.09, 0.7, -0.05, 0.3, -0.01],
[0.1, -0.03, 0.5, -0.07, 0.9]]),
self._npLeakyRelu(
... | LeakyReluTest |
python | pytorch__pytorch | torch/distributed/checkpoint/utils.py | {
"start": 13202,
"end": 16563
} | class ____(io.IOBase):
def __init__(self, base_stream: io.IOBase, offset: int, len: int):
super().__init__()
self.offset = offset
self.len = len
self.base_stream = base_stream
self.seek(0)
def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
if whenc... | _ReaderView |
python | django__django | tests/check_framework/test_templates.py | {
"start": 336,
"end": 530
} | class ____(BaseEngine):
def __init__(self, params):
params.pop("OPTIONS")
super().__init__(params)
def check(self, **kwargs):
return [Error("Example")]
| ErrorEngine |
python | pyparsing__pyparsing | examples/shapes.py | {
"start": 474,
"end": 547
} | class ____(Shape):
def area(self):
return self.side ** 2
| Square |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.