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 | google__jax | jax/experimental/jax2tf/call_tf.py | {
"start": 2018,
"end": 16180
} | class ____:
pass
def call_tf(
callable_tf: Callable,
has_side_effects=True,
ordered=False,
output_shape_dtype=UnspecifiedOutputShapeDtype(),
call_tf_graph=False,
) -> Callable:
"""Calls a TensorFlow function from JAX, with support for reverse autodiff.
The ``callable_tf`` will be called with TensorFlow-compatible arguments (
numpy.ndarray, ``tf.Tensor`` or ``tf.Variable``) or pytrees thereof. The
function must return the same type of results.
If ``call_tf`` appears in a JAX staging context (:func:`jax.jit`,
or :func:`jax.pmap`, or a control-flow primitive) then
``callable_tf`` will be compiled with ``tf.function(callable_tf,
jit_compile=True)``
and the resulting XLA computation will be embedded in JAX's XLA computation.
If ``call_tf`` appears outside a JAX staging context, it will be called inline
using TensorFlow eager mode.
The ``call_tf`` supports JAX's reverse-mode autodiff, in which case the
``callable_tf`` will be differentiated using ``tf.GradientTape``. This means
that the gradient will be TensorFlow-accurate, e.g., will respect the
custom gradients that may be defined for the code in ``callable_tf``.
For an example and more details see the
`README
<https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md#calling-tensorflow-functions-from-jax>`_.
Args:
callable_tf: a TensorFlow Callable that can take a pytree of TensorFlow
arguments.
has_side_effects: if True then it ensures that instances of this primitive
are not removed or replicated by JAX optimizations such as dead-code
elimination.
ordered: If true, calls are modeled as having ordered effects.
output_shape_dtype: An optional declaration of the expected shape and dtype
of the result of the called TensorFlow function. If given it will be used
during JAX tracing to form the abstract values of the results of the
`call_tf`. If not given then we form a `tf.Graph` for the called
TensorFlow function and we use the TensorFlow-inferred shapes and types.
Must be a pytree matching the structure of the nested structure returned
from the TensorFlow function, containing objects with `.shape` and
`.dtype` attributes, e.g., `jax.ShapeDtypeStruct` or `jax.Array`.
call_tf_graph: EXPERIMENTAL, DO NOT USE. We may change the name in the
future.
Returns: a JAX callable that can be invoked with JAX pytree arguments, in
op-by-op mode or in a staged context. This callable can be used with JAX's
reverse-mode autodiff (:func:`jax.grad`).
"""
@jax.custom_vjp
def make_call(*args_jax):
"""We wrap it all in `make_call` so that we can attach custom VJP."""
args_flat_jax, args_treedef = tree_util.tree_flatten(args_jax)
# Canonicalize the arguments; e.g., makes them x32 if JAX is in 32-bit mode
def canonical_arg(v):
v = v if getattr(v, "dtype", None) else np.asarray(v)
dtype = dtypes.canonicalize_dtype(v.dtype)
if dtype != v.dtype:
v = v.astype(dtype)
return v
args_flat_jax = tuple(map(canonical_arg, args_flat_jax))
def make_tensorspec(a_jax):
a_tf_dtype = jax2tf_internal._to_tf_dtype(a_jax.dtype)
a_tf_shape = [d if core.is_constant_dim(d) else None for d in getattr(a_jax, "shape", ())]
return tf.TensorSpec(a_tf_shape, a_tf_dtype)
args_flat_sig_tf = tuple(map(make_tensorspec, args_flat_jax))
if not isinstance(output_shape_dtype, UnspecifiedOutputShapeDtype):
output_shape_dtype_flat, output_shape_dtype_tree = tree_util.tree_flatten(output_shape_dtype)
output_avals = tuple(core.ShapedArray(st.shape, st.dtype) for st in output_shape_dtype_flat)
else:
output_avals, output_shape_dtype_tree = None, None
res_treedef = None # We'll store here the result treedef
res_tf_flat = None # For error reporting
# The function below will be called at least once, either in eager
# mode during jax2tf_call_tf or in graph mode during _get_concrete_function_tf()
def callable_flat_tf(*args_tf_flat: TfVal) -> Sequence[TfVal]:
args_tf = args_treedef.unflatten(args_tf_flat)
res_tf = callable_tf(*args_tf)
# b/279454591: When `callable_tf` is a tf function with zero outputs, it
# returns a `StatefulPartitionedCall` (if the function is stateful) or
# `PartitionedCall` (if the function is stateless) op instead of
# tf.Tensors. We work around this issue by replacing the output `res_tf`
# with an empty list.
if isinstance(res_tf, tf.Operation):
assert (
res_tf.type == "StatefulPartitionedCall"
or res_tf.type == "PartitionedCall"
)
t_out = res_tf.get_attr("Tout")
# t_out should be an empty list.
assert not t_out, (
"The TF function returned an unexpected result, please check its"
f" function body. res_tf = {res_tf}"
)
res_tf = t_out
nonlocal res_treedef, res_tf_flat
res_tf_flat, res_treedef_now = tree_util.tree_flatten(res_tf)
assert res_treedef is None or res_treedef == res_treedef_now, (
f"Subsequent calls had different results. Previous {res_treedef} and now {res_treedef_now}")
res_treedef = res_treedef_now
if output_avals is not None:
if res_treedef != output_shape_dtype_tree:
raise ValueError(
"The pytree of the TensorFlow function results does not match the "
"pytree of the declared output_shape_dtype:\n"
f"results pytree: {res_treedef}\noutput_shape_dtype tree: {output_shape_dtype_tree}")
assert len(output_avals) == len(res_tf_flat)
checked_res_tf_flat = [
check_tf_result(i, r_tf, r_aval)
for i, (r_tf, r_aval) in enumerate(
zip(res_tf_flat,
(output_avals
if output_avals is not None
else (None,) * len(res_tf_flat))))]
return checked_res_tf_flat
# Prepare a tf.function ahead of time, to cache the concrete functions. This
# won't be used in op-by-op execution mode.
function_flat_tf = tf.function(
callable_flat_tf, autograph=False, jit_compile=not call_tf_graph)
res_jax_flat = call_tf_p.bind(
*args_flat_jax,
# Carry the actual function such that op-by-op call can call in TF eager mode.
callable_flat_tf=callable_flat_tf,
function_flat_tf=function_flat_tf,
args_flat_sig_tf=args_flat_sig_tf,
output_avals=output_avals,
has_side_effects=has_side_effects,
ordered=ordered,
call_tf_graph=call_tf_graph,
)
# We must have called callable_flat_tf by nοw
assert res_treedef is not None
return res_treedef.unflatten(res_jax_flat)
# Define the fwd and bwd custom_vjp functions
def make_call_vjp_fwd(*args_jax):
# Return the primal arguments as the residual
return make_call(*args_jax), args_jax
def make_call_vjp_bwd(residual_jax, ct_res_jax):
args_jax = residual_jax # residual is the primal argument
def tf_vjp_fun(args_tf, ct_res_tf):
"""Invoke TF gradient."""
# TF does not like us to watch non-float vars or Nones.
def replace_non_float_or_none(arg_tf):
if arg_tf is not None and (
arg_tf.dtype.is_floating or arg_tf.dtype.is_complex
):
return arg_tf
else:
# When watched, this will be ignored. When used in results it will
# result in a floating 0. gradient, which JAX will ignore (and
# replace it with a float0)
return tf.zeros((), dtype=tf.float32)
watched_args_tf = tf.nest.map_structure(
replace_non_float_or_none, args_tf
)
with tf.GradientTape(persistent=True) as tape:
tape.watch(watched_args_tf)
res = callable_tf(*args_tf)
tf.nest.assert_same_structure(res, ct_res_tf)
dres_darg = tape.gradient(
tf.nest.map_structure(replace_non_float_or_none, res),
sources=watched_args_tf,
output_gradients=ct_res_tf,
unconnected_gradients=tf.UnconnectedGradients.ZERO,
)
dres_darg = tree_util.tree_map(
lambda x: x if x is None else tf.convert_to_tensor(x),
dres_darg,
)
# callable_tf may mutate (the structure of) args_tf, thus we check against
# watched_args_tf which should be structurally the same as the original
# args_tf.
tf.nest.assert_same_structure(dres_darg, watched_args_tf)
return dres_darg
# Use call_tf to call the VJP function
ct_args_jax = call_tf(tf_vjp_fun)(args_jax, ct_res_jax)
# We must make the float0s that JAX expects
def fix_float0(arg_jax, ct_arg_jax):
if arg_jax is None:
return None
arg_dtype = dtypes.result_type(arg_jax) # May be scalar
ct_arg_dtype = core.primal_dtype_to_tangent_dtype(arg_dtype)
if ct_arg_dtype != ct_arg_jax.dtype:
return ad_util.zeros_like_aval(core.ShapedArray(np.shape(arg_jax),
ct_arg_dtype))
return ct_arg_jax
ct_args_jax_fixed = tree_util.tree_map(fix_float0, args_jax, ct_args_jax,
is_leaf=lambda x: x is None)
return ct_args_jax_fixed
make_call.defvjp(make_call_vjp_fwd, make_call_vjp_bwd)
return util.wraps(callable_tf)(make_call)
def check_tf_result(idx: int, r_tf: TfVal, r_aval: core.ShapedArray | None) -> TfVal:
# Check that the TF function returns values of expected types. This
# improves error reporting, preventing hard-to-diagnose errors downstream
try:
jax2tf_internal._tfval_to_tensor_jax_dtype(r_tf)
except Exception as e:
msg = ("The called TF function returns a result that is not "
f"convertible to JAX: {r_tf}.")
raise ValueError(msg) from e
if r_aval is None:
return r_tf
# We convert to TF type, and canonicalize to 32-bit if necessary
r_aval_dtype_tf = jax2tf_internal._to_tf_dtype(r_aval.dtype)
# Checking shapes is trickier in presence of dynamic shapes. I wish we could
# check at runtime that the returned shape matches the declared shape. I wish
# that tf.ensure_shape did this, but it can only take shapes that contain None
# not computed shapes. However, in eager mode we should be able to resolve
# the declared shapes to constants and we get better checking.
r_aval_shape_tf = jax2tf_internal._aval_to_tf_shape(r_aval)
# We do as much checking as we can here, instead of relying on tf.ensure_shape
# because the latter gives different errors in eager vs. compiled mode.
# TODO(b/279454591): This strange error is from TF. Eager function suppose
# return tf Val with concrete shape but not. Here we change exception to warn
# and bypass it. This case need revisit on TF side.
try:
_ = len(r_tf.shape)
except ValueError as e:
msg = (
"The shape check test cannot be performed because the shape of the"
"`r_tf` tensor cannot be obtained."
f"r_tf = {r_tf}, r_aval = {r_aval}"
)
msg += str(e)
logging.warning(msg)
return r_tf
if (r_tf.dtype != r_aval_dtype_tf or
len(r_tf.shape) != len(r_aval_shape_tf) or
any(r_aval_d is not None and r_tf_d is not None and r_aval_d != r_tf_d
for r_tf_d, r_aval_d in zip(r_tf.shape, r_aval_shape_tf))):
msg = ("The shapes or dtypes returned by the TensorFlow function "
"do not match the declared output_shape_dtype:\n"
f"Result[{idx}] is {r_tf.dtype}[{r_tf.shape}] vs. expected {r_aval_dtype_tf}[{r_aval_shape_tf}]")
raise ValueError(msg)
# At this point tf.ensure_shape does not do much, it should never throw an
# error, albeit it may refine the shape a bit.
return tf.ensure_shape(r_tf, r_aval_shape_tf)
call_tf_p = core.Primitive("call_tf")
call_tf_p.multiple_results = True
# The impl will be used in op-by-op mode and calls callable_tf in TF eager mode.
def _call_tf_impl(*args_jax_flat, callable_flat_tf, **_):
# On GPU we use dlpack to avoid copies of data to the host.
def _arg_jax_to_tf(arg_jax):
if (isinstance(arg_jax, jax.Array) and
list(arg_jax.devices())[0].platform in _DLPACK_PLATFORMS and
dlpack.is_supported_dtype(arg_jax.dtype)):
return tf.experimental.dlpack.from_dlpack(arg_jax.__dlpack__())
# The following avoids copies to the host on CPU, always for Array
# and even for ndarray if they are sufficiently aligned.
# TODO(necula): on TPU this copies to the host!
if getattr(arg_jax, 'dtype', None) == dtypes.float0:
return tf.zeros(shape=arg_jax.shape,
dtype=jax2tf_internal._tf_np_dtype_for_float0)
return tf.constant(np.asarray(arg_jax))
args_tf_flat = tuple(map(_arg_jax_to_tf, args_jax_flat))
with jax2tf_internal.inside_call_tf():
# Call in TF eager mode
res_tf_flat = callable_flat_tf(*args_tf_flat)
def _res_tf_to_jax(res_tf: TfVal):
res_tf, jax_dtype = jax2tf_internal._tfval_to_tensor_jax_dtype(res_tf)
if isinstance(res_tf, tf.Tensor) and dlpack.is_supported_dtype(jax_dtype):
res_tf_platform = tf.DeviceSpec.from_string(res_tf.backing_device).device_type
res_jax_platform = res_tf_platform.lower()
if res_jax_platform in _DLPACK_PLATFORMS:
return jax.dlpack.from_dlpack(res_tf)
# When working with a bfloat16 scalar tf.Tensor,np.asarray() can fail.
# To handle this special case, we create a numpy copy.
if res_tf.shape == tf.TensorShape([]) and res_tf.dtype == tf.bfloat16:
return jax.device_put(jnp.array(res_tf.numpy()))
else:
return jax.device_put(np.asarray(res_tf))
return list(map(_res_tf_to_jax, res_tf_flat))
call_tf_p.def_impl(_call_tf_impl)
@functools.lru_cache(maxsize=128)
def _get_concrete_function_tf(function_flat_tf, args_flat_sig_tf): # -> tf.ConcreteFunction
with jax2tf_internal.inside_call_tf():
return function_flat_tf.get_concrete_function(*args_flat_sig_tf)
# Mark the effectful instances of call_tf
@dataclasses.dataclass(frozen=True)
| UnspecifiedOutputShapeDtype |
python | pytorch__pytorch | torch/_decomp/decompositions_for_rng.py | {
"start": 3558,
"end": 9187
} | class ____:
"""
Singleton class to track the philox rng state during AOT Autograd tracing.
For each aot tracing instance, AOT Autograd resets this tracker and keeps
track of both forward and backward offsets. At runtime, we only care about
the total consumed forward and backward offsets. For dynamic shapes, these
offsets are a function of input shapes. Therefore, the AOT generated graphs
have additional outputs that compute total consumed forward and backward
offsets.
"""
running_state: PhiloxState
fwd_state: PhiloxState
bwd_state: PhiloxState
def __enter__(self):
PhiloxStateTracker.reset()
return self
def __exit__(self, exc_type, exc_cal, exc_tb):
PhiloxStateTracker.reset()
@classmethod
def reset(cls):
cls.running_state = PhiloxState()
cls.fwd_state = PhiloxState()
cls.bwd_state = PhiloxState()
@classmethod
def mark_beginning_of_forward(cls):
# Tells the tracker to use fwd_state as the running state
cls.running_state = cls.fwd_state
@classmethod
def mark_beginning_of_backward(cls):
# Tells the tracker to use bwd_state as the running state
cls.running_state = cls.bwd_state
@classmethod
def record_state(cls, seed, offset, mode):
# Records the seed and offset tensors. These tensors are used to invoke
# the philox_rand functional primitives.
if mode == "forward":
cls.fwd_state.set_state(seed, offset)
cls.mark_beginning_of_forward()
else:
assert mode == "backward"
cls.bwd_state.set_state(seed, offset)
@classmethod
def get_state_as_tensor(cls):
# The only reason this exists is because we override get_rng_state and
# set_rng_state during tracing. get_rng_state expects a tensor output,
# so return (seed, offset) tuple upset other parts of the program like
# ctx.saved_tensors.
# A bad consequence is that if user saves and restores rng state, we
# have little bit of ugliness in the generated code, where we first
# concat the (seed, offset) to create a tensor for get_rng_state, and
# then split it back to get (seed, offset) tuple in set_rng_state.
# TODO: Investigate if there is be a better way to wrap the tuple in a
# false Tensor object, and then desugar it later on.
return cls.running_state.get_state_as_tensor()
@classmethod
def get_state_as_tuple(cls):
return cls.running_state.get_state_as_tuple()
@classmethod
def set_state_from_tensor(cls, x):
# This is only needed because we override set_rng_state. Look at the
# comment in get_state_from_tensor method.
cls.running_state.set_state_from_tensor(x)
@classmethod
def advance_offset(cls, consumed_offset):
cls.running_state.advance_offset(consumed_offset)
@classmethod
def get_current_relative_offset(cls):
return cls.running_state.relative_offset
@staticmethod
def multiple_of_4(offset):
# torch cuda rng state offset must be a multiple of 4. For inductor, as
# we sum up all the numel, the result might not be a multiple of 4. This
# method achieves that.
return (offset + 3) // 4 * 4
@classmethod
def get_updated_fwd_offset(cls):
# Short circuit if no rand ops were observed
if not cls.fwd_state.offset_advanced_alteast_once:
return cls.fwd_state.base_offset
return cls.multiple_of_4(
cls.fwd_state.base_offset + cls.fwd_state.relative_offset
)
@classmethod
def get_updated_bwd_offset(cls):
# Short circuit if no rand ops were observed
if not cls.bwd_state.offset_advanced_alteast_once:
return cls.bwd_state.base_offset
return cls.multiple_of_4(
cls.bwd_state.base_offset + cls.bwd_state.relative_offset
)
# Adding more decompositions which eventually use rand_like inside decomps.
# Adding these in rng_decompositions ensures the functionalization of rand_like
# ops used in these decomps. The list is copied from inductor codebase, which
# uses it for similar purpose.
#
# Caution - These decomps do not have same accuracy as that of eager. However,
# we can't just disable them with a config flag like fallback_random, because
# for functionalization of rng ops, we have to decompose these ops.
extra_random_decomps = get_decompositions(
[
aten.cauchy,
aten.cauchy_,
aten.exponential,
aten.exponential_,
aten.geometric,
aten.geometric_,
aten.native_dropout,
aten.normal,
aten.normal_,
aten.normal_functional,
aten.log_normal,
aten.log_normal_,
aten.rrelu_with_noise,
aten.rrelu_with_noise_,
aten.uniform_,
]
)
register_extra_random_decomp = functools.partial(
decomp.register_decomposition, registry=extra_random_decomps
)
@register_extra_random_decomp([aten.bernoulli_])
def bernoulli_(self, p=0.5):
if self.device == torch.device("cpu"):
return NotImplemented
return self.copy_(torch.rand_like(self, dtype=torch.float32) < p)
@register_extra_random_decomp([aten.bernoulli.p])
def bernoulli_p(self, p=0.5, *, generator=None):
if self.device == torch.device("cpu"):
return NotImplemented
assert generator is None
return torch.rand_like(self, dtype=torch.float32) < p
rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type]
| PhiloxStateTracker |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 139323,
"end": 140019
} | class ____(Generic[_P, R]):
def __init__(self, f: Callable[_P, R]) -> None:
self.f = f
self.__name__ = "wrapped_" + self.f.__name__
def __repr__(self) -> str:
return f"<Wrapped function <original {self.f.__name__}>>"
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any:
out = self.f(*args, **kwargs)
return numpy_to_tensor(out)
def numpy_attr_wrapper(obj: Any, name: str) -> Any:
if isinstance(obj, tnp.ndarray):
out = getattr(obj, name)
return numpy_to_tensor(out)
elif isinstance(obj, torch.Tensor):
out = getattr(tnp.ndarray(obj), name)
return numpy_to_tensor(out)
| numpy_to_tensor_wrapper |
python | tiangolo__fastapi | scripts/people.py | {
"start": 1837,
"end": 2015
} | class ____(BaseModel):
number: int
author: Union[Author, None] = None
title: str | None = None
createdAt: datetime
comments: DiscussionsComments
| DiscussionsNode |
python | doocs__leetcode | solution/1700-1799/1742.Maximum Number of Balls in a Box/Solution.py | {
"start": 0,
"end": 292
} | class ____:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
cnt = [0] * 50
for x in range(lowLimit, highLimit + 1):
y = 0
while x:
y += x % 10
x //= 10
cnt[y] += 1
return max(cnt)
| Solution |
python | pytorch__pytorch | torch/export/_draft_export.py | {
"start": 5735,
"end": 7673
} | class ____:
def __init__(
self,
failures: list[FailureReport],
str_to_filename: dict[int, str],
expressions_created: dict[int, dict[str, Any]],
op_profiles: dict[str, set[OpProfile]],
):
self.failures: list[FailureReport] = failures
self.str_to_filename = str_to_filename
self.expressions_created: dict[int, dict[str, Any]] = expressions_created
self.op_profiles = op_profiles
def successful(self) -> bool:
return len(self.failures) == 0 or all(
failure.xfail for failure in self.failures
)
def __repr__(self) -> str:
return f"DraftExportReport({self.failures})"
def __str__(self) -> str:
WARNING_COLOR = "\033[93m"
GREEN_COLOR = "\033[92m"
END_COLOR = "\033[0m"
if self.successful():
return f"""{GREEN_COLOR}
##############################################################################################
Congratuations: No issues are found during export, and it was able to soundly produce a graph.
You can now change back to torch.export.export()
##############################################################################################
{END_COLOR}"""
error = f"""{WARNING_COLOR}
###################################################################################################
WARNING: {len(self.failures)} issue(s) found during export, and it was not able to soundly produce a graph.
Please follow the instructions to fix the errors.
###################################################################################################
"""
for i, failure in enumerate(self.failures):
error += f"{i + 1}. {failure.print(self.str_to_filename)}\n"
error += END_COLOR
return error
def apply_suggested_fixes(self) -> None:
raise NotImplementedError("Not implemented yet")
@dataclass
| DraftExportReport |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_new_mexico_zip.py | {
"start": 1766,
"end": 4123
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid New Mexico zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_new_mexico_zip": ["87001", "87564", "88119", "88439"],
"invalid_new_mexico_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_new_mexico_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_new_mexico_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_new_mexico_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidNewMexicoZip().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidNewMexicoZip |
python | walkccc__LeetCode | solutions/1206. Design Skiplist/1206.py | {
"start": 121,
"end": 1673
} | class ____:
def __init__(self):
self.dummy = Node()
def search(self, target: int) -> bool:
node = self.dummy
while node:
while node.next and node.next.val < target:
node = node.next
if node.next and node.next.val == target:
return True
# Move to the next level
node = node.down
return False
def add(self, num: int) -> None:
# Collect nodes that are before the insertion point.
nodes = []
node = self.dummy
while node:
while node.next and node.next.val < num:
node = node.next
nodes.append(node)
# Move to the next level
node = node.down
shouldInsert = True
down = None
while shouldInsert and nodes:
node = nodes.pop()
node.next = Node(num, node.next, down)
down = node.next
shouldInsert = random.getrandbits(1) == 0
# Create a topmost new level dummy that points to the existing dummy.
if shouldInsert:
self.dummy = Node(-1, None, self.dummy)
def erase(self, num: int) -> bool:
node = self.dummy
found = False
while node:
while node.next and node.next.val < num:
node = node.next
if node.next and node.next.val == num:
# Delete the node
node.next = node.next.next
found = True
# Move to the next level
node = node.down
return found
# Move to the node s.t. node.next.val >= target
def _advance(self, node: Node, target: int) -> None:
while node.next and node.next.val < target:
node = node.next
| Skiplist |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 5454,
"end": 5534
} | class ____(BaseModel):
name: str
type: str = "function"
| ToolChoiceFunction |
python | realpython__materials | asterioids-pygame-project/source_code_step_5/space_rocks/models.py | {
"start": 779,
"end": 1619
} | class ____(GameObject):
MANEUVERABILITY = 3
ACCELERATION = 0.25
def __init__(self, position):
# Make a copy of the original UP vector
self.direction = Vector2(UP)
super().__init__(position, load_sprite("spaceship"), Vector2(0))
def rotate(self, clockwise=True):
sign = 1 if clockwise else -1
angle = self.MANEUVERABILITY * sign
self.direction.rotate_ip(angle)
def accelerate(self):
self.velocity += self.direction * self.ACCELERATION
def draw(self, surface):
angle = self.direction.angle_to(UP)
rotated_surface = rotozoom(self.sprite, angle, 1.0)
rotated_surface_size = Vector2(rotated_surface.get_size())
blit_position = self.position - rotated_surface_size * 0.5
surface.blit(rotated_surface, blit_position)
| Spaceship |
python | pyinstaller__pyinstaller | PyInstaller/building/datastruct.py | {
"start": 1258,
"end": 5226
} | class ____(list):
"""
TOC (Table of Contents) class is a list of tuples of the form (name, path, typecode).
typecode name path description
--------------------------------------------------------------------------------------
EXTENSION Python internal name. Full path name in build. Extension module.
PYSOURCE Python internal name. Full path name in build. Script.
PYMODULE Python internal name. Full path name in build. Pure Python module (including __init__ modules).
PYZ Runtime name. Full path name in build. A .pyz archive (ZlibArchive data structure).
PKG Runtime name. Full path name in build. A .pkg archive (Carchive data structure).
BINARY Runtime name. Full path name in build. Shared library.
DATA Runtime name. Full path name in build. Arbitrary files.
OPTION The option. Unused. Python runtime option (frozen into executable).
A TOC contains various types of files. A TOC contains no duplicates and preserves order.
PyInstaller uses TOC data type to collect necessary files bundle them into an executable.
"""
def __init__(self, initlist=None):
super().__init__()
# Deprecation warning
warnings.warn(
"TOC class is deprecated. Use a plain list of 3-element tuples instead.",
DeprecationWarning,
stacklevel=2,
)
self.filenames = set()
if initlist:
for entry in initlist:
self.append(entry)
def append(self, entry):
if not isinstance(entry, tuple):
logger.info("TOC found a %s, not a tuple", entry)
raise TypeError("Expected tuple, not %s." % type(entry).__name__)
unique = unique_name(entry)
if unique not in self.filenames:
self.filenames.add(unique)
super().append(entry)
def insert(self, pos, entry):
if not isinstance(entry, tuple):
logger.info("TOC found a %s, not a tuple", entry)
raise TypeError("Expected tuple, not %s." % type(entry).__name__)
unique = unique_name(entry)
if unique not in self.filenames:
self.filenames.add(unique)
super().insert(pos, entry)
def __add__(self, other):
result = TOC(self)
result.extend(other)
return result
def __radd__(self, other):
result = TOC(other)
result.extend(self)
return result
def __iadd__(self, other):
for entry in other:
self.append(entry)
return self
def extend(self, other):
# TODO: look if this can be done more efficient with out the loop, e.g. by not using a list as base at all.
for entry in other:
self.append(entry)
def __sub__(self, other):
# Construct new TOC with entries not contained in the other TOC
other = TOC(other)
return TOC([entry for entry in self if unique_name(entry) not in other.filenames])
def __rsub__(self, other):
result = TOC(other)
return result.__sub__(self)
def __setitem__(self, key, value):
if isinstance(key, slice):
if key == slice(None, None, None):
# special case: set the entire list
self.filenames = set()
self.clear()
self.extend(value)
return
else:
raise KeyError("TOC.__setitem__ doesn't handle slices")
else:
old_value = self[key]
old_name = unique_name(old_value)
self.filenames.remove(old_name)
new_name = unique_name(value)
if new_name not in self.filenames:
self.filenames.add(new_name)
super(TOC, self).__setitem__(key, value)
| TOC |
python | celery__celery | t/unit/tasks/test_result.py | {
"start": 32670,
"end": 34096
} | class ____:
def setup_method(self):
@self.app.task(shared=False)
def raising(x, y):
raise KeyError(x, y)
self.raising = raising
def test_wait_raises(self):
res = self.raising.apply(args=[3, 3])
with pytest.raises(KeyError):
res.wait()
assert res.wait(propagate=False)
def test_wait(self):
res = EagerResult('x', 'x', states.RETRY)
res.wait()
assert res.state == states.RETRY
assert res.status == states.RETRY
def test_forget(self):
res = EagerResult('x', 'x', states.RETRY)
res.forget()
def test_revoke(self):
res = self.raising.apply(args=[3, 3])
assert not res.revoke()
@patch('celery.result.task_join_will_block')
def test_get_sync_subtask_option(self, task_join_will_block):
task_join_will_block.return_value = True
tid = uuid()
res_subtask_async = EagerResult(tid, 'x', 'x', states.SUCCESS)
with pytest.raises(RuntimeError):
res_subtask_async.get()
res_subtask_async.get(disable_sync_subtasks=False)
def test_populate_name(self):
res = EagerResult('x', 'x', states.SUCCESS, None, 'test_task')
assert res.name == 'test_task'
res = EagerResult('x', 'x', states.SUCCESS, name='test_task_named_argument')
assert res.name == 'test_task_named_argument'
| test_EagerResult |
python | getsentry__sentry | src/sentry/integrations/source_code_management/status_check.py | {
"start": 508,
"end": 796
} | class ____(ABC):
base_url: str
@abstractmethod
def create_check_run(self, repo: str, data: dict[str, Any]) -> Any:
raise NotImplementedError
@abstractmethod
def get_check_runs(self, repo: str, sha: str) -> Any:
raise NotImplementedError
| StatusCheckClient |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/inline/err/class_def_unclosed_type_param_list.py | {
"start": 0,
"end": 41
} | class ____[T1, *T2(a, b):
pass
x = 10
| Foo |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chartsheet10.py | {
"start": 315,
"end": 1656
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chartsheet10.xlsx")
def test_create_file(self):
"""Test the worksheet properties of an XlsxWriter chartsheet file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chartsheet = workbook.add_chartsheet()
chart = workbook.add_chart({"type": "bar"})
chart.axis_ids = [61357056, 61363328]
chartsheet.set_header(
"&C&G", {"image_center": self.image_dir + "watermark.png"}
)
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chartsheet.set_landscape()
chartsheet.horizontal_dpi = 200
chartsheet.vertical_dpi = 200
chartsheet.set_chart(chart)
chartsheet.activate()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_write_cell_xfs.py | {
"start": 332,
"end": 1021
} | class ____(unittest.TestCase):
"""
Test the Styles _write_cell_xfs() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_cell_xfs(self):
"""Test the _write_cell_xfs() method"""
xf_format = Format()
xf_format.has_font = True
self.styles._set_style_properties([[xf_format], None, 1, 0, 0, 0, [], [], 0])
self.styles._write_cell_xfs()
exp = """<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestWriteCellXfs |
python | huggingface__transformers | src/transformers/models/falcon_h1/configuration_falcon_h1.py | {
"start": 872,
"end": 14497
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FalconH1Model`]. It is used to instantiate a
FalconH1Model model according to the specified arguments, defining the model architecture. Instantiating a configuration
with defaults taken from [ibm-fms/FalconH1-9.8b-2.2T-hf](https://huggingface.co/ibm-fms/FalconH1-9.8b-2.2T-hf).
The FalconH1Model is a hybrid [mamba2](https://github.com/state-spaces/mamba) architecture with SwiGLU.
The checkpoints are jointly trained by IBM, Princeton, and UIUC.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 128000):
Vocabulary size of the FalconH1 model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`FalconH1Model`]
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
model has a output word embedding layer.
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 14336):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
significantly.
pad_token_id (`int`, *optional*, defaults to 0):
The id of the padding token.
bos_token_id (`int`, *optional*, defaults to 1):
The id of the "beginning-of-sequence" token.
eos_token_id (`int`, *optional*, defaults to 2):
The id of the "end-of-sequence" token.
max_position_embeddings (`int`, *optional*, defaults to 8192):
Max cached sequence length for the model
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
mamba_d_ssm (`int`, *optional*, defaults to 1024):
The dimension of the SSM state space latents.
mamba_n_heads (`int`, *optional*, defaults to 128):
The number of mamba heads used in the v2 implementation.
mamba_d_head (`int`, *optional*, defaults to `"auto"`):
Head embeddding dimension size
mamba_n_groups (`int`, *optional*, defaults to 1):
The number of the mamba groups used in the v2 implementation.
mamba_d_state (`int`, *optional*, defaults to 256):
The dimension the mamba state space latents
mamba_d_conv (`int`, *optional*, defaults to 4):
The size of the mamba convolution kernel
mamba_expand (`int`, *optional*, defaults to 2):
Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
mamba_chunk_size (`int`, *optional*, defaults to 256):
The chunks in which to break the sequence when doing prefill/training
mamba_conv_bias (`bool`, *optional*, defaults to `True`):
Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
mamba_proj_bias (`bool`, *optional*, defaults to `False`):
Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
mamba_norm_before_gate (`bool`, *optional*, defaults to `True`):
Whether to use RMSNorm before the gate in the Mamba block
mamba_rms_norm (`bool`, *optional*, defaults to `False`):
Whether to use RMSNorm instead of LayerNorm in the Mamba block
projectors_bias (`bool`, *optional*, defaults to `False`):
Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the attention block
rope_parameters (`float`, *optional*):
The scaling value used for the RoPE embeddings. If `None`, no scaling is applied.
lm_head_multiplier (`float`, *optional*, defaults to 1.0):
The multiplier for the LM head. This is used to scale the output of the LM head.
embedding_multiplier (`float`, *optional*, defaults to 1.0):
The multiplier for the embedding layer. This is used to scale the output of the embedding layer.
mlp_multipliers (`list[float]`, *optional*):
The multipliers for the MLP layers. This is used to scale the output of the MLP layers. The first value is
the multiplier of gate layer, the second value is the multiplier of the down_proj layer.
key_multiplier (`float`, *optional*):
The multiplier for the key layer. This is used to scale the output of the key layer.
attention_out_multiplier (`float`, *optional*):
The multiplier for the attention output layer. This is used to scale the output of the attention output
attention_in_multiplier (`float`, *optional*):
The multiplier for the attention input layer. This is used to scale the output of the attention input layer.
ssm_multipliers (`list[float]`, *optional*):
The multipliers for the SSM layers. This is used to scale the output of the SSM layers.
ssm_in_multiplier (`float`, *optional*):
The multiplier for the SSM input layer. This is used to scale the output of the SSM input layer.
ssm_out_multiplier (`float`, *optional*):
The multiplier for the SSM output layer. This is used to scale the output of the SSM output layer.
"""
model_type = "falcon_h1"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size: Optional[int] = 128000,
tie_word_embeddings: Optional[bool] = False,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 14336,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = 8,
hidden_act: Optional[str] = "silu",
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-5,
use_cache: Optional[int] = True,
num_logits_to_keep: Optional[int] = 1,
pad_token_id: Optional[int] = 0,
bos_token_id: Optional[int] = 1,
eos_token_id: Optional[int] = 2,
max_position_embeddings: Optional[int] = 8192,
attention_dropout: Optional[float] = 0.0,
mamba_d_ssm: Optional[int] = 1024,
mamba_n_heads: Optional[int] = 128,
mamba_d_head: Optional[str] = "auto",
mamba_n_groups: Optional[int] = 1,
mamba_d_state: Optional[int] = 256,
mamba_d_conv: Optional[int] = 4,
mamba_expand: Optional[int] = 2,
mamba_chunk_size: Optional[int] = 256,
mamba_conv_bias: Optional[bool] = True,
mamba_proj_bias: Optional[bool] = False,
mamba_norm_before_gate: Optional[bool] = True,
mamba_rms_norm: Optional[bool] = False,
projectors_bias: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
lm_head_multiplier: Optional[float] = 1.0,
embedding_multiplier: Optional[float] = 1.0,
mlp_multipliers: Optional[int] = None,
key_multiplier: Optional[int] = None,
attention_out_multiplier: Optional[int] = None,
attention_in_multiplier: Optional[int] = None,
ssm_multipliers: Optional[int] = None,
ssm_in_multiplier: Optional[int] = None,
ssm_out_multiplier: Optional[int] = None,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.max_position_embeddings = max_position_embeddings
self.attention_dropout = attention_dropout
self.attention_bias = False
self.mlp_bias = False
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.num_logits_to_keep = num_logits_to_keep
self.projectors_bias = projectors_bias
mamba_intermediate = mamba_expand * hidden_size if mamba_d_ssm is None else mamba_d_ssm
if mamba_intermediate % mamba_n_heads != 0:
raise ValueError("mamba_n_heads must divide mamba_expand * hidden_size")
# for the mamba_v2, must satisfy the following
if mamba_d_head == "auto":
mamba_d_head = mamba_intermediate // mamba_n_heads
if mamba_d_head * mamba_n_heads != mamba_intermediate:
raise ValueError("The dimensions for the Mamba head state do not match the model intermediate_size")
self.mamba_d_ssm = mamba_d_ssm
self.mamba_n_heads = mamba_n_heads
self.mamba_d_head = mamba_d_head
self.mamba_n_groups = mamba_n_groups
self.mamba_d_state = mamba_d_state
self.mamba_d_conv = mamba_d_conv
self.mamba_expand = mamba_expand
self.mamba_chunk_size = mamba_chunk_size
self.mamba_conv_bias = mamba_conv_bias
self.mamba_proj_bias = mamba_proj_bias
self.mamba_norm_before_gate = mamba_norm_before_gate
self.mamba_rms_norm = mamba_rms_norm
self.lm_head_multiplier = lm_head_multiplier
self.embedding_multiplier = embedding_multiplier
if mlp_multipliers is not None:
self.mlp_multipliers = mlp_multipliers
else:
self.mlp_multipliers = [1.0, 1.0]
if attention_out_multiplier is not None:
self.attention_out_multiplier = attention_out_multiplier
else:
self.attention_out_multiplier = 1.0
if attention_in_multiplier is not None:
self.attention_in_multiplier = attention_in_multiplier
else:
self.attention_in_multiplier = 1.0
if key_multiplier is not None:
self.key_multiplier = key_multiplier
else:
self.key_multiplier = 1.0
if ssm_multipliers is not None:
self.ssm_multipliers = ssm_multipliers
else:
self.ssm_multipliers = [1.0, 1.0, 1.0, 1.0, 1.0]
if ssm_in_multiplier is not None:
self.ssm_in_multiplier = ssm_in_multiplier
else:
self.ssm_in_multiplier = 1.0
if ssm_out_multiplier is not None:
self.ssm_out_multiplier = ssm_out_multiplier
else:
self.ssm_out_multiplier = 1.0
self.rope_parameters = rope_parameters
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@property
def layers_block_type(self):
return ["attention" for i in range(self.num_hidden_layers)]
__all__ = ["FalconH1Config"]
| FalconH1Config |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/filters.py | {
"start": 9654,
"end": 9777
} | class ____(TargetFilter[NetworkInventoryConfig]):
"""Target filter for network inventory."""
| NetworkInventoryTargetFilter |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 1558,
"end": 1960
} | class ____(str, Enum):
"""All possible states of callbacks."""
PENDING = "pending"
QUEUED = "queued"
RUNNING = "running"
SUCCESS = "success"
FAILED = "failed"
def __str__(self) -> str:
return self.value
ACTIVE_STATES = frozenset((CallbackState.QUEUED, CallbackState.RUNNING))
TERMINAL_STATES = frozenset((CallbackState.SUCCESS, CallbackState.FAILED))
| CallbackState |
python | getsentry__sentry | src/sentry/analytics/events/issue_unignored.py | {
"start": 72,
"end": 288
} | class ____(analytics.Event):
user_id: int | None = None
default_user_id: int | str
organization_id: int
group_id: int
transition_type: str
analytics.register(IssueUnignoredEvent)
| IssueUnignoredEvent |
python | dask__distributed | distributed/core.py | {
"start": 40969,
"end": 42656
} | class ____:
"""The result of ConnectionPool()('host:port')
See Also:
ConnectionPool
"""
def __init__(self, addr, pool, serializers=None, deserializers=None):
self.addr = addr
self.pool = pool
self.serializers = serializers
self.deserializers = deserializers if deserializers is not None else serializers
@property
def address(self):
return self.addr
def __getattr__(self, key):
async def send_recv_from_rpc(**kwargs):
if self.serializers is not None and kwargs.get("serializers") is None:
kwargs["serializers"] = self.serializers
if self.deserializers is not None and kwargs.get("deserializers") is None:
kwargs["deserializers"] = self.deserializers
comm = await self.pool.connect(self.addr)
prev_name, comm.name = comm.name, "ConnectionPool." + key
try:
return await send_recv(comm=comm, op=key, **kwargs)
finally:
self.pool.reuse(self.addr, comm)
comm.name = prev_name
return send_recv_from_rpc
async def close_rpc(self):
pass
# For compatibility with rpc()
def __enter__(self):
warnings.warn(
"the rpc synchronous context manager is deprecated",
DeprecationWarning,
stacklevel=2,
)
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
def __repr__(self):
return f"<pooled rpc to {self.addr!r}>"
| PooledRPCCall |
python | ansible__ansible | test/lib/ansible_test/_internal/target.py | {
"start": 16743,
"end": 19242
} | class ____(enum.Enum):
"""Type of integration test target."""
CONTROLLER = enum.auto()
TARGET = enum.auto()
UNKNOWN = enum.auto()
CONFLICT = enum.auto()
def extract_plugin_references(name: str, aliases: list[str]) -> list[tuple[str, str]]:
"""Return a list of plugin references found in the given integration test target name and aliases."""
plugins = content_plugins()
found: list[tuple[str, str]] = []
for alias in [name] + aliases:
plugin_type = 'modules'
plugin_name = alias
if plugin_name in plugins.get(plugin_type, {}):
found.append((plugin_type, plugin_name))
parts = alias.split('_')
for type_length in (1, 2):
if len(parts) > type_length:
plugin_type = '_'.join(parts[:type_length])
plugin_name = '_'.join(parts[type_length:])
if plugin_name in plugins.get(plugin_type, {}):
found.append((plugin_type, plugin_name))
return found
def categorize_integration_test(name: str, aliases: list[str], force_target: bool) -> tuple[IntegrationTargetType, IntegrationTargetType]:
"""Return the integration test target types (used and actual) based on the given target name and aliases."""
context_controller = f'context/{IntegrationTargetType.CONTROLLER.name.lower()}' in aliases
context_target = f'context/{IntegrationTargetType.TARGET.name.lower()}' in aliases or force_target
actual_type = None
strict_mode = data_context().content.is_ansible
if context_controller and context_target:
target_type = IntegrationTargetType.CONFLICT
elif context_controller and not context_target:
target_type = IntegrationTargetType.CONTROLLER
elif context_target and not context_controller:
target_type = IntegrationTargetType.TARGET
else:
target_types = {IntegrationTargetType.TARGET if plugin_type in ('modules', 'module_utils') else IntegrationTargetType.CONTROLLER
for plugin_type, plugin_name in extract_plugin_references(name, aliases)}
if len(target_types) == 1:
target_type = target_types.pop()
elif not target_types:
actual_type = IntegrationTargetType.UNKNOWN
target_type = actual_type if strict_mode else IntegrationTargetType.TARGET
else:
target_type = IntegrationTargetType.CONFLICT
return target_type, actual_type or target_type
| IntegrationTargetType |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/api/test_client.py | {
"start": 1416,
"end": 3935
} | class ____:
def test_error_parsing(self):
def handle_request(request: httpx.Request) -> httpx.Response:
"""
A transport handle that always returns errors
"""
return httpx.Response(422, json={"detail": [{"loc": ["#0"], "msg": "err", "type": "required"}]})
client = Client(base_url="", token="", mounts={"'http://": httpx.MockTransport(handle_request)})
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert isinstance(err.value, ServerResponseError)
assert err.value.args == (
"Client error message: {'detail': [{'loc': ['#0'], 'msg': 'err', 'type': 'required'}]}",
)
def test_error_parsing_plain_text(self):
def handle_request(request: httpx.Request) -> httpx.Response:
"""
A transport handle that always returns errors
"""
return httpx.Response(422, content=b"Internal Server Error")
client = Client(base_url="", token="", mounts={"'http://": httpx.MockTransport(handle_request)})
with pytest.raises(httpx.HTTPStatusError) as err:
client.get("http://error")
assert not isinstance(err.value, ServerResponseError)
def test_error_parsing_other_json(self):
def handle_request(request: httpx.Request) -> httpx.Response:
# Some other json than an error body.
return httpx.Response(404, json={"detail": "Not found"})
client = Client(base_url="", token="", mounts={"'http://": httpx.MockTransport(handle_request)})
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert err.value.args == ("Client error message: {'detail': 'Not found'}",)
@pytest.mark.parametrize(
("base_url", "client_kind", "expected_base_url"),
[
("http://localhost:8080", ClientKind.CLI, "http://localhost:8080/api/v2/"),
("http://localhost:8080", ClientKind.AUTH, "http://localhost:8080/auth/"),
("https://example.com", ClientKind.CLI, "https://example.com/api/v2/"),
("https://example.com", ClientKind.AUTH, "https://example.com/auth/"),
],
)
def test_refresh_base_url(self, base_url, client_kind, expected_base_url):
client = Client(base_url="", token="", mounts={})
client.refresh_base_url(base_url=base_url, kind=client_kind)
assert client.base_url == URL(expected_base_url)
| TestClient |
python | gevent__gevent | src/greentest/3.10/test_context.py | {
"start": 11997,
"end": 12387
} | class ____:
def __init__(self, *, error_on_hash=False, error_on_eq=False):
self.error_on_hash = error_on_hash
self.error_on_eq = error_on_eq
def __enter__(self):
if HashKey._crasher is not None:
raise RuntimeError('cannot nest crashers')
HashKey._crasher = self
def __exit__(self, *exc):
HashKey._crasher = None
| HaskKeyCrasher |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 69308,
"end": 69493
} | class ____(BaseModel, extra="forbid"):
"""
Exact match of the given value
"""
value: "ValueVariants" = Field(..., description="Exact match of the given value")
| MatchValue |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 32731,
"end": 33704
} | class ____(TestCase):
"""
An appropriate error is raised if no auth backends are provided.
"""
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user("test", "test@example.com", "test")
def test_raises_exception(self):
msg = (
"No authentication backends have been defined. "
"Does AUTHENTICATION_BACKENDS contain anything?"
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.user.has_perm(("perm", TestObj()))
async def test_araises_exception(self):
msg = (
"No authentication backends have been defined. "
"Does AUTHENTICATION_BACKENDS contain anything?"
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
await self.user.ahas_perm(("perm", TestObj()))
@override_settings(
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"]
)
| NoBackendsTest |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/sensors/metastore_partition.py | {
"start": 1043,
"end": 3379
} | class ____(SqlSensor):
"""
An alternative to the HivePartitionSensor that talk directly to the MySQL db.
This was created as a result of observing sub optimal queries generated by the
Metastore thrift service when hitting subpartitioned tables. The Thrift service's
queries were written in a way that would not leverage the indexes.
:param schema: the schema
:param table: the table
:param partition_name: the partition name, as defined in the PARTITIONS
table of the Metastore. Order of the fields does matter.
Examples: ``ds=2016-01-01`` or
``ds=2016-01-01/sub=foo`` for a sub partitioned table
:param mysql_conn_id: a reference to the MySQL conn_id for the metastore
"""
template_fields: Sequence[str] = ("partition_name", "table", "schema")
ui_color = "#8da7be"
def __init__(
self,
*,
table: str,
partition_name: str,
schema: str = "default",
mysql_conn_id: str = "metastore_mysql",
**kwargs: Any,
):
self.partition_name = partition_name
self.table = table
self.schema = schema
self.first_poke = True
self.conn_id = mysql_conn_id
# TODO(aoen): We shouldn't be using SqlSensor here but MetastorePartitionSensor.
# The problem is the way apply_defaults works isn't compatible with inheritance.
# The inheritance model needs to be reworked in order to support overriding args/
# kwargs with arguments here, then 'conn_id' and 'sql' can be passed into the
# constructor below and apply_defaults will no longer throw an exception.
super().__init__(**kwargs)
def poke(self, context: Context) -> Any:
if self.first_poke:
self.first_poke = False
if "." in self.table:
self.schema, self.table = self.table.split(".")
self.sql = f"""
SELECT 'X'
FROM PARTITIONS A0
LEFT OUTER JOIN TBLS B0 ON A0.TBL_ID = B0.TBL_ID
LEFT OUTER JOIN DBS C0 ON B0.DB_ID = C0.DB_ID
WHERE
B0.TBL_NAME = '{self.table}' AND
C0.NAME = '{self.schema}' AND
A0.PART_NAME = '{self.partition_name}';
"""
return super().poke(context)
| MetastorePartitionSensor |
python | pytorch__pytorch | test/dynamo/test_export_mutations.py | {
"start": 182,
"end": 3325
} | class ____(torch._dynamo.test_case.TestCase):
def check_failure_on_export(self, mod, *args):
with self.assertRaises(AssertionError):
torch._dynamo.export(mod)(*args)
def check_same_with_export(self, mod, arg):
real_result = mod(arg)
graph, _ = torch._dynamo.export(mod)(arg)
result = graph(arg)
self.assertEqual(result, real_result)
def test_module_attribute_mutation_violation_positive_1(self):
# Mutating attribute with a Tensor type
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = torch.randn(3, 2)
def forward(self, x):
self.a = self.a.to(torch.float64)
return x.sum() + self.a.sum()
self.check_same_with_export(Foo(), torch.randn(3, 2))
def test_module_attribute_mutation_violation_negative_1(self):
# Mutating attribute with a Tensor type inside __init__ but
# not in forward()
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = torch.randn(3, 2)
def forward(self, x):
return x.sum() + self.a.to(torch.float64).sum()
self.check_same_with_export(Foo(), torch.randn(3, 2))
def test_module_attribute_mutation_violation_negative_2(self):
# Mutating attribute with a Tensor type inside __init__ twice
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = torch.randn(3, 2)
self.a = self.a.to(torch.float64)
def forward(self, x):
return x.sum() + self.a.sum()
self.check_same_with_export(Foo(), torch.randn(3, 2))
def test_module_attribute_mutation_violation_negative_3(self):
# Mutating local variable inside forward()
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = torch.randn(3, 2)
def forward(self, x):
b = 1
b = b * 5
return x.sum() + self.a.sum() + b
self.check_same_with_export(Foo(), torch.randn(3, 2))
@unittest.skipIf(IS_FBCODE, "Broken in fbcode")
def test_module_attribute_mutation_violation_negative_4(self):
# Mutating attribute with a Tensor type
# But not exporting but using eager mode as well as dynamo optimize mode
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = torch.randn(3, 2)
def forward(self, x):
self.a = self.a.to(torch.float64)
return x.sum() + self.a.sum()
mod = Foo()
arg = torch.randn(3, 2)
real_result = mod(arg)
opt_mod = torch.compile(mod, backend="eager", fullgraph=True)
self.assertEqual(opt_mod(arg), real_result)
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
run_tests()
| MutationExportTests |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 3063,
"end": 3184
} | class ____(DetailView):
model = BucketDataRegisterRequestUser
fields = ["data"]
| BucketDataRegisterRequestUserDetail |
python | tensorflow__tensorflow | tensorflow/python/eager/pywrap_tensor_test.py | {
"start": 964,
"end": 1080
} | class ____:
pass
def my_layer(x):
y = x**2
y.my_dynamic_attribute = MyPythonObject()
return y
| MyPythonObject |
python | numba__numba | numba/tests/test_llvm_pass_timings.py | {
"start": 3742,
"end": 4493
} | class ____(TestCase):
def test_disabled_behavior(self):
@njit
def foo(n):
c = 0
for i in range(n):
c += i
return c
with override_config('LLVM_PASS_TIMINGS', False):
foo(10)
md = foo.get_metadata(foo.signatures[0])
timings = md['llvm_pass_timings']
# Check that the right message is returned
self.assertEqual(timings.summary(), "No pass timings were recorded")
# Check that None is returned
self.assertIsNone(timings.get_total_time())
# Check that empty list is returned
self.assertEqual(timings.list_longest_first(), [])
if __name__ == "__main__":
unittest.main()
| TestLLVMPassTimingsDisabled |
python | django__django | tests/template_tests/test_nodelist.py | {
"start": 1353,
"end": 3103
} | class ____(SimpleTestCase):
"""
Checks whether index of error is calculated correctly in
template debugger in for loops. Refs ticket #5831
"""
def test_correct_exception_index(self):
tests = [
(
"{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}",
(38, 56),
),
(
"{% load bad_tag %}{% for i in range %}{% for j in range %}"
"{% badsimpletag %}{% endfor %}{% endfor %}",
(58, 76),
),
(
"{% load bad_tag %}{% for i in range %}{% badsimpletag %}"
"{% for j in range %}Hello{% endfor %}{% endfor %}",
(38, 56),
),
(
"{% load bad_tag %}{% for i in range %}{% for j in five %}"
"{% badsimpletag %}{% endfor %}{% endfor %}",
(38, 57),
),
(
"{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}",
(18, 37),
),
]
context = Context(
{
"range": range(5),
"five": 5,
}
)
engine = Engine(
debug=True, libraries={"bad_tag": "template_tests.templatetags.bad_tag"}
)
for source, expected_error_source_index in tests:
template = engine.from_string(source)
try:
template.render(context)
except (RuntimeError, TypeError) as e:
debug = e.template_debug
self.assertEqual(
(debug["start"], debug["end"]), expected_error_source_index
)
| ErrorIndexTest |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/integration_tests/integration_test_defs/definitions/other_local_component_sample/__init__.py | {
"start": 129,
"end": 357
} | class ____(dg.Component):
@classmethod
def get_model_cls(cls):
return MyNewComponentSchema
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions:
return dg.Definitions()
| MyNewComponent |
python | Textualize__textual | src/textual/drivers/win32.py | {
"start": 2631,
"end": 2790
} | class ____(Structure):
"""https://docs.microsoft.com/en-us/windows/console/focus-event-record-str"""
_fields_ = [("bSetFocus", BOOL)]
| FOCUS_EVENT_RECORD |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 7576,
"end": 8954
} | class ____(ElementwiseTypePromotionRule):
"""Reference type promotion rule from torch._refs.div.
Rule depends on the value of the `rounding_mode` argument.
"""
def __init__(self) -> None:
super().__init__(
"aten",
"div",
promote_args_positions=(0, 1),
promote_kwargs_names=(),
promotion_kind=_prims_common.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def preview_type_promotion(
self, args: tuple, kwargs: dict
) -> TypePromotionSnapshot:
rounding_mode = kwargs.get("rounding_mode")
if rounding_mode is None:
# true_divide
self.promotion_kind = (
_prims_common.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
)
return super().preview_type_promotion(args, kwargs)
if rounding_mode == "trunc":
# trunc_divide
self.promotion_kind = _prims_common.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
return super().preview_type_promotion(args, kwargs)
if rounding_mode == "floor":
# floor_divide
self.promotion_kind = _prims_common.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
return super().preview_type_promotion(args, kwargs)
raise ValueError(f"Unknown rounding_mode: {rounding_mode}")
| DivElementwiseTypePromotionRule |
python | run-llama__llama_index | llama-index-core/llama_index/core/retrievers/fusion_retriever.py | {
"start": 899,
"end": 1278
} | class ____(str, Enum):
"""Enum for different fusion modes."""
RECIPROCAL_RANK = "reciprocal_rerank" # apply reciprocal rank fusion
RELATIVE_SCORE = "relative_score" # apply relative score fusion
DIST_BASED_SCORE = "dist_based_score" # apply distance-based score fusion
SIMPLE = "simple" # simple re-ordering of results based on original scores
| FUSION_MODES |
python | django__django | django/utils/choices.py | {
"start": 306,
"end": 1108
} | class ____:
"""Base class for lazy iterators for choices."""
def __eq__(self, other):
if isinstance(other, Iterable):
return all(a == b for a, b in zip_longest(self, other, fillvalue=object()))
return super().__eq__(other)
def __getitem__(self, index):
if isinstance(index, slice) or index < 0:
# Suboptimally consume whole iterator to handle slices and negative
# indexes.
return list(self)[index]
try:
return next(islice(self, index, index + 1))
except StopIteration:
raise IndexError("index out of range") from None
def __iter__(self):
raise NotImplementedError(
"BaseChoiceIterator subclasses must implement __iter__()."
)
| BaseChoiceIterator |
python | kevin1024__vcrpy | vcr/stubs/__init__.py | {
"start": 13827,
"end": 14069
} | class ____(VCRConnection):
"""A Mocked class for HTTPS requests"""
_baseclass = HTTPSConnection
_protocol = "https"
is_verified = True
debuglevel = _baseclass.debuglevel
_http_vsn = _baseclass._http_vsn
| VCRHTTPSConnection |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 17816,
"end": 20384
} | class ____(ChatParams):
"""
Format of the request object expected by the chat endpoint.
Args:
messages (List[:py:class:`ChatMessage`]): A list of :py:class:`ChatMessage`
that will be passed to the model. **Optional**, defaults to empty list (``[]``)
temperature (float): A param used to control randomness and creativity during inference.
**Optional**, defaults to ``1.0``
max_tokens (int): The maximum number of new tokens to generate.
**Optional**, defaults to ``None`` (unlimited)
stop (List[str]): A list of tokens at which to stop generation.
**Optional**, defaults to ``None``
n (int): The number of responses to generate.
**Optional**, defaults to ``1``
stream (bool): Whether to stream back responses as they are generated.
**Optional**, defaults to ``False``
top_p (float): An optional param to control sampling with temperature, the model considers
the results of the tokens with top_p probability mass. E.g., 0.1 means only the tokens
comprising the top 10% probability mass are considered.
top_k (int): An optional param for reducing the vocabulary size to top k tokens
(sorted in descending order by their probabilities).
frequency_penalty: (float): An optional param of positive or negative value,
positive values penalize new tokens based on
their existing frequency in the text so far, decreasing the model's likelihood to repeat
the same line verbatim.
presence_penalty: (float): An optional param of positive or negative value,
positive values penalize new tokens based on whether they appear in the text so far,
increasing the model's likelihood to talk about new topics.
custom_inputs (Dict[str, Any]): An optional param to provide arbitrary additional context
to the model. The dictionary values must be JSON-serializable.
tools (List[:py:class:`ToolDefinition`]): An optional list of tools that can be called by
the model.
.. warning::
In an upcoming MLflow release, default values for `temperature`, `n` and `stream` will be
removed. Please provide these values explicitly in your code if needed.
"""
messages: list[ChatMessage] = field(default_factory=list)
def __post_init__(self):
self._convert_dataclass_list("messages", ChatMessage)
super().__post_init__()
@dataclass
| ChatCompletionRequest |
python | getsentry__sentry | src/sentry/models/broadcast.py | {
"start": 523,
"end": 1420
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
upstream_id = models.CharField(max_length=32, null=True, blank=True)
title = models.CharField(max_length=64)
message = models.CharField(max_length=256)
link = models.URLField(null=True, blank=True)
is_active = models.BooleanField(default=True, db_index=True)
date_expires = models.DateTimeField(default=default_expiration, null=True, blank=True)
date_added = models.DateTimeField(default=timezone.now)
media_url = models.URLField(null=True, blank=True)
category = models.CharField(choices=BROADCAST_CATEGORIES, max_length=32, null=True, blank=True)
created_by_id = FlexibleForeignKey("sentry.User", null=True, on_delete=models.SET_NULL)
class Meta:
app_label = "sentry"
db_table = "sentry_broadcast"
__repr__ = sane_repr("message")
@control_silo_model
| Broadcast |
python | PyCQA__pylint | pylint/extensions/consider_ternary_expression.py | {
"start": 506,
"end": 1640
} | class ____(BaseChecker):
name = "consider_ternary_expression"
msgs = {
"W0160": (
"Consider rewriting as a ternary expression",
"consider-ternary-expression",
"Multiple assign statements spread across if/else blocks can be "
"rewritten with a single assignment and ternary expression",
)
}
def visit_if(self, node: nodes.If) -> None:
if isinstance(node.parent, nodes.If):
return
match node:
case nodes.If(body=[nodes.Assign() as bst], orelse=[nodes.Assign() as ost]):
pass
case _:
return
for bname, oname in zip(bst.targets, ost.targets):
if not (
isinstance(bname, nodes.AssignName)
and isinstance(oname, nodes.AssignName)
and bname.name == oname.name
):
return
self.add_message("consider-ternary-expression", node=node)
def register(linter: PyLinter) -> None:
linter.register_checker(ConsiderTernaryExpressionChecker(linter))
| ConsiderTernaryExpressionChecker |
python | ray-project__ray | python/ray/tests/runtime_env_container/test_worker_exit_intended_system_exit_and_user_error.py | {
"start": 2852,
"end": 3639
} | class ____:
def __init__(self):
p.record_pid.remote(os.getpid())
raise Exception("exception in the initialization method")
def ready(self):
pass
a = FaultyActor.remote()
wait_for_condition(lambda: ray.get(p.get_pid.remote()) is not None)
pid = ray.get(p.get_pid.remote())
def verify_exit_by_actor_init_failure():
worker = get_worker_by_pid(pid)
type = worker["exit_type"]
detail = worker["exit_detail"]
assert type == "USER_ERROR" and "exception in the initialization method" in detail
return verify_failed_task(
name="FaultyActor.__init__",
error_type="TASK_EXECUTION_EXCEPTION",
error_message="exception in the initialization method",
)
wait_for_condition(verify_exit_by_actor_init_failure)
| FaultyActor |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 94302,
"end": 96778
} | class ____(nn.Module):
"""Embeds token ids or soft tokens for multimodal content into language model space."""
def __init__(
self,
multimodal_config: Union[Gemma3nAudioConfig, Gemma3nVisionConfig],
text_config: Gemma3nTextConfig,
):
super().__init__()
self.multimodal_hidden_size = multimodal_config.hidden_size
self.eps = multimodal_config.rms_norm_eps
self.vocab_offset = multimodal_config.vocab_offset
self.vocab_size = multimodal_config.vocab_size
self.text_hidden_size = text_config.hidden_size
self.embedding = nn.Embedding(self.vocab_size, self.multimodal_hidden_size)
self.hard_embedding_norm = Gemma3nRMSNorm(self.multimodal_hidden_size, eps=self.eps)
self.soft_embedding_norm = Gemma3nRMSNorm(self.multimodal_hidden_size, eps=self.eps)
self.embedding_projection = nn.Linear(self.multimodal_hidden_size, self.text_hidden_size, bias=False)
self.embedding_post_projection_norm = Gemma3nRMSNorm(self.text_hidden_size, eps=self.eps, with_scale=False)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""Embeds token ids or soft tokens for multimodal content into language model space.
Args:
input_ids: A torch.LongTensor containing the token ids to embed. Values should be in the range
`[vocab_offset, vocab_offset + vocab_size)`.
inputs_embeds: A torch.Tensor containing the soft tokens to embed.
Returns:
A torch.Tensor of embeddings with shape `[batch_size, seq_len, self.config.text_config.hidden_size]`.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is not None:
emb_norm = self.soft_embedding_norm(inputs_embeds)
else:
hard_emb = self.embedding(input_ids - self.vocab_offset)
emb_norm = self.hard_embedding_norm(hard_emb)
emb_norm_proj = self.embedding_projection(emb_norm)
return self.embedding_post_projection_norm(emb_norm_proj)
@auto_docstring(
custom_intro="""
The base Gemma 3n model comprising a vision backbone, an audio backbone, and a language model without a
language modeling head.
"""
)
| Gemma3nMultimodalEmbedder |
python | google__pytype | pytype/tools/traces/traces_test.py | {
"start": 9452,
"end": 10384
} | class ____(MatchAstTestCase):
def test_index(self):
matches = self._get_traces("""
v = "hello"
print(v[0])
""", ast.Subscript)
self.assertTracesEqual(
matches, [((2, 6), "BINARY_SUBSCR", "__getitem__", ("str",))])
def test_simple_slice(self):
matches = self._get_traces("""
v = "hello"
print(v[:-1])
""", ast.Subscript)
if _PYVER >= (3, 12):
expected = [(
(2, 6),
"BINARY_SLICE",
"__getitem__",
("Callable[[Union[int, slice]], str]", "str"),
)]
else:
expected = [((2, 6), "BINARY_SUBSCR", "__getitem__", ("str",))]
self.assertTracesEqual(matches, expected)
def test_complex_slice(self):
matches = self._get_traces("""
v = "hello"
print(v[0:4:2])
""", ast.Subscript)
self.assertTracesEqual(
matches, [((2, 6), "BINARY_SUBSCR", "__getitem__", ("str",))])
| MatchSubscriptTest |
python | PyCQA__bandit | bandit/core/issue.py | {
"start": 1889,
"end": 7069
} | class ____:
def __init__(
self,
severity,
cwe=0,
confidence=constants.CONFIDENCE_DEFAULT,
text="",
ident=None,
lineno=None,
test_id="",
col_offset=-1,
end_col_offset=0,
):
self.severity = severity
self.cwe = Cwe(cwe)
self.confidence = confidence
if isinstance(text, bytes):
text = text.decode("utf-8")
self.text = text
self.ident = ident
self.fname = ""
self.fdata = None
self.test = ""
self.test_id = test_id
self.lineno = lineno
self.col_offset = col_offset
self.end_col_offset = end_col_offset
self.linerange = []
def __str__(self):
return (
"Issue: '%s' from %s:%s: CWE: %s, Severity: %s Confidence: "
"%s at %s:%i:%i"
) % (
self.text,
self.test_id,
(self.ident or self.test),
str(self.cwe),
self.severity,
self.confidence,
self.fname,
self.lineno,
self.col_offset,
)
def __eq__(self, other):
# if the issue text, severity, confidence, and filename match, it's
# the same issue from our perspective
match_types = [
"text",
"severity",
"cwe",
"confidence",
"fname",
"test",
"test_id",
]
return all(
getattr(self, field) == getattr(other, field)
for field in match_types
)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return id(self)
def filter(self, severity, confidence):
"""Utility to filter on confidence and severity
This function determines whether an issue should be included by
comparing the severity and confidence rating of the issue to minimum
thresholds specified in 'severity' and 'confidence' respectively.
Formatters should call manager.filter_results() directly.
This will return false if either the confidence or severity of the
issue are lower than the given threshold values.
:param severity: Severity threshold
:param confidence: Confidence threshold
:return: True/False depending on whether issue meets threshold
"""
rank = constants.RANKING
return rank.index(self.severity) >= rank.index(
severity
) and rank.index(self.confidence) >= rank.index(confidence)
def get_code(self, max_lines=3, tabbed=False):
"""Gets lines of code from a file the generated this issue.
:param max_lines: Max lines of context to return
:param tabbed: Use tabbing in the output
:return: strings of code
"""
lines = []
max_lines = max(max_lines, 1)
lmin = max(1, self.lineno - max_lines // 2)
lmax = lmin + len(self.linerange) + max_lines - 1
if self.fname == "<stdin>":
self.fdata.seek(0)
for line_num in range(1, lmin):
self.fdata.readline()
tmplt = "%i\t%s" if tabbed else "%i %s"
for line in range(lmin, lmax):
if self.fname == "<stdin>":
text = self.fdata.readline()
else:
text = linecache.getline(self.fname, line)
if isinstance(text, bytes):
text = text.decode("utf-8")
if not len(text):
break
lines.append(tmplt % (line, text))
return "".join(lines)
def as_dict(self, with_code=True, max_lines=3):
"""Convert the issue to a dict of values for outputting."""
out = {
"filename": self.fname,
"test_name": self.test,
"test_id": self.test_id,
"issue_severity": self.severity,
"issue_cwe": self.cwe.as_dict(),
"issue_confidence": self.confidence,
"issue_text": self.text.encode("utf-8").decode("utf-8"),
"line_number": self.lineno,
"line_range": self.linerange,
"col_offset": self.col_offset,
"end_col_offset": self.end_col_offset,
}
if with_code:
out["code"] = self.get_code(max_lines=max_lines)
return out
def from_dict(self, data, with_code=True):
self.code = data["code"]
self.fname = data["filename"]
self.severity = data["issue_severity"]
self.cwe = cwe_from_dict(data["issue_cwe"])
self.confidence = data["issue_confidence"]
self.text = data["issue_text"]
self.test = data["test_name"]
self.test_id = data["test_id"]
self.lineno = data["line_number"]
self.linerange = data["line_range"]
self.col_offset = data.get("col_offset", 0)
self.end_col_offset = data.get("end_col_offset", 0)
def cwe_from_dict(data):
cwe = Cwe()
cwe.from_dict(data)
return cwe
def issue_from_dict(data):
i = Issue(severity=data["issue_severity"])
i.from_dict(data)
return i
| Issue |
python | ray-project__ray | python/ray/autoscaler/v2/schema.py | {
"start": 2408,
"end": 3033
} | class ____:
class Status(Enum):
FAILED = "FAILED"
PENDING = "PENDING"
# The instance type name, e.g. p3.2xlarge
instance_type_name: str
# ray node type name.
ray_node_type_name: str
# count.
count: int
# State: (e.g. PENDING, FAILED)
state: Status
# When the launch request was made in unix timestamp in secs.
request_ts_s: int
# When the launch request failed unix timestamp in secs if failed.
failed_ts_s: Optional[int] = None
# Request details, e.g. error reason if the launch request failed.
details: Optional[str] = None
@dataclass
| LaunchRequest |
python | ray-project__ray | python/ray/autoscaler/_private/fake_multi_node/node_provider.py | {
"start": 14731,
"end": 25641
} | class ____(FakeMultiNodeProvider):
"""A node provider that implements multi-node on a single machine.
This is used for laptop mode testing of multi node functionality
where each node has their own FS and IP."""
def __init__(self, provider_config, cluster_name):
super(FakeMultiNodeDockerProvider, self).__init__(provider_config, cluster_name)
fake_head = copy.deepcopy(self._nodes)
self._project_name = self.provider_config["project_name"]
self._docker_image = self.provider_config["image"]
self._host_gcs_port = self.provider_config.get(
"host_gcs_port", FAKE_DOCKER_DEFAULT_GCS_PORT
)
self._host_object_manager_port = self.provider_config.get(
"host_object_manager_port", FAKE_DOCKER_DEFAULT_OBJECT_MANAGER_PORT
)
self._host_client_port = self.provider_config.get(
"host_client_port", FAKE_DOCKER_DEFAULT_CLIENT_PORT
)
self._head_resources = self.provider_config["head_resources"]
# subdirs:
# - ./shared (shared filesystem)
# - ./nodes/<node_id> (node-specific mounted filesystem)
self._volume_dir = self.provider_config["shared_volume_dir"]
self._mounted_cluster_dir = os.path.join(self._volume_dir, "shared")
if not self.in_docker_container:
# Only needed on host
os.makedirs(self._mounted_cluster_dir, mode=0o755, exist_ok=True)
self._boostrap_config_path = os.path.join(
self._volume_dir, "bootstrap_config.yaml"
)
self._private_key_path = os.path.join(self._volume_dir, "bootstrap_key.pem")
self._public_key_path = os.path.join(self._volume_dir, "bootstrap_key.pem.pub")
if not self.in_docker_container:
# Create private key
if not os.path.exists(self._private_key_path):
subprocess.check_call(
f'ssh-keygen -b 2048 -t rsa -q -N "" '
f"-f {self._private_key_path}",
shell=True,
)
# Create public key
if not os.path.exists(self._public_key_path):
subprocess.check_call(
f"ssh-keygen -y "
f"-f {self._private_key_path} "
f"> {self._public_key_path}",
shell=True,
)
self._docker_compose_config_path = os.path.join(
self._volume_dir, "docker-compose.yaml"
)
self._docker_compose_config = None
self._node_state_path = os.path.join(self._volume_dir, "nodes.json")
self._docker_status_path = os.path.join(self._volume_dir, "status.json")
self._load_node_state()
if FAKE_HEAD_NODE_ID not in self._nodes:
# Reset
self._nodes = copy.deepcopy(fake_head)
self._nodes[FAKE_HEAD_NODE_ID][
"node_spec"
] = self._create_node_spec_with_resources(
head=True, node_id=FAKE_HEAD_NODE_ID, resources=self._head_resources
)
self._possibly_terminated_nodes = dict()
self._cleanup_interval = provider_config.get("cleanup_interval", 9.5)
self._docker_status = {}
self._update_docker_compose_config()
self._update_docker_status()
self._save_node_state()
@property
def in_docker_container(self):
return os.path.exists(os.path.join(self._volume_dir, ".in_docker"))
def _create_node_spec_with_resources(
self, head: bool, node_id: str, resources: Dict[str, Any]
):
resources = resources.copy()
# Create shared directory
node_dir = os.path.join(self._volume_dir, "nodes", node_id)
os.makedirs(node_dir, mode=0o777, exist_ok=True)
resource_str = json.dumps(resources, indent=None)
return create_node_spec(
head=head,
docker_image=self._docker_image,
mounted_cluster_dir=self._mounted_cluster_dir,
mounted_node_dir=node_dir,
num_cpus=resources.pop("CPU", 0),
num_gpus=resources.pop("GPU", 0),
host_gcs_port=self._host_gcs_port,
host_object_manager_port=self._host_object_manager_port,
host_client_port=self._host_client_port,
resources=resources,
env_vars={
"RAY_OVERRIDE_NODE_ID_FOR_TESTING": node_id,
ray_constants.RESOURCES_ENVIRONMENT_VARIABLE: resource_str,
**self.provider_config.get("env_vars", {}),
},
volume_dir=self._volume_dir,
node_state_path=self._node_state_path,
docker_status_path=self._docker_status_path,
docker_compose_path=self._docker_compose_config_path,
bootstrap_config_path=self._boostrap_config_path,
public_key_path=self._public_key_path,
private_key_path=self._private_key_path,
)
def _load_node_state(self) -> bool:
if not os.path.exists(self._node_state_path):
return False
try:
with open(self._node_state_path, "rt") as f:
nodes = json.load(f)
except Exception:
return False
if not nodes:
return False
self._nodes = nodes
return True
def _save_node_state(self):
with open(self._node_state_path, "wt") as f:
json.dump(self._nodes, f)
# Make sure this is always writeable from inside the containers
if not self.in_docker_container:
# Only chmod from the outer container
os.chmod(self._node_state_path, 0o777)
def _update_docker_compose_config(self):
config = copy.deepcopy(DOCKER_COMPOSE_SKELETON)
config["services"] = {}
for node_id, node in self._nodes.items():
config["services"][node_id] = node["node_spec"]
with open(self._docker_compose_config_path, "wt") as f:
yaml.safe_dump(config, f)
def _update_docker_status(self):
if not os.path.exists(self._docker_status_path):
return
with open(self._docker_status_path, "rt") as f:
self._docker_status = json.load(f)
def _update_nodes(self):
for node_id in list(self._nodes):
if not self._is_docker_running(node_id):
self._possibly_terminated_nodes.setdefault(node_id, time.monotonic())
else:
self._possibly_terminated_nodes.pop(node_id, None)
self._cleanup_nodes()
def _cleanup_nodes(self):
for node_id, timestamp in list(self._possibly_terminated_nodes.items()):
if time.monotonic() > timestamp + self._cleanup_interval:
if not self._is_docker_running(node_id):
self._nodes.pop(node_id, None)
self._possibly_terminated_nodes.pop(node_id, None)
self._save_node_state()
def _container_name(self, node_id):
node_status = self._docker_status.get(node_id, {})
timeout = time.monotonic() + 60
while not node_status:
if time.monotonic() > timeout:
raise RuntimeError(f"Container for {node_id} never became available.")
time.sleep(1)
self._update_docker_status()
node_status = self._docker_status.get(node_id, {})
return node_status["Name"]
def _is_docker_running(self, node_id):
self._update_docker_status()
return self._docker_status.get(node_id, {}).get("State", None) == "running"
def non_terminated_nodes(self, tag_filters):
self._update_nodes()
return super(FakeMultiNodeDockerProvider, self).non_terminated_nodes(
tag_filters
)
def is_running(self, node_id):
with self.lock:
self._update_nodes()
return node_id in self._nodes and self._is_docker_running(node_id)
def is_terminated(self, node_id):
with self.lock:
self._update_nodes()
return node_id not in self._nodes and not self._is_docker_running(node_id)
def get_command_runner(
self,
log_prefix: str,
node_id: str,
auth_config: Dict[str, Any],
cluster_name: str,
process_runner: ModuleType,
use_internal_ip: bool,
docker_config: Optional[Dict[str, Any]] = None,
) -> CommandRunnerInterface:
if self.in_docker_container:
return super(FakeMultiNodeProvider, self).get_command_runner(
log_prefix,
node_id,
auth_config,
cluster_name,
process_runner,
use_internal_ip,
)
# Else, host command runner:
common_args = {
"log_prefix": log_prefix,
"node_id": node_id,
"provider": self,
"auth_config": auth_config,
"cluster_name": cluster_name,
"process_runner": process_runner,
"use_internal_ip": use_internal_ip,
}
docker_config["container_name"] = self._container_name(node_id)
docker_config["image"] = self._docker_image
return FakeDockerCommandRunner(docker_config, **common_args)
def _get_ip(self, node_id: str) -> Optional[str]:
for i in range(3):
self._update_docker_status()
ip = self._docker_status.get(node_id, {}).get("IP", None)
if ip:
return ip
time.sleep(3)
return None
def set_node_tags(self, node_id, tags):
assert node_id in self._nodes
self._nodes[node_id]["tags"].update(tags)
def create_node_with_resources_and_labels(
self, node_config, tags, count, resources, labels
):
with self.lock:
is_head = tags[TAG_RAY_NODE_KIND] == NODE_KIND_HEAD
if is_head:
next_id = FAKE_HEAD_NODE_ID
else:
next_id = self._next_hex_node_id()
self._nodes[next_id] = {
"tags": tags,
"node_spec": self._create_node_spec_with_resources(
head=is_head, node_id=next_id, resources=resources
),
}
self._update_docker_compose_config()
self._save_node_state()
def create_node(
self, node_config: Dict[str, Any], tags: Dict[str, str], count: int
) -> Optional[Dict[str, Any]]:
resources = self._head_resources
return self.create_node_with_resources_and_labels(
node_config, tags, count, resources, {}
)
def _terminate_node(self, node):
self._update_docker_compose_config()
self._save_node_state()
@staticmethod
def bootstrap_config(cluster_config):
return cluster_config
| FakeMultiNodeDockerProvider |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_addition.py | {
"start": 10983,
"end": 11517
} | class ____(_Adder):
"""Handles additions resulting in a Diag operator."""
def can_add(self, op1, op2):
types = {_type(op1), _type(op2)}
return not types.difference(_DIAG_LIKE)
def _add(self, op1, op2, operator_name, hints):
return linear_operator_diag.LinearOperatorDiag(
diag=op1.diag_part() + op2.diag_part(),
is_non_singular=hints.is_non_singular,
is_self_adjoint=hints.is_self_adjoint,
is_positive_definite=hints.is_positive_definite,
name=operator_name)
| _AddAndReturnDiag |
python | pypa__setuptools | setuptools/_vendor/jaraco/text/__init__.py | {
"start": 11426,
"end": 16249
} | class ____:
r"""
Given a series of lines, find the common prefix and strip it from them.
>>> lines = [
... 'abcdefg\n',
... 'abc\n',
... 'abcde\n',
... ]
>>> res = Stripper.strip_prefix(lines)
>>> res.prefix
'abc'
>>> list(res.lines)
['defg\n', '\n', 'de\n']
If no prefix is common, nothing should be stripped.
>>> lines = [
... 'abcd\n',
... '1234\n',
... ]
>>> res = Stripper.strip_prefix(lines)
>>> res.prefix = ''
>>> list(res.lines)
['abcd\n', '1234\n']
"""
def __init__(self, prefix, lines):
self.prefix = prefix
self.lines = map(self, lines)
@classmethod
def strip_prefix(cls, lines):
prefix_lines, lines = itertools.tee(lines)
prefix = functools.reduce(cls.common_prefix, prefix_lines)
return cls(prefix, lines)
def __call__(self, line):
if not self.prefix:
return line
null, prefix, rest = line.partition(self.prefix)
return rest
@staticmethod
def common_prefix(s1, s2):
"""
Return the common prefix of two lines.
"""
index = min(len(s1), len(s2))
while s1[:index] != s2[:index]:
index -= 1
return s1[:index]
def remove_prefix(text, prefix):
"""
Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ')
'performance'
>>> remove_prefix('something special', 'sample')
'something special'
"""
null, prefix, rest = text.rpartition(prefix)
return rest
def remove_suffix(text, suffix):
"""
Remove the suffix from the text if it exists.
>>> remove_suffix('name.git', '.git')
'name'
>>> remove_suffix('something special', 'sample')
'something special'
"""
rest, suffix, null = text.partition(suffix)
return rest
def normalize_newlines(text):
r"""
Replace alternate newlines with the canonical newline.
>>> normalize_newlines('Lorem Ipsum\u2029')
'Lorem Ipsum\n'
>>> normalize_newlines('Lorem Ipsum\r\n')
'Lorem Ipsum\n'
>>> normalize_newlines('Lorem Ipsum\x85')
'Lorem Ipsum\n'
"""
newlines = ['\r\n', '\r', '\n', '\u0085', '\u2028', '\u2029']
pattern = '|'.join(newlines)
return re.sub(pattern, '\n', text)
def _nonblank(str):
return str and not str.startswith('#')
@functools.singledispatch
def yield_lines(iterable):
r"""
Yield valid lines of a string or iterable.
>>> list(yield_lines(''))
[]
>>> list(yield_lines(['foo', 'bar']))
['foo', 'bar']
>>> list(yield_lines('foo\nbar'))
['foo', 'bar']
>>> list(yield_lines('\nfoo\n#bar\nbaz #comment'))
['foo', 'baz #comment']
>>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n']))
['foo', 'bar', 'baz', 'bing']
"""
return itertools.chain.from_iterable(map(yield_lines, iterable))
@yield_lines.register(str)
def _(text):
return filter(_nonblank, map(str.strip, text.splitlines()))
def drop_comment(line):
"""
Drop comments.
>>> drop_comment('foo # bar')
'foo'
A hash without a space may be in a URL.
>>> drop_comment('http://example.com/foo#bar')
'http://example.com/foo#bar'
"""
return line.partition(' #')[0]
def join_continuation(lines):
r"""
Join lines continued by a trailing backslash.
>>> list(join_continuation(['foo \\', 'bar', 'baz']))
['foobar', 'baz']
>>> list(join_continuation(['foo \\', 'bar', 'baz']))
['foobar', 'baz']
>>> list(join_continuation(['foo \\', 'bar \\', 'baz']))
['foobarbaz']
Not sure why, but...
The character preceding the backslash is also elided.
>>> list(join_continuation(['goo\\', 'dly']))
['godly']
A terrible idea, but...
If no line is available to continue, suppress the lines.
>>> list(join_continuation(['foo', 'bar\\', 'baz\\']))
['foo']
"""
lines = iter(lines)
for item in lines:
while item.endswith('\\'):
try:
item = item[:-2].strip() + next(lines)
except StopIteration:
return
yield item
def read_newlines(filename, limit=1024):
r"""
>>> tmp_path = getfixture('tmp_path')
>>> filename = tmp_path / 'out.txt'
>>> _ = filename.write_text('foo\n', newline='', encoding='utf-8')
>>> read_newlines(filename)
'\n'
>>> _ = filename.write_text('foo\r\n', newline='', encoding='utf-8')
>>> read_newlines(filename)
'\r\n'
>>> _ = filename.write_text('foo\r\nbar\nbing\r', newline='', encoding='utf-8')
>>> read_newlines(filename)
('\r', '\n', '\r\n')
"""
with open(filename, encoding='utf-8') as fp:
fp.read(limit)
return fp.newlines
| Stripper |
python | django__django | tests/postgres_tests/models.py | {
"start": 1455,
"end": 1637
} | class ____(PostgreSQLModel):
datetimes = ArrayField(models.DateTimeField())
dates = ArrayField(models.DateField())
times = ArrayField(models.TimeField())
| DateTimeArrayModel |
python | apache__airflow | providers/dbt/cloud/src/airflow/providers/dbt/cloud/hooks/dbt.py | {
"start": 2937,
"end": 3455
} | class ____(AuthBase):
"""Helper class for Auth when executing requests."""
def __init__(self, token: str) -> None:
self.token = token
def __call__(self, request: PreparedRequest) -> PreparedRequest:
package_name, provider_version = _get_provider_info()
request.headers["User-Agent"] = f"{package_name}-v{provider_version}"
request.headers["Content-Type"] = "application/json"
request.headers["Authorization"] = f"Token {self.token}"
return request
| TokenAuth |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modular_xlm_roberta.py | {
"start": 6121,
"end": 9393
} | class ____(RobertaForMaskedLM):
_tied_weights_keys = {
"lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
"lm_head.decoder.bias": "lm_head.bias",
}
def __init__(self, config):
super().__init__(config)
del self.xlm_roberta
self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
r"""
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
>= 2. All the value in this tensor should be always < type_vocab_size.
[What are token type IDs?](../glossary#token-type-ids)
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
return_dict=True,
**kwargs,
)
sequence_output = outputs[0]
prediction_scores = self.lm_head(sequence_output)
masked_lm_loss = None
if labels is not None:
# move labels to correct device
labels = labels.to(prediction_scores.device)
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring(
custom_intro="""
XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
"""
)
| XLMRobertaForMaskedLM |
python | spack__spack | lib/spack/spack/mirrors/mirror.py | {
"start": 13362,
"end": 16964
} | class ____(Mapping[str, Mirror]):
"""A mapping of mirror names to mirrors."""
def __init__(
self,
mirrors=None,
scope=None,
binary: Optional[bool] = None,
source: Optional[bool] = None,
autopush: Optional[bool] = None,
):
"""Initialize a mirror collection.
Args:
mirrors: A name-to-mirror mapping to initialize the collection with.
scope: The scope to use when looking up mirrors from the config.
binary: If True, only include binary mirrors.
If False, omit binary mirrors.
If None, do not filter on binary mirrors.
source: If True, only include source mirrors.
If False, omit source mirrors.
If None, do not filter on source mirrors.
autopush: If True, only include mirrors that have autopush enabled.
If False, omit mirrors that have autopush enabled.
If None, do not filter on autopush."""
mirrors_data = (
mirrors.items()
if mirrors is not None
else spack.config.CONFIG.get_config("mirrors", scope=scope).items()
)
mirrors = (Mirror(data=mirror, name=name) for name, mirror in mirrors_data)
def _filter(m: Mirror):
if source is not None and m.source != source:
return False
if binary is not None and m.binary != binary:
return False
if autopush is not None and m.autopush != autopush:
return False
return True
self._mirrors = {m.name: m for m in mirrors if _filter(m)}
def __eq__(self, other):
return self._mirrors == other._mirrors
def to_json(self, stream=None):
return sjson.dump(self.to_dict(True), stream)
def to_yaml(self, stream=None):
return syaml.dump(self.to_dict(True), stream)
# TODO: this isn't called anywhere
@staticmethod
def from_yaml(stream, name=None):
data = syaml.load(stream)
return MirrorCollection(data)
@staticmethod
def from_json(stream, name=None):
try:
d = sjson.load(stream)
return MirrorCollection(d)
except Exception as e:
raise sjson.SpackJSONError("error parsing JSON mirror collection:", str(e)) from e
def to_dict(self, recursive=False):
return syaml.syaml_dict(
sorted(
((k, (v.to_dict() if recursive else v)) for (k, v) in self._mirrors.items()),
key=operator.itemgetter(0),
)
)
@staticmethod
def from_dict(d):
return MirrorCollection(d)
def __getitem__(self, item):
return self._mirrors[item]
def display(self):
max_len = max(len(mirror.name) for mirror in self._mirrors.values())
for mirror in self._mirrors.values():
mirror.display(max_len)
def lookup(self, name_or_url):
"""Looks up and returns a Mirror.
If this MirrorCollection contains a named Mirror under the name
[name_or_url], then that mirror is returned. Otherwise, [name_or_url]
is assumed to be a mirror URL, and an anonymous mirror with the given
URL is returned.
"""
result = self.get(name_or_url)
if result is None:
result = Mirror(fetch=name_or_url)
return result
def __iter__(self):
return iter(self._mirrors)
def __len__(self):
return len(self._mirrors)
| MirrorCollection |
python | PyCQA__pylint | tests/regrtest_data/func_block_disable_msg.py | {
"start": 2593,
"end": 4690
} | class ____:
"""shouldn't display to much attributes/not enough methods messages
"""
# pylint: disable=R0902,R0903
def __init__(self):
self.attr1 = 1
self.attr2 = 1
self.attr3 = 1
self.attr4 = 1
self.attr5 = 1
self.attr6 = 1
self.attr7 = 1
self.attr8 = 1
self.attr9 = 1
self.attr0 = 1
def too_complex_but_thats_ok(self, attr1, attr2):
"""THIS Method has too much branches and returns but i don't care
"""
# pylint: disable=R0912,R0911
try:
attr3 = attr1+attr2
except ValueError:
attr3 = None
except:
return 'duh', self
if attr1:
for i in attr1:
if attr2:
return i
else:
return 'duh'
elif attr2:
for i in attr2:
if attr2:
return i
else:
return 'duh'
else:
for i in range(15):
if attr3:
return i
else:
return 'doh'
return None
print('hop, too many lines but i don\'t care')
| ClassLevelMessage |
python | py-pdf__pypdf | pypdf/filters.py | {
"start": 17864,
"end": 18440
} | class ____:
@staticmethod
def decode(
data: bytes,
decode_parms: Optional[DictionaryObject] = None,
**kwargs: Any,
) -> bytes:
"""
Decompresses data encoded using a DCT (discrete cosine transform)
technique based on the JPEG standard (IS0/IEC 10918),
reproducing image sample data that approximates the original data.
Args:
data: text to decode.
decode_parms: this filter does not use parameters.
Returns:
decoded data.
"""
return data
| DCTDecode |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/vgg_block_nchw_test.py | {
"start": 1176,
"end": 2679
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Single vgg layer in NCHW unit tests in TF-TRT."""
def GraphFn(self, x):
dtype = x.dtype
x, _, _ = nn_impl.fused_batch_norm(
x, [1.0, 1.0], [0.0, 0.0],
mean=[0.5, 0.5],
variance=[1.0, 1.0],
data_format="NCHW",
is_training=False)
e = constant_op.constant(
np.random.randn(1, 1, 2, 6), name="weights", dtype=dtype)
conv = nn.conv2d(
input=x,
filter=e,
data_format="NCHW",
strides=[1, 1, 2, 2],
padding="SAME",
name="conv")
b = constant_op.constant(np.random.randn(6), name="bias", dtype=dtype)
t = nn.bias_add(conv, b, data_format="NCHW", name="biasAdd")
relu = nn.relu(t, "relu")
idty = array_ops.identity(relu, "ID")
v = nn_ops.max_pool(
idty, [1, 1, 2, 2], [1, 1, 2, 2],
"VALID",
data_format="NCHW",
name="max_pool")
return array_ops.squeeze(v, name="output_0")
def GetParams(self):
return self.BuildParams(self.GraphFn, dtypes.float32, [[5, 2, 8, 8]],
[[5, 6, 2, 2]])
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return ["TRTEngineOp_000"]
# TODO(b/159459919): remove this routine to disallow native segment execution.
def setUp(self):
super().setUp()
os.environ["TF_TRT_ALLOW_ENGINE_NATIVE_SEGMENT_EXECUTION"] = "True"
if __name__ == "__main__":
test.main()
| VGGBlockNCHWTest |
python | huggingface__transformers | src/transformers/models/siglip/modeling_siglip.py | {
"start": 22150,
"end": 23919
} | class ____(SiglipPreTrainedModel):
config: SiglipTextConfig
input_modalities = ("text",)
def __init__(self, config: SiglipTextConfig):
super().__init__(config)
self.text_model = SiglipTextTransformer(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.text_model.embeddings.token_embedding
def set_input_embeddings(self, value):
self.text_model.embeddings.token_embedding = value
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPooling:
r"""
Examples:
```python
>>> from transformers import AutoTokenizer, SiglipTextModel
>>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
>>> # important: make sure to set padding="max_length" as that's how the model was trained
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
```"""
return self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
**kwargs,
)
| SiglipTextModel |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py | {
"start": 53322,
"end": 54333
} | class ____:
def test_delete_dag_run(self, test_client, session):
response = test_client.delete(f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}")
assert response.status_code == 204
_check_last_log(session, dag_id=DAG1_ID, event="delete_dag_run", logical_date=None)
def test_delete_dag_run_not_found(self, test_client):
response = test_client.delete(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 404
body = response.json()
assert body["detail"] == "The DagRun with dag_id: `test_dag1` and run_id: `invalid` was not found"
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.delete(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.delete(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 403
| TestDeleteDagRun |
python | mahmoud__glom | glom/grouping.py | {
"start": 1221,
"end": 5110
} | class ____:
"""supports nesting grouping operations --
think of a glom-style recursive boltons.iterutils.bucketize
the "branches" of a Group spec are dicts;
the leaves are lists, or an Aggregation object
an Aggregation object is any object that defines the
method agg(target, accumulator)
For example, here we get a map of even and odd counts::
>>> glom(range(10), Group({T % 2: T}))
{0: 8, 1: 9}
And here we create a `"bucketized"
<https://boltons.readthedocs.io/en/latest/iterutils.html#boltons.iterutils.bucketize>`_
map of even and odd numbers::
>>> glom(range(10), Group({T % 2: [T]}))
{0: [0, 2, 4, 6, 8], 1: [1, 3, 5, 7, 9]}
target is the current target, accumulator is a dict
maintained by Group mode
unlike Iter(), Group() converts an iterable target
into a single result; Iter() converts an iterable
target into an iterable result
"""
def __init__(self, spec):
self.spec = spec
def glomit(self, target, scope):
scope[MODE] = GROUP
scope[CUR_AGG] = None # reset aggregation tripwire for sub-specs
scope[ACC_TREE] = {}
# handle the basecase where the spec stops immediately
# TODO: something smarter
if type(self.spec) in (dict, list):
ret = type(self.spec)()
else:
ret = None
for t in target_iter(target, scope):
last, ret = ret, scope[glom](t, self.spec, scope)
if ret is STOP:
return last
return ret
def __repr__(self):
cn = self.__class__.__name__
return f'{cn}({self.spec!r})'
def GROUP(target, spec, scope):
"""
Group mode dispatcher; also sentinel for current mode = group
"""
recurse = lambda spec: scope[glom](target, spec, scope)
tree = scope[ACC_TREE] # current accumulator support structure
if callable(getattr(spec, "agg", None)):
return spec.agg(target, tree)
elif callable(spec):
return spec(target)
_spec_type = type(spec)
if _spec_type not in (dict, list):
raise BadSpec("Group mode expected dict, list, callable, or"
" aggregator, not: %r" % (spec,))
_spec_id = id(spec)
try:
acc = tree[_spec_id] # current accumulator
except KeyError:
acc = tree[_spec_id] = _spec_type()
if _spec_type is dict:
done = True
for keyspec, valspec in spec.items():
if tree.get(keyspec, None) is STOP:
continue
key = recurse(keyspec)
if key is SKIP:
done = False # SKIP means we still want more vals
continue
if key is STOP:
tree[keyspec] = STOP
continue
if key not in acc:
# TODO: guard against key == id(spec)
tree[key] = {}
scope[ACC_TREE] = tree[key]
result = recurse(valspec)
if result is STOP:
tree[keyspec] = STOP
continue
done = False # SKIP or returning a value means we still want more vals
if result is not SKIP:
acc[key] = result
if done:
return STOP
return acc
elif _spec_type is list:
for valspec in spec:
if type(valspec) is dict:
# doesn't make sense due to arity mismatch. did you mean [Auto({...})] ?
raise BadSpec('dicts within lists are not'
' allowed while in Group mode: %r' % spec)
result = recurse(valspec)
if result is STOP:
return STOP
if result is not SKIP:
acc.append(result)
return acc
raise ValueError(f"{_spec_type} not a valid spec type for Group mode") # pragma: no cover
| Group |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 4326,
"end": 4368
} | class ____[T]: ...
@decorator # comment
| Foo3 |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 128944,
"end": 129829
} | class ____:
def test_gzscore_normal_array(self, xp):
x = np.asarray([1, 2, 3, 4])
z = stats.gzscore(xp.asarray(x))
desired = np.log(x / stats.gmean(x)) / np.log(stats.gstd(x, ddof=0))
xp_assert_close(z, xp.asarray(desired, dtype=xp.asarray(1.).dtype))
@skip_xp_invalid_arg
def test_gzscore_masked_array(self):
x = np.array([1, 2, -1, 3, 4])
mask = [0, 0, 1, 0, 0]
mx = np.ma.masked_array(x, mask=mask)
z = stats.gzscore(mx)
desired = ([-1.526072095151, -0.194700599824, np.inf, 0.584101799472,
1.136670895503])
desired = np.ma.masked_array(desired, mask=mask)
assert_allclose(z.compressed(), desired.compressed())
assert_allclose(z.mask, desired.mask)
assert isinstance(z, np.ma.MaskedArray)
@make_xp_test_case(stats.median_abs_deviation)
| TestGZscore |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_base.py | {
"start": 40658,
"end": 44657
} | class ____(TypedDict):
response: str
explanation: str
@pytest.mark.parametrize(
"schema", [ResponseFormat, ResponseFormat.model_json_schema(), ResponseFormatDict]
)
def test_structured_output_and_tools(schema: Any) -> None:
llm = ChatOpenAI(model="gpt-5-nano", verbosity="low").bind_tools(
[GenerateUsername], strict=True, response_format=schema
)
response = llm.invoke("What weighs more, a pound of feathers or a pound of gold?")
if schema == ResponseFormat:
parsed = response.additional_kwargs["parsed"]
assert isinstance(parsed, ResponseFormat)
else:
parsed = json.loads(response.text)
assert isinstance(parsed, dict)
assert parsed["response"]
assert parsed["explanation"]
# Test streaming tool calls
full: BaseMessageChunk | None = None
for chunk in llm.stream(
"Generate a user name for Alice, black hair. Use the tool."
):
assert isinstance(chunk, AIMessageChunk)
full = chunk if full is None else full + chunk
assert isinstance(full, AIMessageChunk)
assert len(full.tool_calls) == 1
tool_call = full.tool_calls[0]
assert tool_call["name"] == "GenerateUsername"
def test_tools_and_structured_output() -> None:
llm = ChatOpenAI(model="gpt-5-nano").with_structured_output(
ResponseFormat, strict=True, include_raw=True, tools=[GenerateUsername]
)
expected_keys = {"raw", "parsing_error", "parsed"}
query = "Hello"
tool_query = "Generate a user name for Alice, black hair. Use the tool."
# Test invoke
## Engage structured output
response = llm.invoke(query)
assert isinstance(response["parsed"], ResponseFormat)
## Engage tool calling
response_tools = llm.invoke(tool_query)
ai_msg = response_tools["raw"]
assert isinstance(ai_msg, AIMessage)
assert ai_msg.tool_calls
assert response_tools["parsed"] is None
# Test stream
aggregated: dict = {}
for chunk in llm.stream(tool_query):
assert isinstance(chunk, dict)
assert all(key in expected_keys for key in chunk)
aggregated = {**aggregated, **chunk}
assert all(key in aggregated for key in expected_keys)
assert isinstance(aggregated["raw"], AIMessage)
assert aggregated["raw"].tool_calls
assert aggregated["parsed"] is None
@pytest.mark.scheduled
def test_prompt_cache_key_invoke() -> None:
"""Test that `prompt_cache_key` works with invoke calls."""
chat = ChatOpenAI(model="gpt-5-nano", max_completion_tokens=500)
messages = [HumanMessage("Say hello")]
# Test that invoke works with prompt_cache_key parameter
response = chat.invoke(messages, prompt_cache_key="integration-test-v1")
assert isinstance(response, AIMessage)
assert isinstance(response.content, str)
assert len(response.content) > 0
# Test that subsequent call with same cache key also works
response2 = chat.invoke(messages, prompt_cache_key="integration-test-v1")
assert isinstance(response2, AIMessage)
assert isinstance(response2.content, str)
assert len(response2.content) > 0
@pytest.mark.scheduled
def test_prompt_cache_key_usage_methods_integration() -> None:
"""Integration test for `prompt_cache_key` usage methods."""
messages = [HumanMessage("Say hi")]
# Test keyword argument method
chat = ChatOpenAI(model="gpt-5-nano", max_completion_tokens=10)
response = chat.invoke(messages, prompt_cache_key="integration-test-v1")
assert isinstance(response, AIMessage)
assert isinstance(response.content, str)
# Test model-level via model_kwargs
chat_model_level = ChatOpenAI(
model="gpt-5-nano",
max_completion_tokens=10,
model_kwargs={"prompt_cache_key": "integration-model-level-v1"},
)
response_model_level = chat_model_level.invoke(messages)
assert isinstance(response_model_level, AIMessage)
assert isinstance(response_model_level.content, str)
| ResponseFormatDict |
python | pikepdf__pikepdf | src/pikepdf/_augments.py | {
"start": 315,
"end": 6188
} | class ____(Protocol):
"""Protocol for any method, with attached booleans."""
_augment_override_cpp: bool
_augment_if_no_cpp: bool
def __call__(self, *args, **kwargs) -> Any:
"""Any function.""" # pragma: no cover
def augment_override_cpp(fn: AugmentedCallable) -> AugmentedCallable:
"""Replace the C++ implementation, if there is one."""
fn._augment_override_cpp = True
return fn
def augment_if_no_cpp(fn: AugmentedCallable) -> AugmentedCallable:
"""Provide a Python implementation if no C++ implementation exists."""
fn._augment_if_no_cpp = True
return fn
def _is_inherited_method(meth: Callable) -> bool:
# Augmenting a C++ with a method that cls inherits from the Python
# object is never what we want.
return meth.__qualname__.startswith('object.')
def _is_augmentable(m: Any) -> bool:
return (
inspect.isfunction(m) and not _is_inherited_method(m)
) or inspect.isdatadescriptor(m)
Tcpp = TypeVar('Tcpp')
T = TypeVar('T')
def augments(cls_cpp: type[Tcpp]):
"""Attach methods of a Python support class to an existing class.
This monkeypatches all methods defined in the support class onto an
existing class. Example:
.. code-block:: python
@augments(ClassDefinedInCpp)
class SupportClass:
def foo(self):
pass
The Python method 'foo' will be monkeypatched on ClassDefinedInCpp. SupportClass
has no meaning on its own and should not be used, but gets returned from
this function so IDE code inspection doesn't get too confused.
We don't subclass because it's much more convenient to monkeypatch Python
methods onto the existing Python binding of the C++ class. For one thing,
this allows the implementation to be moved from Python to C++ or vice
versa. It saves having to implement an intermediate Python subclass and then
ensures that the C++ superclass never 'leaks' to pikepdf users. Finally,
wrapper classes and subclasses can become problematic if the call stack
crosses the C++/Python boundary multiple times.
Any existing methods may be used, regardless of whether they are defined
elsewhere in the support class or in the target class.
For data fields to work, the target class must be
tagged ``py::dynamic_attr`` in pybind11.
Strictly, the target class does not have to be C++ or derived from pybind11.
This works on pure Python classes too.
THIS DOES NOT work for class methods.
(Alternative ideas: https://github.com/pybind/pybind11/issues/1074)
"""
OVERRIDE_WHITELIST = {'__eq__', '__hash__', '__repr__'}
if platform.python_implementation() == 'PyPy':
# Either PyPy or pybind11's interface to PyPy automatically adds a __getattr__
OVERRIDE_WHITELIST |= {'__getattr__'} # pragma: no cover
def class_augment(cls: type[T], cls_cpp: type[Tcpp] = cls_cpp) -> type[T]:
# inspect.getmembers has different behavior on PyPy - in particular it seems
# that a typical PyPy class like cls will have more methods that it considers
# methods than CPython does. Our predicate should take care of this.
for name, member in inspect.getmembers(cls, predicate=_is_augmentable):
if name == '__weakref__':
continue
if (
hasattr(cls_cpp, name)
and hasattr(cls, name)
and name not in getattr(cls, '__abstractmethods__', set())
and name not in OVERRIDE_WHITELIST
and not getattr(getattr(cls, name), '_augment_override_cpp', False)
):
if getattr(getattr(cls, name), '_augment_if_no_cpp', False):
# If tagged as "augment if no C++", we only want the binding to be
# applied when the primary class does not provide a C++
# implementation. Usually this would be a function that not is
# provided by pybind11 in some template.
continue
# If the original C++ class and Python support class both define the
# same name, we generally have a conflict, because this is augmentation
# not inheritance. However, if the method provided by the support class
# is an abstract method, then we can consider the C++ version the
# implementation. Also, pybind11 provides defaults for __eq__,
# __hash__ and __repr__ that we often do want to override directly.
raise RuntimeError(
f"C++ {cls_cpp} and Python {cls} both define the same "
f"non-abstract method {name}: "
f"{getattr(cls_cpp, name, '')!r}, "
f"{getattr(cls, name, '')!r}"
)
if inspect.isfunction(member):
if hasattr(cls_cpp, name):
# If overriding a C++ named method, make a copy of the original
# method. This is so that the Python override can call the C++
# implementation if it needs to.
setattr(cls_cpp, f"_cpp{name}", getattr(cls_cpp, name))
setattr(cls_cpp, name, member)
installed_member = getattr(cls_cpp, name)
installed_member.__qualname__ = member.__qualname__.replace(
cls.__name__, cls_cpp.__name__
)
elif inspect.isdatadescriptor(member):
setattr(cls_cpp, name, member)
def disable_init(self):
# Prevent initialization of the support class
raise NotImplementedError(self.__class__.__name__ + '.__init__')
cls.__init__ = disable_init # type: ignore
return cls
return class_augment
| AugmentedCallable |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_shortid.py | {
"start": 835,
"end": 1058
} | class ____(TypedDict):
organizationSlug: str
projectSlug: str
groupId: str
group: BaseGroupSerializerResponse
shortId: str
@extend_schema(tags=["Organizations"])
@region_silo_endpoint
| ShortIdLookupResponse |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 19446,
"end": 23265
} | class ____(CheckTestCase):
def test_not_iterable(self):
class TestModelAdmin(ModelAdmin):
list_display = 10
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_display' must be a list or tuple.",
"admin.E107",
)
def test_missing_field(self):
class TestModelAdmin(ModelAdmin):
list_display = ("non_existent_field",)
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_display[0]' refers to 'non_existent_field', "
"which is not a callable or attribute of 'TestModelAdmin', "
"or an attribute, method, or field on 'modeladmin.ValidationTestModel'.",
"admin.E108",
)
def test_missing_related_field(self):
class TestModelAdmin(ModelAdmin):
list_display = ("band__non_existent_field",)
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_display[0]' refers to 'band__non_existent_field', "
"which is not a callable or attribute of 'TestModelAdmin', "
"or an attribute, method, or field on 'modeladmin.ValidationTestModel'.",
"admin.E108",
)
def test_invalid_field_type(self):
class TestModelAdmin(ModelAdmin):
list_display = ("users",)
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_display[0]' must not be a many-to-many field or a "
"reverse foreign key.",
"admin.E109",
)
def test_invalid_reverse_related_field(self):
class TestModelAdmin(ModelAdmin):
list_display = ["song_set"]
self.assertIsInvalid(
TestModelAdmin,
Band,
"The value of 'list_display[0]' must not be a many-to-many field or a "
"reverse foreign key.",
"admin.E109",
)
def test_invalid_related_field(self):
class TestModelAdmin(ModelAdmin):
list_display = ["song"]
self.assertIsInvalid(
TestModelAdmin,
Band,
"The value of 'list_display[0]' must not be a many-to-many field or a "
"reverse foreign key.",
"admin.E109",
)
def test_invalid_m2m_related_name(self):
class TestModelAdmin(ModelAdmin):
list_display = ["featured"]
self.assertIsInvalid(
TestModelAdmin,
Band,
"The value of 'list_display[0]' must not be a many-to-many field or a "
"reverse foreign key.",
"admin.E109",
)
def test_valid_case(self):
@admin.display
def a_callable(obj):
pass
class TestModelAdmin(ModelAdmin):
@admin.display
def a_method(self, obj):
pass
list_display = ("name", "decade_published_in", "a_method", a_callable)
self.assertIsValid(TestModelAdmin, ValidationTestModel)
def test_valid_field_accessible_via_instance(self):
class PositionField(Field):
"""Custom field accessible only via instance."""
def contribute_to_class(self, cls, name):
super().contribute_to_class(cls, name)
setattr(cls, self.name, self)
def __get__(self, instance, owner):
if instance is None:
raise AttributeError()
class TestModel(Model):
field = PositionField()
class TestModelAdmin(ModelAdmin):
list_display = ("field",)
self.assertIsValid(TestModelAdmin, TestModel)
| ListDisplayTests |
python | django__django | tests/custom_pk/models.py | {
"start": 263,
"end": 615
} | class ____(models.Model):
employee_code = models.IntegerField(primary_key=True, db_column="code")
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
class Meta:
ordering = ("last_name", "first_name")
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
| Employee |
python | Pylons__pyramid | tests/test_view.py | {
"start": 1337,
"end": 3764
} | class ____(BaseTest, unittest.TestCase):
def _makeOne(self, **kw):
from pyramid.view import notfound_view_config
return notfound_view_config(**kw)
def test_ctor(self):
inst = self._makeOne(
attr='attr', path_info='path_info', append_slash=True
)
self.assertEqual(
inst.__dict__,
{'attr': 'attr', 'path_info': 'path_info', 'append_slash': True},
)
def test_it_function(self):
def view(request): # pragma: no cover
pass
decorator = self._makeOne(
attr='attr', renderer='renderer', append_slash=True
)
venusian = DummyVenusian()
decorator.venusian = venusian
wrapped = decorator(view)
self.assertTrue(wrapped is view)
config = call_venusian(venusian)
settings = config.settings
self.assertEqual(
settings,
[
{
'attr': 'attr',
'venusian': venusian,
'append_slash': True,
'renderer': 'renderer',
'_info': 'codeinfo',
'view': None,
}
],
)
def test_it_class(self):
decorator = self._makeOne()
venusian = DummyVenusian()
decorator.venusian = venusian
decorator.venusian.info.scope = 'class'
class view:
pass
wrapped = decorator(view)
self.assertTrue(wrapped is view)
config = call_venusian(venusian)
settings = config.settings
self.assertEqual(len(settings), 1)
self.assertEqual(len(settings[0]), 4)
self.assertEqual(settings[0]['venusian'], venusian)
self.assertEqual(settings[0]['view'], None) # comes from call_venusian
self.assertEqual(settings[0]['attr'], 'view')
self.assertEqual(settings[0]['_info'], 'codeinfo')
def test_call_with_venusian_args(self):
decorator = self._makeOne(_depth=1, _category='foo')
venusian = DummyVenusian()
decorator.venusian = venusian
def foo(): # pragma: no cover
pass
decorator(foo)
attachments = venusian.attachments
category = attachments[0][2]
depth = attachments[0][3]
self.assertEqual(depth, 2)
self.assertEqual(category, 'foo')
| Test_notfound_view_config |
python | pypa__setuptools | setuptools/_distutils/compilers/C/tests/test_unix.py | {
"start": 930,
"end": 14642
} | class ____(support.TempdirManager):
@pytest.mark.skipif('platform.system == "Windows"')
def test_runtime_libdir_option(self): # noqa: C901
# Issue #5900; GitHub Issue #37
#
# Ensure RUNPATH is added to extension modules with RPATH if
# GNU ld is used
# darwin
sys.platform = 'darwin'
darwin_ver_var = 'MACOSX_DEPLOYMENT_TARGET'
darwin_rpath_flag = '-Wl,-rpath,/foo'
darwin_lib_flag = '-L/foo'
# (macOS version from syscfg, macOS version from env var) -> flag
# Version value of None generates two tests: as None and as empty string
# Expected flag value of None means an mismatch exception is expected
darwin_test_cases = [
((None, None), darwin_lib_flag),
((None, '11'), darwin_rpath_flag),
(('10', None), darwin_lib_flag),
(('10.3', None), darwin_lib_flag),
(('10.3.1', None), darwin_lib_flag),
(('10.5', None), darwin_rpath_flag),
(('10.5.1', None), darwin_rpath_flag),
(('10.3', '10.3'), darwin_lib_flag),
(('10.3', '10.5'), darwin_rpath_flag),
(('10.5', '10.3'), darwin_lib_flag),
(('10.5', '11'), darwin_rpath_flag),
(('10.4', '10'), None),
]
def make_darwin_gcv(syscfg_macosx_ver):
def gcv(var):
if var == darwin_ver_var:
return syscfg_macosx_ver
return "xxx"
return gcv
def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag):
env = os.environ
msg = f"macOS version = (sysconfig={syscfg_macosx_ver!r}, env={env_macosx_ver!r})"
# Save
old_gcv = sysconfig.get_config_var
old_env_macosx_ver = env.get(darwin_ver_var)
# Setup environment
_clear_cached_macosx_ver()
sysconfig.get_config_var = make_darwin_gcv(syscfg_macosx_ver)
if env_macosx_ver is not None:
env[darwin_ver_var] = env_macosx_ver
elif darwin_ver_var in env:
env.pop(darwin_ver_var)
# Run the test
if expected_flag is not None:
assert self.cc.rpath_foo() == expected_flag, msg
else:
with pytest.raises(
DistutilsPlatformError, match=darwin_ver_var + r' mismatch'
):
self.cc.rpath_foo()
# Restore
if old_env_macosx_ver is not None:
env[darwin_ver_var] = old_env_macosx_ver
elif darwin_ver_var in env:
env.pop(darwin_ver_var)
sysconfig.get_config_var = old_gcv
_clear_cached_macosx_ver()
for macosx_vers, expected_flag in darwin_test_cases:
syscfg_macosx_ver, env_macosx_ver = macosx_vers
do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag)
# Bonus test cases with None interpreted as empty string
if syscfg_macosx_ver is None:
do_darwin_test("", env_macosx_ver, expected_flag)
if env_macosx_ver is None:
do_darwin_test(syscfg_macosx_ver, "", expected_flag)
if syscfg_macosx_ver is None and env_macosx_ver is None:
do_darwin_test("", "", expected_flag)
old_gcv = sysconfig.get_config_var
# hp-ux
sys.platform = 'hp-ux'
def gcv(v):
return 'xxx'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == ['+s', '-L/foo']
def gcv(v):
return 'gcc'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo']
def gcv(v):
return 'g++'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo']
sysconfig.get_config_var = old_gcv
# GCC GNULD
sys.platform = 'bar'
def gcv(v):
if v == 'CC':
return 'gcc'
elif v == 'GNULD':
return 'yes'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == consolidate_linker_args([
'-Wl,--enable-new-dtags',
'-Wl,-rpath,/foo',
])
def gcv(v):
if v == 'CC':
return 'gcc -pthread -B /bar'
elif v == 'GNULD':
return 'yes'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == consolidate_linker_args([
'-Wl,--enable-new-dtags',
'-Wl,-rpath,/foo',
])
# GCC non-GNULD
sys.platform = 'bar'
def gcv(v):
if v == 'CC':
return 'gcc'
elif v == 'GNULD':
return 'no'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == '-Wl,-R/foo'
# GCC GNULD with fully qualified configuration prefix
# see #7617
sys.platform = 'bar'
def gcv(v):
if v == 'CC':
return 'x86_64-pc-linux-gnu-gcc-4.4.2'
elif v == 'GNULD':
return 'yes'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == consolidate_linker_args([
'-Wl,--enable-new-dtags',
'-Wl,-rpath,/foo',
])
# non-GCC GNULD
sys.platform = 'bar'
def gcv(v):
if v == 'CC':
return 'cc'
elif v == 'GNULD':
return 'yes'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == consolidate_linker_args([
'-Wl,--enable-new-dtags',
'-Wl,-rpath,/foo',
])
# non-GCC non-GNULD
sys.platform = 'bar'
def gcv(v):
if v == 'CC':
return 'cc'
elif v == 'GNULD':
return 'no'
sysconfig.get_config_var = gcv
assert self.cc.rpath_foo() == '-Wl,-R/foo'
@pytest.mark.skipif('platform.system == "Windows"')
def test_cc_overrides_ldshared(self):
# Issue #18080:
# ensure that setting CC env variable also changes default linker
def gcv(v):
if v == 'LDSHARED':
return 'gcc-4.2 -bundle -undefined dynamic_lookup '
return 'gcc-4.2'
def gcvs(*args, _orig=sysconfig.get_config_vars):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig()
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with EnvironmentVarGuard() as env:
env['CC'] = 'my_cc'
del env['LDSHARED']
sysconfig.customize_compiler(self.cc)
assert self.cc.linker_so[0] == 'my_cc'
@pytest.mark.skipif('platform.system == "Windows"')
def test_cxx_commands_used_are_correct(self):
def gcv(v):
if v == 'LDSHARED':
return 'ccache gcc-4.2 -bundle -undefined dynamic_lookup'
elif v == 'LDCXXSHARED':
return 'ccache g++-4.2 -bundle -undefined dynamic_lookup'
elif v == 'CXX':
return 'ccache g++-4.2'
elif v == 'CC':
return 'ccache gcc-4.2'
return ''
def gcvs(*args, _orig=sysconfig.get_config_vars):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig() # pragma: no cover
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with (
mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
mock.patch.object(self.cc, '_need_link', return_value=True),
mock.patch.object(self.cc, 'mkpath', return_value=None),
EnvironmentVarGuard() as env,
):
# override environment overrides in case they're specified by CI
del env['CXX']
del env['LDCXXSHARED']
sysconfig.customize_compiler(self.cc)
assert self.cc.linker_so_cxx[0:2] == ['ccache', 'g++-4.2']
assert self.cc.linker_exe_cxx[0:2] == ['ccache', 'g++-4.2']
self.cc.link(None, [], 'a.out', target_lang='c++')
call_args = mock_spawn.call_args[0][0]
expected = ['ccache', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
assert call_args[:5] == expected
self.cc.link_executable([], 'a.out', target_lang='c++')
call_args = mock_spawn.call_args[0][0]
expected = ['ccache', 'g++-4.2', '-o', self.cc.executable_filename('a.out')]
assert call_args[:4] == expected
env['LDCXXSHARED'] = 'wrapper g++-4.2 -bundle -undefined dynamic_lookup'
env['CXX'] = 'wrapper g++-4.2'
sysconfig.customize_compiler(self.cc)
assert self.cc.linker_so_cxx[0:2] == ['wrapper', 'g++-4.2']
assert self.cc.linker_exe_cxx[0:2] == ['wrapper', 'g++-4.2']
self.cc.link(None, [], 'a.out', target_lang='c++')
call_args = mock_spawn.call_args[0][0]
expected = ['wrapper', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup']
assert call_args[:5] == expected
self.cc.link_executable([], 'a.out', target_lang='c++')
call_args = mock_spawn.call_args[0][0]
expected = [
'wrapper',
'g++-4.2',
'-o',
self.cc.executable_filename('a.out'),
]
assert call_args[:4] == expected
@pytest.mark.skipif('platform.system == "Windows"')
@pytest.mark.usefixtures('disable_macos_customization')
def test_cc_overrides_ldshared_for_cxx_correctly(self):
"""
Ensure that setting CC env variable also changes default linker
correctly when building C++ extensions.
pypa/distutils#126
"""
def gcv(v):
if v == 'LDSHARED':
return 'gcc-4.2 -bundle -undefined dynamic_lookup '
elif v == 'LDCXXSHARED':
return 'g++-4.2 -bundle -undefined dynamic_lookup '
elif v == 'CXX':
return 'g++-4.2'
elif v == 'CC':
return 'gcc-4.2'
return ''
def gcvs(*args, _orig=sysconfig.get_config_vars):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig()
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with (
mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn,
mock.patch.object(self.cc, '_need_link', return_value=True),
mock.patch.object(self.cc, 'mkpath', return_value=None),
EnvironmentVarGuard() as env,
):
env['CC'] = 'ccache my_cc'
env['CXX'] = 'my_cxx'
del env['LDSHARED']
sysconfig.customize_compiler(self.cc)
assert self.cc.linker_so[0:2] == ['ccache', 'my_cc']
self.cc.link(None, [], 'a.out', target_lang='c++')
call_args = mock_spawn.call_args[0][0]
expected = ['my_cxx', '-bundle', '-undefined', 'dynamic_lookup']
assert call_args[:4] == expected
@pytest.mark.skipif('platform.system == "Windows"')
def test_explicit_ldshared(self):
# Issue #18080:
# ensure that setting CC env variable does not change
# explicit LDSHARED setting for linker
def gcv(v):
if v == 'LDSHARED':
return 'gcc-4.2 -bundle -undefined dynamic_lookup '
return 'gcc-4.2'
def gcvs(*args, _orig=sysconfig.get_config_vars):
if args:
return list(map(sysconfig.get_config_var, args))
return _orig()
sysconfig.get_config_var = gcv
sysconfig.get_config_vars = gcvs
with EnvironmentVarGuard() as env:
env['CC'] = 'my_cc'
env['LDSHARED'] = 'my_ld -bundle -dynamic'
sysconfig.customize_compiler(self.cc)
assert self.cc.linker_so[0] == 'my_ld'
def test_has_function(self):
# Issue https://github.com/pypa/distutils/issues/64:
# ensure that setting output_dir does not raise
# FileNotFoundError: [Errno 2] No such file or directory: 'a.out'
self.cc.output_dir = 'scratch'
os.chdir(self.mkdtemp())
self.cc.has_function('abort')
def test_find_library_file(self, monkeypatch):
compiler = unix.Compiler()
compiler._library_root = lambda dir: dir
monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)
libname = 'libabc.dylib' if sys.platform != 'cygwin' else 'cygabc.dll'
dirs = ('/foo/bar/missing', '/foo/bar/existing')
assert (
compiler.find_library_file(dirs, 'abc').replace('\\', '/')
== f'/foo/bar/existing/{libname}'
)
assert (
compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
== f'/foo/bar/existing/{libname}'
)
monkeypatch.setattr(
os.path,
'exists',
lambda d: 'existing' in d and '.a' in d and '.dll.a' not in d,
)
assert (
compiler.find_library_file(dirs, 'abc').replace('\\', '/')
== '/foo/bar/existing/libabc.a'
)
assert (
compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/')
== '/foo/bar/existing/libabc.a'
)
| TestUnixCCompiler |
python | apache__airflow | helm-tests/tests/helm_tests/security/test_elasticsearch_secret.py | {
"start": 929,
"end": 4936
} | class ____:
"""Tests elasticsearch secret."""
def _get_connection(self, values: dict) -> str:
docs = render_chart(
values=values,
show_only=["templates/secrets/elasticsearch-secret.yaml"],
)
encoded_connection = jmespath.search("data.connection", docs[0])
return base64.b64decode(encoded_connection).decode()
def test_should_correctly_handle_password_with_special_characters(self):
connection = self._get_connection(
{
"elasticsearch": {
"enabled": True,
"connection": {
"user": "username!@#$%%^&*()",
"pass": "password!@#$%%^&*()",
"host": "elastichostname",
},
}
}
)
assert (
connection
== "http://username%21%40%23$%25%25%5E&%2A%28%29:password%21%40%23$%25%25%5E&%2A%28%29@"
"elastichostname:9200"
)
def test_should_generate_secret_with_specified_port(self):
connection = self._get_connection(
{
"elasticsearch": {
"enabled": True,
"connection": {
"user": "username",
"pass": "password",
"host": "elastichostname",
"port": 2222,
},
}
}
)
assert connection == "http://username:password@elastichostname:2222"
@pytest.mark.parametrize("scheme", ["http", "https"])
def test_should_generate_secret_with_specified_schemes(self, scheme):
connection = self._get_connection(
{
"elasticsearch": {
"enabled": True,
"connection": {
"scheme": scheme,
"user": "username",
"pass": "password",
"host": "elastichostname",
},
}
}
)
assert f"{scheme}://username:password@elastichostname:9200" == connection
@pytest.mark.parametrize(
("extra_conn_kwargs", "expected_user_info"),
[
# When both user and password are empty.
({}, ""),
# When password is empty
({"user": "admin"}, ""),
# When user is empty
({"pass": "password"}, ""),
# Valid username/password
({"user": "admin", "pass": "password"}, "admin:password"),
],
)
def test_url_generated_when_user_pass_empty_combinations(self, extra_conn_kwargs, expected_user_info):
connection = self._get_connection(
{
"elasticsearch": {
"enabled": True,
"connection": {"host": "elastichostname", "port": 8080, **extra_conn_kwargs},
}
}
)
if not expected_user_info:
assert connection == "http://elastichostname:8080"
else:
assert f"http://{expected_user_info}@elastichostname:8080" == connection
def test_should_add_annotations_to_elasticsearch_secret(self):
docs = render_chart(
values={
"elasticsearch": {
"enabled": True,
"connection": {
"user": "username",
"pass": "password",
"host": "elastichostname",
},
"secretAnnotations": {"test_annotation": "test_annotation_value"},
}
},
show_only=["templates/secrets/elasticsearch-secret.yaml"],
)[0]
assert "annotations" in jmespath.search("metadata", docs)
assert jmespath.search("metadata.annotations", docs)["test_annotation"] == "test_annotation_value"
| TestElasticsearchSecret |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 52825,
"end": 53248
} | class ____(GraphenePipeline):
class Meta: # pyright: ignore[reportIncompatibleVariableOverride]
interfaces = (GrapheneSolidContainer, GrapheneIPipelineSnapshot)
name = "Job"
# doesn't inherit from base class
def __init__(self, remote_job):
super().__init__() # pyright: ignore[reportCallIssue]
self._remote_job = check.inst_param(remote_job, "remote_job", RemoteJob)
| GrapheneJob |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 15736,
"end": 19522
} | class ____(BaseModel):
type: Literal["OAuthAuthenticator"]
client_id: str = Field(
...,
description="The OAuth client ID. Fill it in the user inputs.",
examples=["{{ config['client_id }}", "{{ config['credentials']['client_id }}"],
title="Client ID",
)
client_secret: str = Field(
...,
description="The OAuth client secret. Fill it in the user inputs.",
examples=[
"{{ config['client_secret }}",
"{{ config['credentials']['client_secret }}",
],
title="Client Secret",
)
refresh_token: Optional[str] = Field(
None,
description="Credential artifact used to get a new access token.",
examples=[
"{{ config['refresh_token'] }}",
"{{ config['credentials]['refresh_token'] }}",
],
title="Refresh Token",
)
token_refresh_endpoint: str = Field(
...,
description="The full URL to call to obtain a new access token.",
examples=["https://connect.squareup.com/oauth2/token"],
title="Token Refresh Endpoint",
)
access_token_name: Optional[str] = Field(
"access_token",
description="The name of the property which contains the access token in the response from the token refresh endpoint.",
examples=["access_token"],
title="Access Token Property Name",
)
expires_in_name: Optional[str] = Field(
"expires_in",
description="The name of the property which contains the expiry date in the response from the token refresh endpoint.",
examples=["expires_in"],
title="Token Expiry Property Name",
)
grant_type: Optional[str] = Field(
"refresh_token",
description="Specifies the OAuth2 grant type. If set to refresh_token, the refresh_token needs to be provided as well. For client_credentials, only client id and secret are required. Other grant types are not officially supported.",
examples=["refresh_token", "client_credentials"],
title="Grant Type",
)
refresh_request_body: Optional[Dict[str, Any]] = Field(
None,
description="Body of the request sent to get a new access token.",
examples=[
{
"applicationId": "{{ config['application_id'] }}",
"applicationSecret": "{{ config['application_secret'] }}",
"token": "{{ config['token'] }}",
}
],
title="Refresh Request Body",
)
scopes: Optional[List[str]] = Field(
None,
description="List of scopes that should be granted to the access token.",
examples=[["crm.list.read", "crm.objects.contacts.read", "crm.schema.contacts.read"]],
title="Scopes",
)
token_expiry_date: Optional[str] = Field(
None,
description="The access token expiry date.",
examples=["2023-04-06T07:12:10.421833+00:00", 1680842386],
title="Token Expiry Date",
)
token_expiry_date_format: Optional[str] = Field(
None,
description="The format of the time to expiration datetime. Provide it if the time is returned as a date-time string instead of seconds.",
examples=["%Y-%m-%d %H:%M:%S.%f+00:00"],
title="Token Expiry Date Format",
)
refresh_token_updater: Optional[RefreshTokenUpdater] = Field(
None,
description="When the token updater is defined, new refresh tokens, access tokens and the access token expiry date are written back from the authentication response to the config object. This is important if the refresh token can only used once.",
title="Token Updater",
)
parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
| OAuthAuthenticator |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_typed_mapping.py | {
"start": 115443,
"end": 135929
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
@testing.fixture
def decl_base(self):
class Base(DeclarativeBase):
pass
yield Base
Base.registry.dispose()
@testing.combinations(
(Relationship, _CollectionAttributeImpl),
(Mapped, _CollectionAttributeImpl),
(WriteOnlyMapped, _WriteOnlyAttributeImpl),
(DynamicMapped, _DynamicAttributeImpl),
argnames="mapped_cls,implcls",
)
def test_use_relationship(self, decl_base, mapped_cls, implcls):
"""test #10611"""
# anno only: global B
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
# for future annotations support, need to write these
# directly in source code
if mapped_cls is Relationship:
bs: Relationship[List[B]] = relationship()
elif mapped_cls is Mapped:
bs: Mapped[List[B]] = relationship()
elif mapped_cls is WriteOnlyMapped:
bs: WriteOnlyMapped[List[B]] = relationship()
elif mapped_cls is DynamicMapped:
bs: DynamicMapped[List[B]] = relationship()
decl_base.registry.configure()
assert isinstance(A.bs.impl, implcls)
def test_no_typing_in_rhs(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
bs = relationship("List['B']")
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
with expect_raises_message(
sa_exc.InvalidRequestError,
r"When initializing mapper Mapper\[A\(a\)\], expression "
r'"relationship\(\"List\[\'B\'\]\"\)\" seems to be using a '
r"generic class as the argument to relationship\(\); please "
r"state the generic argument using an annotation, e.g. "
r'"bs: Mapped\[List\[\'B\'\]\] = relationship\(\)"',
):
decl_base.registry.configure()
def test_required_no_arg(self, decl_base):
with expect_raises_message(
sa_exc.ArgumentError,
r"Python typing annotation is required for attribute "
r'"A.bs" when primary '
r'argument\(s\) for "Relationship" construct are None or '
r"not present",
):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
bs = relationship()
def test_legacy_dataclasses_not_currently_using_annotations(
self, registry
):
"""test if relationship() inspects annotations when using
the legacy dataclass style.
As of #8692, we are not looking at any annotations that don't use
``Mapped[]``. dataclass users should use MappedAsDataclass and
new conventions.
"""
@registry.mapped
@dataclasses.dataclass
class A:
__tablename__ = "a"
__sa_dataclass_metadata_key__ = "sa"
id: Mapped[int] = mapped_column(primary_key=True)
bs: List["B"] = dataclasses.field( # noqa: F821
default_factory=list, metadata={"sa": relationship()}
)
@registry.mapped
@dataclasses.dataclass
class B:
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
a_id = mapped_column(ForeignKey("a.id"))
with expect_raises_message(
ArgumentError,
"relationship 'bs' expects a class or a mapper argument",
):
registry.configure()
@testing.variation(
"datatype",
[
"typing_sequence",
"collections_sequence",
"typing_mutable_sequence",
"collections_mutable_sequence",
],
)
@testing.variation("include_explicit", [True, False])
def test_relationship_abstract_cls_error(
self, decl_base, datatype, include_explicit
):
"""test #9100"""
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
data: Mapped[str]
if include_explicit:
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
# note this can be done more succinctly by assigning to
# an interim type, however making it explicit here
# allows us to further test de-stringifying of these
# collection types
if datatype.typing_sequence:
bs: Mapped[typing.Sequence[B]] = relationship(
collection_class=list
)
elif datatype.collections_sequence:
bs: Mapped[collections.abc.Sequence[B]] = relationship(
collection_class=list
)
elif datatype.typing_mutable_sequence:
bs: Mapped[typing.MutableSequence[B]] = relationship(
collection_class=list
)
elif datatype.collections_mutable_sequence:
bs: Mapped[collections.abc.MutableSequence[B]] = (
relationship(collection_class=list)
)
else:
datatype.fail()
decl_base.registry.configure()
self.assert_compile(
select(A).join(A.bs),
"SELECT a.id FROM a JOIN b ON a.id = b.a_id",
)
else:
with expect_raises_message(
sa_exc.ArgumentError,
r"Collection annotation type "
r".*Sequence.* cannot be "
r"instantiated; please provide an explicit "
r"'collection_class' parameter \(e.g. list, set, etc.\) to "
r"the relationship\(\) function to accompany this annotation",
):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
if datatype.typing_sequence:
bs: Mapped[typing.Sequence[B]] = relationship()
elif datatype.collections_sequence:
bs: Mapped[collections.abc.Sequence[B]] = (
relationship()
)
elif datatype.typing_mutable_sequence:
bs: Mapped[typing.MutableSequence[B]] = relationship()
elif datatype.collections_mutable_sequence:
bs: Mapped[collections.abc.MutableSequence[B]] = (
relationship()
)
else:
datatype.fail()
decl_base.registry.configure()
@testing.variation(
"collection_type",
["list", "List", "set", "Set"],
)
def test_14_style_anno_accepted_w_allow_unmapped(self, collection_type):
"""test for #8692 and #10385"""
class Base(DeclarativeBase):
__allow_unmapped__ = True
class A(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: str = Column(String)
if collection_type.list:
bs: list["B"] = relationship( # noqa: F821
"B",
back_populates="a",
)
elif collection_type.List:
bs: List["B"] = relationship( # noqa: F821
"B",
back_populates="a",
)
elif collection_type.set:
bs: set["B"] = relationship( # noqa: F821
"B",
back_populates="a",
)
elif collection_type.Set:
bs: Set["B"] = relationship( # noqa: F821
"B",
back_populates="a",
)
else:
collection_type.fail()
class B(Base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
data: Mapped[str]
a: A = relationship("A", back_populates="bs")
Base.registry.configure()
self.assert_compile(
select(A).join(A.bs),
"SELECT a.id, a.data FROM a JOIN b ON a.id = b.a_id",
)
self.assert_compile(
select(B).join(B.a),
"SELECT b.id, b.a_id, b.data FROM b JOIN a ON a.id = b.a_id",
)
@testing.combinations(
("not_optional",),
("optional",),
("optional_fwd_ref",),
("union_none",),
("pep604",),
argnames="optional_on_m2o",
)
def test_basic_bidirectional(self, decl_base, optional_on_m2o):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
bs: Mapped[List["B"]] = relationship( # noqa: F821
back_populates="a"
)
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
if optional_on_m2o == "optional":
a: Mapped[Optional["A"]] = relationship(
back_populates="bs", primaryjoin=a_id == A.id
)
elif optional_on_m2o == "optional_fwd_ref":
a: Mapped["Optional[A]"] = relationship(
back_populates="bs", primaryjoin=a_id == A.id
)
elif optional_on_m2o == "union_none":
a: Mapped[Union[A, None]] = relationship(
back_populates="bs", primaryjoin=a_id == A.id
)
elif optional_on_m2o == "pep604":
a: Mapped[A | None] = relationship(
back_populates="bs", primaryjoin=a_id == A.id
)
else:
a: Mapped["A"] = relationship(
back_populates="bs", primaryjoin=a_id == A.id
)
a1 = A(data="data")
b1 = B()
a1.bs.append(b1)
is_(a1, b1.a)
def test_wrong_annotation_type_one(self, decl_base):
with expect_annotation_syntax_error("A.data"):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: "B" = relationship() # type: ignore # noqa
def test_wrong_annotation_type_two(self, decl_base):
with expect_annotation_syntax_error("A.data"):
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: B = relationship() # type: ignore # noqa
def test_wrong_annotation_type_three(self, decl_base):
with expect_annotation_syntax_error("A.data"):
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: "List[B]" = relationship() # type: ignore # noqa
def test_collection_class_uselist(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
bs_list: Mapped[List["B"]] = relationship( # noqa: F821
viewonly=True
)
bs_set: Mapped[Set["B"]] = relationship( # noqa: F821
viewonly=True
)
bs_list_warg: Mapped[List["B"]] = relationship( # noqa: F821
"B", viewonly=True
)
bs_set_warg: Mapped[Set["B"]] = relationship( # noqa: F821
"B", viewonly=True
)
# note this is string annotation
b_one_to_one: Mapped["B"] = relationship( # noqa: F821
viewonly=True
)
b_one_to_one_warg: Mapped["B"] = relationship( # noqa: F821
"B", viewonly=True
)
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
a: Mapped["A"] = relationship(viewonly=True)
a_warg: Mapped["A"] = relationship("A", viewonly=True)
is_(A.__mapper__.attrs["bs_list"].collection_class, list)
is_(A.__mapper__.attrs["bs_set"].collection_class, set)
is_(A.__mapper__.attrs["bs_list_warg"].collection_class, list)
is_(A.__mapper__.attrs["bs_set_warg"].collection_class, set)
is_true(A.__mapper__.attrs["bs_list"].uselist)
is_true(A.__mapper__.attrs["bs_set"].uselist)
is_true(A.__mapper__.attrs["bs_list_warg"].uselist)
is_true(A.__mapper__.attrs["bs_set_warg"].uselist)
is_false(A.__mapper__.attrs["b_one_to_one"].uselist)
is_false(A.__mapper__.attrs["b_one_to_one_warg"].uselist)
is_false(B.__mapper__.attrs["a"].uselist)
is_false(B.__mapper__.attrs["a_warg"].uselist)
def test_one_to_one_example_quoted(self, decl_base: Type[DeclarativeBase]):
"""test example in the relationship docs will derive uselist=False
correctly"""
class Parent(decl_base):
__tablename__ = "parent"
id: Mapped[int] = mapped_column(primary_key=True)
child: Mapped["Child"] = relationship( # noqa: F821
back_populates="parent"
)
class Child(decl_base):
__tablename__ = "child"
id: Mapped[int] = mapped_column(primary_key=True)
parent_id: Mapped[int] = mapped_column(ForeignKey("parent.id"))
parent: Mapped["Parent"] = relationship(back_populates="child")
c1 = Child()
p1 = Parent(child=c1)
is_(p1.child, c1)
is_(c1.parent, p1)
def test_one_to_one_example_non_quoted(
self, decl_base: Type[DeclarativeBase]
):
"""test example in the relationship docs will derive uselist=False
correctly"""
class Child(decl_base):
__tablename__ = "child"
id: Mapped[int] = mapped_column(primary_key=True)
parent_id: Mapped[int] = mapped_column(ForeignKey("parent.id"))
parent: Mapped["Parent"] = relationship(back_populates="child")
class Parent(decl_base):
__tablename__ = "parent"
id: Mapped[int] = mapped_column(primary_key=True)
child: Mapped[Child] = relationship( # noqa: F821
back_populates="parent"
)
c1 = Child()
p1 = Parent(child=c1)
is_(p1.child, c1)
is_(c1.parent, p1)
def test_collection_class_dict_no_collection(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
bs: Mapped[Dict[str, "B"]] = relationship() # noqa: F821
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
name: Mapped[str] = mapped_column()
# this is the old collections message. it's not great, but at the
# moment I like that this is what's raised
with expect_raises_message(
sa_exc.ArgumentError,
"Type InstrumentedDict must elect an appender",
):
decl_base.registry.configure()
def test_collection_class_dict_attr_mapped_collection(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
bs: Mapped[KeyFuncDict[str, "B"]] = relationship( # noqa: F821
collection_class=attribute_keyed_dict("name")
)
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
name: Mapped[str] = mapped_column()
decl_base.registry.configure()
a1 = A()
b1 = B(name="foo")
# collection appender on MappedCollection
a1.bs.set(b1)
is_(a1.bs["foo"], b1)
@testing.combinations(
"include_relationship",
"no_relationship",
argnames="include_relationship",
)
@testing.combinations(
"direct_name", "indirect_name", argnames="indirect_name"
)
def test_indirect_name_collection(
self, decl_base, include_relationship, indirect_name
):
"""test #8759"""
# anno only: global B_
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
B_ = B
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
if indirect_name == "indirect_name":
if include_relationship == "include_relationship":
bs: Mapped[List[B_]] = relationship("B")
else:
bs: Mapped[List[B_]] = relationship()
else:
if include_relationship == "include_relationship":
bs: Mapped[List[B]] = relationship("B")
else:
bs: Mapped[List[B]] = relationship()
self.assert_compile(
select(A).join(A.bs),
"SELECT a.id, a.data FROM a JOIN b ON a.id = b.a_id",
)
@testing.combinations(
"include_relationship",
"no_relationship",
argnames="include_relationship",
)
@testing.combinations(
"direct_name", "indirect_name", argnames="indirect_name"
)
def test_indirect_name_scalar(
self, decl_base, include_relationship, indirect_name
):
"""test #8759"""
# anno only: global A_
class A(decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str] = mapped_column()
A_ = A
class B(decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
if indirect_name == "indirect_name":
if include_relationship == "include_relationship":
a: Mapped[A_] = relationship("A")
else:
a: Mapped[A_] = relationship()
else:
if include_relationship == "include_relationship":
a: Mapped[A] = relationship("A")
else:
a: Mapped[A] = relationship()
self.assert_compile(
select(B).join(B.a),
"SELECT b.id, b.a_id FROM b JOIN a ON a.id = b.a_id",
)
| RelationshipLHSTest |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-example/test_flow_segmenter.py | {
"start": 183,
"end": 1215
} | class ____(Executor):
"""dummySegment represents a basic segment of two values"""
@requests
def segment(self, docs, *args, **kwargs):
"""create a dummy segment of two values."""
for d in docs:
d.chunks = [Document(blob=b'aa'), Document(blob=b'bb')]
def validate(req):
"""simple check for validating tests."""
chunk_ids = [c.id for d in req.docs for c in d.chunks]
assert len(chunk_ids) == len(set(chunk_ids))
assert len(chunk_ids) == 20
@pytest.mark.parametrize('protocol', ['websocket', 'grpc', 'http'])
@pytest.mark.parametrize(
'uses',
[
'DummySegment',
os.path.join(cur_dir, 'yaml/dummy-seg-not-random.yml'),
],
)
def test_seg(mocker, protocol, uses):
"""tests segments provided the uses for a flow."""
mock = mocker.Mock()
f = Flow(protocol=protocol).add(uses=uses)
with f:
f.index(inputs=random_docs(10, chunks_per_doc=0), on_done=mock)
mock.assert_called_once()
validate_callback(mock, validate)
| DummySegment |
python | huggingface__transformers | src/transformers/models/camembert/modeling_camembert.py | {
"start": 34925,
"end": 38687
} | class ____(CamembertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.classifier = CamembertClassificationHead(config)
self.roberta = CamembertModel(config, add_pooling_layer=False)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
r"""
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
>= 2. All the value in this tensor should be always < type_vocab_size.
[What are token type IDs?](../glossary#token-type-ids)
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
sequence_output = outputs[0]
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
# move labels to correct device
labels = labels.to(logits.device)
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
| CamembertForSequenceClassification |
python | pydantic__pydantic | pydantic/fields.py | {
"start": 66600,
"end": 80191
} | class ____:
"""A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
Attributes:
decorator_repr: A class variable representing the decorator string, '@computed_field'.
wrapped_property: The wrapped computed field property.
return_type: The type of the computed field property's return value.
alias: The alias of the property to be used during serialization.
alias_priority: The priority of the alias. This affects whether an alias generator is used.
title: Title of the computed field to include in the serialization JSON schema.
field_title_generator: A callable that takes a field name and returns title for it.
description: Description of the computed field to include in the serialization JSON schema.
deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
examples: Example values of the computed field to include in the serialization JSON schema.
json_schema_extra: A dict or callable to provide extra JSON schema properties.
repr: A boolean indicating whether to include the field in the __repr__ output.
"""
decorator_repr: ClassVar[str] = '@computed_field'
wrapped_property: property
return_type: Any
alias: str | None
alias_priority: int | None
title: str | None
field_title_generator: Callable[[str, ComputedFieldInfo], str] | None
description: str | None
deprecated: Deprecated | str | bool | None
examples: list[Any] | None
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
repr: bool
# NOTE: if you add a new field, add it to the `__copy__()` implementation.
def __copy__(self) -> Self:
return type(self)(
wrapped_property=self.wrapped_property,
return_type=self.return_type,
alias=self.alias,
alias_priority=self.alias_priority,
title=self.title,
field_title_generator=self.field_title_generator,
description=self.description,
deprecated=self.deprecated,
examples=self.examples.copy() if isinstance(self.examples, list) else self.examples,
json_schema_extra=self.json_schema_extra.copy()
if isinstance(self.json_schema_extra, dict)
else self.json_schema_extra,
repr=self.repr,
)
@property
def deprecation_message(self) -> str | None:
"""The deprecation message to be emitted, or `None` if not set."""
if self.deprecated is None:
return None
if isinstance(self.deprecated, bool):
return 'deprecated' if self.deprecated else None
return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None:
"""Update the instance from the configuration set on the class this computed field belongs to."""
title_generator = self.field_title_generator or config_wrapper.field_title_generator
if title_generator is not None and self.title is None:
self.title = title_generator(name, self)
if config_wrapper.alias_generator is not None:
self._apply_alias_generator(config_wrapper.alias_generator, name)
def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None:
"""Apply an alias generator to aliases if appropriate.
Args:
alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
name: The name of the computed field from which to generate the alias.
"""
# Apply an alias_generator if
# 1. An alias is not specified
# 2. An alias is specified, but the priority is <= 1
if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None:
alias, _, serialization_alias = None, None, None
if isinstance(alias_generator, AliasGenerator):
alias, _, serialization_alias = alias_generator.generate_aliases(name)
elif callable(alias_generator):
alias = alias_generator(name)
# if priority is not set, we set to 1
# which supports the case where the alias_generator from a child class is used
# to generate an alias for a field in a parent class
if self.alias_priority is None or self.alias_priority <= 1:
self.alias_priority = 1
# if the priority is 1, then we set the aliases to the generated alias
# note that we use the serialization_alias with priority over alias, as computed_field
# aliases are used for serialization only (not validation)
if self.alias_priority == 1:
self.alias = _utils.get_first_not_none(serialization_alias, alias)
def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore
"""Returns true if provided property is private, False otherwise."""
wrapped_name: str = ''
if isinstance(property_, property):
wrapped_name = getattr(property_.fget, '__name__', '')
elif isinstance(property_, cached_property): # type: ignore
wrapped_name = getattr(property_.func, '__name__', '') # type: ignore
return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
# See https://github.com/python/typing/issues/985 and linked issues
PropertyT = TypeVar('PropertyT')
@overload
def computed_field(func: PropertyT, /) -> PropertyT: ...
@overload
def computed_field(
*,
alias: str | None = None,
alias_priority: int | None = None,
title: str | None = None,
field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
description: str | None = None,
deprecated: Deprecated | str | bool | None = None,
examples: list[Any] | None = None,
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
repr: bool = True,
return_type: Any = PydanticUndefined,
) -> Callable[[PropertyT], PropertyT]: ...
def computed_field(
func: PropertyT | None = None,
/,
*,
alias: str | None = None,
alias_priority: int | None = None,
title: str | None = None,
field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
description: str | None = None,
deprecated: Deprecated | str | bool | None = None,
examples: list[Any] | None = None,
json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
repr: bool | None = None,
return_type: Any = PydanticUndefined,
) -> PropertyT | Callable[[PropertyT], PropertyT]:
"""!!! abstract "Usage Documentation"
[The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
Decorator to include `property` and `cached_property` when serializing models or dataclasses.
This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
```python
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: int
length: int
@computed_field
@property
def area(self) -> int:
return self.width * self.length
print(Rectangle(width=3, length=2).model_dump())
#> {'width': 3, 'length': 2, 'area': 6}
```
If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
and confuse static type checkers, thus explicit use of `@property` is recommended.
!!! warning "Mypy Warning"
Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
mypy may throw a `Decorated property not supported` error.
See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
[pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
```python
import random
from pydantic import BaseModel, computed_field
class Square(BaseModel):
width: float
@computed_field
def area(self) -> float: # converted to a `property` by `computed_field`
return round(self.width**2, 2)
@area.setter
def area(self, new_area: float) -> None:
self.width = new_area**0.5
@computed_field(alias='the magic number', repr=False)
def random_number(self) -> int:
return random.randint(0, 1_000)
square = Square(width=1.3)
# `random_number` does not appear in representation
print(repr(square))
#> Square(width=1.3, area=1.69)
print(square.random_number)
#> 3
square.area = 4
print(square.model_dump_json(by_alias=True))
#> {"width":2.0,"area":4.0,"the magic number":3}
```
!!! warning "Overriding with `computed_field`"
You can't override a field from a parent class with a `computed_field` in the child class.
`mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
See the example below:
```python
from pydantic import BaseModel, computed_field
class Parent(BaseModel):
a: str
try:
class Child(Parent):
@computed_field
@property
def a(self) -> str:
return 'new a'
except TypeError as e:
print(e)
'''
Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
'''
```
Private properties decorated with `@computed_field` have `repr=False` by default.
```python
from functools import cached_property
from pydantic import BaseModel, computed_field
class Model(BaseModel):
foo: int
@computed_field
@cached_property
def _private_cached_property(self) -> int:
return -self.foo
@computed_field
@property
def _private_property(self) -> int:
return -self.foo
m = Model(foo=1)
print(repr(m))
#> Model(foo=1)
```
Args:
func: the function to wrap.
alias: alias to use when serializing this computed field, only used when `by_alias=True`
alias_priority: priority of the alias. This affects whether an alias generator is used
title: Title to use when including this computed field in JSON Schema
field_title_generator: A callable that takes a field name and returns title for it.
description: Description to use when including this computed field in JSON Schema, defaults to the function's
docstring
deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
`deprecated` decorator.
examples: Example values to use when including this computed field in JSON Schema
json_schema_extra: A dict or callable to provide extra JSON schema properties.
repr: whether to include this computed field in model repr.
Default is `False` for private properties and `True` for public properties.
return_type: optional return for serialization logic to expect when serializing to JSON, if included
this must be correct, otherwise a `TypeError` is raised.
If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
objects.
Returns:
A proxy wrapper for the property.
"""
def dec(f: Any) -> Any:
nonlocal description, deprecated, return_type, alias_priority
unwrapped = _decorators.unwrap_wrapped_function(f)
if description is None and unwrapped.__doc__:
description = inspect.cleandoc(unwrapped.__doc__)
if deprecated is None and hasattr(unwrapped, '__deprecated__'):
deprecated = unwrapped.__deprecated__
# if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
f = _decorators.ensure_property(f)
alias_priority = (alias_priority or 2) if alias is not None else None
if repr is None:
repr_: bool = not _wrapped_property_is_private(property_=f)
else:
repr_ = repr
dec_info = ComputedFieldInfo(
f,
return_type,
alias,
alias_priority,
title,
field_title_generator,
description,
deprecated,
examples,
json_schema_extra,
repr_,
)
return _decorators.PydanticDescriptorProxy(f, dec_info)
if func is None:
return dec
else:
return dec(func)
| ComputedFieldInfo |
python | kamyu104__LeetCode-Solutions | Python/n-th-tribonacci-number.py | {
"start": 870,
"end": 1094
} | class ____(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
a, b, c = 0, 1, 1
for _ in xrange(n):
a, b, c = b, c, a+b+c
return a
| Solution2 |
python | huggingface__transformers | src/transformers/models/deepseek_v2/modeling_deepseek_v2.py | {
"start": 20533,
"end": 21425
} | class ____(PreTrainedModel):
config: DeepseekV2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["DeepseekV2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": DeepseekV2DecoderLayer,
"attentions": DeepseekV2Attention,
}
@torch.no_grad()
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, DeepseekV2Experts):
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
@auto_docstring
| DeepseekV2PreTrainedModel |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_dynamo.py | {
"start": 1100,
"end": 5604
} | class ____:
EXPORT_STATUS_COMPLETED = "COMPLETED"
EXPORT_STATUS_FAILED = "FAILED"
EXPORT_STATUS_IN_PROGRESS = "IN_PROGRESS"
IMPORT_STATUS_FAILED = ("CANCELLING", "CANCELLED", "FAILED")
IMPORT_STATUS_COMPLETED = "COMPLETED"
IMPORT_STATUS_IN_PROGRESS = "IN_PROGRESS"
@pytest.fixture(autouse=True)
def _setup_test_cases(self, monkeypatch):
self.resource = boto3.resource("dynamodb", region_name="eu-west-3")
monkeypatch.setattr(DynamoDBHook, "conn", self.resource)
self.client = self.resource.meta.client
@pytest.fixture
def mock_describe_export(self):
"""Mock ``DynamoDBHook.Client.describe_export`` method."""
with mock.patch.object(self.client, "describe_export") as m:
yield m
@pytest.fixture
def mock_describe_import(self):
"""Mock ``DynamoDBHook.Client.describe_import`` method."""
with mock.patch.object(self.client, "describe_import") as m:
yield m
def test_service_waiters(self):
hook_waiters = DynamoDBHook(aws_conn_id=None).list_waiters()
assert "export_table" in hook_waiters
assert "import_table" in hook_waiters
@staticmethod
def describe_export(status: str):
"""
Helper function for generate minimal DescribeExport response for single job.
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeExport.html
"""
return {"ExportDescription": {"ExportStatus": status}}
@staticmethod
def describe_import(status: str):
"""
Helper function for generate minimal DescribeImport response for single job.
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeImport.html
"""
return {"ImportTableDescription": {"ImportStatus": status}}
def test_export_table_to_point_in_time_completed(self, mock_describe_export):
"""Test state transition from `in progress` to `completed` during init."""
waiter = DynamoDBHook(aws_conn_id=None).get_waiter("export_table")
mock_describe_export.side_effect = [
self.describe_export(self.EXPORT_STATUS_IN_PROGRESS),
self.describe_export(self.EXPORT_STATUS_COMPLETED),
]
waiter.wait(
ExportArn="LoremIpsumissimplydummytextoftheprintingandtypesettingindustry",
WaiterConfig={"Delay": 0.01, "MaxAttempts": 3},
)
def test_export_table_to_point_in_time_failed(self, mock_describe_export):
"""Test state transition from `in progress` to `failed` during init."""
with mock.patch("boto3.client") as client:
client.return_value = self.client
mock_describe_export.side_effect = [
self.describe_export(self.EXPORT_STATUS_IN_PROGRESS),
self.describe_export(self.EXPORT_STATUS_FAILED),
]
waiter = DynamoDBHook(aws_conn_id=None).get_waiter("export_table", client=self.client)
with pytest.raises(WaiterError, match='we matched expected path: "FAILED"'):
waiter.wait(
ExportArn="LoremIpsumissimplydummytextoftheprintingandtypesettingindustry",
WaiterConfig={"Delay": 0.01, "MaxAttempts": 3},
)
def test_import_table_completed(self, mock_describe_import):
waiter = DynamoDBHook(aws_conn_id=None).get_waiter("import_table")
mock_describe_import.side_effect = [
self.describe_import(self.IMPORT_STATUS_IN_PROGRESS),
self.describe_import(self.IMPORT_STATUS_COMPLETED),
]
waiter.wait(
ImportArn=TEST_IMPORT_ARN,
WaiterConfig={"Delay": 0.01, "MaxAttempts": 3},
)
@pytest.mark.parametrize(
"status",
[
pytest.param(IMPORT_STATUS_FAILED[0]),
pytest.param(IMPORT_STATUS_FAILED[1]),
pytest.param(IMPORT_STATUS_FAILED[2]),
],
)
def test_import_table_failed(self, status, mock_describe_import):
waiter = DynamoDBHook(aws_conn_id=None).get_waiter("import_table")
mock_describe_import.side_effect = [
self.describe_import(self.EXPORT_STATUS_IN_PROGRESS),
self.describe_import(status),
]
with pytest.raises(WaiterError, match=f'we matched expected path: "{status}"'):
waiter.wait(ImportArn=TEST_IMPORT_ARN, WaiterConfig={"Delay": 0.01, "MaxAttempts": 3})
| TestCustomDynamoDBServiceWaiters |
python | ethereum__web3.py | tests/integration/go_ethereum/common.py | {
"start": 794,
"end": 2966
} | class ____(EthModuleTest):
@pytest.mark.xfail(reason="eth_signTypedData has not been released in geth")
def test_eth_sign_typed_data(self, w3, keyfile_account_address_dual_type):
super().test_eth_sign_typed_data(w3, keyfile_account_address_dual_type)
@pytest.mark.xfail(reason="eth_signTypedData has not been released in geth")
def test_invalid_eth_sign_typed_data(self, w3, keyfile_account_address_dual_type):
super().test_invalid_eth_sign_typed_data(w3, keyfile_account_address_dual_type)
@pytest.mark.xfail(reason="Inconsistently creating timeout issues.", strict=False)
def test_eth_estimate_gas(
self, w3: "Web3", keyfile_account_address_dual_type: ChecksumAddress
) -> None:
super().test_eth_estimate_gas(w3, keyfile_account_address_dual_type)
@pytest.mark.xfail(reason="Inconsistently creating timeout issues.", strict=False)
def test_eth_estimate_gas_with_block(
self, w3: "Web3", keyfile_account_address_dual_type: ChecksumAddress
) -> None:
super().test_eth_estimate_gas_with_block(w3, keyfile_account_address_dual_type)
@pytest.mark.xfail(reason="Inconsistently creating timeout issues.", strict=False)
def test_eth_get_transaction_receipt_unmined(
self, w3: "Web3", keyfile_account_address_dual_type: ChecksumAddress
) -> None:
super().test_eth_get_transaction_receipt_unmined(
w3, keyfile_account_address_dual_type
)
@pytest.mark.xfail(reason="Inconsistently creating timeout issues.", strict=False)
def test_eth_wait_for_transaction_receipt_unmined(
self, w3: "Web3", keyfile_account_address_dual_type: ChecksumAddress
) -> None:
super().test_eth_wait_for_transaction_receipt_unmined(
w3, keyfile_account_address_dual_type
)
def test_eth_get_raw_transaction_by_block(
self,
w3: "Web3",
keyfile_account_address_dual_type: ChecksumAddress,
block_with_txn: BlockData,
) -> None:
super().test_eth_get_raw_transaction_by_block(
w3, keyfile_account_address_dual_type, block_with_txn
)
| GoEthereumEthModuleTest |
python | celery__celery | t/unit/tasks/test_result.py | {
"start": 32044,
"end": 32670
} | class ____:
def setup_method(self):
self.ts = self.app.GroupResult(
uuid(), [self.app.AsyncResult(uuid()),
self.app.AsyncResult(uuid())])
def test_completed_count(self):
assert self.ts.completed_count() == 0
def test_ready(self):
assert not self.ts.ready()
def test_waiting(self):
assert self.ts.waiting()
def test_join(self):
with pytest.raises(TimeoutError):
self.ts.join(timeout=0.001)
def test_join_longer(self):
with pytest.raises(TimeoutError):
self.ts.join(timeout=1)
| test_pending_Group |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 17251,
"end": 21393
} | class ____(SimpleShuffle):
"""P2P worker-based shuffle implementation"""
@functools.cached_property
def _meta(self):
return self.frame._meta.drop(columns=self.partitioning_index)
def _layer(self):
from distributed.shuffle._core import (
P2PBarrierTask,
ShuffleId,
barrier_key,
p2p_barrier,
)
from distributed.shuffle._shuffle import DataFrameShuffleSpec, shuffle_unpack
dsk = {}
token = self._name.split("-")[-1]
shuffle_id = ShuffleId(token)
_barrier_key = barrier_key(shuffle_id)
name = f"shuffle-transfer-{token}"
parts_out = (
self._partitions if self._filtered else list(range(self.npartitions_out))
)
# Avoid embedding a materialized list unless necessary
parts_out_arg = (
tuple(self._partitions) if self._filtered else self.npartitions_out
)
transfer_keys = list()
for i in range(self.frame.npartitions):
t = Task(
(name, i),
_shuffle_transfer,
TaskRef((self.frame._name, i)),
token,
i,
)
dsk[t.key] = t
transfer_keys.append(t.ref())
barrier = P2PBarrierTask(
_barrier_key,
p2p_barrier,
token,
*transfer_keys,
spec=DataFrameShuffleSpec(
id=shuffle_id,
npartitions=self.npartitions_out,
column=self.partitioning_index,
meta=self.frame._meta,
parts_out=parts_out_arg,
disk=True,
drop_column=True,
),
)
dsk[barrier.key] = barrier
# TODO: Decompose p2p Into transfer/barrier + unpack
name = self._name
for i, part_out in enumerate(parts_out):
t = Task(
(name, i),
shuffle_unpack,
token,
part_out,
barrier.ref(),
)
dsk[t.key] = t
return dsk
#
# Helper logic
#
def _select_columns_or_index(df, columns_or_index):
"""
Make a column selection that may include the index
Parameters
----------
columns_or_index
Column or index name, or a list of these
"""
# Ensure columns_or_index is a list
columns_or_index = (
columns_or_index if isinstance(columns_or_index, list) else [columns_or_index]
)
column_names = [n for n in columns_or_index if _is_column_label_reference(df, n)]
selected_df = df[column_names]
if _contains_index_name(df, columns_or_index):
# Index name was included
selected_df = selected_df.assign(_index=df.index)
return selected_df
def _is_column_label_reference(df, key):
"""
Test whether a key is a column label reference
To be considered a column label reference, `key` must match the name of at
least one column.
"""
return (
not isinstance(key, Expr)
and (np.isscalar(key) or pd.api.types.is_scalar(key) or isinstance(key, tuple))
and key in df.columns
)
def _contains_index_name(df, columns_or_index):
"""
Test whether the input contains a reference to the index of the df
"""
if isinstance(columns_or_index, list):
return any(_is_index_level_reference(df, n) for n in columns_or_index)
else:
return _is_index_level_reference(df, columns_or_index)
def _is_index_level_reference(df, key):
"""
Test whether a key is an index level reference
To be considered an index level reference, `key` must match the index name
and must NOT match the name of any column.
"""
index_name = df.index._meta.name if isinstance(df, Expr) else df.index.name
return (
index_name is not None
and not isinstance(key, Expr)
and (np.isscalar(key) or pd.api.types.is_scalar(key) or isinstance(key, tuple))
and key == index_name
and key not in getattr(df, "columns", ())
)
| P2PShuffle |
python | scipy__scipy | scipy/stats/_distribution_infrastructure.py | {
"start": 182369,
"end": 184695
} | class ____(ContinuousDistribution):
def __init__(self, X, /, *args, **kwargs):
if not isinstance(X, ContinuousDistribution):
message = "Transformations are currently only supported for continuous RVs."
raise NotImplementedError(message)
self._copy_parameterization()
self._variable = X._variable
self._dist = X
if X._parameterization:
# Add standard distribution parameters to our parameterization
dist_parameters = X._parameterization.parameters
set_params = set(dist_parameters)
if not self._parameterizations:
self._parameterizations.append(_Parameterization())
for parameterization in self._parameterizations:
if set_params.intersection(parameterization.parameters):
message = (f"One or more of the parameters of {X} has "
"the same name as a parameter of "
f"{self.__class__.__name__}. Name collisions "
"create ambiguities and are not supported.")
raise ValueError(message)
parameterization.parameters.update(dist_parameters)
super().__init__(*args, **kwargs)
def _overrides(self, method_name):
return (self._dist._overrides(method_name)
or super()._overrides(method_name))
def reset_cache(self):
self._dist.reset_cache()
super().reset_cache()
def _update_parameters(self, *, validation_policy=None, **params):
# maybe broadcast everything before processing?
parameters = {}
# There may be some issues with _original_parameters
# We only want to update with _dist._original_parameters during
# initialization. Afterward that, we want to start with
# self._original_parameters.
parameters.update(self._dist._original_parameters)
parameters.update(params)
super()._update_parameters(validation_policy=validation_policy, **parameters)
def _process_parameters(self, **params):
return self._dist._process_parameters(**params)
def __repr__(self):
raise NotImplementedError()
def __str__(self):
raise NotImplementedError()
| TransformedDistribution |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 2575,
"end": 4441
} | class ____(serializers.Serializer):
integer = serializers.IntegerField(
validators=(
MaxValueValidator(limit_value=99),
MinValueValidator(limit_value=-11),
)
)
string = serializers.CharField(
validators=(
MaxLengthValidator(limit_value=10),
MinLengthValidator(limit_value=2),
)
)
regex = serializers.CharField(
validators=(
RegexValidator(regex=r'[ABC]12{3}'),
),
help_text='must have an A, B, or C followed by 1222'
)
lst = serializers.ListField(
validators=(
MaxLengthValidator(limit_value=10),
MinLengthValidator(limit_value=2),
)
)
decimal1 = serializers.DecimalField(max_digits=6, decimal_places=2, coerce_to_string=False)
decimal2 = serializers.DecimalField(max_digits=5, decimal_places=0, coerce_to_string=False,
validators=(DecimalValidator(max_digits=17, decimal_places=4),))
decimal3 = serializers.DecimalField(max_digits=8, decimal_places=2, coerce_to_string=True)
decimal4 = serializers.DecimalField(max_digits=8, decimal_places=2, coerce_to_string=True,
validators=(DecimalValidator(max_digits=17, decimal_places=4),))
decimal5 = serializers.DecimalField(max_digits=6, decimal_places=2)
email = serializers.EmailField(default='foo@bar.com')
url = serializers.URLField(default='http://www.example.com', allow_null=True)
uuid = serializers.UUIDField()
ip4 = serializers.IPAddressField(protocol='ipv4')
ip6 = serializers.IPAddressField(protocol='ipv6')
ip = serializers.IPAddressField()
duration = serializers.DurationField(
validators=(
MinValueValidator(timedelta(seconds=10)),
)
)
| ExampleValidatedSerializer |
python | tiangolo__fastapi | tests/test_additional_properties_bool.py | {
"start": 213,
"end": 378
} | class ____(BaseModel):
if PYDANTIC_V2:
model_config = ConfigDict(extra="forbid")
else:
class Config:
extra = "forbid"
| FooBaseModel |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/inset_locator.py | {
"start": 17874,
"end": 19906
} | class ____(TransformedBbox):
"""
Variant of `.TransformBbox` which calls *callback* before returning points.
Used by `.mark_inset` to unstale the parent axes' viewlim as needed.
"""
def __init__(self, *args, callback, **kwargs):
super().__init__(*args, **kwargs)
self._callback = callback
def get_points(self):
self._callback()
return super().get_points()
@_docstring.interpd
def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
"""
Draw a box to mark the location of an area represented by an inset axes.
This function draws a box in *parent_axes* at the bounding box of
*inset_axes*, and shows a connection with the inset axes by drawing lines
at the corners, giving a "zoomed in" effect.
Parameters
----------
parent_axes : `~matplotlib.axes.Axes`
Axes which contains the area of the inset axes.
inset_axes : `~matplotlib.axes.Axes`
The inset axes.
loc1, loc2 : {1, 2, 3, 4}
Corners to use for connecting the inset axes and the area in the
parent axes.
**kwargs
Patch properties for the lines and box drawn:
%(Patch:kwdoc)s
Returns
-------
pp : `~matplotlib.patches.Patch`
The patch drawn to represent the area of the inset axes.
p1, p2 : `~matplotlib.patches.Patch`
The patches connecting two corners of the inset axes and its area.
"""
rect = _TransformedBboxWithCallback(
inset_axes.viewLim, parent_axes.transData,
callback=parent_axes._unstale_viewLim)
kwargs.setdefault("fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))
pp = BboxPatch(rect, **kwargs)
parent_axes.add_patch(pp)
p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
inset_axes.add_patch(p1)
p1.set_clip_on(False)
p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
inset_axes.add_patch(p2)
p2.set_clip_on(False)
return pp, p1, p2
| _TransformedBboxWithCallback |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 50600,
"end": 54883
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.is_decoder = config.is_decoder
if config.is_decoder:
attention_layer = LongT5LayerSelfAttention
elif config.encoder_attention_type == "local":
attention_layer = LongT5LayerLocalSelfAttention
elif config.encoder_attention_type == "transient-global":
attention_layer = LongT5LayerTransientGlobalSelfAttention
else:
raise ValueError(
"For encoder attention mechanism, either `local` or `transient-global` attention type is expected, "
f"but got {config.encoder_attention_type}."
)
self.layer = nn.ModuleList()
self.layer.append(
attention_layer(config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx)
)
if self.is_decoder:
self.layer.append(LongT5LayerCrossAttention(config, layer_idx=layer_idx))
self.layer.append(LongT5LayerFF(config))
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
encoder_decoder_position_bias=None,
past_key_values=None,
use_cache=False,
output_attentions=False,
return_dict=True,
cache_position=None,
):
self_attention_outputs = self.layer[0](
hidden_states,
attention_mask=attention_mask,
position_bias=position_bias,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
cache_position=cache_position,
)
hidden_states = self_attention_outputs[0]
attention_outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights
# clamp inf values to enable fp16 inference - check https://github.com/huggingface/transformers/pull/19229/
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
if do_cross_attention:
cross_attention_outputs = self.layer[1](
hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
position_bias=encoder_decoder_position_bias,
past_key_values=past_key_values,
query_length=cache_position[-1] + 1,
use_cache=use_cache,
output_attentions=output_attentions,
cache_position=cache_position,
)
hidden_states = cross_attention_outputs[0]
# clamp inf values to enable fp16 inference - check https://github.com/huggingface/transformers/pull/19229/
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
# Keep cross-attention outputs and relative position weights
attention_outputs = attention_outputs + cross_attention_outputs[1:]
# Apply Feed Forward layer
hidden_states = self.layer[-1](hidden_states)
# clamp inf values to enable fp16 inference - check https://github.com/huggingface/transformers/pull/19229/
if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
return (
(hidden_states,) + attention_outputs
) # hidden-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
@auto_docstring
| LongT5Block |
python | huggingface__transformers | tests/models/pvt/test_modeling_pvt.py | {
"start": 1649,
"end": 4660
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=64,
num_channels=3,
num_encoder_blocks=4,
depths=[2, 2, 2, 2],
sr_ratios=[8, 4, 2, 1],
hidden_sizes=[16, 32, 64, 128],
downsampling_rates=[1, 4, 8, 16],
num_attention_heads=[1, 2, 4, 8],
is_training=True,
use_labels=True,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
num_labels=3,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.image_size = image_size
self.num_channels = num_channels
self.num_encoder_blocks = num_encoder_blocks
self.sr_ratios = sr_ratios
self.depths = depths
self.hidden_sizes = hidden_sizes
self.downsampling_rates = downsampling_rates
self.num_attention_heads = num_attention_heads
self.is_training = is_training
self.use_labels = use_labels
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.num_labels = num_labels
self.scope = scope
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
labels = None
if self.use_labels:
labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
config = self.get_config()
return config, pixel_values, labels
def get_config(self):
return PvtConfig(
image_size=self.image_size,
num_channels=self.num_channels,
num_encoder_blocks=self.num_encoder_blocks,
depths=self.depths,
hidden_sizes=self.hidden_sizes,
num_attention_heads=self.num_attention_heads,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
initializer_range=self.initializer_range,
)
def create_and_check_model(self, config, pixel_values, labels):
model = PvtModel(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
self.parent.assertIsNotNone(result.last_hidden_state)
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values, labels = config_and_inputs
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
# We will verify our results on an image of cute cats
def prepare_img():
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
return image
@require_torch
| PvtModelTester |
python | getsentry__sentry | src/sentry/db/models/fields/jsonfield.py | {
"start": 6295,
"end": 6368
} | class ____(ContainsLookupMixin, Contains):
pass
| JSONFieldContainsLookup |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 215328,
"end": 217614
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3]", L_v_: "f32[3, 3]"):
l_x_ = L_x_
l_v_ = L_v_
_jvp_increment_nesting = torch._C._functorch._jvp_increment_nesting(); _jvp_increment_nesting = None
_set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled = None
_enter_dual_level = torch._C._enter_dual_level(); _enter_dual_level = None
_maybe_load_decompositions = torch.autograd.forward_ad._maybe_load_decompositions(); _maybe_load_decompositions = None
aux: "f32[3, 3]" = torch._make_dual(l_x_, l_v_, level = 0); l_x_ = l_v_ = None
sin: "f32[3, 3]" = aux.sin()
result_duals: "f32[]" = sin.sum(); sin = None
aux_1: "f32[3, 3]" = torch._C._functorch._unwrap_for_grad(aux, 1); aux = None
_unpack_dual = torch._unpack_dual(result_duals, level = 0); result_duals = None
primal: "f32[]" = _unpack_dual[0]
dual: "f32[]" = _unpack_dual[1]; _unpack_dual = None
primals_out_unflatten: "f32[]" = torch._C._functorch._unwrap_for_grad(primal, 1); primal = None
tangents_out_unflatten: "f32[]" = torch._C._functorch._unwrap_for_grad(dual, 1); dual = None
_exit_dual_level = torch._C._exit_dual_level(0); _exit_dual_level = None
_set_fwd_grad_enabled_1 = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled_1 = None
_jvp_decrement_nesting = torch._C._functorch._jvp_decrement_nesting(); _jvp_decrement_nesting = None
return (primals_out_unflatten, tangents_out_unflatten, aux_1)
""",
)
def test_jvp_two_tensors_has_aux(self):
counters.clear()
def fn(x, y):
return (x.sin().sum() + y.cos()), x
def wrapper_fn(x, y, v):
return torch.func.jvp(fn, (x, y), (v, v), has_aux=True)
x = torch.randn(3, 3)
y = torch.randn(3, 3)
v = torch.randn(3, 3)
wrapped_gm = self._compile_check(wrapper_fn, (x, y, v))
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | streamlit__streamlit | lib/tests/streamlit/runtime/websocket_session_manager_test.py | {
"start": 1833,
"end": 12117
} | class ____(unittest.TestCase):
def setUp(self):
self.session_mgr = WebsocketSessionManager(
session_storage=MockSessionStorage(),
uploaded_file_manager=MagicMock(),
script_cache=MagicMock(),
message_enqueued_callback=MagicMock(),
)
def connect_session(self, existing_session_id=None, session_id_override=None):
return self.session_mgr.connect_session(
client=MagicMock(),
script_data=ScriptData("/fake/script_path.py", is_hello=False),
user_info={},
existing_session_id=existing_session_id,
session_id_override=session_id_override,
)
def test_connect_session(self):
session_id = self.connect_session()
session_info = self.session_mgr._active_session_info_by_id[session_id]
assert session_info.session.id == session_id
def test_connect_session_check(self):
with pytest.raises(
RuntimeError,
match=r"Only one of existing_session_id and session_id_override should be truthy. "
r"This should never happen.",
):
self.connect_session(
existing_session_id="existing_session_id",
session_id_override="session_id_override",
)
def test_connect_session_with_session_id_override(self):
self.connect_session(session_id_override="my_session_id")
session_info = self.session_mgr._active_session_info_by_id["my_session_id"]
assert session_info.session.id == "my_session_id"
def test_connect_session_on_invalid_session_id(self):
"""Test that connect_session gives us a new session if existing_session_id is invalid."""
session_id = self.connect_session(existing_session_id="not a valid session")
session_info = self.session_mgr._active_session_info_by_id[session_id]
assert session_info.session.id == session_id
assert session_info.session.id != "not a valid session"
@patch("streamlit.runtime.websocket_session_manager._LOGGER.warning")
def test_connect_session_connects_new_session_if_already_connected(
self, patched_warning
):
session_id = self.connect_session()
new_session_id = self.connect_session(existing_session_id=session_id)
assert session_id != new_session_id
patched_warning.assert_called_with(
"Session with id %s is already connected! Connecting to a new session.",
session_id,
)
def test_connect_session_explodes_if_ID_collission(self):
session_id = self.connect_session()
with (
pytest.raises(RuntimeError),
patch("streamlit.runtime.app_session.uuid.uuid4", return_value=session_id),
):
self.connect_session()
@patch(
"streamlit.runtime.app_session.AppSession.disconnect_file_watchers",
new=MagicMock(),
)
@patch(
"streamlit.runtime.app_session.AppSession.request_script_stop",
new=MagicMock(),
)
@patch(
"streamlit.runtime.app_session.AppSession.register_file_watchers",
new=MagicMock(),
)
def test_disconnect_and_reconnect_session(self):
session_id = self.connect_session()
original_session_info = self.session_mgr.get_session_info(session_id)
original_client = original_session_info.client
# File watchers are registered on AppSession creation.
original_session_info.session.register_file_watchers.assert_called_once()
self.session_mgr.disconnect_session(session_id)
assert session_id not in self.session_mgr._active_session_info_by_id
assert session_id in self.session_mgr._session_storage._cache
original_session_info.session.disconnect_file_watchers.assert_called_once()
original_session_info.session.request_script_stop.assert_called_once()
# Call disconnect_session again to verify that disconnect_session is idempotent.
self.session_mgr.disconnect_session(session_id)
assert session_id not in self.session_mgr._active_session_info_by_id
assert session_id in self.session_mgr._session_storage._cache
original_session_info.session.disconnect_file_watchers.assert_called_once()
original_session_info.session.request_script_stop.assert_called_once()
# Reconnect to the existing session.
reconnected_session_id = self.connect_session(existing_session_id=session_id)
reconnected_session_info = self.session_mgr.get_session_info(
reconnected_session_id
)
assert reconnected_session_id == session_id
assert reconnected_session_info.session == original_session_info.session
assert reconnected_session_info != original_session_info
assert reconnected_session_info.client != original_client
# File watchers are registered on AppSession creation and again on AppSession
# reconnect.
assert reconnected_session_info.session.register_file_watchers.call_count == 2
def test_disconnect_session_on_invalid_session_id(self):
# Just check that no error is thrown.
self.session_mgr.disconnect_session("nonexistent_session")
def test_get_active_session_info(self):
session_id = self.connect_session()
active_session_info = self.session_mgr.get_active_session_info(session_id)
assert active_session_info.session.id == session_id
def test_get_active_session_info_on_invalid_session_id(self):
assert self.session_mgr.get_active_session_info("nonexistent_session") is None
def test_get_active_session_info_on_disconnected_session(self):
session_id = self.connect_session()
self.session_mgr.disconnect_session(session_id)
assert self.session_mgr.get_active_session_info(session_id) is None
def test_is_active_session(self):
session_id = self.connect_session()
assert self.session_mgr.is_active_session(session_id)
def test_is_active_session_on_invalid_session_id(self):
assert not self.session_mgr.is_active_session("nonexistent_session")
def test_is_active_session_on_disconnected_session(self):
session_id = self.connect_session()
self.session_mgr.disconnect_session(session_id)
assert not self.session_mgr.is_active_session(session_id)
def test_list_active_sessions(self):
session_ids = []
for _ in range(3):
session_ids.append(self.connect_session())
assert [
s.session.id for s in self.session_mgr.list_active_sessions()
] == session_ids
@patch("streamlit.runtime.app_session.AppSession.shutdown", new=MagicMock())
def test_close_session_on_active_session(self):
session_id = self.connect_session()
session_info = self.session_mgr.get_session_info(session_id)
self.session_mgr.close_session(session_id)
assert session_id not in self.session_mgr._active_session_info_by_id
assert session_id not in self.session_mgr._session_storage._cache
session_info.session.shutdown.assert_called_once()
@patch("streamlit.runtime.app_session.AppSession.shutdown", new=MagicMock())
def test_close_session_on_inactive_session(self):
session_id = self.connect_session()
session_info = self.session_mgr.get_session_info(session_id)
self.session_mgr.disconnect_session(session_id)
# Sanity check.
assert not self.session_mgr.is_active_session(session_id)
self.session_mgr.close_session(session_id)
assert session_id not in self.session_mgr._active_session_info_by_id
assert session_id not in self.session_mgr._session_storage._cache
session_info.session.shutdown.assert_called_once()
def test_close_session_on_invalid_session_id(self):
self.session_mgr.close_session("nonexistent_session")
def test_clear_cache_on_last_session_disconnect(self):
"""Test that script cache is cleared on last session disconnect."""
session_id_1 = self.connect_session()
session_id_2 = self.connect_session()
self.session_mgr.disconnect_session(session_id_1)
self.session_mgr._script_cache.clear.assert_not_called()
self.session_mgr.disconnect_session(session_id_2)
self.session_mgr._script_cache.clear.assert_called_once()
@patch("streamlit.runtime.app_session.AppSession.shutdown", new=MagicMock())
def test_clear_cache_on_last_session_close(self):
"""Test that script cache is cleared on last session close."""
session_id_1 = self.connect_session()
session_id_2 = self.connect_session()
self.session_mgr.close_session(session_id_1)
self.session_mgr._script_cache.clear.assert_not_called()
self.session_mgr.close_session(session_id_2)
self.session_mgr._script_cache.clear.assert_called_once()
def test_get_session_info_on_active_session(self):
session_id = self.connect_session()
session_info = self.session_mgr.get_session_info(session_id)
assert session_info.session.id == session_id
def test_get_session_info_on_inactive_session(self):
session_id = self.connect_session()
self.session_mgr.disconnect_session(session_id)
# Sanity check.
assert not self.session_mgr.is_active_session(session_id)
session_info = self.session_mgr.get_session_info(session_id)
assert session_info.session.id == session_id
def test_get_session_info_on_invalid_session_id(self):
assert self.session_mgr.get_session_info("nonexistent_session") is None
def test_list_sessions(self):
session_ids = []
for _ in range(3):
session_ids.append(self.connect_session())
self.session_mgr.disconnect_session(session_ids[1])
# Sanity check.
assert self.session_mgr.is_active_session(session_ids[0])
assert not self.session_mgr.is_active_session(session_ids[1])
assert self.session_mgr.is_active_session(session_ids[2])
assert {s.session.id for s in self.session_mgr.list_sessions()} == set(
session_ids
)
| WebsocketSessionManagerTests |
python | automl__auto-sklearn | test/test_util/test_common.py | {
"start": 102,
"end": 488
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def test_check_pid(self):
our_pid = os.getpid()
exists = check_pid(our_pid)
self.assertTrue(exists)
our_pid = -11000 # We hope this pid does not exist
exists = check_pid(our_pid)
self.assertFalse(exists)
if __name__ == "__main__":
unittest.main()
| TestUtilsCommon |
python | python-visualization__folium | folium/plugins/float_image.py | {
"start": 80,
"end": 1688
} | class ____(MacroElement):
"""Adds a floating image in HTML canvas on top of the map.
Parameters
----------
image: str
Url to image location. Can also be an inline image using a data URI
or a local file using `file://`.
bottom: int, default 75
Vertical position from the bottom, as a percentage of screen height.
left: int, default 75
Horizontal position from the left, as a percentage of screen width.
**kwargs
Additional keyword arguments are applied as CSS properties.
For example: `width='300px'`.
"""
_template = Template(
"""
{% macro header(this,kwargs) %}
<style>
#{{this.get_name()}} {
position: absolute;
bottom: {{this.bottom}}%;
left: {{this.left}}%;
{%- for property, value in this.css.items() %}
{{ property }}: {{ value }};
{%- endfor %}
}
</style>
{% endmacro %}
{% macro html(this,kwargs) %}
<img id="{{this.get_name()}}" alt="float_image"
src="{{ this.image }}"
style="z-index: 999999">
</img>
{% endmacro %}
"""
)
def __init__(self, image, bottom=75, left=75, **kwargs):
super().__init__()
self._name = "FloatImage"
self.image = image
self.bottom = bottom
self.left = left
self.css = kwargs
| FloatImage |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-firebase-realtimedb/llama_index/readers/firebase_realtimedb/base.py | {
"start": 183,
"end": 2697
} | class ____(BaseReader):
"""
Firebase Realtime Database reader.
Retrieves data from Firebase Realtime Database and converts it into the Document used by LlamaIndex.
Args:
database_url (str): Firebase Realtime Database URL.
service_account_key_path (Optional[str]): Path to the service account key file.
"""
def __init__(
self,
database_url: str,
service_account_key_path: Optional[str] = None,
) -> None:
"""Initialize with parameters."""
try:
import firebase_admin
from firebase_admin import credentials
except ImportError:
raise ImportError(
"`firebase_admin` package not found, please run `pip install"
" firebase-admin`"
)
if not firebase_admin._apps:
if service_account_key_path:
cred = credentials.Certificate(service_account_key_path)
firebase_admin.initialize_app(
cred, options={"databaseURL": database_url}
)
else:
firebase_admin.initialize_app(options={"databaseURL": database_url})
def load_data(self, path: str, field: Optional[str] = None) -> List[Document]:
"""
Load data from Firebase Realtime Database and convert it into documents.
Args:
path (str): Path to the data in the Firebase Realtime Database.
field (str, Optional): Key to pick data from
Returns:
List[Document]: A list of documents.
"""
try:
from firebase_admin import db
except ImportError:
raise ImportError(
"`firebase_admin` package not found, please run `pip install"
" firebase-admin`"
)
ref = db.reference(path)
data = ref.get()
documents = []
if isinstance(data, Dict):
for key in data:
entry = data[key]
extra_info = {
"document_id": key,
}
if type(entry) is Dict and field in entry:
text = entry[field]
else:
text = str(entry)
document = Document(text=text, extra_info=extra_info)
documents.append(document)
elif isinstance(data, str):
documents.append(Document(text=data))
return documents
| FirebaseRealtimeDatabaseReader |
python | huggingface__transformers | src/transformers/models/llava_onevision/video_processing_llava_onevision.py | {
"start": 816,
"end": 1358
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
size = {"height": 384, "width": 384}
rescale_factor = 1 / 255
default_to_square = False
crop_size = None
do_resize = True
do_center_crop = None
do_rescale = True
do_normalize = True
do_convert_rgb = True
do_sample_frames = False # Set to False for BC, recommended to set `True` in new models
__all__ = ["LlavaOnevisionVideoProcessor"]
| LlavaOnevisionVideoProcessor |
python | sqlalchemy__sqlalchemy | test/orm/test_recursive_loaders.py | {
"start": 705,
"end": 1356
} | class ____(_fixtures.FixtureTest):
@classmethod
def setup_mappers(cls):
cls._setup_stock_mapping()
@testing.combinations(selectinload, immediateload, argnames="loader")
def test_no_recursion_depth_non_self_referential(self, loader):
User = self.classes.User
sess = fixture_session()
stmt = select(User).options(
selectinload(User.addresses, recursion_depth=-1)
)
with expect_raises_message(
sa.exc.InvalidRequestError,
"recursion_depth option on relationship User.addresses not valid",
):
sess.execute(stmt).all()
| NonRecursiveTest |
python | walkccc__LeetCode | solutions/830. Positions of Large Groups/830.py | {
"start": 0,
"end": 273
} | class ____:
def largeGroupPositions(self, s: str) -> list[list[int]]:
n = len(s)
ans = []
i = 0
j = 0
while i < n:
while j < n and s[j] == s[i]:
j += 1
if j - i >= 3:
ans.append([i, j - 1])
i = j
return ans
| Solution |
python | wandb__wandb | tests/unit_tests/test_launch/test_inputs/test_internal.py | {
"start": 3208,
"end": 3290
} | class ____(str, Enum):
cifar10 = "cifar10"
cifar100 = "cifar100"
| DatasetEnum |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_method.py | {
"start": 1514,
"end": 1646
} | class ____(Structure):
def __contains__(self, _):
pass
# +1: [abstract-method, abstract-method, abstract-method]
| Container |
python | django__django | tests/fixtures/models.py | {
"start": 4236,
"end": 4480
} | class ____(models.Model):
key = models.CharField(max_length=3, unique=True)
obj = models.ForeignKey("CircularA", models.SET_NULL, null=True)
objects = NaturalKeyManager()
def natural_key(self):
return (self.key,)
| CircularB |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/literalString2.py | {
"start": 261,
"end": 372
} | class ____(Generic[L]):
def __init__(self, value: L) -> None:
self.value = value
foo = Foo("hmm")
| Foo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.