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 | RaRe-Technologies__gensim | gensim/test/test_fasttext.py | {
"start": 73000,
"end": 74089
} | class ____(unittest.TestCase):
def test_sanity(self):
m = np.array(range(9))
m.shape = (3, 3)
hash2index = {10: 0, 11: 1, 12: 2}
n = _unpack(m, 25, hash2index)
self.assertTrue(np.all(np.array([0, 1, 2]) == n[10]))
self.assertTrue(np.all(np.array([3, 4, 5]) == n[11]))... | UnpackTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py | {
"start": 9648,
"end": 10966
} | class ____(AwsBaseWaiterTrigger):
"""
Poll an Emr Serverless application and wait for it to be started.
:param application_id: The ID of the application being polled.
:waiter_delay: polling period in seconds to check for the status
:param waiter_max_attempts: The maximum number of attempts to be ma... | EmrServerlessStartApplicationTrigger |
python | readthedocs__readthedocs.org | readthedocs/api/v3/filters.py | {
"start": 1396,
"end": 1804
} | class ____(filters.FilterSet):
running = filters.BooleanFilter(method="get_running")
class Meta:
model = Build
fields = [
"commit",
"running",
]
def get_running(self, queryset, name, value):
if value:
return queryset.exclude(state__in=BUI... | BuildFilter |
python | pallets__werkzeug | tests/test_debug.py | {
"start": 6863,
"end": 11346
} | class ____:
def test_object_dumping(self):
drg = DebugReprGenerator()
out = drg.dump_object(Foo())
assert re.search("Details for test_debug.Foo object at", out)
assert re.search('<th>x.*<span class="number">42</span>', out, flags=re.DOTALL)
assert re.search('<th>y.*<span clas... | TestDebugHelpers |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/typed_dict.py | {
"start": 1595,
"end": 2000
} | class ____(TypedDict):
genuine: int
nested: SanitizedFieldTypedDict
def test_sanitize_field():
d: NestedTypedDict = _test_source()
_test_sink(d["genuine"])
d: NestedTypedDict = _test_source()
# TODO(T81192268): this should not trigger an issue.
_test_sink(d["nested"]["sanitized"])
ba... | NestedTypedDict |
python | wandb__wandb | wandb/sdk/wandb_run.py | {
"start": 14844,
"end": 147235
} | class ____:
"""A unit of computation logged by W&B. Typically, this is an ML experiment.
Call [`wandb.init()`](https://docs.wandb.ai/ref/python/init/) to create a
new run. `wandb.init()` starts a new run and returns a `wandb.Run` object.
Each run is associated with a unique ID (run ID). W&B recommends ... | Run |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/graph.py | {
"start": 3372,
"end": 3775
} | class ____(Enum):
"""Enum for different curve styles supported by Mermaid."""
BASIS = "basis"
BUMP_X = "bumpX"
BUMP_Y = "bumpY"
CARDINAL = "cardinal"
CATMULL_ROM = "catmullRom"
LINEAR = "linear"
MONOTONE_X = "monotoneX"
MONOTONE_Y = "monotoneY"
NATURAL = "natural"
STEP = "st... | CurveStyle |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 24830,
"end": 26735
} | class ____(QuantizedLayer):
def __init__(
self,
nbits: int = 4,
axis_key: int = 0,
axis_value: int = 0,
q_group_size: int = 64,
residual_length: int = 128,
):
super().__init__(
nbits=nbits,
axis_key=axis_key,
axis_value=... | QuantoQuantizedLayer |
python | django__django | tests/auth_tests/test_management.py | {
"start": 53213,
"end": 59323
} | class ____(TransactionTestCase):
available_apps = [
"django.contrib.contenttypes",
"django.contrib.auth",
"auth_tests",
]
databases = {"default", "other"}
def setUp(self):
app_config = apps.get_app_config("auth_tests")
models.signals.post_migrate.connect(
... | PermissionRenameOperationsTests |
python | sqlalchemy__sqlalchemy | test/orm/test_utils.py | {
"start": 17800,
"end": 20366
} | class ____(_fixtures.FixtureTest):
run_inserts = None
def _cases():
return testing.combinations(
(orm_util,), (Session,), argnames="ormutil"
)
@_cases()
def test_identity_key_1(self, ormutil):
User, users = self.classes.User, self.tables.users
self.mapper_r... | IdentityKeyTest |
python | spack__spack | lib/spack/spack/util/windows_registry.py | {
"start": 5342,
"end": 6221
} | class ____(RegistryKey):
"""Subclass of RegistryKey to represent the prebaked, always open registry HKEY constants"""
def __init__(self, hkey_constant):
hkey_name = hkey_constant
# This class is instantiated at module import time
# on non Windows platforms, winreg would not have been
... | _HKEY_CONSTANT |
python | pytorch__pytorch | torch/distributed/elastic/agent/server/api.py | {
"start": 5112,
"end": 7684
} | class ____:
"""A worker instance.
Contrast this with ``WorkerSpec`` that represents the specifications of a
worker. A ``Worker`` is created from a ``WorkerSpec``. A ``Worker`` is to
a ``WorkerSpec`` as an object is to a class.
The ``id`` of the worker is interpreted
by the specific implementat... | Worker |
python | pypa__warehouse | tests/functional/manage/test_views.py | {
"start": 701,
"end": 4419
} | class ____:
def test_save_account(self, pyramid_services, user_service, db_request):
breach_service = pretend.stub()
organization_service = pretend.stub()
pyramid_services.register_service(user_service, IUserService, None)
pyramid_services.register_service(
breach_service... | TestManageAccount |
python | Delgan__loguru | tests/test_coroutine_sink.py | {
"start": 289,
"end": 15759
} | class ____:
async def __call__(self, msg):
await asyncio.sleep(0.01)
print(msg, end="")
def test_coroutine_function(capsys):
async def worker():
logger.debug("A message")
await logger.complete()
logger.add(async_writer, format="{message}")
asyncio.run(worker())
o... | AsyncWriter |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3084,
"end": 3216
} | class ____(APIStatusError):
status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride]
| BadRequestError |
python | sympy__sympy | sympy/holonomic/recurrence.py | {
"start": 9036,
"end": 10344
} | class ____:
"""
A Holonomic Sequence is a type of sequence satisfying a linear homogeneous
recurrence relation with Polynomial coefficients. Alternatively, A sequence
is Holonomic if and only if its generating function is a Holonomic Function.
"""
def __init__(self, recurrence, u0=[]):
... | HolonomicSequence |
python | falconry__falcon | falcon/media/multipart.py | {
"start": 20808,
"end": 23778
} | class ____:
"""Defines a set of configurable multipart form parser options.
An instance of this class is exposed via the
:attr:`MultipartFormHandler.parse_options
<falcon.media.MultipartFormHandler.parse_options>` attribute.
The handler's options are also passed down to every :class:`BodyPart`
... | MultipartParseOptions |
python | doocs__leetcode | solution/2400-2499/2413.Smallest Even Multiple/Solution.py | {
"start": 0,
"end": 109
} | class ____:
def smallestEvenMultiple(self, n: int) -> int:
return n if n % 2 == 0 else n * 2
| Solution |
python | ray-project__ray | python/ray/_private/thirdparty/pathspec/pathspec.py | {
"start": 207,
"end": 7027
} | class ____(object):
"""
The :class:`PathSpec` class is a wrapper around a list of compiled
:class:`.Pattern` instances.
"""
def __init__(self, patterns):
"""
Initializes the :class:`PathSpec` instance.
*patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`)
yields each com... | PathSpec |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1053621,
"end": 1054357
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for WorkflowRun."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("WorkflowRunEdge"), graphql_name="edges")
"""A list of edges."""
nodes ... | WorkflowRunConnection |
python | getsentry__sentry | src/sentry/eventtypes/nel.py | {
"start": 33,
"end": 249
} | class ____(DefaultEvent):
key = "nel"
def extract_metadata(self, data):
metadata = super().extract_metadata(data)
metadata["uri"] = data.get("request").get("url")
return metadata
| NelEvent |
python | numpy__numpy | benchmarks/benchmarks/bench_indexing.py | {
"start": 2269,
"end": 2790
} | class ____(Benchmark):
params = ['C', 'F']
param_names = ['order']
def setup(self, order):
shape = (64, 64, 64)
# emulate gh-30156: boolean assignment into a Fortran/C array
self.base = np.zeros(shape, dtype=np.uint32, order=order)
mask = np.random.RandomState(0).rand(*self.... | BooleanAssignmentOrder |
python | django__django | django/forms/widgets.py | {
"start": 11238,
"end": 11804
} | class ____(Widget):
"""
Base class for all <input> widgets.
"""
input_type = None # Subclasses must define this.
template_name = "django/forms/widgets/input.html"
def __init__(self, attrs=None):
if attrs is not None:
attrs = attrs.copy()
self.input_type = attrs... | Input |
python | neetcode-gh__leetcode | python/0344-reverse-string.py | {
"start": 0,
"end": 280
} | class ____:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
l = 0
r = len(s) - 1
while l < r:
s[l],s[r] = s[r],s[l]
l += 1
r -= 1
| Solution |
python | kamyu104__LeetCode-Solutions | Python/selling-pieces-of-wood.py | {
"start": 52,
"end": 657
} | class ____(object):
def sellingWood(self, m, n, prices):
"""
:type m: int
:type n: int
:type prices: List[List[int]]
:rtype: int
"""
dp = [[0]*(n+1) for i in xrange(m+1)]
for h, w, p in prices:
dp[h][w] = p
for i in xrange(1, m+1):
... | Solution |
python | xlwings__xlwings | xlwings/__init__.py | {
"start": 564,
"end": 4533
} | class ____(XlwingsError):
pass
# API
from .main import (
App,
Book,
Chart,
Engine,
Name,
Picture,
Range,
RangeColumns,
RangeRows,
Shape,
Sheet,
apps,
books,
engines,
load,
sheets,
view,
)
from .utils import xlserial_to_datetime as to_datetime
__... | NoSuchObjectError |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 1373,
"end": 2718
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Spectrogram generation loss.
duration_outputs (`torch.LongTensor` of shape `(batch_size, max_text_length + 1)`, *optional*):
Outputs of the duration predictor.
pitch_... | FastSpeech2ConformerModelOutput |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_list_tools_param.py | {
"start": 271,
"end": 611
} | class ____(TypedDict, total=False):
input_schema: Required[object]
"""The JSON schema describing the tool's input."""
name: Required[str]
"""The name of the tool."""
annotations: Optional[object]
"""Additional annotations about the tool."""
description: Optional[str]
"""The descriptio... | Tool |
python | spack__spack | lib/spack/spack/llnl/util/link_tree.py | {
"start": 1295,
"end": 11994
} | class ____(fs.BaseDirectoryVisitor):
"""
Visitor that produces actions:
- An ordered list of directories to create in dst
- A list of files to link in dst
- A list of merge conflicts in dst/
"""
def __init__(
self, ignore: Optional[Callable[[str], bool]] = None, normalize_paths: boo... | SourceMergeVisitor |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/command_palette_discovery.py | {
"start": 92,
"end": 797
} | class ____(Provider):
def goes_nowhere_does_nothing(self) -> None:
pass
async def discover(self) -> Hits:
for n in range(10):
command = f"This is a test of this code {n}"
yield DiscoveryHit(
command,
self.goes_nowhere_does_nothing,
... | TestSource |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 86762,
"end": 89087
} | class ____(Request):
"""
For each task, get a list of metrics for which the requested event type was reported
:param tasks: Task IDs
:type tasks: Sequence[str]
:param event_type: Event type
:type event_type: EventTypeEnum
"""
_service = "events"
_action = "get_task_metrics"
_ve... | GetTaskMetricsRequest |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py | {
"start": 26898,
"end": 28886
} | class ____(nn.Module):
def __init__(self, config: Phi4MultimodalAudioConfig):
super().__init__()
self.config = config
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.scaling = self.head_dim**-0.5
self.attention_dropout = conf... | Phi4MultimodalAudioAttention |
python | GoogleCloudPlatform__python-docs-samples | dialogflow-cx/streaming_detect_intent_infinite.py | {
"start": 8661,
"end": 23975
} | class ____:
"""Manages the interaction with the Dialogflow CX Streaming API."""
def __init__(
self,
agent_name: str,
language_code: str,
single_utterance: bool,
model: str | None,
voice: str | None,
sample_rate: int,
dialogflow_timeout: float,
... | DialogflowCXStreaming |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/objecteditor.py | {
"start": 762,
"end": 5775
} | class ____(QObject):
def __init__(self):
QObject.__init__(self)
self.dialogs = {}
self.namespace = None
def set_namespace(self, namespace):
self.namespace = namespace
def create_dialog(self, dialog, refname, func):
self.dialogs[id(dialog)] = dialog, refname, func
... | DialogKeeper |
python | spyder-ide__spyder | spyder/plugins/console/utils/ansihandler.py | {
"start": 197,
"end": 4173
} | class ____(object):
"""ANSI Escape sequences handler"""
if os.name == 'nt':
# Windows terminal colors:
ANSI_COLORS = ( # Normal, Bright/Light
('#000000', '#808080'), # 0: black
('#800000', '#ff0000'), # 1: red
('#008000', '#00f... | ANSIEscapeCodeHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py | {
"start": 3385,
"end": 3941
} | class ____(Generic[T1, T2, *Ts1]): ...
ta1 = ClassTA()
reveal_type(ta1, expected_text="ClassTA[str, str, str, str]")
ta2 = ClassTA[int]()
reveal_type(ta2, expected_text="ClassTA[int, int, int, int]")
ta3 = ClassTA[int, float]()
reveal_type(ta3, expected_text="ClassTA[int, float, int, float]")
ta4 = ClassTA[int, fl... | ClassTA |
python | optuna__optuna | optuna/_gp/acqf.py | {
"start": 6457,
"end": 6881
} | class ____(BaseAcquisitionFunc):
def __init__(
self,
gpr: GPRegressor,
search_space: SearchSpace,
beta: float,
) -> None:
self._gpr = gpr
self._beta = beta
super().__init__(gpr.length_scales, search_space)
def eval_acqf(self, x: torch.Tensor) -> torch... | UCB |
python | jina-ai__jina | jina/excepts.py | {
"start": 1744,
"end": 1879
} | class ____(Exception, BaseJinaException):
"""Exception when an image name can not be found either local & remote"""
| BadImageNameError |
python | pytorch__pytorch | test/inductor/test_static_cuda_launcher.py | {
"start": 715,
"end": 15596
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.tmp_files = []
def tearDown(self):
super().tearDown()
for tmp_file in self.tmp_files:
try:
os.remove(tmp_file.name)
except OSError:
pass
def write_cubin_to_tm... | TestStaticCudaLauncher |
python | PrefectHQ__prefect | tests/test_task_worker.py | {
"start": 18884,
"end": 22301
} | class ____:
async def test_nested_task_run_via_task_worker(
self, prefect_client, events_pipeline
):
@task
def inner_task(x):
return x
@task
def outer_task(x):
return inner_task(x)
task_worker = TaskWorker(outer_task)
task_run_fu... | TestTaskWorkerNestedTasks |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_adjoint_test.py | {
"start": 1370,
"end": 10273
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enable... | LinearOperatorAdjointTest |
python | ray-project__ray | python/ray/autoscaler/_private/autoscaler.py | {
"start": 2938,
"end": 3868
} | class ____:
active_nodes: Dict[NodeType, int]
idle_nodes: Optional[Dict[NodeType, int]]
pending_nodes: List[Tuple[NodeIP, NodeType, NodeStatus]]
pending_launches: Dict[NodeType, int]
failed_nodes: List[Tuple[NodeIP, NodeType]]
node_availability_summary: NodeAvailabilitySummary = field(
d... | AutoscalerSummary |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 138567,
"end": 138828
} | class ____(VegaLiteSchema):
"""
BBox schema wrapper.
Bounding box https://tools.ietf.org/html/rfc7946#section-5
"""
_schema = {"$ref": "#/definitions/BBox"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| BBox |
python | readthedocs__readthedocs.org | readthedocs/settings/base.py | {
"start": 696,
"end": 43766
} | class ____(Settings):
"""Community base settings, don't use this directly."""
# Django settings
SITE_ID = 1
ROOT_URLCONF = "readthedocs.urls"
LOGIN_REDIRECT_URL = "/dashboard/"
FORCE_WWW = False
SECRET_KEY = "replace-this-please" # noqa
ATOMIC_REQUESTS = True
DEFAULT_AUTO_FIELD = ... | CommunityBaseSettings |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 21408,
"end": 21689
} | class ____:
def __init__(self, wrapped_name):
self._wrapped_name = wrapped_name
def __getattr__(self, name):
return getattr(self._wrapped_name, name)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self._wrapped_name)
| NameWrapper |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 160552,
"end": 169851
} | class ____:
def test_invalid_distribution_points(self):
with pytest.raises(TypeError):
x509.CRLDistributionPoints(
["notadistributionpoint"], # type:ignore[list-item]
)
def test_iter_len(self):
cdp = x509.CRLDistributionPoints(
[
... | TestCRLDistributionPoints |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 1630,
"end": 3477
} | class ____(abc.ABC):
"""Base class for type promotion rule per 'torch.ops.{namespace}.{op_name}'."""
def __init__(self, namespace: str, op_name: str) -> None:
self.namespace = namespace
self.op_name = op_name
# Make this abstract as well because subclass needs to override __eq__().
# A... | TypePromotionRule |
python | coleifer__peewee | peewee.py | {
"start": 136459,
"end": 144983
} | class ____(Database):
field_types = {
'AUTO': 'INTEGER AUTO_INCREMENT',
'BIGAUTO': 'BIGINT AUTO_INCREMENT',
'BOOL': 'BOOL',
'DECIMAL': 'NUMERIC',
'DOUBLE': 'DOUBLE PRECISION',
'FLOAT': 'FLOAT',
'UUID': 'VARCHAR(40)',
'UUIDB': 'VARBINARY(16)'}
opera... | MySQLDatabase |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 23678,
"end": 24157
} | class ____(PointEvent):
''' Announce the end of a rotate event on a Bokeh plot.
Attributes:
sx (float) : x-coordinate of the event in *screen* space
sy (float) : y-coordinate of the event in *screen* space
x (float) : x-coordinate of the event in *data* space
y (float) : y-coord... | RotateEnd |
python | huggingface__transformers | src/transformers/models/mixtral/modular_mixtral.py | {
"start": 9441,
"end": 11085
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MixtralConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MixtralAttention(config, layer_idx)
self.mlp = MixtralSparseMoeBlock(config)
self.input_layernorm = M... | MixtralDecoderLayer |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 1172,
"end": 1522
} | class ____(object):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._buffer = StringIO()
return self
def __exit__(self, *args):
self.data = self._buffer.getvalue()
sys.stdout = self._stdout
EXPECTED = """
from peewee import *
database = SqliteDatabase... | capture_output |
python | has2k1__plotnine | plotnine/composition/_plot_layout.py | {
"start": 277,
"end": 3732
} | class ____(ComposeAddable):
"""
Customise the layout of plots in a composition
"""
nrow: int | None = None
"""
Number of rows
"""
ncol: int | None = None
"""
Number of columns
"""
byrow: bool | None = None
"""
How to place plots into the grid.
If None or Tr... | plot_layout |
python | numba__numba | numba/core/typing/collections.py | {
"start": 1687,
"end": 2381
} | class ____(AbstractTemplate):
def generic(self, args, kws):
seq, idx, value = args
if isinstance(seq, types.MutableSequence):
idx = normalize_1d_index(idx)
if isinstance(idx, types.SliceType):
return signature(types.none, seq, idx, seq)
elif isinst... | SetItemSequence |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py | {
"start": 1534,
"end": 5671
} | class ____(Sequence[int]):
"""Class for storing a list of non-negative integers compactly.
We store them as the smallest size integer array we can get
away with. When we try to add an integer that is too large,
we upgrade the array to the smallest word size needed to store
the new value."""
AR... | IntList |
python | numba__numba | numba/core/types/common.py | {
"start": 783,
"end": 3022
} | class ____(IterableType, ArrayCompatible):
"""
Type class for objects providing the buffer protocol.
Derived classes exist for more specific cases.
"""
mutable = True
slice_is_copy = False
aligned = True
# CS and FS are not reserved for inner contig but strided
LAYOUTS = frozenset([... | Buffer |
python | automl__auto-sklearn | autosklearn/evaluation/__init__.py | {
"start": 5064,
"end": 22256
} | class ____(AbstractTAFunc):
def __init__(
self,
backend: Backend,
autosklearn_seed: int,
resampling_strategy: Union[
str, BaseCrossValidator, _RepeatedSplits, BaseShuffleSplit
],
metrics: Sequence[Scorer],
cost_for_crash: float,
abort_on_fi... | ExecuteTaFuncWithQueue |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops_test.py | {
"start": 46855,
"end": 48720
} | class ____(test_util.TensorFlowTestCase):
def testErrorReceivedIfDtypeMismatchFromOp(self):
if context.executing_eagerly():
error = errors_impl.InvalidArgumentError
error_message = (
r"cannot compute Add(V2)? as input #1\(zero-based\) was expected to "
r"be a int32 tensor but is a... | BinaryOpsTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_int.py | {
"start": 34932,
"end": 35024
} | class ____(IntStrDigitLimitsTests):
int_class = IntSubclass
| IntSubclassStrDigitLimitsTests |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/automation_condition_scenario.py | {
"start": 1558,
"end": 5030
} | class ____(ScenarioState):
automation_condition: Optional[dg.AutomationCondition] = None
condition_cursor: Optional[AutomationConditionCursor] = None
requested_asset_partitions: Optional[Sequence[AssetKeyPartitionKey]] = None
ensure_empty_result: bool = True
request_backfills: bool = False
def ... | AutomationConditionScenarioState |
python | django__django | django/template/defaulttags.py | {
"start": 18090,
"end": 29381
} | class ____(Node):
def __init__(self, var, name, nodelist, extra_context=None):
self.nodelist = nodelist
# var and name are legacy attributes, being left in case they are used
# by third-party subclasses of this Node.
self.extra_context = extra_context or {}
if name:
... | WithNode |
python | PyCQA__pylint | pylint/testutils/functional/test_file.py | {
"start": 1315,
"end": 4346
} | class ____:
"""A single functional test case file with options."""
_CONVERTERS: dict[str, Callable[[str], tuple[int, ...] | list[str]]] = {
"min_pyver": parse_python_version,
"max_pyver": parse_python_version,
"min_pyver_end_position": parse_python_version,
"requires": lambda s:... | FunctionalTestFile |
python | pytorch__pytorch | test/onnx/model_defs/mnist.py | {
"start": 56,
"end": 680
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forwar... | MNIST |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 28459,
"end": 30310
} | class ____(nn.Module):
"""
ASPP module defined in DeepLab papers: https://huggingface.co/papers/1606.00915, https://huggingface.co/papers/1706.05587
"""
def __init__(self, config: MobileViTConfig) -> None:
super().__init__()
in_channels = config.neck_hidden_sizes[-2]
out_channe... | MobileViTASPP |
python | walkccc__LeetCode | solutions/889. Construct Binary Tree from Preorder and Postorder Traversal/889.py | {
"start": 0,
"end": 897
} | class ____:
def constructFromPrePost(
self,
pre: list[int],
post: list[int],
) -> TreeNode | None:
postToIndex = {num: i for i, num in enumerate(post)}
def build(preStart: int, preEnd: int, postStart: int, postEnd: int) -> TreeNode | None:
if preStart > preEnd:
return None
... | Solution |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 701,
"end": 835
} | class ____(TypedDict):
time_period: int
sensitivity: str
direction: str
expected_seasonality: str
| AnomalyDetectionConfig |
python | coleifer__peewee | peewee.py | {
"start": 65986,
"end": 66888
} | class ____(Query):
union_all = __add__ = __compound_select__('UNION ALL')
union = __or__ = __compound_select__('UNION')
intersect = __and__ = __compound_select__('INTERSECT')
except_ = __sub__ = __compound_select__('EXCEPT')
__radd__ = __compound_select__('UNION ALL', inverted=True)
__ror__ = __... | SelectQuery |
python | getsentry__sentry | src/sentry/new_migrations/monkey/executor.py | {
"start": 674,
"end": 2089
} | class ____(Exception):
"""
Raised when migration operation is missing information needed for selecting
correct database connection.
"""
def _check_bitfield_flags(name: str, old: list[str], new: list[str]) -> None:
deleted = set(old) - set(new)
if deleted:
raise ValueError(
... | MissingDatabaseRoutingInfo |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_base.py | {
"start": 700,
"end": 36761
} | class ____(BaseModel):
"""Base Pydantic model for an Azure PostgreSQL-backed vector store.
This class encapsulates configuration (connection pool, table/column
names, embedding type/dimension, index configuration and metadata
column) and performs runtime verification that the target table
exists wi... | BaseAzurePGVectorStore |
python | sympy__sympy | sympy/plotting/pygletplot/plot_modes.py | {
"start": 915,
"end": 1494
} | class ____(PlotSurface):
i_vars, d_vars = 'xy', 'z'
intervals = [[-1, 1, 40], [-1, 1, 40]]
aliases = ['cartesian', 'monge']
is_default = True
def _get_sympy_evaluator(self):
fz = self.d_vars[0]
x = self.u_interval.v
y = self.v_interval.v
@float_vec3
def e(_x... | Cartesian3D |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 39309,
"end": 41449
} | class ____(ChineseCLIPPreTrainedModel):
config: ChineseCLIPVisionConfig
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = ["ChineseCLIPVisionEmbeddings", "ChineseCLIPVisionAttention"]
def __init__(self, config: ChineseCLIPVisionConfig):
super().__init__(conf... | ChineseCLIPVisionModel |
python | automl__auto-sklearn | test/test_evaluation/test_train_evaluator.py | {
"start": 2346,
"end": 108172
} | class ____(BaseEvaluatorTest, unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
"""
Creates a backend mock
"""
tmp_dir_name = self.id()
self.ev_path = os.path.join(this_directory, ".tmp_evaluations", tmp_dir_name)
if os.path.exists(self.ev_path... | TestTrainEvaluator |
python | kamyu104__LeetCode-Solutions | Python/count-mentions-per-user.py | {
"start": 75,
"end": 947
} | class ____(object):
def countMentions(self, numberOfUsers, events):
"""
:type numberOfUsers: int
:type events: List[List[str]]
:rtype: List[int]
"""
result = [0]*numberOfUsers
lookup = [1]*numberOfUsers
events.sort(key=lambda x: (int(x[1]), x[0] == "ME... | Solution |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 7188,
"end": 9312
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads ... | MobileBertSelfAttention |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_cloud_run_worker_v2_filtering.py | {
"start": 1543,
"end": 14269
} | class ____:
def test_populate_env_filters_plaintext_api_key_when_secret_configured(
self, cloud_run_worker_v2_job_config
):
# Add plaintext API key to env
cloud_run_worker_v2_job_config.env["PREFECT_API_KEY"] = "plaintext-api-key"
cloud_run_worker_v2_job_config.prefect_api_key_se... | TestCloudRunWorkerJobV2ConfigurationFiltering |
python | django__django | django/core/management/color.py | {
"start": 1896,
"end": 3168
} | class ____:
pass
def make_style(config_string=""):
"""
Create a Style object from the given config_string.
If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used.
"""
style = Style()
color_settings = termcolors.parse_color_setting(config_string)
# The nocolor pal... | Style |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass7.py | {
"start": 136,
"end": 311
} | class ____:
val: str
def func1(val: DC1):
result = val
match result:
case DC1(result):
reveal_type(result, expected_text="str")
@dataclass
| DC1 |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 88498,
"end": 90035
} | class ____:
force_extern_kernel_in_multi_template: bool = False
max_mm_configs: Optional[int] = None
runtime_triton_dtype_assert = False
runtime_triton_shape_assert = False
static_cpp_dtype_assert = False
# regex to control the set of considered autotuning
# choices (aka configs) by name ... | test_configs |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_finder.py | {
"start": 14375,
"end": 18327
} | class ____:
def __init__(self, collection_finder, pathctx):
# when called from a path_hook, find_module doesn't usually get the path arg, so this provides our context
self._pathctx = _to_text(pathctx)
self._collection_finder = collection_finder
# cache the native FileFinder (take adv... | _AnsiblePathHookFinder |
python | pytorch__pytorch | torch/_inductor/tiling_utils.py | {
"start": 21600,
"end": 21836
} | class ____:
"""
Tiling of a var by `tiling_factor` that yields additional coalesced mem accesses by `benefit_score`
"""
var: sympy.Symbol
tiling_factor: int
score: int
@dataclasses.dataclass(frozen=True)
| VarTiling |
python | fastai__fastai | fastai/callback/rnn.py | {
"start": 396,
"end": 884
} | class ____(Callback):
"`Callback` that resets the model at each validation/training step"
def before_train(self): self.model.reset()
def before_validate(self): self.model.reset()
def after_fit(self): self.model.reset()
_docs = dict(before_train="Reset the model before training",
... | ModelResetter |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py | {
"start": 962,
"end": 6266
} | class ____:
"""Finder to locate distributions.
The main purpose of this class is to memoize found distributions' names, so
only one distribution is returned for each package name. At lot of pip code
assumes this (because it is setuptools's behavior), and not doing the same
can potentially cause a d... | _DistributionFinder |
python | getsentry__sentry | tests/sentry/replays/endpoints/test_project_replay_clicks_index.py | {
"start": 271,
"end": 11067
} | class ____(APITestCase, ReplaysSnubaTestCase):
endpoint = "sentry-api-0-project-replay-clicks-index"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.replay_id = uuid4().hex
self.url = reverse(
self.endpoint, args=(self.organization.slug, s... | OrganizationReplayDetailsTest |
python | bokeh__bokeh | tests/unit/bokeh/test_themes.py | {
"start": 1555,
"end": 1752
} | class ____(ThemedModel):
another_string = String("world")
FILE_CONTENTS = b"""
attrs:
ThemedModel:
number: 57
SubOfThemedModel:
another_string: "boo"
"""
| SubOfThemedModel |
python | walkccc__LeetCode | solutions/3533. Concatenated Divisibility/3533.py | {
"start": 0,
"end": 1217
} | class ____:
def concatenatedDivisibility(self, nums: list[int], k: int) -> list[int]:
n = len(nums)
nums.sort()
lengths = [len(str(num)) for num in nums]
pows = [pow(10, length, k) for length in lengths]
@functools.lru_cache(None)
def dp(mask: int, mod: int) -> bool:
"""
Returns T... | Solution |
python | django__django | tests/force_insert_update/models.py | {
"start": 468,
"end": 587
} | class ____(models.Model):
name = models.IntegerField(primary_key=True)
value = models.IntegerField()
| WithCustomPK |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/schema.py | {
"start": 2460,
"end": 3495
} | class ____:
"""Helper to compare types inside of datastructures based on affinity.
E.g.::
eq_(
inspect(connection).get_columns("foo"),
[
{
"name": "id",
"type": testing.eq_type_affinity(sqltypes.INTEGER),
... | eq_type_affinity |
python | ray-project__ray | python/ray/air/tests/test_integration_comet.py | {
"start": 10673,
"end": 12262
} | class ____(unittest.TestCase):
def setUp(self):
self.logger = CometLoggerCallback()
self.trials = [
MockTrial({"p1": 1}, "trial_1", 1, "artifact"),
MockTrial({"p1": 2}, "trial_2", 2, "artifact"),
MockTrial({"p1": 2}, "trial_3", 3, "artifact"),
]
def t... | LogTrialEndTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_payment_methods.py | {
"start": 3598,
"end": 9898
} | class ____(TestCase):
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
StripeRequestBuilder.customers_endpoint(_ACCOUNT_ID, _CLIENT_SECRET).with_any_query_params().build(),
_customers_response().with_reco... | FullRefreshTest |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 90990,
"end": 91066
} | class ____(BinOpFrame):
operation = M.le
_operator_repr = "<="
| LEFrame |
python | palantir__python-language-server | versioneer.py | {
"start": 15934,
"end": 18956
} | class ____(Exception):
"""Exception raised if a method is not valid for the current scenario."""
# these dictionaries contain VCS-specific tools
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
de... | NotThisMethod |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/path_replacer.py | {
"start": 48,
"end": 273
} | class ____(ABC):
"""
Replaces SDK frame paths with a new path. Runs only for SDK frames.
"""
@abstractmethod
def replace_path(self, path_field: str, path_value: str) -> str | None:
pass
| PathReplacer |
python | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 3626,
"end": 3754
} | class ____(_TestFFTBase):
def setup_method(self):
self.cdt = np.complex128
self.rdt = np.float64
| TestDoubleFFT |
python | prabhupant__python-ds | data_structures/binary_trees/sum_of_all_nodes.py | {
"start": 46,
"end": 291
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sum_nodes(root):
if root is None:
return 0
return root.val + sum_nodes(root.left) + sum_nodes(root.right)
| Node |
python | optuna__optuna | optuna/cli.py | {
"start": 14468,
"end": 16257
} | class ____(_BaseCommand):
"""Show a list of studies."""
_study_list_header = [
("name", ""),
("direction", ""),
("n_trials", ""),
("datetime_start", ""),
]
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument(
"-f",
... | _Studies |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 66208,
"end": 75370
} | class ____(VariableTracker):
_nonvar_fields = {
"value",
"reason",
*VariableTracker._nonvar_fields,
}
def __init__(self, value: Any, reason: Optional[str] = None, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.value = value
self.reason = reason
... | SkipFunctionVariable |
python | kamyu104__LeetCode-Solutions | Python/moving-stones-until-consecutive.py | {
"start": 29,
"end": 421
} | class ____(object):
def numMovesStones(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
s = [a, b, c]
s.sort()
if s[0]+1 == s[1] and s[1]+1 == s[2]:
return [0, 0]
return [1 if s[0]+2 >= s[1] o... | Solution |
python | python-markdown__markdown | tests/test_apis.py | {
"start": 2593,
"end": 3897
} | class ____(unittest.TestCase):
""" Tests of ConvertFile. """
def setUp(self):
self.saved = sys.stdin, sys.stdout
sys.stdin = StringIO('foo')
sys.stdout = TextIOWrapper(BytesIO())
def tearDown(self):
sys.stdin, sys.stdout = self.saved
def getTempFiles(self, src):
... | TestConvertFile |
python | ray-project__ray | python/ray/_common/tests/test_filters.py | {
"start": 127,
"end": 4186
} | class ____:
def test_driver_process(self, shutdown_only):
log_context = ["job_id", "worker_id", "node_id"]
filter = CoreContextFilter()
record = logging.makeLogRecord({})
assert filter.filter(record)
# Ray is not initialized so no context except PID which should be available
... | TestCoreContextFilter |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 143017,
"end": 328557
} | class ____:
# This is a wrapper over the actual __init__ function.
#
# Where to add a new constructor parameter to ShapeEnv?
# =====================================================
# This __init__ function should be used only for parameters related to event recording.
# These are parameters that... | ShapeEnv |
python | coleifer__peewee | tests/models.py | {
"start": 122616,
"end": 126775
} | class ____(BaseTestCase):
def test_table_name(self):
class Foo(Model):
class Meta:
def table_function(klass):
return 'xxx_%s' % klass.__name__.lower()
class Bar(Foo): pass
class Baze(Foo):
class Meta:
table_name = '... | TestMetaInheritance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.