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 | ray-project__ray | release/release_logs/fetch_release_logs.py | {
"start": 1803,
"end": 1990
} | class ____:
id: str
number: int
commit: str
job_dict_list: List[Dict]
pipeline: str = BUILDKITE_PIPELINE
organization: str = BUILDKITE_ORGANIZATION
@dataclass
| Build |
python | cherrypy__cherrypy | cherrypy/test/test_tools.py | {
"start": 16246,
"end": 16785
} | class ____(unittest.TestCase):
def test_login_screen_returns_bytes(self):
"""
login_screen must return bytes even if unicode parameters are passed.
Issue 1132 revealed that login_screen would return unicode if the
username and password were unicode.
"""
sa = cherrypy.... | SessionAuthTest |
python | coleifer__peewee | playhouse/dataset.py | {
"start": 6044,
"end": 10523
} | class ____(object):
def __init__(self, dataset, name, model_class):
self.dataset = dataset
self.name = name
if model_class is None:
model_class = self._create_model()
model_class.create_table()
self.dataset._models[name] = model_class
@property
de... | Table |
python | facebookresearch__faiss | tests/test_ivflib.py | {
"start": 4470,
"end": 5564
} | class ____(unittest.TestCase):
"""Test in case of nprobe > nlist."""
def test_small_data(self):
d = 20
# nlist = (2^4)^2 = 256
index = faiss.index_factory(d, 'IMI2x4,Flat')
# When nprobe >= nlist, it is equivalent to an IndexFlat.
rs = np.random.RandomState(123)
... | TestSmallData |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/source.py | {
"start": 2108,
"end": 3147
} | class ____(ScalarUnion):
def __init__(self):
super().__init__(
scalar_type=bool,
non_scalar_schema=Selector({"env": str}),
_key="BoolSourceType",
)
def post_process(self, value):
check.param_invariant(isinstance(value, (dict, bool)), "value", "Should ... | BoolSourceType |
python | PyCQA__pylint | tests/functional/n/not_context_manager.py | {
"start": 415,
"end": 551
} | class ____(Manager):
pass
with AnotherManager():
pass
# Tests message for class that doesn't implement the protocol
| AnotherManager |
python | spyder-ide__spyder | spyder/plugins/outlineexplorer/widgets.py | {
"start": 5730,
"end": 6024
} | class ____(QTreeWidgetItem):
def clear(self):
self.takeChildren()
def append_children(self, index, node):
self.insertChild(index, node)
node.parent = self
def remove_children(self, node):
self.removeChild(node)
node.parent = None
| BaseTreeItem |
python | neetcode-gh__leetcode | python/0658-find-k-closest-elements.py | {
"start": 953,
"end": 1271
} | class ____:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr) - k
while l < r:
m = (l + r) // 2
if x - arr[m] > arr[m + k] - x:
l = m + 1
else:
r = m
return arr[l : l + k]
| Solution |
python | django__django | django/db/models/functions/datetime.py | {
"start": 6285,
"end": 7367
} | class ____(Func):
template = "CURRENT_TIMESTAMP"
output_field = DateTimeField()
def as_postgresql(self, compiler, connection, **extra_context):
# PostgreSQL's CURRENT_TIMESTAMP means "the time at the start of the
# transaction". Use STATEMENT_TIMESTAMP to be cross-compatible with
# ... | Now |
python | huggingface__transformers | src/transformers/models/idefics2/modeling_idefics2.py | {
"start": 12794,
"end": 13499
} | class ____(nn.Module):
def __init__(
self,
hidden_size: int,
intermediate_size: int,
output_size: int,
hidden_act: str,
):
super().__init__()
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
self.up_proj = nn.Linear(hidden_siz... | Idefics2MLP |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid_connect/views.py | {
"start": 472,
"end": 4176
} | class ____(OAuth2Adapter):
def __init__(self, request, provider_id):
self.provider_id = provider_id
super().__init__(request)
@property
def openid_config(self):
if not hasattr(self, "_openid_config"):
server_url = self.get_provider().server_url
resp = get_ada... | OpenIDConnectOAuth2Adapter |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 11624,
"end": 12522
} | class ____(object):
"""*
jina gRPC service to expose Endpoints from Executors.
"""
@staticmethod
def endpoint_discovery(
request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wa... | JinaDiscoverEndpointsRPC |
python | apache__thrift | lib/py/test/test_socket.py | {
"start": 1054,
"end": 3780
} | class ____(unittest.TestCase):
def test_failed_connection_raises_exception(self):
sock = TSocket(host="localhost", port=60606) # unused port
with self.assertRaises(TTransportException) as ctx:
sock.open()
exc = ctx.exception
self.assertEqual(exc.type, TTransportException.... | TSocketTest |
python | wandb__wandb | wandb/automations/_filters/run_metrics.py | {
"start": 11821,
"end": 12547
} | class ____(BaseMetricOperand):
"""Represents a single metric value when defining metric event filters."""
name: str
# Allow conversion of a single-value metric into an aggregated expression.
def max(self, window: int) -> MetricAgg:
return MetricAgg(name=self.name, agg=Agg.MAX, window=window)
... | MetricVal |
python | Textualize__textual | src/textual/command.py | {
"start": 12010,
"end": 13097
} | class ____(Option):
"""Class that holds a hit in the [`CommandList`][textual.command.CommandList]."""
def __init__(
self,
prompt: VisualType,
hit: DiscoveryHit | Hit,
id: str | None = None,
disabled: bool = False,
) -> None:
"""Initialise the option.
... | Command |
python | pypa__setuptools | setuptools/_vendor/wheel/cli/convert.py | {
"start": 2680,
"end": 3054
} | class ____(metaclass=ABCMeta):
name: str
version: str
pyver: str = "py2.py3"
abi: str = "none"
platform: str = "any"
metadata: Message
@property
def dist_info_dir(self) -> str:
return f"{self.name}-{self.version}.dist-info"
@abstractmethod
def generate_contents(self) ->... | ConvertSource |
python | pytorch__pytorch | torch/optim/adadelta.py | {
"start": 508,
"end": 16873
} | class ____(Optimizer):
def __init__(
self,
params: ParamsT,
lr: Union[float, Tensor] = 1.0,
rho: float = 0.9,
eps: float = 1e-6,
weight_decay: float = 0,
foreach: Optional[bool] = None,
*,
capturable: bool = False,
maximize: bool = Fals... | Adadelta |
python | numpy__numpy | numpy/polynomial/tests/test_laguerre.py | {
"start": 915,
"end": 3265
} | class ____:
x = np.linspace(-3, 3, 100)
def test_lagadd(self):
for i in range(5):
for j in range(5):
msg = f"At i={i}, j={j}"
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = lag.lagadd([0] * i + [1],... | TestArithmetic |
python | ray-project__ray | python/ray/_common/tests/test_ray_option_utils.py | {
"start": 6684,
"end": 7333
} | class ____:
def test_simple_update(self):
original = {"num_cpus": 1, "name": "a"}
new = {"num_cpus": 2, "num_gpus": 1}
updated = update_options(original, new)
assert updated == {"num_cpus": 2, "name": "a", "num_gpus": 1}
def test_update_with_empty_new(self):
original = {... | TestUpdateOptions |
python | walkccc__LeetCode | solutions/17. Letter Combinations of a Phone Number/17-2.py | {
"start": 0,
"end": 396
} | class ____:
def letterCombinations(self, digits: str) -> list[str]:
if not digits:
return []
ans = ['']
digitToLetters = ['', '', 'abc', 'def', 'ghi',
'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
for d in digits:
temp = []
for s in ans:
for c in digitToLetters... | Solution |
python | jina-ai__jina | tests/integration/inspect_deployments_flow/test_inspect_deployments_flow.py | {
"start": 491,
"end": 3288
} | class ____(DummyEvaluator1):
tag = 3
docs = DocumentArray([x for x in random_docs(1)])
params = ['HANG', 'COLLECT', 'REMOVE']
def validate(ids, expect):
assert len(ids) > 0
for j in ids:
tmp_dir = os.environ.get('TEST_EVAL_FLOW_TMPDIR')
fname = f'{tmp_dir}/{j}.txt'
assert os.path... | DummyEvaluator3 |
python | pytransitions__transitions | tests/test_threading.py | {
"start": 716,
"end": 5455
} | class ____(TestTransitions):
def setUp(self):
self.machine_cls = LockedMachine # type: Type[LockedMachine]
self.stuff = Stuff(machine_cls=self.machine_cls)
self.stuff.heavy_processing = heavy_processing
self.stuff.machine.add_transition('forward', 'A', 'B', before='heavy_processing... | TestLockedTransitions |
python | TheAlgorithms__Python | conversions/prefix_conversions.py | {
"start": 132,
"end": 442
} | class ____(Enum):
yotta = 24
zetta = 21
exa = 18
peta = 15
tera = 12
giga = 9
mega = 6
kilo = 3
hecto = 2
deca = 1
deci = -1
centi = -2
milli = -3
micro = -6
nano = -9
pico = -12
femto = -15
atto = -18
zepto = -21
yocto = -24
| SIUnit |
python | getsentry__sentry | src/sentry/utils/snowflake.py | {
"start": 2096,
"end": 2300
} | class ____(APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = "Max allowed ID retry reached. Please try again in a second"
@dataclass(frozen=True, eq=True)
| MaxSnowflakeRetryError |
python | keras-team__keras | keras/src/ops/linalg.py | {
"start": 16636,
"end": 18455
} | class ____(Operation):
def __init__(self, full_matrices=True, compute_uv=True, *, name=None):
super().__init__(name=name)
self.full_matrices = full_matrices
self.compute_uv = compute_uv
def call(self, x):
return _svd(x, self.full_matrices, self.compute_uv)
def compute_outpu... | SVD |
python | celery__celery | celery/exceptions.py | {
"start": 4161,
"end": 4231
} | class ____(CeleryWarning):
"""Fixup related warning."""
| FixupWarning |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 4057,
"end": 4250
} | class ____(GenericProperty[bool, bool]):
"""A property that requires a True or False value."""
def validate_value(self, value: object) -> bool:
return bool(value)
| BooleanProperty |
python | eventlet__eventlet | tests/patcher_test.py | {
"start": 12520,
"end": 17515
} | class ____(ProcessBase):
prologue = """import eventlet
eventlet.monkey_patch()
import threading
def test():
t = threading.currentThread()
"""
epilogue = """
t = eventlet.spawn(test)
t.wait()
"""
def test_join(self):
self.write_to_tempfile("newmod", self.prologue + """
def test2():
g... | GreenThreadWrapper |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_suspect_flags.py | {
"start": 868,
"end": 3078
} | class ____(GroupEndpoint):
publish_status = {"GET": ApiPublishStatus.PRIVATE}
def get(self, request: Request, group: Group) -> Response:
"""Stats bucketed by time."""
if not features.has(
"organizations:feature-flag-suspect-flags",
group.organization,
actor=r... | OrganizationGroupSuspectFlagsEndpoint |
python | gevent__gevent | src/gevent/events.py | {
"start": 6316,
"end": 6901
} | class ____(Interface):
"""
The event emitted when the event loop is blocked.
This event is emitted in the monitor thread.
.. versionchanged:: 24.11.1
Add the *hub* attribute.
"""
greenlet = Attribute("The greenlet that appeared to be blocking the loop.")
blocking_time = Attribute("... | IEventLoopBlocked |
python | PrefectHQ__prefect | src/prefect/task_runners.py | {
"start": 17233,
"end": 18853
} | class ____(concurrent.futures.Future[bytes]):
"""Wraps a future-of-future and unwraps the result."""
def __init__(
self,
resolution_future: concurrent.futures.Future[concurrent.futures.Future[bytes]],
):
super().__init__()
self._resolution_future = resolution_future
... | _ChainedFuture |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 31910,
"end": 32557
} | class ____(Base):
"""
SQLAlchemy model of a logging statement.
"""
name: Mapped[str]
level: Mapped[int] = mapped_column(sa.SmallInteger, index=True)
flow_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True)
task_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True)
... | Log |
python | getsentry__sentry | tests/sentry/workflow_engine/test_task.py | {
"start": 1624,
"end": 4950
} | class ____(TestCase):
def test__no_detector_id(self) -> None:
"""
Test that the workflow_status_update_handler does not crash
when no detector_id is provided in the status change message.
"""
group = self.create_group(project=self.project)
activity = Activity(
... | WorkflowStatusUpdateHandlerTests |
python | nedbat__coveragepy | tests/test_arcs.py | {
"start": 38459,
"end": 42094
} | class ____(CoverageTest):
"""Arc tests for generators."""
def test_yield_in_loop(self) -> None:
self.check_coverage(
"""\
def gen(inp):
for n in inp:
yield n
list(gen([1,2,3]))
""",
branchz="23 2-1",
... | YieldTest |
python | ray-project__ray | rllib/examples/envs/classes/memory_leaking_env.py | {
"start": 182,
"end": 915
} | class ____(RandomEnv):
"""An env that leaks very little memory.
Useful for proving that our memory-leak tests can catch the
slightest leaks.
"""
def __init__(self, config=None):
super().__init__(config)
self._leak = {}
self._steps_after_reset = 0
@override(RandomEnv)
... | MemoryLeakingEnv |
python | gevent__gevent | src/greentest/3.14/test_thread.py | {
"start": 13300,
"end": 14691
} | class ____(unittest.TestCase):
def setUp(self):
self.read_fd, self.write_fd = os.pipe()
@support.requires_fork()
@threading_helper.reap_threads
def test_forkinthread(self):
pid = None
def fork_thread(read_fd, write_fd):
nonlocal pid
# Ignore the warning... | TestForkInThread |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/partitions_schedules_sensors/static_partitioned_job.py | {
"start": 400,
"end": 653
} | class ____(Config):
continent_name: str
@op
def continent_op(context: OpExecutionContext, config: ContinentOpConfig):
context.log.info(config.continent_name)
@job(config=continent_config)
def continent_job():
continent_op()
| ContinentOpConfig |
python | keras-team__keras | keras/src/trainers/data_adapters/py_dataset_adapter_test.py | {
"start": 2466,
"end": 2915
} | class ____(py_dataset_adapter.PyDataset):
@property
def num_batches(self):
return 4
def __getitem__(self, index):
if index < 2:
return (
np.random.random((8, 4)).astype("float32"),
np.random.random((8, 2)).astype("float32"),
)
... | ExceptionPyDataset |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datafusion.py | {
"start": 18800,
"end": 22500
} | class ____(GoogleCloudBaseOperator):
"""
Creates a Cloud Data Fusion pipeline.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataFusionCreatePipelineOperator`
:param pipeline_name: Your pipeline name.
:param pipel... | CloudDataFusionCreatePipelineOperator |
python | jazzband__django-oauth-toolkit | tests/test_password.py | {
"start": 1308,
"end": 2708
} | class ____(BaseTest):
def test_get_token(self):
"""
Request an access token using Resource Owner Password Flow
"""
token_request_data = {
"grant_type": "password",
"username": "test_user",
"password": "123456",
}
auth_headers = get_... | TestPasswordTokenView |
python | kamyu104__LeetCode-Solutions | Python/reconstruct-original-digits-from-english.py | {
"start": 62,
"end": 901
} | class ____(object):
def originalDigits(self, s):
"""
:type s: str
:rtype: str
"""
# The count of each char in each number string.
cnts = [Counter(_) for _ in ["zero", "one", "two", "three", \
"four", "five", "six", "seven", \
... | Solution |
python | facelessuser__soupsieve | tests/test_level4/test_required.py | {
"start": 53,
"end": 877
} | class ____(util.TestCase):
"""Test required selectors."""
MARKUP = """
<form>
<input id="1" type="name" required>
<input id="2" type="checkbox" required>
<input id="3" type="email">
<textarea id="4" name="name" cols="30" rows="10" required></textarea>
<select id="5" name="nm" required>
... | TestRequired |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_test_util.py | {
"start": 38408,
"end": 40409
} | class ____(
LinearOperatorDerivedClassTest, metaclass=abc.ABCMeta):
"""Base test class appropriate for square operators.
Sub-classes must still define all abstractmethods from
LinearOperatorDerivedClassTest that are not defined here.
"""
@staticmethod
def operator_shapes_infos():
shapes_info = Ope... | SquareLinearOperatorDerivedClassTest |
python | scipy__scipy | scipy/_lib/_testutils.py | {
"start": 3935,
"end": 12279
} | class ____:
'''
These are situations that can be tested in our pythran tests:
- A function with multiple array arguments and then
other positional and keyword arguments.
- A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
Note: list/tuple input is not yet tested!
`sel... | _TestPythranFunc |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 523627,
"end": 524527
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("completed_iterations", "duration", "iterations", "start_day")
completed_iterations = sgqlc.types.Field(
sgqlc.types.non_null(
sgqlc.types.list_of(
... | ProjectV2IterationFieldConfiguration |
python | huggingface__transformers | src/transformers/models/gpt_neox/modeling_gpt_neox.py | {
"start": 14113,
"end": 15907
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: GPTNeoXConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GPTNeoXAttention(config=config, layer_idx=layer_idx)
self.mlp = GPTNeoXMLP(config)
self.input_layerno... | GPTNeoXDecoderLayer |
python | scikit-learn__scikit-learn | sklearn/utils/_encode.py | {
"start": 10066,
"end": 11773
} | class ____(Counter):
"""Counter with support for nan values."""
def __init__(self, items):
super().__init__(self._generate_items(items))
def _generate_items(self, items):
"""Generate items without nans. Stores the nan counts separately."""
for item in items:
if not is_s... | _NaNCounter |
python | walkccc__LeetCode | solutions/2915. Length of the Longest Subsequence That Sums to Target/2915.py | {
"start": 0,
"end": 651
} | class ____:
def lengthOfLongestSubsequence(self, nums: list[int], target: int) -> int:
n = len(nums)
# dp[i][j] := the maximum length of any subsequence of the first i numbers
# that sum to j
dp = [[-1] * (target + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 0
for i in ... | Solution |
python | spyder-ide__spyder | spyder/plugins/completion/api.py | {
"start": 13197,
"end": 17401
} | class ____:
"""Text document synchronization modes supported by a lsp-server"""
NONE = 0 # Text synchronization is not supported
FULL = 1 # Text synchronization requires all document contents
INCREMENTAL = 2 # Partial text synchronization is supported
# Save options.
SAVE_OPTIONS = {
# The cli... | TextDocumentSyncKind |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | {
"start": 4947,
"end": 7097
} | class ____:
Row = 'row_section'
ColumnAndRest = 'column_section'
# Supported real and complex number types
REAL_NUMBER_TYPES = (float, int, np.int64, np.int32)
COMPLEX_NUMBER_TYPES = (complex, np.complex64, np.complex128)
# Used to convert bool intrance to false since bool('False') will return True
_bool_fal... | DataframeEditorToolbarSections |
python | apache__airflow | airflow-core/src/airflow/jobs/job.py | {
"start": 3002,
"end": 16970
} | class ____(Base, LoggingMixin):
"""
The ORM class representing Job stored in the database.
Jobs are processing items with state and duration that aren't task instances.
"""
__tablename__ = "job"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
dag_id: Mapped[str | None] = mapped... | Job |
python | huggingface__transformers | tests/models/swin2sr/test_image_processing_swin2sr.py | {
"start": 1184,
"end": 3205
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_rescale=True,
rescale_factor=1 / 255,
do_pad=True,
size_divisor=8,
):
self.parent = paren... | Swin2SRImageProcessingTester |
python | pallets__click | src/click/types.py | {
"start": 6436,
"end": 6684
} | class ____(ParamType):
name = "text"
def convert(
self, value: t.Any, param: Parameter | None, ctx: Context | None
) -> t.Any:
return value
def __repr__(self) -> str:
return "UNPROCESSED"
| UnprocessedParamType |
python | doocs__leetcode | solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/Solution.py | {
"start": 329,
"end": 1454
} | class ____:
def intersect(self, quadTree1: "Node", quadTree2: "Node") -> "Node":
def dfs(t1, t2):
if t1.isLeaf and t2.isLeaf:
return Node(t1.val or t2.val, True)
if t1.isLeaf:
return t1 if t1.val else t2
if t2.isLeaf:
return... | Solution |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 5191,
"end": 5496
} | class ____(XsdString):
@classmethod
def validate(cls, value: Any) -> None:
cls.validate_string(value)
valid_values = ("page", "column", "textWrapping")
if value not in valid_values:
raise ValueError("must be one of %s, got '%s'" % (valid_values, value))
| ST_BrType |
python | Netflix__metaflow | test/test_config/hellodecos.py | {
"start": 481,
"end": 2080
} | class ____(MyBaseFlowSpec):
cfg = Config(
"cfg",
default_value={
"args_decorator": "with_args",
"user_retry_decorator": "my_decorators.retry",
"bar": 43,
},
)
@conda(python="3.10.*")
@environment(vars={"FOO": 42})
@step
def start(self)... | DecoFlow |
python | fastapi__sqlmodel | docs_src/tutorial/automatic_id_none_refresh/tutorial001.py | {
"start": 92,
"end": 2084
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
... | Hero |
python | keras-team__keras | keras/src/initializers/constant_initializers.py | {
"start": 1484,
"end": 2476
} | class ____(Initializer):
"""Initializer that generates tensors initialized to 0.
Examples:
>>> # Standalone usage:
>>> initializer = Zeros()
>>> values = initializer(shape=(2, 2))
>>> # Usage in a Keras layer:
>>> initializer = Zeros()
>>> layer = Dense(units=3, kernel_initializer=ini... | Zeros |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_T.py | {
"start": 4310,
"end": 5935
} | class ____(Benchmark):
r"""
Trefethen objective function.
This class defines the Trefethen [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Trefethen}}(x) = 0.25 x_{1}^{2} + 0.25 x_{2}^{2}
... | Trefethen |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 19389,
"end": 20422
} | class ____(HTTPException):
"""Adds an optional ``retry_after`` parameter which will set the
``Retry-After`` header. May be an :class:`int` number of seconds or
a :class:`~datetime.datetime`.
"""
def __init__(
self,
description: str | None = None,
response: SansIOResponse | N... | _RetryAfter |
python | patrick-kidger__equinox | equinox/debug/_max_traces.py | {
"start": 909,
"end": 964
} | class ____:
__slots__ = ("__weakref__",)
| _Weakrefable |
python | PyCQA__pylint | tests/functional/m/match_class_pattern.py | {
"start": 238,
"end": 283
} | class ____(A):
__match_args__ = ("x", "y")
| B |
python | numpy__numpy | numpy/lib/tests/test_index_tricks.py | {
"start": 16575,
"end": 19552
} | class ____:
def test_basic(self):
a = np.zeros((3, 3), int)
fill_diagonal(a, 5)
assert_array_equal(
a, np.array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
)
def test_tall_matrix(self):
a = np.zeros((10, 3), int)
... | TestFillDiagonal |
python | pytest-dev__pytest | src/_pytest/timing.py | {
"start": 572,
"end": 1611
} | class ____:
"""
Represents an instant in time, used to both get the timestamp value and to measure
the duration of a time span.
Inspired by Rust's `std::time::Instant`.
"""
# Creation time of this instant, using time.time(), to measure actual time.
# Note: using a `lambda` to correctly get... | Instant |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/hooks/test_consume.py | {
"start": 1068,
"end": 2108
} | class ____:
"""
Test consumer hook.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="kafka_d",
conn_type="kafka",
extra=json.dumps(
... | TestConsumerHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 536228,
"end": 536705
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateDiscussion"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "discussion")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | CreateDiscussionPayload |
python | python__mypy | mypy/test/teststubgen.py | {
"start": 59251,
"end": 60928
} | class ____(unittest.TestCase):
def test_python_module(self) -> None:
with ModuleInspect() as m:
p = m.get_package_properties("inspect")
assert p is not None
assert p.name == "inspect"
assert p.file
assert p.path is None
assert p.is_c_mo... | ModuleInspectSuite |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 423,
"end": 2026
} | class ____(
object
): # Y040 Do not inherit from "object" explicitly, as it is redundant in Python 3
def __new__(cls, *args: Any, **kwargs: Any) -> Bad:
... # Y034 "__new__" methods usually return "self" at runtime. Consider using "typing_extensions.Self" in "Bad.__new__", e.g. "def __new__(cls, *args... | Bad |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 1130,
"end": 7916
} | class ____(TestCase):
CHARSET = "utf-8"
def setUp(self):
self.test_precompiler = os.path.join(test_dir, "precompiler.py")
self.setup_infile()
self.cached_precompiler_args = dict(
content=self.content,
charset=self.CHARSET,
filename=self.filename,
... | PrecompilerTestCase |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/graphql_client.py | {
"start": 6634,
"end": 10298
} | class ____:
def __init__(
self,
url: str,
session: requests.Session,
headers: Optional[dict[str, Any]] = None,
verify: bool = True,
timeout: int = DEFAULT_TIMEOUT,
cookies: Optional[dict[str, Any]] = None,
proxies: Optional[dict[str, Any]] = None,
... | DagsterCloudGraphQLClient |
python | google__jax | tests/api_test.py | {
"start": 254419,
"end": 257174
} | class ____(jtu.JaxTestCase):
def test_non_jaxtype_arg(self):
# For the test to fail without the invalid JaxType filter we need to pass
# in a valid JaxType that forces the invalid Jaxtype to be raised to an
# abstract value.
def f(not_a_jaxtype, a_jaxtype):
# then Jax needs to try and evaluate ... | NamedCallTest |
python | jazzband__django-pipeline | pipeline/compressors/closure.py | {
"start": 91,
"end": 290
} | class ____(SubProcessCompressor):
def compress_js(self, js):
command = (settings.CLOSURE_BINARY, settings.CLOSURE_ARGUMENTS)
return self.execute_command(command, js)
| ClosureCompressor |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py | {
"start": 5394,
"end": 7048
} | class ____:
"""Helper class for validating transfer job body."""
def __init__(self, body: dict) -> None:
if not body:
raise AirflowException("The required parameter 'body' is empty or None")
self.body = body
def _verify_data_source(self) -> None:
is_gcs = GCS_DATA_SOUR... | TransferJobValidator |
python | getsentry__sentry | src/sentry/notifications/notification_action/action_validation.py | {
"start": 5369,
"end": 6557
} | class ____(BaseActionValidatorHandler):
provider = Action.Type.PAGERDUTY
notify_action_form = PagerDutyNotifyServiceForm
def _get_services(self) -> list[tuple[int, str]]:
organization_integrations = integration_service.get_organization_integrations(
providers=[Action.Type.PAGERDUTY], or... | PagerdutyActionValidatorHandler |
python | pallets__quart | src/quart/ctx.py | {
"start": 847,
"end": 4055
} | class ____:
"""A base context relating to either request or websockets, bound to the
current task.
Attributes:
app: The app itself.
request_websocket: The request or websocket itself.
url_adapter: An adapter bound to this request.
session: The session information relating to... | _BaseRequestWebsocketContext |
python | kamyu104__LeetCode-Solutions | Python/count-fertile-pyramids-in-a-land.py | {
"start": 33,
"end": 852
} | class ____(object):
def countPyramids(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def count(grid, reverse):
def get_grid(i, j):
return grid[~i][j] if reverse else grid[i][j]
result = 0
dp = [0]*len(grid[0])... | Solution |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 26455,
"end": 30008
} | class ____(Generic[EnumType]):
"""Descriptor for getting and setting string properties and ensuring that the set
value belongs in the set of valid values.
Args:
valid_values: The set of valid values that the descriptor can take.
default: The default value (or a factory thereof) of the prope... | StringEnumProperty |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 16427,
"end": 17986
} | class ____:
def setup_method(self):
self.rect = Rectangle([0, 0], [1, 1])
def test_min_inside(self):
assert_almost_equal(self.rect.min_distance_point([0.5, 0.5]), 0)
def test_min_one_side(self):
assert_almost_equal(self.rect.min_distance_point([0.5, 1.5]), 0.5)
def test_min_t... | Test_rectangle |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 25381,
"end": 28386
} | class ____(GlobalValue):
"""Represent a LLVM Function but does uses a Module as parent.
Global Values are stored as a set of dependencies (attribute `depends`).
"""
def __init__(self, module, ftype, name):
assert isinstance(ftype, types.Type)
super(Function, self).__init__(module, ftype... | Function |
python | getsentry__sentry | tests/sentry/backup/test_imports.py | {
"start": 3862,
"end": 29532
} | class ____(ImportTestCase):
"""
Ensure that potentially damaging data is properly scrubbed at import time.
"""
def test_users_sanitized_in_user_scope(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir).joinpath(f"{self._testMethodName}.json")
... | SanitizationTests |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 19497,
"end": 23642
} | class ____(Expr):
""" A generalized hypergeometric function. """
def __new__(cls, ap, bq):
obj = super().__new__(cls)
obj.ap = Tuple(*list(map(expand, ap)))
obj.bq = Tuple(*list(map(expand, bq)))
return obj
@property
def args(self):
return (self.ap, self.bq)
... | Hyper_Function |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 10968,
"end": 11945
} | class ____(hp.HasProps):
foo = Either(List(Int), Int, default=10)
def test_HasProps_apply_theme_either_simple() -> None:
# check applying multiple themes
c = EitherSimpleDefault()
assert c.foo == 10
theme = dict(foo=20)
c.apply_theme(theme)
assert c.foo == 20
theme = dict(foo=30)
... | EitherSimpleDefault |
python | ray-project__ray | rllib/offline/estimators/tests/test_ope.py | {
"start": 2962,
"end": 6409
} | class ____(unittest.TestCase):
"""Compilation tests for using OPE both standalone and in an RLlib Algorithm"""
@classmethod
def setUpClass(cls):
ray.init()
seed = 42
np.random.seed(seed)
rllib_dir = Path(__file__).parent.parent.parent.parent
train_data = os.path.joi... | TestOPE |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 41176,
"end": 46513
} | class ____(_TorchDynamoContext):
def __init__(self, msg: Optional[str] = None, wrapping: bool = True) -> None:
super().__init__(callback=None)
self.msg = msg
self.wrapping = wrapping
def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]:
# Earlier this code was in the... | DisableContext |
python | pytorch__pytorch | torch/_higher_order_ops/effects.py | {
"start": 2090,
"end": 10100
} | class ____(HigherOrderOperator):
"""
with_effects(token, op, args, kwargs) -> (new_token, op_results)
This HOP helps ensure ordering between side effectful ops like prints or ops
using torchbind objects. This is needed to ensure a traced graph from
AOTAutograd is functional so that future optimizat... | WithEffects |
python | doocs__leetcode | solution/3300-3399/3311.Construct 2D Grid Matching Graph Layout/Solution.py | {
"start": 0,
"end": 1290
} | class ____:
def constructGridLayout(self, n: int, edges: List[List[int]]) -> List[List[int]]:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
deg = [-1] * 5
for x, ys in enumerate(g):
deg[len(ys)] = x
if deg[1] !... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-ascii-delete-sum-for-two-strings.py | {
"start": 33,
"end": 767
} | class ____(object):
def minimumDeleteSum(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
dp = [[0] * (len(s2)+1) for _ in xrange(2)]
for j in xrange(len(s2)):
dp[0][j+1] = dp[0][j] + ord(s2[j])
for i in xrange(len(s1)):
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-changes-to-make-k-semi-palindromes.py | {
"start": 2879,
"end": 3796
} | class ____(object):
def minimumChanges(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
def min_dist(left, right): # Time: O(nlogn)
return min(sum(s[left+i] != s[right-((i//d+1)*d-1)+(i%d)] for i in xrange((right-left+1)//2))
for d in divisors[... | Solution3 |
python | huggingface__transformers | src/transformers/integrations/finegrained_fp8.py | {
"start": 24943,
"end": 26863
} | class ____(ConversionOps):
"""Inverse operation of :class:`Fp8Quantize`. Takes a pair (weight, scale) and reconstructs the fp32 tensor."""
def __init__(self, block_size: tuple[int, int] | None = None):
self.block_size = block_size
def convert(
self,
value: Sequence[torch.Tensor] | ... | Fp8Dequantize |
python | huggingface__transformers | tests/models/xlm/test_modeling_xlm.py | {
"start": 1396,
"end": 12252
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_lengths=True,
use_token_type_ids=True,
use_labels=True,
gelu_activation=True,
sinusoidal_embeddings=False,
causal=False,
as... | XLMModelTester |
python | sphinx-doc__sphinx | sphinx/util/build_phase.py | {
"start": 105,
"end": 277
} | class ____(IntEnum):
"""Build phase of Sphinx application."""
INITIALIZATION = 1
READING = 2
CONSISTENCY_CHECK = 3
RESOLVING = 3
WRITING = 4
| BuildPhase |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/fields.py | {
"start": 4355,
"end": 4441
} | class ____(BaseField):
"""String field."""
types = six.string_types
| StringField |
python | numba__numba | numba/tests/test_range.py | {
"start": 1130,
"end": 5324
} | class ____(unittest.TestCase):
def test_loop1_int16(self):
pyfunc = loop1
cfunc = njit((types.int16,))(pyfunc)
self.assertTrue(cfunc(5), pyfunc(5))
def test_loop2_int16(self):
pyfunc = loop2
cfunc = njit((types.int16, types.int16))(pyfunc)
self.assertTrue(cfunc(... | TestRange |
python | pytorch__pytorch | test/distributed/checkpoint/e2e/test_fine_tuning.py | {
"start": 2343,
"end": 7139
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
return min(4, torch.accelerator.device_count())
@property
def backend(self):
curr_backend = dist.get_default_backend_for_device(self.device_type)
return f"cpu:gloo,{self.device_type}:{curr_backend}"
def pre... | TestFineTuning |
python | openai__openai-python | src/openai/types/responses/file_search_tool_param.py | {
"start": 546,
"end": 817
} | class ____(TypedDict, total=False):
embedding_weight: Required[float]
"""The weight of the embedding in the reciprocal ranking fusion."""
text_weight: Required[float]
"""The weight of the text in the reciprocal ranking fusion."""
| RankingOptionsHybridSearch |
python | allegroai__clearml | examples/frameworks/jsonargparse/jsonargparse_nested_namespaces.py | {
"start": 112,
"end": 594
} | class ____:
opt1: str = "from default 1"
opt2: str = "from default 2"
if __name__ == "__main__":
Task.init(project_name="examples", task_name="jsonargparse nested namespaces")
parser = ArgumentParser()
parser.add_argument("--arg1.opt1", default="from default 1")
parser.add_argument("--arg1.opt... | Arg2 |
python | falconry__falcon | falcon/bench/queues/messages.py | {
"start": 586,
"end": 754
} | class ____:
def on_post(self, req, resp, tenant_id, queue_name):
pass
def on_get(self, req, resp, tenant_id, queue_name):
pass
| CollectionResource |
python | huggingface__transformers | src/transformers/models/auto/video_processing_auto.py | {
"start": 10032,
"end": 20188
} | class ____:
r"""
This is a generic video processor class that will be instantiated as one of the video processor classes of the
library when created with the [`AutoVideoProcessor.from_pretrained`] class method.
This class cannot be instantiated directly using `__init__()` (throws an error).
"""
... | AutoVideoProcessor |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_be_in_set.py | {
"start": 2383,
"end": 17631
} | class ____(ColumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnValuesToBeInSet is a \
Column Map Expectation.
Column Map Expectations are one of the most common types of Expectation.
They are evaluated for a single column and ask a yes/no question for every row in that... | ExpectColumnValuesToBeInSet |
python | spack__spack | lib/spack/spack/util/s3.py | {
"start": 4217,
"end": 5843
} | class ____(BufferedReader):
def __init__(self, raw):
# In botocore >=1.23.47, StreamingBody inherits from IOBase, so we
# only add missing attributes in older versions.
# https://github.com/boto/botocore/commit/a624815eabac50442ed7404f3c4f2664cd0aa784
if not isinstance(raw, IOBase):
... | WrapStream |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.