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 | cherrypy__cherrypy | cherrypy/process/win32.py | {
"start": 196,
"end": 2464
} | class ____(plugins.SimplePlugin):
"""A WSPBus plugin for handling Win32 console events (like Ctrl-C)."""
def __init__(self, bus):
"""Initialize the console control handler."""
self.is_set = False
plugins.SimplePlugin.__init__(self, bus)
def start(self):
"""Register handling... | ConsoleCtrlHandler |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py | {
"start": 1746,
"end": 2556
} | class ____(Component):
"""A simple asset that runs a Python script with the Pipes subprocess client.
Because it is a pipes asset, no value is returned.
"""
@classmethod
def get_model_cls(cls):
return SimplePipesScriptComponentModel
def __init__(self, asset_key: AssetKey, script_path: ... | SimplePipesScriptComponent |
python | great-expectations__great_expectations | tests/data_context/test_data_context_state_management.py | {
"start": 2367,
"end": 6516
} | class ____(EphemeralDataContext):
"""
Simply wraps around EphemeralDataContext but keeps tabs on specific method calls around state management.
""" # noqa: E501 # FIXME CoP
def __init__(
self,
project_config: DataContextConfig,
) -> None:
# expectation store is required for... | EphemeralDataContextSpy |
python | scipy__scipy | scipy/sparse/_lil.py | {
"start": 18801,
"end": 20889
} | class ____(spmatrix, _lil_base):
"""
Row-based LIst of Lists sparse matrix.
This is a structure for constructing sparse matrices incrementally.
Note that inserting a single item can take linear time in the worst case;
to construct the matrix efficiently, make sure the items are pre-sorted by
in... | lil_matrix |
python | skorch-dev__skorch | examples/benchmarks/history.py | {
"start": 706,
"end": 3621
} | class ____(Callback):
def on_batch_end(self, net, **kwargs):
side_effects.append((
torch.cuda.memory_allocated() / 1e6,
torch.cuda.memory_cached() / 1e6
))
def train():
X, y = make_classification(1000, 20, n_informative=10, random_state=0)
X = X.astype(np.float32)
... | PrintMemory |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock_agent.py | {
"start": 1558,
"end": 3019
} | class ____(TestBedrockAgentCustomWaitersBase):
WAITER_NAME = "knowledge_base_active"
WAITER_ARGS = {"knowledgeBaseId": "kb_id"}
SENSOR = BedrockKnowledgeBaseActiveSensor
@pytest.fixture
def mock_getter(self):
with mock.patch.object(self.client, "get_knowledge_base") as getter:
y... | TestKnowledgeBaseActiveWaiter |
python | ray-project__ray | python/ray/data/datasource/datasink.py | {
"start": 471,
"end": 1209
} | class ____(Generic[WriteReturnType]):
"""Aggregated result of the Datasink write operations."""
# Total number of written rows.
num_rows: int
# Total size in bytes of written data.
size_bytes: int
# All returned values of `Datasink.write`.
write_returns: List[WriteReturnType]
@classmet... | WriteResult |
python | cherrypy__cherrypy | cherrypy/test/test_wsgiapps.py | {
"start": 99,
"end": 4084
} | class ____(helper.CPWebCase):
@staticmethod
def setup_server():
def test_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
output = [
'Hello, world!\... | WSGIGraftTests |
python | pypa__hatch | tests/conftest.py | {
"start": 1023,
"end": 1129
} | class ____(NamedTuple):
repo: str
index_name: str
user: str
auth: str
ca_cert: str
| Devpi |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_engine/types.py | {
"start": 15961,
"end": 17409
} | class ____(str, Enum):
"""Chat Engine Modes."""
SIMPLE = "simple"
"""Corresponds to `SimpleChatEngine`.
Chat with LLM, without making use of a knowledge base.
"""
CONDENSE_QUESTION = "condense_question"
"""Corresponds to `CondenseQuestionChatEngine`.
First generate a standalone quest... | ChatMode |
python | ray-project__ray | python/ray/train/predictor.py | {
"start": 930,
"end": 9689
} | class ____(abc.ABC):
"""Predictors load models from checkpoints to perform inference.
.. note::
The base ``Predictor`` class cannot be instantiated directly. Only one of
its subclasses can be used.
**How does a Predictor work?**
Predictors expose a ``predict`` method that accepts an i... | Predictor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-analytics-data-api/components.py | {
"start": 476,
"end": 1975
} | class ____(RecordExtractor):
"""
Extractor that merges the output of multiple sub-extractors into a single record.
This extractor takes a list of `RecordExtractor` instances (`extractors`), each of which
independently extracts records from the response. For each response, the extractor:
1. Invokes e... | CombinedExtractor |
python | crytic__slither | slither/core/slither_core.py | {
"start": 1201,
"end": 25841
} | class ____(Context):
"""
Slither static analyzer
"""
def __init__(self) -> None:
super().__init__()
self._filename: Optional[str] = None
self._raw_source_code: Dict[str, str] = {}
self._source_code_to_line: Optional[Dict[str, List[str]]] = None
self._previous_r... | SlitherCore |
python | openai__openai-python | src/openai/lib/azure.py | {
"start": 1628,
"end": 3104
} | class ____(BaseClient[_HttpxClientT, _DefaultStreamT]):
_azure_endpoint: httpx.URL | None
_azure_deployment: str | None
@override
def _build_request(
self,
options: FinalRequestOptions,
*,
retries_taken: int = 0,
) -> httpx.Request:
if options.url in _deploym... | BaseAzureClient |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 46050,
"end": 50790
} | class ____(RobertaPreLayerNormPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.roberta_prelayernorm = RobertaPreLayerNormModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initi... | RobertaPreLayerNormForMultipleChoice |
python | huggingface__transformers | src/transformers/models/audioflamingo3/modeling_audioflamingo3.py | {
"start": 2921,
"end": 8669
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
layer_idx: O... | AudioFlamingo3Attention |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 3527,
"end": 4021
} | class ____(LeafResource):
def render_GET(self, request):
n = getarg(request, b"n", 1, type_=float)
b = getarg(request, b"b", 1, type_=int)
if b:
# send headers now and delay body
request.write("")
self.deferRequest(request, n, self._delayedRender, request, n)
... | Delay |
python | pandas-dev__pandas | pandas/tests/series/test_constructors.py | {
"start": 957,
"end": 82044
} | class ____:
def test_from_ints_with_non_nano_dt64_dtype(self, index_or_series):
values = np.arange(10)
res = index_or_series(values, dtype="M8[s]")
expected = index_or_series(values.astype("M8[s]"))
tm.assert_equal(res, expected)
res = index_or_series(list(values), dtype="M... | TestSeriesConstructors |
python | huggingface__transformers | tests/models/bert_japanese/test_tokenization_bert_japanese.py | {
"start": 1197,
"end": 14323
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "cl-tohoku/bert-base-japanese"
tokenizer_class = BertJapaneseTokenizer
test_rust_tokenizer = False
space_between_special_tokens = True
@classmethod
def setUpClass(cls):
super().setUpClass()
# Create a sep... | BertJapaneseTokenizationTest |
python | walkccc__LeetCode | solutions/72. Edit Distance/72.py | {
"start": 0,
"end": 604
} | class ____:
def minDistance(self, word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
# dp[i][j] := the minimum number of operations to convert word1[0..i) to
# word2[0..j)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
dp[i][0] = i
for j in range(1,... | Solution |
python | apache__airflow | airflow-core/tests/unit/utils/test_sqlalchemy.py | {
"start": 1782,
"end": 2803
} | class ____:
def test_returns_dialect_name_when_present(self, mocker):
mock_session = mocker.Mock()
mock_bind = mocker.Mock()
mock_bind.dialect.name = "postgresql"
mock_session.get_bind.return_value = mock_bind
assert get_dialect_name(mock_session) == "postgresql"
def te... | TestGetDialectName |
python | huggingface__transformers | src/transformers/models/led/modeling_led.py | {
"start": 47124,
"end": 47912
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(
self,
input_dim: int,
inner_dim: int,
num_classes: int,
pooler_dropout: float,
):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
self.dro... | LEDClassificationHead |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 7764,
"end": 8726
} | class ____(IncrementalShopifyGraphQlBulkStream):
bulk_query: Transaction = Transaction
cursor_field = "created_at"
@property
def name(self) -> str:
# override default name. This stream is essentially the same as `Transactions` stream, but it's using GraphQL API, which does not include the user_... | TransactionsGraphql |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 21118,
"end": 21574
} | class ____(TestCase):
def test_basic(self):
a = np.array([3, 4, 5, 10, -3, -5, 6.0])
assert_equal(a.ptp(axis=0), 15.0)
b = np.array([[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]])
assert_equal(b.ptp(axis=0), [5.0, 7.0, 7.0])
assert_equal(b.ptp(axis=-1), [6.0, 6.0, 6.0])
... | TestPtp |
python | doocs__leetcode | solution/3500-3599/3565.Sequential Grid Path Cover/Solution.py | {
"start": 0,
"end": 1188
} | class ____:
def findPath(self, grid: List[List[int]], k: int) -> List[List[int]]:
def f(i: int, j: int) -> int:
return i * n + j
def dfs(i: int, j: int, v: int):
nonlocal st
path.append([i, j])
if len(path) == m * n:
return True
... | Solution |
python | numpy__numpy | benchmarks/benchmarks/bench_core.py | {
"start": 5680,
"end": 6242
} | class ____(Benchmark):
def setup(self):
self.d = np.ones(10000, dtype=np.uint8)
self.d2 = np.ones((200, 1000), dtype=np.uint8)
def time_unpackbits(self):
np.unpackbits(self.d)
def time_unpackbits_little(self):
np.unpackbits(self.d, bitorder="little")
def time_unpackbit... | UnpackBits |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 172865,
"end": 172968
} | class ____:
def result(self) -> Callable[..., Any]:
raise NotImplementedError
| CodeCacheFuture |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass10.py | {
"start": 1116,
"end": 1225
} | class ____(A): ...
# This should generate an error.
C.method1()
# This should generate an error.
C.method3()
| C |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 4609,
"end": 4739
} | class ____(Web3Exception):
"""
Raised when an ABI is present, but doesn't contain any functions.
"""
| NoABIFunctionsFound |
python | doocs__leetcode | lcof/面试题18. 删除链表的节点/Solution.py | {
"start": 134,
"end": 430
} | class ____:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
dummy = cur = ListNode(0, head)
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
break
cur = cur.next
return dummy.next
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol3.py | {
"start": 2656,
"end": 2812
} | class ____(NamedTuple):
x: str
# This should generate an error because the protocol
# indicates that 'a' must be writable.
a: Proto7 = Class7("")
| Class7 |
python | huggingface__transformers | src/transformers/models/mask2former/modeling_mask2former.py | {
"start": 19914,
"end": 25584
} | class ____(nn.Module):
"""This class computes an assignment between the labels and the predictions of the network.
For efficiency reasons, the labels don't include the no_object. Because of this, in general, there are more
predictions than labels. In this case, we do a 1-to-1 matching of the best predictio... | Mask2FormerHungarianMatcher |
python | doocs__leetcode | solution/2500-2599/2520.Count the Digits That Divide a Number/Solution.py | {
"start": 0,
"end": 189
} | class ____:
def countDigits(self, num: int) -> int:
ans, x = 0, num
while x:
x, val = divmod(x, 10)
ans += num % val == 0
return ans
| Solution |
python | kubernetes-client__python | kubernetes/client/exceptions.py | {
"start": 2623,
"end": 3794
} | class ____(OpenApiException):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
... | ApiException |
python | justquick__django-activity-stream | actstream/tests/base.py | {
"start": 739,
"end": 983
} | class ____(int):
def __new__(cls, n):
obj = super(LTE, cls).__new__(cls, n)
obj.n = n
return obj
def __eq__(self, other):
return other <= self.n
def __repr__(self):
return "<= %s" % self.n
| LTE |
python | doocs__leetcode | solution/1300-1399/1324.Print Words Vertically/Solution.py | {
"start": 0,
"end": 348
} | class ____:
def printVertically(self, s: str) -> List[str]:
words = s.split()
n = max(len(w) for w in words)
ans = []
for j in range(n):
t = [w[j] if j < len(w) else ' ' for w in words]
while t[-1] == ' ':
t.pop()
ans.append(''.join... | Solution |
python | apache__airflow | providers/mysql/tests/unit/mysql/hooks/test_mysql_connector_python.py | {
"start": 981,
"end": 3585
} | class ____:
def setup_method(self):
self.connection = Connection(
conn_id="test_conn_id",
conn_type="mysql",
login="login",
password="password",
host="host",
schema="schema",
extra='{"client": "mysql-connector-python"}',
... | TestMySqlHookConnMySqlConnectorPython |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_test.py | {
"start": 56429,
"end": 59472
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_keys_and_metadata(self):
class MultiTensor(base.Trackable):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def _serialize_to_tensors(self):
return {"v1": self.v1, "v2": self.v2}
def ... | SerializeToTensorTest |
python | optuna__optuna | optuna/storages/_in_memory.py | {
"start": 681,
"end": 15186
} | class ____(BaseStorage):
"""Storage class that stores data in memory of the Python process.
Example:
Create an :class:`~optuna.storages.InMemoryStorage` instance.
.. testcode::
import optuna
def objective(trial):
x = trial.suggest_float("x", -100, 10... | InMemoryStorage |
python | google__jax | tests/lobpcg_test.py | {
"start": 12402,
"end": 13968
} | class ____(LobpcgTest):
def setUp(self):
# TODO(phawkins): investigate this failure
if jtu.test_device_matches(["gpu"]):
raise unittest.SkipTest("Test is failing on CUDA gpus")
super().setUp()
def testLobpcgValidatesArguments(self):
A, _ = _concrete_generators(np.float32)['id'](100, 10)
... | F32LobpcgTest |
python | lazyprogrammer__machine_learning_examples | ann_class2/dropout_tensorflow.py | {
"start": 961,
"end": 5004
} | class ____(object):
def __init__(self, hidden_layer_sizes, p_keep):
self.hidden_layer_sizes = hidden_layer_sizes
self.dropout_rates = p_keep
def fit(self, X, Y, Xvalid, Yvalid, lr=1e-4, mu=0.9, decay=0.9, epochs=15, batch_sz=100, print_every=50):
X = X.astype(np.float32)
Y = Y.a... | ANN |
python | ray-project__ray | python/ray/_private/thirdparty/pathspec/util.py | {
"start": 12252,
"end": 13313
} | class ____(Exception):
"""
The :exc:`AlreadyRegisteredError` exception is raised when a pattern
factory is registered under a name already in use.
"""
def __init__(self, name, pattern_factory):
"""
Initializes the :exc:`AlreadyRegisteredError` instance.
*name* (:class:`str`) is the name of the registered p... | AlreadyRegisteredError |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 16392,
"end": 17295
} | class ____(rv_continuous):
r"""An arcsine continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `arcsine` is:
.. math::
f(x) = \frac{1}{\pi \sqrt{x (1-x)}}
for :math:`0 < x < 1`.
%(after_notes)s
%(example)s
"""
def _shap... | arcsine_gen |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 553,
"end": 677
} | class ____(ParentC):
# This should generate an error because "x" is Required in the parent.
x: NotRequired[int]
| ChildC |
python | keon__algorithms | algorithms/heap/binary_heap.py | {
"start": 1018,
"end": 1486
} | class ____(metaclass=ABCMeta):
"""Abstract Class for Binary Heap."""
def __init__(self):
"""Pass."""
@abstractmethod
def perc_up(self, i):
"""Pass."""
@abstractmethod
def insert(self, val):
"""Pass."""
@abstractmethod
def perc_down(self, i):
"""Pass.""... | AbstractHeap |
python | kamyu104__LeetCode-Solutions | Python/shift-2d-grid.py | {
"start": 33,
"end": 834
} | class ____(object):
def shiftGrid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def rotate(grids, k):
def reverse(grid, start, end):
while start < end:
start_r, start_c = divmod... | Solution |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_api_server.py | {
"start": 1224,
"end": 24338
} | class ____:
"""Tests api-server deployment."""
@pytest.mark.parametrize(
("revision_history_limit", "global_revision_history_limit"),
[(8, 10), (10, 8), (8, None), (None, 10), (None, None)],
)
def test_revision_history_limit(self, revision_history_limit, global_revision_history_limit):
... | TestAPIServerDeployment |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/session_debug_file_test.py | {
"start": 4514,
"end": 5117
} | class ____(
session_debug_testlib.DebugConcurrentRunCallsTest):
def setUp(self):
self._num_concurrent_runs = 3
self._dump_roots = []
for _ in range(self._num_concurrent_runs):
self._dump_roots.append(tempfile.mkdtemp())
def tearDown(self):
ops.reset_default_graph()
for dump_root in s... | SessionDebugConcurrentTest |
python | google__jax | jax/experimental/jax2tf/tests/jax2tf_limitations.py | {
"start": 882,
"end": 7546
} | class ____(test_harnesses.Limitation):
"""Specific primitive limitations for jax2tf.
See the primitive_test module docstring for details.
"""
def __init__(
self,
description: str,
*,
devices: str | Sequence[str] = ("cpu", "gpu", "tpu"),
dtypes: Sequence[DType] = (),
enabled... | Jax2TfLimitation |
python | huggingface__transformers | src/transformers/models/funnel/configuration_funnel.py | {
"start": 761,
"end": 7640
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FunnelModel`]. It is used to
instantiate a Funnel Transformer model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a sim... | FunnelConfig |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 46657,
"end": 46881
} | class ____(BaseModel, extra="forbid"):
"""
Filter points which have specific vector assigned
"""
has_vector: str = Field(..., description="Filter points which have specific vector assigned")
| HasVectorCondition |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 31090,
"end": 31600
} | class ____(DomainMixin, UpdateView):
success_message = _("Domain updated")
def form_valid(self, form):
response = super().form_valid(form)
self.object.restart_validation_process()
return response
def post(self, request, *args, **kwargs):
project = self.get_project()
... | DomainUpdate |
python | sphinx-doc__sphinx | sphinx/util/requests.py | {
"start": 1690,
"end": 3655
} | class ____(requests.Session):
_ignored_redirects: Sequence[re.Pattern[str]]
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._ignored_redirects = kwargs.pop('_ignored_redirects', ())
super().__init__(*args, **kwargs)
def get_redirect_target(self, resp: requests.Response) -> str ... | _Session |
python | jina-ai__jina | tests/integration/reduce/test_reduce.py | {
"start": 1164,
"end": 3325
} | class ____(Executor):
@requests
def fake_reduce(self, **kwargs):
return DocumentArray([Document(id='fake_document')])
@pytest.mark.parametrize('n_docs', [3, 5])
def test_reduce_shards(n_docs, port_generator):
exposed_port = port_generator()
n_shards = 3
search_flow = Flow(port=exposed_port... | DummyExecutor |
python | Delgan__loguru | loguru/_error_interceptor.py | {
"start": 30,
"end": 1107
} | class ____:
def __init__(self, should_catch, handler_id):
self._should_catch = should_catch
self._handler_id = handler_id
def should_catch(self):
return self._should_catch
def print(self, record=None, *, exception=None):
if not sys.stderr:
return
if exc... | ErrorInterceptor |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 67453,
"end": 67953
} | class ____(PrefectFilterBaseModel):
"""Filter by `WorkPool.id`."""
any_: Optional[list[UUID]] = Field(
default=None, description="A list of work pool ids to include"
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
fil... | WorkPoolFilterId |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 17825,
"end": 18680
} | class ____(PrefectFilterBaseModel):
"""Filter by `FlowRun.expected_start_time`."""
before_: Optional[DateTime] = Field(
default=None,
description="Only include flow runs scheduled to start at or before this time",
)
after_: Optional[DateTime] = Field(
default=None,
descr... | FlowRunFilterExpectedStartTime |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/utils/mixins.py | {
"start": 2070,
"end": 2227
} | class ____(Protocol):
"""Protocol for execute_complete method."""
statement_id: str
_hook: DatabricksHook
log: Logger
| ExecuteCompleteHasFields |
python | python__mypy | mypyc/transform/log_trace.py | {
"start": 1940,
"end": 5374
} | class ____(IRTransform):
def __init__(self, builder: LowLevelIRBuilder, fullname: str) -> None:
super().__init__(builder)
self.fullname = fullname.encode("utf-8")
def visit_call(self, op: Call) -> Value:
# TODO: Use different op name when constructing an instance
return self.log... | LogTraceEventTransform |
python | astropy__astropy | astropy/extern/configobj/validate.py | {
"start": 12150,
"end": 12525
} | class ____(ValidateError):
"""The value supplied was of the wrong type"""
def __init__(self, value):
"""
>>> raise VdtTypeError('jedi')
Traceback (most recent call last):
VdtTypeError: the value "jedi" is of the wrong type.
"""
ValidateError.__init__(self, 'the v... | VdtTypeError |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 18060,
"end": 18148
} | class ____(Sam2VideoPositionEmbeddingSine):
pass
| Sam3TrackerVideoPositionEmbeddingSine |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 121677,
"end": 128944
} | class ____:
def test_zscore(self, xp):
# not in R, so tested by using:
# (testcase[i] - mean(testcase, axis=0)) / sqrt(var(testcase) * 3/4)
y = stats.zscore(xp.asarray([1, 2, 3, 4]))
desired = [-1.3416407864999, -0.44721359549996,
0.44721359549996, 1.34164078649... | TestZscore |
python | kamyu104__LeetCode-Solutions | Python/3sum.py | {
"start": 1024,
"end": 1919
} | class ____(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums, result, i = sorted(nums), [], 0
while i < len(nums) - 2:
if i == 0 or nums[i] != nums[i - 1]:
j, k = i + 1, len(nums) - 1
... | Solution2 |
python | django-crispy-forms__django-crispy-forms | tests/forms.py | {
"start": 6638,
"end": 6715
} | class ____(forms.CheckboxSelectMultiple):
pass
| CustomCheckboxSelectMultiple |
python | ZoranPandovski__al-go-rithms | data_structures/trie/Python/trie.py | {
"start": 281,
"end": 2605
} | class ____:
# Trie data structure class
def __init__(self):
self.root = self.getNode()
def getNode(self):
# Returns new trie node (initialized to NULLs)
return TrieNode()
def _charToIndex(self,ch):
# private helper function
... | Trie |
python | walkccc__LeetCode | solutions/1320. Minimum Distance to Type a Word Using Two Fingers/1320.py | {
"start": 0,
"end": 791
} | class ____:
def minimumDistance(self, word: str) -> int:
def dist(a: int, b: int) -> int:
if a == 26: # the first hovering state
return 0
x1, y1 = a // 6, a % 6
x2, y2 = b // 6, b % 6
return abs(x1 - x2) + abs(y1 - y2)
@functools.lru_cache(None)
def dp(i: int, j: int, k: ... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/base.py | {
"start": 108926,
"end": 112849
} | class ____(reflection.Inspector):
dialect: PGDialect
def get_table_oid(
self, table_name: str, schema: Optional[str] = None
) -> int:
"""Return the OID for the given table name.
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
... | PGInspector |
python | aio-libs__aiohttp | aiohttp/multipart.py | {
"start": 19881,
"end": 27499
} | class ____:
"""Multipart body reader."""
#: Response wrapper, used when multipart readers constructs from response.
response_wrapper_cls = MultipartResponseWrapper
#: Multipart reader class, used to handle multipart/* body parts.
#: None points to type(self)
multipart_reader_cls: type["Multipar... | MultipartReader |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py | {
"start": 1149,
"end": 1307
} | class ____: ...
def func3(c1: Callable[[int], None]):
if isinstance(c1, IsNotFinal):
reveal_type(c1, expected_text="IsNotFinal")
@final
| IsNotFinal |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 94420,
"end": 106963
} | class ____(OpInfo):
"""Operator information for 'universal binary functions (binary ufuncs).'
These are functions of two tensors with common properties like:
- they are elementwise functions
- the output shape is determined by the input shape
- they typically have method and inplace variants
... | BinaryUfuncInfo |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 3239,
"end": 3332
} | class ____(CommandTimeout):
exit_code = ExitCode.CLUSTER_WAIT_TIMEOUT
| PrepareCommandTimeout |
python | django__django | django/db/backends/oracle/utils.py | {
"start": 61,
"end": 1198
} | class ____:
"""
A late-binding cursor variable that can be passed to Cursor.execute
as a parameter, in order to receive the id of the row created by an
insert statement.
"""
types = {
"AutoField": int,
"BigAutoField": int,
"SmallAutoField": int,
"IntegerField": i... | BoundVar |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_project_processing_errors_index.py | {
"start": 299,
"end": 2475
} | class ____(MonitorTestCase, APITestCase):
endpoint = "sentry-api-0-project-processing-errors-index"
method = "delete"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_no_error_type(self) -> None:
resp = self.get_error_response(self.organization.sl... | ProjectProcessingErrorsIndexEndpointTest |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/ref_bundle.py | {
"start": 741,
"end": 14667
} | class ____:
"""A group of data block references and their metadata.
Operators take in and produce streams of RefBundles.
Most commonly a RefBundle consists of a single block object reference.
In some cases, e.g., due to block splitting, or for a reduce task, there may
be more than one block.
... | RefBundle |
python | aio-libs__aiohttp | tests/test_pytest_plugin.py | {
"start": 6457,
"end": 7267
} | class ____(TestClient):
pass
@pytest.fixture
def aiohttp_client_cls():
return CustomClient
async def test_hello(aiohttp_client) -> None:
client = await aiohttp_client(Application())
assert isinstance(client, CustomClient)
"""
)
testdir.makeconftest(CONFTEST)
result = testdir.runpytest()... | CustomClient |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 3388,
"end": 6098
} | class ____(Initializer):
"""Initializer that generates tensors initialized to 0.
@compatibility(TF2)
`tf.compat.v1.zeros_initializer` is compatible with eager execution
and `tf.function`.
To migrate to TF2, please use `tf.zeros_initializer` instead. The `dtype`
argument in `tf.compat.v1.zeros_initializer.... | Zeros |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 84748,
"end": 87829
} | class ____(fixtures.TestBase):
def test_all_positional(self):
class Foo:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
eq_(util.generic_repr(Foo(1, 2, 3)), "Foo(1, 2, 3)")
def test_positional_plus_kw(self):
cla... | GenericReprTest |
python | astropy__astropy | astropy/cosmology/_src/flrw/lambdacdm.py | {
"start": 672,
"end": 22294
} | class ____(FLRW):
"""FLRW cosmology with a cosmological constant and curvature.
This has no additional attributes beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
... | LambdaCDM |
python | pypa__pipenv | pipenv/vendor/plette/lockfiles.py | {
"start": 1552,
"end": 5241
} | class ____(DataModel):
"""Representation of a Pipfile.lock.
"""
__SCHEMA__ = {
"_meta": {"type": "dict", "required": True},
"default": {"type": "dict", "required": True},
"develop": {"type": "dict", "required": True},
}
@classmethod
def validate(cls, data):
for k... | Lockfile |
python | facebook__pyre-check | client/commands/tests/language_server_test.py | {
"start": 49704,
"end": 52570
} | class ____(testslide.TestCase, abc.ABC):
def _assert_json_equal(
self,
actual_json_string: str,
expected_json_string: str,
) -> None:
self.assertEqual(
json.loads(actual_json_string),
json.loads(expected_json_string),
)
def _expect_success_mes... | ApiTestCase |
python | google__pytype | pytype/metrics.py | {
"start": 9668,
"end": 12061
} | class ____(Metric):
"""A metric to track memory usage via tracemalloc snapshots."""
def __init__(
self, name, enabled=False, groupby="lineno", nframes=1, count=10
):
if enabled and tracemalloc is None:
raise RuntimeError("tracemalloc module couldn't be imported")
super().__init__(name)
se... | Snapshot |
python | fluentpython__example-code | 14-it-generator/sentence_gen.py | {
"start": 122,
"end": 447
} | class ____:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
for word in self.words: # <1>
yield word # <2>
return # <3>
# done! <4>... | Sentence |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_city_name.py | {
"start": 906,
"end": 1901
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_city_name"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(... | ColumnValuesToBeValidCityName |
python | facebookresearch__faiss | tests/test_index_accuracy.py | {
"start": 5410,
"end": 10562
} | class ____(unittest.TestCase):
"""tests IP in addition to L2, non multiple of 8 dimensions"""
def add2columns(self, x):
return np.hstack((x, np.zeros((x.shape[0], 2), dtype="float32")))
def subtest_add2col(self, xb, xq, index, qname):
"""Test with 2 additional dimensions to take also the n... | TestSQFlavors |
python | pypa__pip | src/pip/_internal/operations/build/build_tracker.py | {
"start": 1760,
"end": 4771
} | class ____:
"""Ensure that an sdist cannot request itself as a setup requirement.
When an sdist is prepared, it identifies its setup requirements in the
context of ``BuildTracker.track()``. If a requirement shows up recursively, this
raises an exception.
This stops fork bombs embedded in malicious... | BuildTracker |
python | google__jax | jaxlib/gpu_common_utils.py | {
"start": 630,
"end": 905
} | class ____(Exception):
"""Raised when the GPU library is not linked."""
error_msg = (
'JAX was not built with GPU support. Please use a GPU-enabled JAX to use'
' this function.'
)
def __init__(self):
super().__init__(self.error_msg)
| GpuLibNotLinkedError |
python | pytorch__pytorch | test/dynamo/test_functions.py | {
"start": 86699,
"end": 87218
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[2, 2]"):
l_x_ = L_x_
mul: "f32[2, 2]" = l_x_ * 4
mul_1: "f32[2, 2]" = mul * l_x_; mul = None
mul_2: "f32[2, 2]" = 20 * l_x_; l_x_ = None
mul_3: "f32[2, 2]" = torch.mul(mul_1, mul_2); mul_1 = mul_2 = None
r... | GraphModule |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes5.py | {
"start": 136,
"end": 549
} | class ____:
cv1: ClassVar[int] = 0
cv2: ClassVar[int] = 0
cv3: ClassVar[int] = 0
cv4: ClassVar[int] = 0
var1: int
var2: str
var3: int | str
var4: int
var5: int
var6: int
var7: list[float]
var8: list[int]
var9: int
_var1: int
__var1: int
def __init__(sel... | ParentClass1 |
python | walkccc__LeetCode | solutions/1695. Maximum Erasure Value/1695.py | {
"start": 0,
"end": 349
} | class ____:
def maximumUniqueSubarray(self, nums: list[int]) -> int:
ans = 0
score = 0
seen = set()
l = 0
for r, num in enumerate(nums):
while num in seen:
score -= nums[l]
seen.remove(nums[l])
l += 1
seen.add(nums[r])
score += nums[r]
ans = max(ans... | Solution |
python | Farama-Foundation__Gymnasium | gymnasium/envs/classic_control/cartpole.py | {
"start": 13958,
"end": 22781
} | class ____(VectorEnv):
metadata = {
"render_modes": ["rgb_array"],
"render_fps": 50,
"autoreset_mode": AutoresetMode.NEXT_STEP,
}
def __init__(
self,
num_envs: int = 1,
max_episode_steps: int = 500,
render_mode: str | None = None,
sutton_barto... | CartPoleVectorEnv |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/dataframe_partitioners.py | {
"start": 1784,
"end": 2209
} | class ____(_PartitionerDatetime):
column_name: str
sort_ascending: bool = True
method_name: Literal["partition_on_year_and_month"] = "partition_on_year_and_month"
@property
@override
def param_names(self) -> List[str]:
return ["year", "month"]
@override
def partitioner_method_k... | DataframePartitionerMonthly |
python | facebook__pyre-check | tools/generate_taint_models/tests/get_filtered_sources_test.py | {
"start": 769,
"end": 9824
} | class ____(unittest.TestCase):
@patch.object(RESTApiSourceGenerator, "generate_models")
@patch.object(AnnotatedFreeFunctionWithDecoratorGenerator, "generate_models")
def test_compute_models_with_no_intersection(
self,
mock_annotated_decorator_generate_models,
mock_RESTapi_decorator_g... | GetFilteredSourcesTest |
python | ray-project__ray | release/nightly_tests/decision_tree/cart_with_tree.py | {
"start": 3439,
"end": 13857
} | class ____:
def __init__(self, max_depth=None, tree_limit=5000, feature_limit=2000):
self.max_depth = max_depth
self.tree_limit = tree_limit
self.feature_limit = feature_limit
def fit(self, X, y):
"""Build decision tree classifier."""
self.n_classes_ = len(set(y)) # cla... | DecisionTreeClassifier |
python | PyCQA__pylint | tests/functional/p/protocol_classes.py | {
"start": 540,
"end": 738
} | class ____(Protocol):
"""A hashing algorithm, e.g. :func:`hashlib.sha256`."""
def update(self, blob: bytes): # [unused-argument]
...
def digest(self) -> bytes:
...
| HasherFake |
python | spyder-ide__spyder | spyder/plugins/projects/utils/config.py | {
"start": 2730,
"end": 2932
} | class ____(MultiUserConfig):
"""Plugin configuration handler with multifile support."""
DEFAULT_FILE_NAME = WORKSPACE
def get_config_class(self):
return ProjectConfig
| ProjectMultiConfig |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_connect.py | {
"start": 1396,
"end": 4495
} | class ____(
test_ecsv.ReadWriteECSVTestMixin,
test_html.ReadWriteHTMLTestMixin,
test_json.ReadWriteJSONTestMixin,
test_latex.WriteLATEXTestMixin,
):
"""
Tests for a CosmologyRead/Write on a |Cosmology|.
This class will not be directly called by :mod:`pytest` since its name does
not begin... | ReadWriteTestMixin |
python | getsentry__responses | responses/tests/test_responses.py | {
"start": 76571,
"end": 77314
} | class ____:
"""Validates that ``RequestsMock`` could be used as ``mock.patch``.
This class is present as example in README.rst
"""
def setup_method(self):
self.r_mock = responses.RequestsMock(assert_all_requests_are_fired=True)
self.r_mock.start()
self.r_mock.get("https://exam... | TestUnitTestPatchSetup |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 7883,
"end": 8102
} | class ____(_Permission[UsersAction]):
users: str
def _to_weaviate(self) -> List[WeaviatePermission]:
return [{"action": action, "users": {"users": self.users}} for action in self.actions]
| _UsersPermission |
python | hyperopt__hyperopt | hyperopt/exceptions.py | {
"start": 113,
"end": 205
} | class ____(BadSearchSpace):
"""A search space included a duplicate label"""
| DuplicateLabel |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py | {
"start": 630,
"end": 790
} | class ____(DbtCloudException):
"""
Raised when a triggered job run does not complete in the configured max
wait seconds
"""
| DbtCloudJobRunTimedOut |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.