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 | pypa__warehouse | warehouse/admin/interfaces.py | {
"start": 78,
"end": 676
} | class ____(Interface):
def create_service(context, request):
"""
Create the service, given the context and request for which it is being
created for, passing a name for settings.
"""
def store(path, file_path, content_type=None, *, meta=None):
"""
Save the file l... | ISponsorLogoStorage |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/retrievers/sequential_retriever.py | {
"start": 163,
"end": 844
} | class ____(BaseRetriever):
"""Test util that returns a sequence of documents."""
sequential_responses: list[list[Document]]
response_index: int = 0
@override
def _get_relevant_documents(
self,
query: str,
**kwargs: Any,
) -> list[Document]:
if self.response_inde... | SequentialRetriever |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/test_utils/basic_components.py | {
"start": 1173,
"end": 1435
} | class ____(dg.Component):
@classmethod
def get_model_cls(cls) -> type[MyNestedComponentModel]:
return MyNestedComponentModel
def build_defs(self, context: ComponentLoadContext) -> dg.Definitions:
return dg.Definitions()
| MyNestedComponent |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_search_tool_request_error_param.py | {
"start": 320,
"end": 506
} | class ____(TypedDict, total=False):
error_code: Required[BetaWebSearchToolResultErrorCode]
type: Required[Literal["web_search_tool_result_error"]]
| BetaWebSearchToolRequestErrorParam |
python | django__django | tests/postgres_tests/test_ranges.py | {
"start": 9899,
"end": 14954
} | class ____(PostgreSQLTestCase):
@classmethod
def setUpTestData(cls):
cls.objs = RangesModel.objects.bulk_create(
[
RangesModel(ints=NumericRange(0, 10)),
RangesModel(ints=NumericRange(5, 15)),
RangesModel(ints=NumericRange(None, 0)),
... | TestQuerying |
python | sympy__sympy | sympy/physics/quantum/state.py | {
"start": 11022,
"end": 12564
} | class ____(State, KetBase):
"""A general time-independent Ket in quantum mechanics.
Inherits from State and KetBase. This class should be used as the base
class for all physical, time-independent Kets in a system. This class
and its subclasses will be the main classes that users will use for
expres... | Ket |
python | fsspec__filesystem_spec | fsspec/implementations/tests/memory/memory_test.py | {
"start": 274,
"end": 349
} | class ____(abstract.AbstractPutTests, MemoryFixtures):
pass
| TestMemoryPut |
python | cherrypy__cherrypy | cherrypy/test/test_misc_tools.py | {
"start": 4088,
"end": 6820
} | class ____(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_Accept_Tool(self):
# Test with no header provided
self.getPage('/accept/feed')
self.assertStatus(200)
self.assertInBody('<title>Unknown Blog</title>')
# Specify exact media type
sel... | AcceptTest |
python | cython__cython | Cython/Compiler/MatchCaseNodes.py | {
"start": 260,
"end": 4187
} | class ____(StatNode):
"""
subject ExprNode The expression to be matched
cases [MatchCaseBaseNode] list of cases
subject_clonenode CloneNode of subject
"""
child_attrs = ["subject", "cases"]
def validate_irrefutable(self):
found_irrefutable_case = None
for case in ... | MatchNode |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_str01.py | {
"start": 315,
"end": 1421
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_str01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file when the chart data contains strings."""
... | TestCompareXLSXFiles |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 48429,
"end": 49337
} | class ____:
def test_basic(self):
x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
1, 1j, -1, -1j, 1 - 3j, -1 + 3j]
y = angle(x)
yo = [
np.arctan(3.0 / 1.0),
np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,
-np.arctan(3.0 / 1.0), np.pi ... | TestAngle |
python | kamyu104__LeetCode-Solutions | Python/guess-number-higher-or-lower-ii.py | {
"start": 32,
"end": 455
} | class ____(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
dp = [[0]*(n+1) for _ in xrange(n+1)] # dp[i][j]: min pay in [i+1, j+1)
for j in xrange(n+1):
for i in reversed(xrange(j-1)):
dp[i][j] = min((k+1) + max(dp[i... | Solution |
python | huggingface__transformers | src/transformers/models/pvt_v2/modeling_pvt_v2.py | {
"start": 16709,
"end": 18439
} | class ____(PvtV2PreTrainedModel):
def __init__(self, config: PvtV2Config):
super().__init__(config)
self.config = config
# hierarchical Transformer encoder
self.encoder = PvtV2Encoder(config)
# Initialize weights and apply final processing
self.post_init()
@aut... | PvtV2Model |
python | scikit-learn__scikit-learn | sklearn/ensemble/_base.py | {
"start": 2943,
"end": 6026
} | class ____(MetaEstimatorMixin, BaseEstimator, metaclass=ABCMeta):
"""Base class for all ensemble classes.
Warning: This class should not be used directly. Use derived classes
instead.
Parameters
----------
estimator : object
The base estimator from which the ensemble is built.
n_e... | BaseEnsemble |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/postgres_to_gcs.py | {
"start": 2719,
"end": 8841
} | class ____(BaseSQLToGCSOperator):
"""
Copy data from Postgres to Google Cloud Storage in JSON, CSV or Parquet format.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:PostgresToGCSOperator`
:param postgres_conn_id: Reference ... | PostgresToGCSOperator |
python | ethereum__web3.py | tests/core/manager/test_provider_request_wrapping.py | {
"start": 100,
"end": 962
} | class ____(BaseProvider):
def make_request(self, method, params):
return {
"jsonrpc": "2.0",
"id": 1,
"result": {
"method": method,
"params": params,
"middleware": [],
},
}
def test_provider_property_se... | DummyProvider |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 4508,
"end": 5668
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, default="")
name = indexes.CharField()
is_active = indexes.BooleanField()
post_count = indexes.IntegerField()
average_rating = indexes.FloatField()
price = indexes.DecimalField()
pub_date = indexes.Da... | Elasticsearch5RoundTripSearchIndex |
python | pandas-dev__pandas | pandas/tests/indexes/test_old_base.py | {
"start": 32541,
"end": 36965
} | class ____:
@pytest.fixture(
params=[
RangeIndex(start=0, stop=20, step=2),
Index(np.arange(5, dtype=np.float64)),
Index(np.arange(5, dtype=np.float32)),
Index(np.arange(5, dtype=np.uint64)),
Index(range(0, 20, 2), dtype=np.int64),
Inde... | TestNumericBase |
python | conda__conda | conda/core/path_actions.py | {
"start": 30452,
"end": 34633
} | class ____(CreateInPrefixPathAction):
# this is the action that creates a packages json file in the conda-meta/ directory
@classmethod
def create_actions(
cls,
transaction_context,
package_info,
target_prefix,
requested_link_type,
requested_spec,
all_... | CreatePrefixRecordAction |
python | jazzband__django-waffle | waffle/tests/test_waffle.py | {
"start": 18808,
"end": 24031
} | class ____(TestCase):
databases = DATABASES
def assert_switch_dynamically_created_with_value(self, expected_value):
SWITCH_NAME = 'my_dynamically_created_switch'
assert waffle.get_waffle_switch_model().objects.count() == 0
assert expected_value == waffle.switch_is_active(SWITCH_NAME)
... | SwitchTests |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_sdk.py | {
"start": 7871,
"end": 30811
} | class ____:
# Resource bundles.
bundles: List[dict]
# List of detail information about the request
details: List[str]
def assert_gang_requests(
state: ClusterResourceState, expected: List[GangResourceRequest]
):
"""
Assert a GetClusterResourceStateReply has gang requests that
matches w... | GangResourceRequest |
python | hynek__structlog | tests/test_tracebacks.py | {
"start": 27347,
"end": 33196
} | class ____:
"""
Higher level integration tests for `Logger.exception()`.
"""
@pytest.fixture
def cap_logs(self) -> structlog.testing.LogCapture:
"""
Create a LogCapture to be used as processor and fixture for retrieving
logs in tests.
"""
return structlog.tes... | TestLogException |
python | plotly__plotly.py | plotly/graph_objs/scattermap/unselected/_marker.py | {
"start": 233,
"end": 4065
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermap.unselected"
_path_str = "scattermap.unselected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exi... | Marker |
python | PyCQA__pylint | pylint/config/_breaking_changes/__init__.py | {
"start": 1900,
"end": 1998
} | class ____(NamedTuple):
msgid_or_symbol: str
extension: str | None = None
| MessageInformation |
python | doocs__leetcode | solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.py | {
"start": 0,
"end": 593
} | class ____:
def __init__(self):
self.children = {}
self.fid = -1
def insert(self, i, f):
node = self
ps = f.split('/')
for p in ps[1:]:
if p not in node.children:
node.children[p] = Trie()
node = node.children[p]
node.fid =... | Trie |
python | docker__docker-py | docker/models/nodes.py | {
"start": 1785,
"end": 2928
} | class ____(Collection):
"""Nodes on the Docker server."""
model = Node
def get(self, node_id):
"""
Get a node.
Args:
node_id (string): ID of the node to be inspected.
Returns:
A :py:class:`Node` object.
Raises:
:py:class:`docker... | NodeCollection |
python | PyCQA__pylint | tests/functional/u/unsubscriptable_value.py | {
"start": 653,
"end": 1586
} | class ____:
def __getitem__(self, key):
return key + key
NonSubscriptable()[0] # [unsubscriptable-object]
NonSubscriptable[0] # [unsubscriptable-object]
Subscriptable()[0]
Subscriptable[0] # [unsubscriptable-object]
# generators are not subscriptable
def powers_of_two():
k = 0
while k < 10:
... | Subscriptable |
python | mlflow__mlflow | mlflow/utils/_spark_utils.py | {
"start": 4704,
"end": 8056
} | class ____:
"""Distribute spark directory from driver to executors."""
_extracted_dir_paths = {}
def __init__(self):
pass
@staticmethod
def add_dir(spark, dir_path):
"""Given a SparkSession and a model_path which refers to a pyfunc directory locally,
we will zip the direct... | _SparkDirectoryDistributor |
python | viewflow__viewflow | viewflow/workflow/chart.py | {
"start": 1863,
"end": 20684
} | class ____(object):
def __init__(self, nodes):
self.width = -1
self.height = -1
self.grid = {node: Cell(node) for node in nodes}
self.edges = [
Edge(edge.src, edge.dst) for node in nodes for edge in node._incoming()
]
def __getitem__(self, node):
ret... | Grid |
python | joke2k__faker | faker/providers/emoji/__init__.py | {
"start": 30,
"end": 52706
} | class ____(BaseProvider):
emojis = [
"😀",
"😃",
"😄",
"😁",
"😆",
"😅",
"🤣",
"😂",
"🙂",
"🙃",
"😉",
"😊",
"😇",
"🥰",
"😍",
"🤩",
"😘",
"😗",
"☺️",
"😚",... | Provider |
python | ansible__ansible | test/lib/ansible_test/_internal/util.py | {
"start": 31529,
"end": 39561
} | class ____(ApplicationError):
"""
Raised when the initial connection during host profile setup has failed and all retries have been exhausted.
Raised by provisioning code when one or more provisioning threads raise this exception.
Also raised when an SSH connection fails for the shell command.
"""
... | HostConnectionError |
python | great-expectations__great_expectations | great_expectations/expectations/row_conditions.py | {
"start": 6006,
"end": 9714
} | class ____(Condition):
"""Condition representing the comparison of a column with a parameter."""
type: Literal["comparison"] = Field(default="comparison")
column: Column
operator: Operator
parameter: Parameter = Field(...)
@root_validator
def _validate_parameter_not_none(cls, values):
... | ComparisonCondition |
python | ray-project__ray | rllib/evaluation/collectors/simple_list_collector.py | {
"start": 3613,
"end": 3940
} | class ____:
def __init__(self, policy_map):
self.policy_collectors = {}
# Total env-steps (1 env-step=up to N agents stepped).
self.env_steps = 0
# Total agent steps (1 agent-step=1 individual agent (out of N)
# stepped).
self.agent_steps = 0
@OldAPIStack
| _PolicyCollectorGroup |
python | automl__auto-sklearn | autosklearn/pipeline/components/data_preprocessing/text_encoding/__init__.py | {
"start": 963,
"end": 4514
} | class ____(AutoSklearnChoice):
@classmethod
def get_components(cls: BaseEstimator) -> Dict[str, BaseEstimator]:
components: Dict[str, BaseEstimator] = OrderedDict()
components.update(_bows)
components.update(additional_components.components)
return components
def get_hyperpa... | BagOfWordChoice |
python | pandas-dev__pandas | pandas/tests/scalar/period/test_period.py | {
"start": 28279,
"end": 39975
} | class ____:
"""Test properties such as year, month, weekday, etc...."""
@pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])
def test_is_leap_year(self, freq):
# GH 13727
p = Period("2000-01-01 00:00:00", freq=freq)
assert p.is_leap_year
assert isinstance(p.is_leap_year, b... | TestPeriodProperties |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 761,
"end": 1033
} | class ____(ParseError):
"""
An array was found that had two or more element types.
"""
def __init__(self, line: int, col: int) -> None:
message = "Mixed types found in array"
super().__init__(line, col, message=message)
| MixedArrayTypesError |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_opensearch_serverless.py | {
"start": 1130,
"end": 4705
} | class ____:
def setup_method(self):
self.default_op_kwargs = dict(
task_id="test_sensor",
collection_id="knowledge_base_id",
poke_interval=5,
max_retries=1,
)
self.sensor = OpenSearchServerlessCollectionActiveSensor(**self.default_op_kwargs, aw... | TestOpenSearchServerlessCollectionActiveSensor |
python | joke2k__faker | tests/test_generator.py | {
"start": 85,
"end": 159
} | class ____:
def foo_formatter(self):
return "barfoo"
| BarProvider |
python | doocs__leetcode | solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/Solution.py | {
"start": 0,
"end": 415
} | class ____:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
cnt = nums.count(1)
if cnt:
return n - cnt
mi = n + 1
for i in range(n):
g = 0
for j in range(i, n):
g = gcd(g, nums[j])
if g == 1:
... | Solution |
python | ipython__ipython | IPython/core/display.py | {
"start": 22870,
"end": 26743
} | class ____(TextDisplayObject):
def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
"""Create a Javascript display object given raw data.
When this object is returned by an expression or passed to the
display function, it will result in the data being displayed
... | Javascript |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 6832,
"end": 6909
} | class ____:
x: int
# Auto-detect
@attr.s(auto_detect=True)
| TransformedAttrs |
python | openai__openai-python | src/openai/types/responses/response_function_web_search.py | {
"start": 911,
"end": 1261
} | class ____(BaseModel):
pattern: str
"""The pattern or text to search for within the page."""
type: Literal["find"]
"""The action type."""
url: str
"""The URL of the page searched for the pattern."""
Action: TypeAlias = Annotated[Union[ActionSearch, ActionOpenPage, ActionFind], PropertyInfo(d... | ActionFind |
python | Textualize__textual | docs/examples/styles/padding.py | {
"start": 384,
"end": 553
} | class ____(App):
CSS_PATH = "padding.tcss"
def compose(self):
yield Label(TEXT)
if __name__ == "__main__":
app = PaddingApp()
app.run()
| PaddingApp |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solverScoring4.py | {
"start": 275,
"end": 456
} | class ____(Protocol[T_contra]):
def __call__(self, resolve_value: T_contra) -> None: ...
TA1 = Callable[[T], R | "Promise[R]"]
TA2 = Callable[[ResolveFunc[T]], None]
| ResolveFunc |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_early_fraud_warnings.py | {
"start": 3590,
"end": 7995
} | class ____(TestCase):
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
_early_fraud_warnings_request().with_limit(100).build(),
_early_fraud_warnings_response().with_record(_an_early_fraud_warning()).with... | FullRefreshTest |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc_strides.py | {
"start": 219,
"end": 2124
} | class ____(Benchmark):
params = []
param_names = ['ufunc', 'stride_in0', 'stride_in1', 'stride_out', 'dtype']
timeout = 10
arrlen = 1000000
data_finite = True
data_denormal = False
data_zeros = False
def setup(self, ufunc, stride_in0, stride_in1, stride_out, dtype):
ufunc_insig ... | _AbstractBinary |
python | tornadoweb__tornado | tornado/test/iostream_test.py | {
"start": 27107,
"end": 33453
} | class ____(TestReadWriteMixin):
def _make_server_iostream(self, connection, **kwargs):
raise NotImplementedError()
def _make_client_iostream(self, connection, **kwargs):
raise NotImplementedError()
@gen.coroutine
def make_iostream_pair(self, **kwargs):
listener, port = bind_unu... | TestIOStreamMixin |
python | kamyu104__LeetCode-Solutions | Python/maximize-the-topmost-element-after-k-moves.py | {
"start": 63,
"end": 396
} | class ____(object):
def maximumTop(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if len(nums) == 1 == k%2:
return -1
if k <= 1:
return nums[k]
return max(nums[i] for i in xrange(min(k+1, len(nums))) if i... | Solution |
python | openai__openai-python | src/openai/types/beta/realtime/transcription_session_create_params.py | {
"start": 3046,
"end": 3190
} | class ____(TypedDict, total=False):
expires_at: ClientSecretExpiresAt
"""Configuration for the ephemeral token expiration."""
| ClientSecret |
python | pytorch__pytorch | test/distributed/checkpoint/e2e/test_fsdp_ep.py | {
"start": 1440,
"end": 1719
} | class ____(nn.Module):
def __init__(self, rank):
super().__init__()
torch.manual_seed(0)
self.second = SecondTier(rank)
self.net = nn.Sequential(nn.Linear(16, 16), nn.ReLU())
def forward(self, x):
raise NotImplementedError
| TopModel |
python | sphinx-doc__sphinx | sphinx/search/en.py | {
"start": 193,
"end": 596
} | class ____(SearchLanguage):
lang = 'en'
language_name = 'English'
js_stemmer_rawcode = 'english-stemmer.js'
stopwords = ENGLISH_STOPWORDS
def __init__(self, options: dict[str, str]) -> None:
super().__init__(options)
self.stemmer = snowballstemmer.stemmer('english')
def stem(se... | SearchEnglish |
python | Netflix__metaflow | metaflow/plugins/argo/argo_events.py | {
"start": 299,
"end": 384
} | class ____(MetaflowException):
headline = "Argo Event Exception"
| ArgoEventException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass10.py | {
"start": 404,
"end": 463
} | class ____(Generic[T]):
x: B[T] = B[T]()
@dataclass
| CBase |
python | google__pytype | pytype/overlays/collections_overlay.py | {
"start": 974,
"end": 1320
} | class ____(typing_overlay.Redirect):
"""A custom overlay for the 'collections.abc' module."""
def __init__(self, ctx):
# collections.abc.Set equates to typing.AbstractSet rather than typing.Set.
# This is the only such mismatch.
aliases = {"Set": "typing.AbstractSet"}
super().__init__("collections.... | ABCOverlay |
python | pytorch__pytorch | torch/testing/_internal/distributed/nn/api/remote_module_test.py | {
"start": 2996,
"end": 3949
} | class ____(RpcAgentTestFixture):
@property
def world_size(self): # Override setting in RpcAgentTestFixture
return 2
@staticmethod
def _create_remote_module_iter(remote_device, modes=None):
if modes is None:
modes = ModuleCreationMode.__members__.values()
args = (1,... | CommonRemoteModuleTest |
python | ray-project__ray | python/ray/serve/tests/test_target_capacity.py | {
"start": 31688,
"end": 40612
} | class ____:
def deploy_config_and_wait_for_target_capacity(
self,
client: ServeControllerClient,
config: ServeDeploySchema,
target_capacity: float,
):
config.target_capacity = target_capacity
client.deploy_apps(config)
wait_for_condition(lambda: serve.stat... | TestInitialReplicasHandling |
python | celery__celery | celery/backends/consul.py | {
"start": 627,
"end": 3816
} | class ____(KeyValueStoreBackend):
"""Consul.io K/V store backend for Celery."""
consul = consul
supports_autoexpire = True
consistency = 'consistent'
path = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.consul is None:
raise ... | ConsulBackend |
python | dagster-io__dagster | examples/docs_projects/project_dspy/dspy_modules/solver.py | {
"start": 637,
"end": 3501
} | class ____(dspy.Module):
"""DSPy module for solving Connections puzzles."""
def __init__(self):
self.predict = dspy.ChainOfThought(
"rules, available_words, history_feedback, guess_index -> guess"
)
self.logic = ConnectionsGameLogic()
# end_connections_solver
# sta... | ConnectionsSolver |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_grouping_configs.py | {
"start": 49,
"end": 570
} | class ____(APITestCase):
endpoint = "sentry-api-0-grouping-configs"
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization(owner=self.user)
self.login_as(user=self.user)
def test_no_slug(self) -> None:
resp = self.get_response()
assert... | GroupingConfigsNoSlugTest |
python | scrapy__scrapy | tests/test_settings/__init__.py | {
"start": 777,
"end": 2256
} | class ____:
def setup_method(self):
self.attribute = SettingsAttribute("value", 10)
def test_set_greater_priority(self):
self.attribute.set("value2", 20)
assert self.attribute.value == "value2"
assert self.attribute.priority == 20
def test_set_equal_priority(self):
... | TestSettingsAttribute |
python | TheAlgorithms__Python | data_structures/binary_tree/binary_search_tree_recursive.py | {
"start": 311,
"end": 523
} | class ____:
def __init__(self, label: int, parent: Node | None) -> None:
self.label = label
self.parent = parent
self.left: Node | None = None
self.right: Node | None = None
| Node |
python | kamyu104__LeetCode-Solutions | Python/clone-n-ary-tree.py | {
"start": 54,
"end": 213
} | class ____(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
| Node |
python | ansible__ansible | test/units/playbook/test_attribute.py | {
"start": 805,
"end": 1833
} | class ____(unittest.TestCase):
def setUp(self):
self.one = Attribute(priority=100)
self.two = Attribute(priority=0)
def test_eq(self):
self.assertTrue(self.one == self.one)
self.assertFalse(self.one == self.two)
def test_ne(self):
self.assertFalse(self.one != self.... | TestAttribute |
python | pytorch__pytorch | torch/distributed/_composable/contract.py | {
"start": 1021,
"end": 10921
} | class ____(Protocol, Generic[_P, _T, _TState]):
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ...
def state(self, module: nn.Module) -> _TState: ...
def contract(
state_cls: type[_TState] = _State, # type: ignore[assignment]
) -> Callable[
[Callable[Concatenate[_M, _P], _M]],
_C... | _ContractFn |
python | great-expectations__great_expectations | tests/expectations/test_condition_validators.py | {
"start": 4760,
"end": 5475
} | class ____:
"""Test that the validator applies to all BatchExpectation subclasses with row_condition."""
def test_validator_applies_to_core_expectations(self):
"""Test that expectations in core/ directory also get validated."""
column_1 = Column("column_1")
column_2 = Column("column_2")... | TestValidatorAppliesAcrossExpectations |
python | rq__rq | tests/test_registry.py | {
"start": 20432,
"end": 30174
} | class ____(RQTestCase):
def setUp(self):
super().setUp()
self.registry = StartedJobRegistry(connection=self.connection)
self.queue = Queue(connection=self.connection)
def test_job_deletion(self):
"""Ensure job is removed from StartedJobRegistry when deleted."""
worker = ... | TestStartedJobRegistry |
python | scikit-learn__scikit-learn | sklearn/decomposition/_base.py | {
"start": 482,
"end": 7314
} | class ____(
ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator, metaclass=ABCMeta
):
"""Base class for PCA methods.
Warning: This class should not be used directly.
Use derived classes instead.
"""
def get_covariance(self):
"""Compute data covariance with the generative m... | _BasePCA |
python | Textualize__textual | tests/command_palette/test_declare_sources.py | {
"start": 2669,
"end": 2730
} | class ____(ExampleCommandSource):
pass
| AnotherCommandSource |
python | openai__openai-python | src/openai/types/beta/realtime/rate_limits_updated_event.py | {
"start": 247,
"end": 670
} | class ____(BaseModel):
limit: Optional[int] = None
"""The maximum allowed value for the rate limit."""
name: Optional[Literal["requests", "tokens"]] = None
"""The name of the rate limit (`requests`, `tokens`)."""
remaining: Optional[int] = None
"""The remaining value before the limit is reache... | RateLimit |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_sqs.py | {
"start": 1449,
"end": 17522
} | class ____:
@pytest.fixture(autouse=True)
def _setup_test_cases(self):
self.default_op_kwargs = {
"task_id": "test_task",
"aws_conn_id": None,
"region_name": REGION_NAME,
"sqs_queue": QUEUE_URL,
}
self.sensor = SqsSensor(**self.default_op_k... | TestSqsSensor |
python | sphinx-doc__sphinx | sphinx/directives/patches.py | {
"start": 1683,
"end": 2800
} | class ____(tables.CSVTable): # type: ignore[misc]
"""The csv-table directive which searches a CSV file from Sphinx project's source
directory when an absolute path is given via :file: option.
"""
def run(self) -> list[Node]:
if 'file' in self.options and self.options['file'].startswith((SEP, o... | CSVTable |
python | kamyu104__LeetCode-Solutions | Python/most-expensive-item-that-can-not-be-bought.py | {
"start": 56,
"end": 504
} | class ____(object):
def mostExpensiveItem(self, primeOne, primeTwo):
"""
:type primeOne: int
:type primeTwo: int
:rtype: int
"""
# reference:
# - https://en.wikipedia.org/wiki/Coin_problem
# - https://mikebeneschan.medium.com/the-chicken-mcnugget-theor... | Solution |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 36107,
"end": 36515
} | class ____(IterableDataset):
def __init__(self, length):
self.length = length
def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
assert worker_info is not None
worker_id = worker_info.id
for _ in range(self.length // worker_info.num_workers):
... | TestMultiEpochDataset |
python | allegroai__clearml | examples/frameworks/fire/fire_class_cmd.py | {
"start": 131,
"end": 488
} | class ____(object):
def __init__(self, offset=1):
self._offset = offset
def add(self, x, y):
return x + y + self._offset
def multiply(self, x, y):
return x * y + self._offset
if __name__ == "__main__":
Task.init(project_name="examples", task_name="Fire class command")
fir... | BrokenCalculator |
python | cython__cython | Cython/Compiler/CmdLine.py | {
"start": 573,
"end": 1032
} | class ____(Action):
def __call__(self, parser, namespace, values, option_string=None):
options = dict(getattr(namespace, self.dest, {}))
for opt in values.split(','):
if '=' in opt:
n, v = opt.split('=', 1)
v = v.lower() not in ('false', 'f', '0', 'no')
... | ParseOptionsAction |
python | kamyu104__LeetCode-Solutions | Python/verify-preorder-serialization-of-a-binary-tree.py | {
"start": 29,
"end": 755
} | class ____(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
def split_iter(s, tok):
start = 0
for i in xrange(len(s)):
if s[i] == tok:
yield s[start:i]
s... | Solution |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 35011,
"end": 37434
} | class ____(TestCase):
def test_valid_path(self) -> None:
paths = [os.path.dirname(__file__)]
class Schema(Config):
option = c.ListOfPaths()
self.get_config(Schema, {'option': paths})
def test_missing_path(self) -> None:
paths = [os.path.join("does", "not", "exist",... | ListOfPathsTest |
python | pallets__werkzeug | examples/cupoftee/pages.py | {
"start": 2058,
"end": 2212
} | class ____(Page):
def get_response(self):
response = super().get_response()
response.status_code = 404
return response
| MissingPage |
python | openai__openai-python | src/openai/types/chat/chat_completion_function_tool.py | {
"start": 263,
"end": 445
} | class ____(BaseModel):
function: FunctionDefinition
type: Literal["function"]
"""The type of the tool. Currently, only `function` is supported."""
| ChatCompletionFunctionTool |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/simple/datamodels/login.py | {
"start": 1025,
"end": 1160
} | class ____(StrictBaseModel):
"""Login serializer for post bodies."""
username: str = Field()
password: str = Field()
| LoginBody |
python | giampaolo__psutil | tests/test_connections.py | {
"start": 3228,
"end": 6880
} | class ____(ConnectionTestCase):
"""Tests sockets which are open but not connected to anything."""
def get_conn_from_sock(self, sock):
cons = this_proc_net_connections(kind='all')
smap = {c.fd: c for c in cons}
if NETBSD or FREEBSD:
# NetBSD opens a UNIX socket to /var/log/ru... | TestUnconnectedSockets |
python | facebookresearch__faiss | tests/test_residual_quantizer.py | {
"start": 41841,
"end": 43849
} | class ____(unittest.TestCase):
def eval_index_accuracy(self, factory_key):
ds = datasets.SyntheticDataset(32, 1000, 1000, 100)
index = faiss.index_factory(ds.d, factory_key)
index.train(ds.get_train())
index.add(ds.get_database())
inters = []
for nprobe in 1, 2, 5,... | TestIndexIVFProductResidualQuantizer |
python | explosion__spaCy | spacy/lang/el/__init__.py | {
"start": 696,
"end": 1330
} | class ____(Language):
lang = "el"
Defaults = GreekDefaults
@Greek.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={
"model": None,
"mode": "rule",
"overwrite": False,
"scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"},
},
default_score_weigh... | Greek |
python | pytorch__pytorch | test/jit/test_upgraders.py | {
"start": 441,
"end": 14019
} | class ____(JitTestCase):
def _load_model_version(self, loaded_model):
buffer = io.BytesIO()
torch.jit.save(loaded_model, buffer)
buffer.seek(0)
zipped_model = zipfile.ZipFile(buffer)
# there was a change in how we store version number
# in a package between version 3 ... | TestUpgraders |
python | PrefectHQ__prefect | tests/runner/test_storage.py | {
"start": 5015,
"end": 30636
} | class ____:
def test_adheres_to_runner_storage_interface(self):
assert isinstance(GitRepository, RunnerStorage)
async def test_init_no_credentials(self, mock_run_process: AsyncMock):
repo = GitRepository(url="https://github.com/org/repo.git")
await repo.pull_code()
# should be ... | TestGitRepository |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 1304,
"end": 2448
} | class ____(ModelOutput):
r"""
cls_token_value (`torch.FloatTensor` of shape `(batch_size, 1, hidden_size)`):
Classification token at the output of the last layer of the model.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
cls_token_value: Optional[torch.FloatTensor] = None
h... | BaseModelOutputWithCLSToken |
python | streamlit__streamlit | lib/tests/streamlit/runtime/fragment_test.py | {
"start": 1505,
"end": 3492
} | class ____(unittest.TestCase):
"""Sanity checks for MemoryFragmentStorage.
These tests may be a bit excessive given that MemoryFragmentStorage is currently
just a wrapper around a Python dict, but we include them for completeness.
"""
def setUp(self):
self._storage = MemoryFragmentStorage(... | MemoryFragmentStorageTest |
python | python-openxml__python-docx | src/docx/image/constants.py | {
"start": 54,
"end": 1885
} | class ____:
"""JPEG marker codes."""
TEM = b"\x01"
DHT = b"\xc4"
DAC = b"\xcc"
JPG = b"\xc8"
SOF0 = b"\xc0"
SOF1 = b"\xc1"
SOF2 = b"\xc2"
SOF3 = b"\xc3"
SOF5 = b"\xc5"
SOF6 = b"\xc6"
SOF7 = b"\xc7"
SOF9 = b"\xc9"
SOFA = b"\xca"
SOFB = b"\xcb"
SOFD = b"\x... | JPEG_MARKER_CODE |
python | gevent__gevent | src/greentest/3.13/test_ssl.py | {
"start": 194279,
"end": 207924
} | class ____(unittest.TestCase):
def test_pha_setter(self):
protocols = [
ssl.PROTOCOL_TLS_SERVER, ssl.PROTOCOL_TLS_CLIENT
]
for protocol in protocols:
ctx = ssl.SSLContext(protocol)
self.assertEqual(ctx.post_handshake_auth, False)
ctx.post_hand... | TestPostHandshakeAuth |
python | kamyu104__LeetCode-Solutions | Python/range-sum-query-mutable.py | {
"start": 1453,
"end": 4621
} | class ____(object):
def __init__(self, nums,
query_fn=lambda x, y: x+y,
update_fn=lambda x, y: y,
default_val=0):
"""
initialize your data structure here.
:type nums: List[int]
"""
N = len(nums)
self.__original_length... | NumArray2 |
python | pypa__hatch | tests/python/test_resolve.py | {
"start": 2952,
"end": 7320
} | class ____:
def test_legacy_option(self, current_arch):
variant = "v4"
with EnvVars({"HATCH_PYTHON_VARIANT_LINUX": variant}):
dist = get_distribution("3.12")
if current_arch != "x86_64":
assert variant not in dist.source
else:
assert variant in di... | TestVariantCPU |
python | allegroai__clearml | clearml/binding/artifacts.py | {
"start": 1311,
"end": 9895
} | class ____(object):
"""
Read-Only Artifact object
"""
_not_set = object()
@property
def url(self) -> str:
"""
:return: The URL of uploaded artifact.
"""
return self._url
@property
def name(self) -> str:
"""
:return: The name of artifact.... | Artifact |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 10591,
"end": 10653
} | class ____(SubClassBoringModel):
pass
| SubSubClassBoringModel |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 71809,
"end": 72003
} | class ____(Union):
_fields_ = [
('str', c_char * NVML_DEVICE_UUID_ASCII_LEN),
('bytes', c_ubyte * NVML_DEVICE_UUID_BINARY_LEN),
]
nvmlUUID_v1 = 0x1000034
| c_nvmlUUIDValue_t |
python | nedbat__coveragepy | coverage/plugin.py | {
"start": 12299,
"end": 13462
} | class ____:
"""Data for a region of code found by :meth:`FileReporter.code_regions`."""
#: The kind of region, like `"function"` or `"class"`. Must be one of the
#: singular values returned by :meth:`FileReporter.code_region_kinds`.
kind: str
#: The name of the region. For example, a function or c... | CodeRegion |
python | chroma-core__chroma | chromadb/telemetry/opentelemetry/grpc.py | {
"start": 103,
"end": 698
} | class ____(
collections.namedtuple(
"_ClientCallDetails", ("method", "timeout", "metadata", "credentials")
),
grpc.ClientCallDetails,
):
pass
def _encode_span_id(span_id: int) -> str:
return binascii.hexlify(span_id.to_bytes(8, "big")).decode()
def _encode_trace_id(trace_id: int) -> str:... | _ClientCallDetails |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-document360/llama_index/readers/document360/errors.py | {
"start": 76,
"end": 184
} | class ____(Exception):
pass
__all__ = ["RetryError", "HTTPError", "RateLimitException"]
| RateLimitException |
python | pallets__itsdangerous | src/itsdangerous/exc.py | {
"start": 2561,
"end": 3201
} | class ____(BadData):
"""Raised if a payload is invalid. This could happen if the payload
is loaded despite an invalid signature, or if there is a mismatch
between the serializer and deserializer. The original exception
that occurred during loading is stored on as :attr:`original_error`.
.. versiona... | BadPayload |
python | doocs__leetcode | solution/0200-0299/0242.Valid Anagram/Solution.py | {
"start": 0,
"end": 264
} | class ____:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return False
return True
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format13.py | {
"start": 345,
"end": 4602
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.