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 | readthedocs__readthedocs.org | readthedocs/subscriptions/tests/test_products.py | {
"start": 189,
"end": 2073
} | class ____(TestCase):
def test_add_feature(self):
feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=1)
feature_b = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=2)
feature_c = feature_a + feature_b
self.assertEqual(feature_c.unlimited, False)
self.assertEqual(fea... | TestRTDProductFeature |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 30202,
"end": 30647
} | class ____(Sized, Iterable[AbstractResource], Container[AbstractResource]):
def __init__(self, resources: list[AbstractResource]) -> None:
self._resources = resources
def __len__(self) -> int:
return len(self._resources)
def __iter__(self) -> Iterator[AbstractResource]:
yield from ... | ResourcesView |
python | django__django | tests/queries/models.py | {
"start": 9454,
"end": 9494
} | class ____(ObjectA):
pass
| ChildObjectA |
python | scikit-learn__scikit-learn | sklearn/linear_model/_stochastic_gradient.py | {
"start": 17141,
"end": 31423
} | class ____(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta):
loss_functions = {
"hinge": (Hinge, 1.0),
"squared_hinge": (SquaredHinge, 1.0),
"perceptron": (Hinge, 0.0),
"log_loss": (CyHalfBinomialLoss,),
"modified_huber": (ModifiedHuber,),
"squared_error": (CyHalfSq... | BaseSGDClassifier |
python | gevent__gevent | src/greentest/3.12/test_subprocess.py | {
"start": 70872,
"end": 79708
} | class ____(BaseTestCase):
def run_python(self, code, **kwargs):
"""Run Python code in a subprocess using subprocess.run"""
argv = [sys.executable, "-c", code]
return subprocess.run(argv, **kwargs)
def test_returncode(self):
# call() function with sequence argument
cp = s... | RunFuncTestCase |
python | django__django | tests/admin_widgets/models.py | {
"start": 4128,
"end": 4633
} | class ____(models.Model):
"""
A model with a FK to itself. It won't be registered with the admin, so the
corresponding raw ID widget won't have a magnifying glass link to select
related instances (rendering will be called programmatically in this case).
"""
name = models.CharField(max_length=20... | Individual |
python | spyder-ide__spyder | spyder/plugins/pythonpath/plugin.py | {
"start": 743,
"end": 4490
} | class ____(SpyderPluginV2):
"""
Pythonpath manager plugin.
"""
NAME = "pythonpath_manager"
REQUIRES = [Plugins.Toolbar, Plugins.MainMenu]
OPTIONAL = [Plugins.Projects]
CONTAINER_CLASS = PythonpathContainer
CONF_SECTION = NAME
CONF_FILE = False
sig_pythonpath_changed = Signal(ob... | PythonpathManager |
python | dask__dask | dask/utils.py | {
"start": 19285,
"end": 33396
} | class ____:
"""Simple single dispatch."""
def __init__(self, name=None):
self._lookup = {}
self._lazy = {}
if name:
self.__name__ = name
def register(self, type, func=None):
"""Register dispatch of `func` on arguments of type `type`"""
def wrapper(func)... | Dispatch |
python | numpy__numpy | numpy/ma/core.py | {
"start": 72969,
"end": 78959
} | class ____:
"""
Handle the string used to represent missing data in a masked array.
"""
def __init__(self, display):
"""
Create the masked_print_option object.
"""
self._display = display
self._enabled = True
def display(self):
"""
Display ... | _MaskedPrintOption |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 13765,
"end": 14097
} | class ____(torch.nn.Module):
"""Once the below lazy module is initialized with its first input,
it is transformed into this module."""
param: Parameter
def __init__(self) -> None:
super().__init__()
self.register_parameter("param", None)
def forward(self, x):
return x
| MaterializedModule |
python | Textualize__textual | tests/test_disabled.py | {
"start": 415,
"end": 2865
} | class ____(App[None]):
"""Application for testing Widget.disabled."""
def compose(self) -> ComposeResult:
"""Compose the child widgets."""
yield VerticalScroll(
Button(),
DataTable(),
DirectoryTree("."),
Input(),
ListView(),
... | DisableApp |
python | celery__celery | celery/contrib/testing/worker.py | {
"start": 766,
"end": 7217
} | class ____(worker.WorkController):
"""Worker that can synchronize on being fully started."""
# When this class is imported in pytest files, prevent pytest from thinking
# this is a test class
__test__ = False
logger_queue = None
def __init__(self, *args, **kwargs):
# type: (*Any, **An... | TestWorkController |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1113713,
"end": 1115255
} | class ____(sgqlc.types.Type, Node, RepositoryNode):
"""A thread of comments on a commit."""
__schema__ = github_schema
__field_names__ = ("comments", "commit", "path", "position")
comments = sgqlc.types.Field(
sgqlc.types.non_null(CommitCommentConnection),
graphql_name="comments",
... | CommitCommentThread |
python | scikit-learn__scikit-learn | sklearn/model_selection/tests/test_validation.py | {
"start": 64053,
"end": 72199
} | class ____(RandomForestClassifier):
# None of the current multioutput-multiclass estimators have
# decision function methods. Create a mock decision function
# to test the cross_val_predict function's handling of this case.
def decision_function(self, X):
probs = self.predict_proba(X)
ms... | RFWithDecisionFunction |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 26475,
"end": 27571
} | class ____(ModelTestCase):
requires = [MMA, MMB, MMC]
def test_resolve_multimodel_query(self):
MMA.insert_many([('k0', 0), ('k1', 1)]).execute()
MMB.insert_many([('k10',), ('k11',)]).execute()
MMC.insert_many([('k20', 20, 'a'), ('k21', 21, 'b')]).execute()
mma = MMA.select(MMA.... | TestResolveMultiModelQuery |
python | pytorch__pytorch | torch/export/_unlift.py | {
"start": 17121,
"end": 33186
} | class ____(torch.fx.GraphModule, metaclass=_StatefulGraphModuleFactory):
def __init__(self, root, graph, range_constraints=None):
super().__init__(root, graph)
# Need to fix up non-persistent buffers.
self.range_constraints = range_constraints or []
self.validate_inputs = True
def ... | _StatefulGraphModule |
python | realpython__materials | asterioids-pygame-project/source_code_step_4/space_rocks/game.py | {
"start": 76,
"end": 1266
} | class ____:
def __init__(self):
self._init_pygame()
self.screen = pygame.display.set_mode((800, 600))
self.background = load_sprite("space", False)
self.clock = pygame.time.Clock()
self.spaceship = GameObject(
(400, 300), load_sprite("spaceship"), (0, 0)
)... | SpaceRocks |
python | kamyu104__LeetCode-Solutions | Python/minimum-numbers-of-function-calls-to-make-target-array.py | {
"start": 33,
"end": 496
} | class ____(object):
def minOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def popcount(n):
result = 0
while n:
n &= n-1
result += 1
return result
result, max_len = 0, 1
for... | Solution |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/obscure_tito.py | {
"start": 335,
"end": 694
} | class ____(C):
def update(self, parameter):
...
def taint_parameter(self, tainted_parameter):
...
def test_obscure_tito():
c = C()
c.update(_test_source())
return c
def test_obscure_return():
c = C()
return c.update(_test_source())
def test_obscure_sink(parameter):
... | D |
python | openai__openai-python | src/openai/_response.py | {
"start": 18334,
"end": 18786
} | class ____(APIResponse[bytes]):
def stream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
"""Streams the output to the given file.
Accepts a filename or any path-like object, e.g. pathlib.Path
"""
with op... | StreamedBinaryAPIResponse |
python | openai__openai-python | src/openai/_client.py | {
"start": 35432,
"end": 39867
} | class ____:
_client: OpenAI
def __init__(self, client: OpenAI) -> None:
self._client = client
@cached_property
def completions(self) -> completions.CompletionsWithStreamingResponse:
from .resources.completions import CompletionsWithStreamingResponse
return CompletionsWithStrea... | OpenAIWithStreamedResponse |
python | numba__numba | numba/cuda/tests/nocuda/test_import.py | {
"start": 68,
"end": 1641
} | class ____(unittest.TestCase):
def test_no_impl_import(self):
"""
Tests that importing cuda doesn't trigger the import of modules
containing lowering implementation that would likely install things in
the builtins registry and have side effects impacting other targets.
"""
... | TestImport |
python | realpython__materials | python-all-attribute/webreader.py | {
"start": 323,
"end": 472
} | class ____:
def __init__(self, page):
self.response = _fetch_page(page)
def get_content(self):
return self.response.text
| WebPage |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py | {
"start": 904,
"end": 1014
} | class ____:
def __hash__(self):
print("raise some error")
raise NotImplementedError
| HashWrong6 |
python | networkx__networkx | networkx/algorithms/approximation/tests/test_traveling_salesman.py | {
"start": 5293,
"end": 9438
} | class ____(TestBase):
tsp = staticmethod(nx_app.simulated_annealing_tsp)
def test_simulated_annealing_directed(self):
cycle = self.tsp(self.DG, "greedy", source="D", seed=42)
cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle))
validate_solution(cycle, cost, self.DG_cycle... | TestSimulatedAnnealingTSP |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 826020,
"end": 826428
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("OrganizationInvitation", ... | OrganizationInvitationEdge |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 3433,
"end": 4348
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter by flows by deployment"""
is_null_: Optional[bool] = Field(
default=None,
description="If true, only include flows without deployments",
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpre... | FlowFilterDeployment |
python | kamyu104__LeetCode-Solutions | Python/tree-diameter.py | {
"start": 55,
"end": 1092
} | class ____(object):
def treeDiameter(self, edges):
"""
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs():
result = 0
stk = [(1, (0, -1, [0]))]
while stk:
step, args = stk.pop()
if step == 1:
... | Solution |
python | apache__avro | lang/py/avro/codecs.py | {
"start": 1860,
"end": 2835
} | class ____(abc.ABC):
"""Abstract base class for all Avro codec classes."""
@staticmethod
@abc.abstractmethod
def compress(data: bytes) -> Tuple[bytes, int]:
"""Compress the passed data.
:param data: a byte string to be compressed
:type data: str
:rtype: tuple
:... | Codec |
python | gevent__gevent | src/gevent/monkey/_patch_thread_lt313.py | {
"start": 224,
"end": 3182
} | class ____(BasePatcher):
def patch_active_threads(self):
from gevent.threading import main_native_thread
threading_mod = self.threading_mod
for thread in threading_mod._active.values():
if thread == main_native_thread():
continue
thread.join = self._m... | Patcher |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 20603,
"end": 21491
} | class ____(Parser, metaclass=abc.ABCMeta):
"""Base class for composite argument parsers which parse a type name, a colon and then parse results based on the type given by the type name."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]: # pylint: disable=unused-argument
"""Return a dic... | TypeParser |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 132149,
"end": 133718
} | class ____(CythonTransform):
def visit_ModuleNode(self, node):
self.directives = node.directives
self.imported_names = set() # hack, see visit_FromImportStatNode()
self.scope = node.scope
self.visitchildren(node)
return node
def visit_DefNode(self, node):
if (s... | AutoCpdefFunctionDefinitions |
python | paramiko__paramiko | paramiko/_winapi.py | {
"start": 7308,
"end": 7351
} | class ____:
TOKEN_QUERY = 0x8
| TokenAccess |
python | python__mypy | mypyc/options.py | {
"start": 49,
"end": 3020
} | class ____:
def __init__(
self,
strip_asserts: bool = False,
multi_file: bool = False,
verbose: bool = False,
separate: bool = False,
target_dir: str | None = None,
include_runtime_files: bool | None = None,
capi_version: tuple[int, int] | None = None,... | CompilerOptions |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 155971,
"end": 158804
} | class ____:
def test_broadcast_in_args(self):
# gh-5881
arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),
np.empty((5, 1, 7))]
mits = [np.broadcast(*arrs),
np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])),
np.broadcas... | TestBroadcast |
python | cython__cython | docs/examples/userguide/buffer/matrix_with_buffer.py | {
"start": 139,
"end": 1816
} | class ____:
ncols: cython.Py_ssize_t
shape: cython.Py_ssize_t[2]
strides: cython.Py_ssize_t[2]
v: vector[cython.float]
def __cinit__(self, ncols: cython.Py_ssize_t):
self.ncols = ncols
def add_row(self):
"""Adds a row, initially zero-filled."""
self.v.resize(self.v.size... | Matrix |
python | huggingface__transformers | examples/modular-transformers/modeling_dummy_bert.py | {
"start": 21103,
"end": 21811
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.h... | DummyBertPredictionHeadTransform |
python | readthedocs__readthedocs.org | readthedocs/oauth/services/base.py | {
"start": 698,
"end": 982
} | class ____(Exception):
"""Error raised when a service failed to sync."""
INVALID_OR_REVOKED_ACCESS_TOKEN = _(
"Our access to your following accounts was revoked: {provider}. "
"Please, reconnect them from your social account connections."
)
| SyncServiceError |
python | pdm-project__pdm | src/pdm/models/versions.py | {
"start": 355,
"end": 5908
} | class ____:
"""A loosely semantic version implementation that allows '*' in version part.
This class is designed for Python specifier set merging only, hence up to 3 version
parts are kept, plus optional prerelease suffix.
This is a slightly different purpose than packaging.version.Version which is
... | Version |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 38102,
"end": 43328
} | class ____(BaseTestCase):
FORMAT_CONVERT = {
'yearlong': '%Y',
'monthlong': '%m',
'daylong': '%d',
'hourslong': '%H',
'minuteslong': '%M',
'secondslong': '%S',
'secondslong0': '%S',
}
def test_ods_export_import_set(self):
date = dt.date(2019, ... | ODSTests |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py | {
"start": 353,
"end": 591
} | class ____(GQLResult):
current_manifest: Optional[DeferredManifestFragment] = Field(
alias="currentManifest"
)
FetchArtifactManifest.model_rebuild()
FetchArtifactManifestArtifact.model_rebuild()
| FetchArtifactManifestArtifact |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 2138,
"end": 4413
} | class ____:
def test_1d(self):
a = [1, 2, 3, 4]
desired = np.power(1*2*3*4, 1./4.)
check_equal_gmean(a, desired, rtol=1e-14)
def test_1d_ma(self):
# Test a 1d masked array
a = ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
desired = 45.2872868812
ch... | TestGeoMean |
python | ray-project__ray | python/ray/serve/tests/test_metrics_2.py | {
"start": 23228,
"end": 34087
} | class ____:
def test_queued_queries_basic(self, metrics_start_shutdown):
signal = SignalActor.options(name="signal123").remote()
timeseries = PrometheusTimeseries()
serve.run(WaitForSignal.options(max_ongoing_requests=1).bind(), name="app1")
# First call should get assigned to a rep... | TestHandleMetrics |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 19840,
"end": 20273
} | class ____(WrapperLine):
wrapper: PythonWrapperCodegen
node: Union[BufferLike, ir.TorchBindObject]
def codegen(self, code: IndentedBuffer) -> None:
assert self.node.get_name() not in V.graph.removed_buffers
code.writeline(self.wrapper.make_buffer_free(self.node))
def codegen_fx(self, c... | FreeLine |
python | getsentry__sentry | tests/sentry/uptime/rdap/test_tasks.py | {
"start": 203,
"end": 1062
} | class ____(UptimeTestCase):
@mock.patch(
"sentry.uptime.rdap.tasks.resolve_rdap_network_details",
)
def test(self, mock_fetch_subscription_rdap_info: mock.MagicMock) -> None:
test_info: DomainAddressDetails = {
"handle": "TEST-HANDLE",
"owner_name": "Rick Sanchez",
... | RDAPTasksTest |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/codeeditor/tests/assets/black_max_line.py | {
"start": 408,
"end": 663
} | class ____:
def __init__(
self,
):
super().__init__()
self.x = 2
def method3(
self,
):
pass
def method2(
self,
):
pass
def method1(
self,
):
pass
| Class1 |
python | doocs__leetcode | solution/2600-2699/2611.Mice and Cheese/Solution.py | {
"start": 0,
"end": 292
} | class ____:
def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:
n = len(reward1)
idx = sorted(range(n), key=lambda i: reward1[i] - reward2[i], reverse=True)
return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:])
| Solution |
python | langchain-ai__langchain | libs/core/langchain_core/example_selectors/length_based.py | {
"start": 390,
"end": 3366
} | class ____(BaseExampleSelector, BaseModel):
"""Select examples based on length."""
examples: list[dict]
"""A list of the examples that the prompt template expects."""
example_prompt: PromptTemplate
"""Prompt template used to format the examples."""
get_text_length: Callable[[str], int] = _get... | LengthBasedExampleSelector |
python | vyperlang__vyper | vyper/venom/passes/load_elimination.py | {
"start": 1835,
"end": 5763
} | class ____(IRAnalysis):
InstToLattice = dict[IRInstruction, Lattice]
lattice: dict[Effects | str, InstToLattice]
cfg: CFGAnalysis
eff_bb_lattice: dict[Effects | str, dict[IRBasicBlock, Lattice]]
def analyze(self):
self.cfg = self.analyses_cache.request_analysis(CFGAnalysis)
self.dfg... | LoadAnalysis |
python | joblib__joblib | joblib/hashing.py | {
"start": 1158,
"end": 1304
} | class ____(object):
"""Class used to hash objects that won't normally pickle"""
def __init__(self, *args):
self.args = args
| _MyHash |
python | django__django | django/contrib/gis/geos/geometry.py | {
"start": 886,
"end": 23439
} | class ____(GEOSBase):
_GEOS_CLASSES = None
ptr_type = GEOM_PTR
destructor = capi.destroy_geom
has_cs = False # Only Point, LineString, LinearRing have coordinate sequences
def __init__(self, ptr, cls):
self._ptr = ptr
# Setting the class type (e.g., Point, Polygon, etc.)
... | GEOSGeometryBase |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/extractor/extractor_test.py | {
"start": 867,
"end": 2746
} | class ____(absltest.TestCase):
def test_exported_docstring(self):
exporter = exported_api.ExportedApi()
p = extractor.Parser(
exporter,
decorator='tf.tf_export',
api_name='tf',
)
p.process(
'test.py',
'''# 1
"""this is an exported docstring.
API docstring: tf.t... | ParserTest |
python | mlflow__mlflow | mlflow/utils/databricks_utils.py | {
"start": 44616,
"end": 54490
} | class ____(NamedTuple):
is_client_image: bool
major: int
minor: int
@classmethod
def parse(cls, databricks_runtime: str | None = None):
dbr_version = databricks_runtime or get_databricks_runtime_version()
try:
dbr_version_splits = dbr_version.split(".", maxsplit=2)
... | DatabricksRuntimeVersion |
python | optuna__optuna | optuna/samplers/nsgaii/_crossovers/_spx.py | {
"start": 295,
"end": 2191
} | class ____(BaseCrossover):
"""Simplex Crossover operation used by :class:`~optuna.samplers.NSGAIISampler`.
Uniformly samples child individuals from within a single simplex
that is similar to the simplex produced by the parent individual.
For further information about SPX crossover, please refer to the ... | SPXCrossover |
python | google__jax | jax/_src/linear_util.py | {
"start": 4082,
"end": 4582
} | class ____:
__slots__ = ('_store',)
def __init__(self):
self._store = Store()
@property
def val(self):
return self._store.val
def store(self, val):
try:
self._store.store(val)
except StoreException as e:
try:
okay = bool(self._store._val == val)
except:
rai... | EqualStore |
python | celery__celery | t/unit/worker/test_strategy.py | {
"start": 521,
"end": 1807
} | class ____:
def setup_method(self):
self.message = Mock(name='message')
self.body = {
'args': (1,),
'kwargs': {'foo': 'baz'},
'utc': False,
'taskset': '123',
}
def test_message_without_args(self):
self.body.pop('args')
bod... | test_proto1_to_proto2 |
python | sphinx-doc__sphinx | sphinx/ext/napoleon/docstring.py | {
"start": 7301,
"end": 39447
} | class ____:
"""Convert Google style docstrings to reStructuredText.
Parameters
----------
docstring : :obj:`str` or :obj:`list` of :obj:`str`
The docstring to parse, given either as a string or split into
individual lines.
config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.co... | GoogleDocstring |
python | allegroai__clearml | clearml/utilities/process/mp.py | {
"start": 16901,
"end": 31945
} | class ____(object):
# If we need multiple monitoring contexts (i.e. subprocesses) this will become a dict
_main_process = None
_main_process_proc_obj = None
_main_process_task_id = None
_parent_pid = None
_sub_process_started = None
_at_exit = False
_instances: Dict[int, List["Background... | BackgroundMonitor |
python | scrapy__scrapy | tests/test_downloadermiddleware.py | {
"start": 1985,
"end": 4354
} | class ____(TestManagerBase):
"""Tests default behavior with default settings"""
@deferred_f_from_coro_f
async def test_request_response(self):
req = Request("http://example.com/index.html")
resp = Response(req.url, status=200)
async with self.get_mwman() as mwman:
ret = ... | TestDefaults |
python | PyCQA__pylint | tests/functional/n/name/name_preset_snake_case.py | {
"start": 269,
"end": 607
} | class ____: # [invalid-name]
def __init__(self, arg_x):
self._my_secret_x = arg_x
@property
def my_public_x(self):
return self._my_secret_x * 2
def __eq__(self, other):
return isinstance(other, MyClass) and self.my_public_x == other.my_public_x
def sayHello(): # [invalid-na... | MyClass |
python | gevent__gevent | src/gevent/tests/test__hub.py | {
"start": 3175,
"end": 4018
} | class ____(greentest.TestCase):
def test(self):
waiter = Waiter()
self.assertEqual(str(waiter), '<Waiter greenlet=None>')
waiter.switch(25)
self.assertEqual(str(waiter), '<Waiter greenlet=None value=25>')
self.assertEqual(waiter.get(), 25)
waiter = Waiter()
... | TestWaiter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format10.py | {
"start": 315,
"end": 1779
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format10.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | joblib__joblib | joblib/_memmapping_reducer.py | {
"start": 3809,
"end": 12379
} | class ____:
"""A variant of weakref.WeakKeyDictionary for unhashable numpy arrays.
This datastructure will be used with numpy arrays as obj keys, therefore we
do not use the __get__ / __set__ methods to avoid any conflict with the
numpy fancy indexing syntax.
"""
def __init__(self):
se... | _WeakArrayKeyMap |
python | viewflow__viewflow | tests/contrib/__init__.py | {
"start": 310,
"end": 1794
} | class ____(TransactionTestCase):
SETTINGS = "cookbook.workflow101.config"
def setUp(self):
"""Start celery worker connection the the test database"""
env = os.environ.copy()
database_url = env["DATABASE_URL"]
env["DATABASE_URL"] = "{}/{}".format(
database_url[: datab... | CeleryTestCase |
python | huggingface__transformers | src/transformers/models/dpr/modeling_dpr.py | {
"start": 8989,
"end": 13321
} | class ____(DPRPretrainedContextEncoder):
def __init__(self, config: DPRConfig):
super().__init__(config)
self.config = config
self.ctx_encoder = DPREncoder(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
s... | DPRContextEncoder |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_0.py | {
"start": 48,
"end": 578
} | class ____[_T]:
buf: list[_T]
def append(self, t: _T):
self.buf.append(t)
# simple case, replace _T in signature and body
def second[_T](var: tuple[_T]) -> _T:
y: _T = var[1]
return y
# one diagnostic for each variable, comments are preserved
def many_generics[
_T, # first generic
... | Generic |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 88421,
"end": 88627
} | class ____:
xlDataFieldScope = 2 # from enum XlPivotConditionScope
xlFieldsScope = 1 # from enum XlPivotConditionScope
xlSelectionScope = 0 # from enum XlPivotConditionScope
| PivotConditionScope |
python | huggingface__transformers | src/transformers/models/sam3/image_processing_sam3_fast.py | {
"start": 1824,
"end": 16146
} | class ____(ImagesKwargs, total=False):
r"""
mask_size (`dict[str, int]`, *optional*):
The size `{"height": int, "width": int}` to resize the segmentation maps to.
"""
mask_size: dict[str, int]
def _compute_stability_score(masks: "torch.Tensor", mask_threshold: float, stability_score_offset: i... | Sam3FastImageProcessorKwargs |
python | getsentry__sentry | src/sentry/integrations/perforce/repository.py | {
"start": 532,
"end": 2915
} | class ____(IntegrationRepositoryProvider):
"""Repository provider for Perforce integration."""
name = "Perforce"
repo_provider = "perforce"
def get_repository_data(
self, organization: Organization, config: dict[str, Any]
) -> Mapping[str, Any]:
"""
Validate and return repo... | PerforceRepositoryProvider |
python | simplejson__simplejson | simplejson/tests/test_default.py | {
"start": 58,
"end": 221
} | class ____(TestCase):
def test_default(self):
self.assertEqual(
json.dumps(type, default=repr),
json.dumps(repr(type)))
| TestDefault |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_run.py | {
"start": 14735,
"end": 17604
} | class ____:
def test_template_fields(self):
operator = CloudRunCreateServiceOperator(
task_id=TASK_ID,
project_id=PROJECT_ID,
region=REGION,
service=SERVICE,
service_name=SERVICE_NAME,
)
_assert_common_template_fields(operator.temp... | TestCloudRunCreateServiceOperator |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 35184,
"end": 41210
} | class ____(BaseTestCase):
def _run_and_join(self, script):
script = """if 1:
import sys, os, time, threading
# a thread, which waits for the main program to terminate
def joiningfunc(mainthread):
mainthread.join()
print('end of thread')
... | ThreadJoinOnShutdown |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/solids.py | {
"start": 1428,
"end": 2862
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
description = graphene.String()
type = graphene.NonNull(GrapheneDagsterType)
metadata_entries = non_null_list(GrapheneMetadataEntry)
class Meta:
name = "InputDefinition"
def __init__(self, represented_job: Repres... | GrapheneInputDefinition |
python | django__django | tests/user_commands/management/commands/required_option.py | {
"start": 54,
"end": 349
} | class ____(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("-n", "--need-me", required=True)
parser.add_argument("-t", "--need-me-too", required=True, dest="needme2")
def handle(self, *args, **options):
self.stdout.write(",".join(options))
| Command |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_rich_string05.py | {
"start": 315,
"end": 1123
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("rich_string05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | google__pytype | pytype/tests/test_typing2.py | {
"start": 26915,
"end": 33984
} | class ____(test_base.BaseTest):
"""Tests for typing.Literal in source code."""
def test_basic(self):
ty = self.Infer("""
from typing_extensions import Literal
x1: Literal["hello"]
x2: Literal[b"hello"]
x3: Literal[u"hello"]
x4: Literal[0]
x5: Literal[True]
x6: Literal[... | LiteralTest |
python | coleifer__peewee | tests/schema.py | {
"start": 31910,
"end": 32741
} | class ____(ModelDatabaseTestCase):
database = get_in_memory_db()
requires = [TMKV]
def test_create_table_as_sql(self):
query = (TMKV
.select(TMKV.key, TMKV.value.alias('val'))
.where(TMKV.extra < 4))
ctx = TMKV._schema._create_table_as('tmkv_new', query)
... | TestCreateTableAsSQL |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/compression_ops_test.py | {
"start": 2973,
"end": 6746
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(element=_test_objects())) +
combinations.times(
test_base.v2_eager_only_combinations(),
combin... | CompressionOpsTest |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/snippets/expect_column_max_to_be_between_custom.py | {
"start": 1540,
"end": 3696
} | class ____(ColumnAggregateMetricProvider):
# </snippet>
"""MetricProvider Class for Custom Aggregate Max MetricProvider"""
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py metric_name">
metric_name = "column.custom_max"
# </snippet>
# <snippet name="docs... | ColumnCustomMax |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_call_code_done_event.py | {
"start": 217,
"end": 806
} | class ____(BaseModel):
code: str
"""The final code snippet output by the code interpreter."""
item_id: str
"""The unique identifier of the code interpreter tool call item."""
output_index: int
"""The index of the output item in the response for which the code is finalized."""
sequence_num... | ResponseCodeInterpreterCallCodeDoneEvent |
python | Netflix__metaflow | metaflow/plugins/cards/card_server.py | {
"start": 952,
"end": 2963
} | class ____(Thread):
"""
A thread that watches for new runs and sends the run_id to the
card server when a new run is detected. It observes the `latest_run`
file in the `.metaflow/<flowname>` directory.
"""
def __init__(self, flow_name, connection: Connection):
super().__init__()
... | RunWatcher |
python | sympy__sympy | sympy/vector/integrals.py | {
"start": 533,
"end": 6837
} | class ____(Basic):
"""
Represents integral of a scalar or vector field
over a Parametric Region
Examples
========
>>> from sympy import cos, sin, pi
>>> from sympy.vector import CoordSys3D, ParametricRegion, ParametricIntegral
>>> from sympy.abc import r, t, theta, phi
>>> C = Coo... | ParametricIntegral |
python | tensorflow__tensorflow | tensorflow/python/autograph/operators/py_builtins_test.py | {
"start": 1480,
"end": 1595
} | class ____:
def overridden_method(self, x):
return x + 20
@test_util.run_all_in_graph_and_eager_modes
| TestBase |
python | django__django | tests/admin_docs/tests.py | {
"start": 462,
"end": 643
} | class ____(SimpleTestCase):
pass
@override_settings(ROOT_URLCONF="admin_docs.urls")
@modify_settings(INSTALLED_APPS={"append": "django.contrib.admindocs"})
| AdminDocsSimpleTestCase |
python | pyca__cryptography | tests/hazmat/asn1/test_serialization.py | {
"start": 6554,
"end": 18605
} | class ____:
def test_ok_sequence_single_field(self) -> None:
@asn1.sequence
@_comparable_dataclass
class Example:
foo: int
assert_roundtrips([(Example(foo=9), b"\x30\x03\x02\x01\x09")])
def test_ok_sequence_multiple_fields(self) -> None:
@asn1.sequence
... | TestSequence |
python | doocs__leetcode | solution/3200-3299/3289.The Two Sneaky Numbers of Digitville/Solution2.py | {
"start": 0,
"end": 384
} | class ____:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
n = len(nums) - 2
xx = nums[n] ^ nums[n + 1]
for i in range(n):
xx ^= i ^ nums[i]
k = xx.bit_length() - 1
ans = [0, 0]
for x in nums:
ans[x >> k & 1] ^= x
for i in ra... | Solution |
python | pydantic__pydantic | pydantic/errors.py | {
"start": 4496,
"end": 4816
} | class ____(PydanticUserError):
"""An error raised during failures to generate a `CoreSchema` for some type.
Attributes:
message: Description of the error.
"""
def __init__(self, message: str) -> None:
super().__init__(message, code='schema-for-unknown-type')
| PydanticSchemaGenerationError |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/monitoring_job/event_stream.py | {
"start": 5088,
"end": 6540
} | class ____(AirflowEvent):
task_instance: TaskInstance
metadata: dict[str, MetadataValue]
@property
def timestamp(self) -> float:
return self.task_instance.end_date.timestamp()
def persist_state(
self,
context: OpExecutionContext,
airflow_data: AirflowDefinitionsData... | TaskInstanceCompleted |
python | vyperlang__vyper | vyper/semantics/types/primitives.py | {
"start": 8120,
"end": 10549
} | class ____(NumericT):
"""
General integer type. All signed and unsigned ints from uint8 thru int256
Attributes
----------
bits : int
Number of bits the value occupies in memory
is_signed : bool
Is the value signed?
"""
typeclass = "integer"
_valid_literal = (vy_ast... | IntegerT |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/prefetching_ops.py | {
"start": 9750,
"end": 11621
} | class ____(dataset_ops.UnaryDataset):
"""A `Dataset` that maps a function over elements in its using a GPU."""
def __init__(self, input_dataset, map_func, use_inter_op_parallelism=True):
"""See `Dataset.map()` for details."""
self._input_dataset = input_dataset
self._use_inter_op_parallelism = use_inte... | _MapOnGpuDataset |
python | chroma-core__chroma | chromadb/auth/token_authn/__init__.py | {
"start": 3594,
"end": 8316
} | class ____(ServerAuthenticationProvider):
"""
Server authentication provider for token-based auth. The provider will
- On initialization, read the users from the file specified in
`chroma_server_authn_credentials_file`. This file must be a well-formed
YAML file with a top-level array called ... | TokenAuthenticationServerProvider |
python | spack__spack | lib/spack/spack/enums.py | {
"start": 174,
"end": 403
} | class ____(enum.Flag):
"""Enum flag to facilitate querying status from the DB"""
INSTALLED = enum.auto()
DEPRECATED = enum.auto()
MISSING = enum.auto()
ANY = INSTALLED | DEPRECATED | MISSING
| InstallRecordStatus |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-finish-the-race.py | {
"start": 66,
"end": 1082
} | class ____(object):
def minimumFinishTime(self, tires, changeTime, numLaps):
"""
:type tires: List[List[int]]
:type changeTime: int
:type numLaps: int
:rtype: int
"""
def ceil_log2(x):
return (x-1).bit_length()
dp = [float("inf")]*ceil_log... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/del1.py | {
"start": 885,
"end": 1162
} | class ____:
@property
def x(self) -> str: ...
@x.setter
def x(self, value: str) -> None: ...
@x.deleter
def x(self) -> None: ...
c = ClassC()
c.x = "x"
reveal_type(c.x, expected_text="Literal['x']")
del c.x
reveal_type(c.x, expected_text="str")
| ClassC |
python | ray-project__ray | rllib/models/preprocessors.py | {
"start": 9038,
"end": 10612
} | class ____(Preprocessor):
"""Preprocesses each tuple element, then flattens it all into a vector.
RLlib models will unpack the flattened output before _build_layers_v2().
"""
@override(Preprocessor)
def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
assert isinstance(... | TupleFlatteningPreprocessor |
python | tensorflow__tensorflow | tensorflow/python/keras/constraints.py | {
"start": 2881,
"end": 4229
} | class ____(Constraint):
"""MaxNorm weight constraint.
Constrains the weights incident to each hidden unit
to have a norm less than or equal to a desired value.
Also available via the shortcut function `tf.keras.constraints.max_norm`.
Args:
max_value: the maximum norm value for the incoming weights.
... | MaxNorm |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_assistant_message_param.py | {
"start": 284,
"end": 914
} | class ____(TypedDict, total=False):
audio: str
"""
Base64-encoded audio bytes, these will be parsed as the format specified in the
session output audio type configuration. This defaults to PCM 16-bit 24kHz mono
if not specified.
"""
text: str
"""The text content."""
transcript: str... | Content |
python | ray-project__ray | python/ray/serve/_private/deployment_state.py | {
"start": 2644,
"end": 2770
} | class ____(Enum):
NONE = 1
SUCCEEDED = 2
APP_FAILURE = 3
ACTOR_CRASHED = 4
@dataclass
| ReplicaHealthCheckResponse |
python | fsspec__filesystem_spec | fsspec/implementations/cache_mapper.py | {
"start": 1900,
"end": 2421
} | class ____(AbstractCacheMapper):
"""Cache mapper that uses a hash of the remote URL."""
def __call__(self, path: str) -> str:
return hashlib.sha256(path.encode()).hexdigest()
def create_cache_mapper(same_names: bool) -> AbstractCacheMapper:
"""Factory method to create cache mapper for backward co... | HashCacheMapper |
python | pypa__warehouse | warehouse/macaroons/models.py | {
"start": 607,
"end": 4446
} | class ____(db.Model):
__tablename__ = "macaroons"
__table_args__ = (
UniqueConstraint(
"description", "user_id", name="_user_macaroons_description_uc"
),
CheckConstraint(
"(user_id::text IS NULL) <> (oidc_publisher_id::text IS NULL)",
name="_user_xor_o... | Macaroon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.