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 | pyinstaller__pyinstaller | bootloader/waflib/Tools/qt5.py | {
"start": 6706,
"end": 7624
} | class ____(Task.Task):
color = 'BLUE'
run_str = '${QT_RCC} -name ${tsk.rcname()} ${SRC[0].abspath()} ${RCC_ST} -o ${TGT}'
ext_out = ['.h']
def rcname(self):
return os.path.splitext(self.inputs[0].name)[0]
def scan(self):
if not has_xml:
Logs.error('No xml.sax support was found, rcc dependencies will be incomplete!')
return ([], [])
parser = make_parser()
curHandler = XMLHandler()
parser.setContentHandler(curHandler)
with open(self.inputs[0].abspath(), 'r') as f:
parser.parse(f)
nodes = []
names = []
root = self.inputs[0].parent
for x in curHandler.files:
nd = root.find_resource(x)
if nd:
nodes.append(nd)
else:
names.append(x)
return (nodes, names)
def quote_flag(self, x):
return x
| rcc |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 8008,
"end": 8207
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DISABLED", "ENABLED")
| EnterpriseMembersCanMakePurchasesSettingValue |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 41057,
"end": 46514
} | class ____(Model):
"""
Perform an affine transformation in 2 dimensions.
Parameters
----------
matrix : array
A 2x2 matrix specifying the linear transformation to apply to the
inputs
translation : array
A 2D vector (given as either a 2x1 or 1x2 array) specifying a
translation to apply to the inputs
"""
n_inputs = 2
n_outputs = 2
standard_broadcasting = False
_separable = False
matrix = Parameter(default=[[1.0, 0.0], [0.0, 1.0]])
translation = Parameter(default=[0.0, 0.0])
def _matrix_validator(self, value):
"""Validates that the input matrix is a 2x2 2D array."""
if np.shape(value) != (2, 2):
raise InputParameterError(
"Expected transformation matrix to be a 2x2 array"
)
matrix._validator = _matrix_validator
def _translation_validator(self, value):
"""
Validates that the translation vector is a 2D vector. This allows
either a "row" vector or a "column" vector where in the latter case the
resultant Numpy array has ``ndim=2`` but the shape is ``(1, 2)``.
"""
if not (
(np.ndim(value) == 1 and np.shape(value) == (2,))
or (np.ndim(value) == 2 and np.shape(value) == (1, 2))
):
raise InputParameterError(
"Expected translation vector to be a 2 element row or column "
"vector array"
)
translation._validator = _translation_validator
def __init__(self, matrix=matrix, translation=translation, **kwargs):
super().__init__(matrix=matrix, translation=translation, **kwargs)
self.inputs = ("x", "y")
self.outputs = ("x", "y")
@property
def inverse(self):
"""
Inverse transformation.
Raises `~astropy.modeling.InputParameterError` if the transformation cannot be inverted.
"""
det = np.linalg.det(self.matrix.value)
if det == 0:
raise InputParameterError(
f"Transformation matrix is singular; {self.__class__.__name__} model"
" does not have an inverse"
)
matrix = np.linalg.inv(self.matrix.value)
if self.matrix.unit is not None:
matrix = matrix * self.matrix.unit
# If matrix has unit then translation has unit, so no need to assign it.
translation = -np.dot(matrix, self.translation.value)
return self.__class__(matrix=matrix, translation=translation)
@classmethod
def evaluate(cls, x, y, matrix, translation):
"""
Apply the transformation to a set of 2D Cartesian coordinates given as
two lists--one for the x coordinates and one for a y coordinates--or a
single coordinate pair.
Parameters
----------
x, y : array, float
x and y coordinates
"""
if x.shape != y.shape:
raise ValueError("Expected input arrays to have the same shape")
shape = x.shape or (1,)
# Use asarray to ensure loose the units.
inarr = np.vstack(
[np.asarray(x).ravel(), np.asarray(y).ravel(), np.ones(x.size, x.dtype)]
)
if inarr.shape[0] != 3 or inarr.ndim != 2:
raise ValueError("Incompatible input shapes")
augmented_matrix = cls._create_augmented_matrix(matrix, translation)
result = np.dot(augmented_matrix, inarr)
x, y = result[0], result[1]
x.shape = y.shape = shape
return x, y
@staticmethod
def _create_augmented_matrix(matrix, translation):
unit = None
if any([hasattr(translation, "unit"), hasattr(matrix, "unit")]):
if not all([hasattr(translation, "unit"), hasattr(matrix, "unit")]):
raise ValueError(
"To use AffineTransformation with quantities, "
"both matrix and unit need to be quantities."
)
unit = translation.unit
# matrix should have the same units as translation
if not (matrix.unit / translation.unit) == u.dimensionless_unscaled:
raise ValueError("matrix and translation must have the same units.")
augmented_matrix = np.empty((3, 3), dtype=float)
augmented_matrix[0:2, 0:2] = matrix
augmented_matrix[0:2, 2:].flat = translation
augmented_matrix[2] = [0, 0, 1]
if unit is not None:
return augmented_matrix * unit
return augmented_matrix
@property
def input_units(self):
translation_unit = self.translation.input_unit
matrix_unit = self.matrix.input_unit
if translation_unit is None and matrix_unit is None:
return None
elif translation_unit is not None:
return dict(zip(self.inputs, [translation_unit] * 2))
else:
return dict(zip(self.inputs, [matrix_unit] * 2))
for long_name, short_name in _PROJ_NAME_CODE:
# define short-name projection equivalent classes:
globals()["Pix2Sky_" + short_name] = globals()["Pix2Sky_" + long_name]
globals()["Sky2Pix_" + short_name] = globals()["Sky2Pix_" + long_name]
# set inverse classes:
globals()["Pix2Sky_" + long_name]._inv_cls = globals()["Sky2Pix_" + long_name]
globals()["Sky2Pix_" + long_name]._inv_cls = globals()["Pix2Sky_" + long_name]
| AffineTransformation2D |
python | getsentry__sentry | src/sentry/relay/config/ai_model_costs.py | {
"start": 570,
"end": 1295
} | class ____(TypedDict):
version: Required[int]
models: Required[dict[ModelId, AIModelCostV2]]
def ai_model_costs_config() -> AIModelCosts | None:
"""
Get AI model costs configuration.
AI model costs are set in cache by a cron job,
if there are no costs, it should be investigated why.
Returns:
AIModelCosts object containing cost information for AI models
"""
if settings.SENTRY_AIR_GAP:
return None
cached_costs = cache.get(AI_MODEL_COSTS_CACHE_KEY)
if cached_costs is not None:
return cached_costs
if not settings.IS_DEV:
# in dev environment, we don't want to log this
logger.warning("Empty model costs")
return None
| AIModelCosts |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 8027,
"end": 44094
} | class ____(_RingRotater):
"""
Allgather the kv and return only the required kv.
Only one communication will be done.
"""
def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None:
self._pg = pg
self._seq_dim = seq_dim
self._aggregated_buffer: torch.Tensor | None = None
self._idx = 0
def exchange_buffers(self, curr_buffer: torch.Tensor) -> None:
# We only need to perform allgather once.
self._idx += 1
if self._aggregated_buffer is None:
self._aggregated_buffer = ft_c.all_gather_tensor(
curr_buffer.contiguous(), gather_dim=0, group=self._pg
)
def next_buffer(self) -> torch.Tensor:
rank = dist.get_rank(self._pg)
idx = rank - self._idx
assert self._aggregated_buffer is not None
self._aggregated_buffer = _maybe_wait(self._aggregated_buffer)
return self._aggregated_buffer.chunk(dist.get_world_size(self._pg))[idx]
def _create_rotater(
pg: dist.ProcessGroup, seq_dim: int, method: _RotateMethod | None = None
) -> _RingRotater:
if method is None:
method = _cp_options.rotate_method
if method == _RotateMethod.ALL_TO_ALL:
return _AllToAllRotater(pg, seq_dim)
elif method == _RotateMethod.ALL_GATHER:
return _AllGatherRotater(pg, seq_dim)
else:
raise NotImplementedError(f"Unknown method {method}")
def _templated_ring_attention(
group: dist.ProcessGroup,
seq_dim: int,
op: _AttentionOp,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
is_causal: bool = False,
**kwargs: object,
) -> tuple[torch.Tensor, ...]:
"""
A generalized ring attention implementation that can support multiple attention ops.
Note [Context parallelism load balance algorithm for causal masking]
=====================
This explanation uses an example to illustrate the CP algorithm with causal
masking.
Consider a scenario where the sequence length of q, k, and v is 4 (e.g.,
q = (q0, q1, q2, q3)), and there are two ranks. For simplicity, we will discuss
only q and k, as v follows the same pattern as k.
The diagram below represents a complete QK^T operation without parallelism.
The `****` entries indicate that the result is not required due to causal
masking (e.g., q0k1 is marked as `****`).
+----+------------------------+
| | k0 k1 k2 k3 |
+----+------------------------+
| q0 | q0k0, ****, ****, **** |
| q1 | q1k0, q1k1, ****, **** |
| q2 | q2k0, q2k1, q2k2, **** |
| q3 | q3k0, q3k1, q3k2, q3k3 |
+----+------------------------+
### No Load Balance:
In this scenario, each rank owns a local chunk of q, k, and v, with each chunk
containing two elements. Rank0 is responsible for managing (q0, q1) and (k0, k1),
while rank1 manages (q2, q3) and (k2, k3).
First Iteration: Both rank0 and rank1 perform SDPA with their local qkv pairs.
Causal masking is enabled as some results are not required (e.g., q0k1).
Second Iteration: Local queries remain the same, but local kv pairs are exchanged.
Rank0 now has (q0, q1) and (k2, k3); rank1 has (q2, q3) and (k0, k1). Rank0 performs
no computation, while rank1 computes locally without causal masking since all results
(q2k0, q2k1, q3k0, q3k1) are needed.
### Round-robin Load Balance:
In this setup, each rank owns two local chunks of q, k, and v, with each chunk
containing one element. Rank0 manages (q0, q3) and (k0, k3); Rank1 manages (q1, q2)
and (k1, k2). Although the local chunks are not consecutive, they are concatenated to
enable SDPA to be performed in a single call for each step. Consequently, the chunk()
function may be required to prepare the correct q, k, and v configurations.
First Iteration: Both ranks perform SDPA with their local qkv pairs, similar to the
no-load-balance case. This iteration corresponds to the `if` of the
(`if, `elif`, `else`) in the implementation.
Second Iteration: Rank0 now has (q0, q3) and (k1, k2); rank1 has (q1, q2) and
(k0, k3). For rank0, no computation is needed for q0. However, computations for
q3k1 and q3k2 are required, so only q3 is used for SDPA. This corresponds to the
`else` of the (`if`, `elif`, `else`) in the implementation.
For rank1, k3 is not needed for q1 and q2, so only k0 is used for SDPA. This
corresponds to the `elif` of (`if`, `elif`, `else`) in the implementation.
Parameters
----------
op:
The attention op to use
*args:
additional args are passed to the op
**kwargs:
additional kwargs are passed to the op
Returns
-------
out:
The merged attention output
softmax_lse:
The logsumexp of the merged attention output
"""
if is_causal and (query.size(2) != key.size(2)):
raise NotImplementedError(
"is_causal requires the same query and context sequence lengths"
)
if not is_causal and _cp_options.enable_load_balance:
raise RuntimeError("Load balancing requires `is_causal=True`.")
assert isinstance(group, dist.ProcessGroup), (
"process group must be single dimension"
)
rank = dist.get_rank(group)
size = dist.get_world_size(group)
next_kv = None
# Without making key and value contiguous(), the loss curve is bad.
# TODO(fegin): figure out why this is a requirement since SDPA does not have
# this requirement.
key = key.contiguous()
value = value.contiguous()
sdpa_merger = _SDPAMerger(_cp_options.convert_to_f32, seq_dim=seq_dim)
rest: list[Any]
out: torch.Tensor
logsumexp: torch.Tensor
rotater = _create_rotater(group, 2)
for i in range(size):
if i > 0:
# Wait for the kv from the (cp_rank - 1) rank.
next_kv = rotater.next_buffer()
key = next_kv[: key.numel()].reshape(key.shape)
value = next_kv[key.numel() :].reshape(value.shape)
if i < (size - 1):
# Send the k, v to the next rank
next_kv = torch.cat([key.flatten(), value.flatten()])
next_kv = rotater.exchange_buffers(next_kv)
is_causal_behavior = _is_causal_behavior(
rank=rank, world_size=size, i=i, is_causal=is_causal
)
# For a detailed understanding of the load balancing algorithm, see
# Note [Context parallelism load balance algorithm for causal masking]
if is_causal_behavior == _CausalBehavior.SKIP:
# If i > rank and load balancing is not turned on.
continue
if i == 0 or (not _cp_options.enable_load_balance or not is_causal):
# When local balance is enabled, we still need to do SDPA with
# the both local chunks of q, k, v for the first iteration.
q, k, v, partial = (query, key, value, False)
elif i <= rank:
# Round-robin load balancing case, and i <= rank.
# We need to do SDPA with only the first local chunk of k, v.
# Note that q, k, v each contains two local chunks.
ROUND_ROBIN_CYCLE = 2
q, k, v, partial = (
query,
key.chunk(ROUND_ROBIN_CYCLE, dim=2)[0],
value.chunk(ROUND_ROBIN_CYCLE, dim=2)[0],
False,
)
else:
# Round-robin load balancing case, and i > rank.
# We need to do SDPA with only the second half of q, and update
# only the second part of logsumexp. So partial is True.
# Note that q, k, v each contains two chunks.
q, k, v, partial = query.chunk(2, dim=2)[1], key, value, True
# See https://github.com/pytorch/pytorch/blob/release/2.4/aten/src/ATen/native/native_functions.yaml#L14695
# for the SDPA kernel definitions.
out, logsumexp, *rest = op(
q,
k,
v,
is_causal=is_causal_behavior.value,
**kwargs,
)
sdpa_merger.step(out, logsumexp, partial)
# pyrefly: ignore [unbound-name]
return *sdpa_merger.results(), *rest
def _templated_ring_attention_backward(
group: dist.ProcessGroup,
seq_dim: int,
op: _AttentionOp,
grad_out: torch.Tensor,
grad_out_name: str,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
is_causal: bool,
**kwargs: Any,
) -> tuple[torch.Tensor, ...]:
"""This API implements the backward pass of the ring attention."""
if not is_causal and _cp_options.enable_load_balance:
raise RuntimeError("Load balancing requires `is_causal=True`.")
rank = dist.get_rank(group)
size = dist.get_world_size(group)
next_kv = None
next_grad_kv = None
rest: list[Any]
grad_query_, grad_key_, grad_value_ = None, None, None
accum_dtype = torch.float32 if _cp_options.convert_to_f32 else query.dtype
grad_query = torch.zeros_like(query, dtype=accum_dtype)
grad_key = torch.zeros_like(key, dtype=accum_dtype)
grad_value = torch.zeros_like(value, dtype=accum_dtype)
key = key.contiguous()
value = value.contiguous()
kv_rotater = _create_rotater(group, 2)
dkv_rotater = _create_rotater(group, 2, method=_RotateMethod.ALL_TO_ALL)
for i in range(size):
if i > 0:
# Wait for the kv from the (cp_rank - 1) rank.
buffer = kv_rotater.next_buffer()
pointer = 0
key = buffer[pointer : pointer + key.numel()].reshape(key.shape)
pointer += key.numel()
value = buffer[pointer : pointer + value.numel()].reshape(value.shape)
pointer += value.numel()
if i != size - 1:
# Send the kv to the next rank.
next_kv = torch.cat([key.flatten(), value.flatten()])
kv_rotater.exchange_buffers(next_kv)
is_causal_behavior = _is_causal_behavior(
rank=rank, world_size=size, i=i, is_causal=is_causal
)
if is_causal_behavior != _CausalBehavior.SKIP:
if i == 0 or (not _cp_options.enable_load_balance or not is_causal):
# We need to do SDPA with the full local q, k, v.
q, k, v, out_, dout, lse = (query, key, value, out, grad_out, logsumexp)
elif i <= rank:
# Round-robin load balancing case, and i <= rank.
# We need to do SDPA with only the first half of k, v.
# Note that q, k, v each contains two chunks.
q, k, v, out_, dout, lse = (
query,
key.chunk(2, dim=seq_dim)[0],
value.chunk(2, dim=seq_dim)[0],
out,
grad_out,
logsumexp,
)
else:
# Round-robin load balancing case, and i > rank.
# We need to do SDPA with only the second half of q.
# Note that q, k, v each contains two chunks.
q, k, v, out_, dout, lse = (
query.chunk(2, dim=seq_dim)[1],
key,
value,
out.chunk(2, dim=seq_dim)[1],
grad_out.chunk(2, dim=seq_dim)[1],
# Need to make logsumexp contiguous, otherwise there will
# be numerical error.
logsumexp.chunk(2, dim=seq_dim)[1].contiguous(),
)
kwargs[grad_out_name] = dout
# See https://github.com/pytorch/pytorch/blob/release/2.4/aten/src/ATen/native/native_functions.yaml#L14695
# for the SDPA kernel definitions.
grad_query_, grad_key_, grad_value_, *rest = op(
query=q,
key=k,
value=v,
out=out_,
logsumexp=lse,
is_causal=is_causal_behavior.value,
**kwargs,
)
else:
grad_query_ = torch.zeros_like(query, dtype=accum_dtype)
grad_key_ = torch.zeros_like(key, dtype=accum_dtype)
grad_value_ = torch.zeros_like(value, dtype=accum_dtype)
ROUND_ROBIN_CYCLE = 2
if i == 0:
grad_key += grad_key_
grad_value += grad_value_
else:
pointer = 0
# Wait for the kv gradient from (cp_rank - 1) rank.
next_grad_kv = dkv_rotater.next_buffer()
grad_key = next_grad_kv[pointer : pointer + grad_key.numel()].reshape(
grad_key.shape
)
pointer += grad_key.numel()
grad_value = next_grad_kv[pointer : pointer + grad_value.numel()].reshape(
grad_value.shape
)
if i <= rank and _cp_options.enable_load_balance:
grad_key = _partial_update(
grad_key,
grad_key_,
dim=seq_dim,
n_chunks=ROUND_ROBIN_CYCLE,
idx=0,
add=True,
)
grad_value = _partial_update(
grad_value,
grad_value_,
dim=seq_dim,
n_chunks=ROUND_ROBIN_CYCLE,
idx=0,
add=True,
)
else:
grad_key += grad_key_
grad_value += grad_value_
next_grad_kv = torch.cat([grad_key.flatten(), grad_value.flatten()])
# Send the grad key and grad value to the next rank.
dkv_rotater.exchange_buffers(next_grad_kv)
if i <= rank or not _cp_options.enable_load_balance:
grad_query += grad_query_
else:
grad_query = _partial_update(
grad_query,
grad_query_,
dim=seq_dim,
n_chunks=ROUND_ROBIN_CYCLE,
idx=1,
add=True,
)
assert grad_key_ is not None
assert grad_value_ is not None
grad_query = grad_query.to(query.dtype)
next_grad_kv = dkv_rotater.next_buffer().to(key.dtype)
grad_key = next_grad_kv[: grad_key.numel()].reshape(grad_key.shape)
grad_value = next_grad_kv[grad_key.numel() :].reshape(grad_value.shape)
return (
grad_query,
grad_key,
grad_value,
# pyrefly: ignore [unbound-name]
*rest,
)
def _scaled_dot_product_ring_flash_attention(
mesh: DeviceMesh,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
dropout_p: float = 0.0,
is_causal: bool = False,
return_debug_mask: bool = False,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
if return_debug_mask:
raise NotImplementedError("return_debug_mask is not supported yet")
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention(
group,
seq_dim,
aten._scaled_dot_product_flash_attention,
query=query,
key=key,
value=value,
is_causal=is_causal,
dropout_p=dropout_p,
scale=scale,
)
def _scaled_dot_product_ring_efficient_attention(
mesh: DeviceMesh,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: torch.Tensor | None = None,
compute_log_sumexp: bool = True,
dropout_p: float = 0.0,
is_causal: bool = False,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
if attn_bias is not None:
raise NotImplementedError("attn_bias is not supported yet")
if not compute_log_sumexp:
# CP requires compute_log_sumexp to be True because it always merges LSE
compute_log_sumexp = True
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention(
group,
seq_dim,
aten._scaled_dot_product_efficient_attention,
query=query,
key=key,
value=value,
is_causal=is_causal,
attn_bias=attn_bias,
dropout_p=dropout_p,
scale=scale,
compute_log_sumexp=compute_log_sumexp,
)
def _scaled_dot_product_ring_cudnn_attention(
mesh: DeviceMesh,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: torch.Tensor | None = None,
compute_log_sumexp: bool = True,
dropout_p: float = 0.0,
is_causal: bool = False,
return_debug_mask: bool = False,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
if attn_bias is not None:
raise NotImplementedError("attn_bias is not supported yet")
if not compute_log_sumexp:
# CP requires compute_log_sumexp to be True because it always merges LSE
compute_log_sumexp = True
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention(
group,
seq_dim,
aten._scaled_dot_product_cudnn_attention,
query=query,
key=key,
value=value,
attn_bias=attn_bias,
compute_log_sumexp=compute_log_sumexp,
dropout_p=dropout_p,
is_causal=is_causal,
return_debug_mask=return_debug_mask,
scale=scale,
)
def _scaled_dot_product_ring_flash_attention_backward(
mesh: DeviceMesh,
grad_out: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
cum_seq_q: torch.Tensor,
cum_seq_k: torch.Tensor,
max_q: int,
max_k: int,
dropout_p: float,
is_causal: bool,
philox_seed: torch.Tensor,
philox_offset: torch.Tensor,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention_backward(
group,
seq_dim,
aten._scaled_dot_product_flash_attention_backward.default,
grad_out=grad_out,
grad_out_name="grad_out",
query=query,
key=key,
value=value,
out=out,
logsumexp=logsumexp,
is_causal=is_causal,
cum_seq_q=cum_seq_q,
cum_seq_k=cum_seq_k,
max_q=max_q,
max_k=max_k,
dropout_p=dropout_p,
philox_seed=philox_seed,
philox_offset=philox_offset,
scale=scale,
)
def _scaled_dot_product_ring_efficient_attention_backward(
mesh: DeviceMesh,
grad_out: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
bias: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
philox_seed: torch.Tensor,
philox_offset: torch.Tensor,
dropout_p: float,
grad_input_mask: tuple[bool, ...],
is_causal: bool = False,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention_backward(
group,
seq_dim,
aten._scaled_dot_product_efficient_attention_backward.default,
grad_out=grad_out,
grad_out_name="grad_out_",
query=query,
key=key,
value=value,
attn_bias=bias,
out=out,
logsumexp=logsumexp,
philox_seed=philox_seed,
philox_offset=philox_offset,
dropout_p=dropout_p,
grad_input_mask=grad_input_mask,
is_causal=is_causal,
scale=scale,
)
def _scaled_dot_product_ring_cudnn_attention_backward(
mesh: DeviceMesh,
grad_out: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
philox_seed: torch.Tensor,
philox_offset: torch.Tensor,
attn_bias: torch.Tensor,
cum_seq_q: torch.Tensor,
cum_seq_k: torch.Tensor,
max_q: int,
max_k: int,
dropout_p: float,
is_causal: bool,
*,
scale: float | None = None,
) -> tuple[torch.Tensor, ...]:
# TODO: remove this hardcoding
seq_dim = 2
group = mesh.get_group()
return _templated_ring_attention_backward(
group,
seq_dim,
aten._scaled_dot_product_cudnn_attention_backward.default,
grad_out=grad_out,
grad_out_name="grad_out",
query=query,
key=key,
value=value,
out=out,
logsumexp=logsumexp,
philox_seed=philox_seed,
philox_offset=philox_offset,
attn_bias=attn_bias,
cum_seq_q=cum_seq_q,
cum_seq_k=cum_seq_k,
max_q=max_q,
max_k=max_k,
dropout_p=dropout_p,
is_causal=is_causal,
scale=scale,
)
def _sdpa_handler(
op_call: torch._ops.OpOverload,
args: tuple[object, ...],
kwargs: dict[str, object],
) -> object:
# extract local tensor and sharding infos to a OpInfo
op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
logger.debug("Dispatching op_call: %s", op_info.schema)
# sharding propagation
# TODO: remove the context parallel strategy from the default propagation
# rule. Either figure out how to dynamically enable it or just don't call
# propagate.
DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
output_sharding = op_info.output_sharding
assert output_sharding is not None, "output sharding should not be None"
assert not output_sharding.needs_redistribute, "inputs need to be redistributed"
call_maps: dict[torch._ops.OpOverload, Callable] = {
aten._scaled_dot_product_flash_attention.default: _scaled_dot_product_ring_flash_attention,
aten._scaled_dot_product_efficient_attention.default: _scaled_dot_product_ring_efficient_attention,
aten._scaled_dot_product_cudnn_attention.default: _scaled_dot_product_ring_cudnn_attention,
aten._scaled_dot_product_flash_attention_backward.default: _scaled_dot_product_ring_flash_attention_backward,
aten._scaled_dot_product_efficient_attention_backward.default: _scaled_dot_product_ring_efficient_attention_backward,
aten._scaled_dot_product_cudnn_attention_backward.default: _scaled_dot_product_ring_cudnn_attention_backward,
}
if op_call in call_maps:
local_results = call_maps[op_call](
op_info.compute_mesh,
*op_info.local_args, # type: ignore[arg-type]
**op_info.local_kwargs, # type: ignore[arg-type]
)
else:
raise NotImplementedError(
"CP only supports flash attention and memory efficient attention now."
)
return DTensor._op_dispatcher.wrap(local_results, output_sharding.output_spec)
custom_ops = {
aten._scaled_dot_product_flash_attention.default: _sdpa_handler,
aten._scaled_dot_product_flash_attention_backward.default: _sdpa_handler,
aten._scaled_dot_product_efficient_attention.default: _sdpa_handler,
aten._scaled_dot_product_efficient_attention_backward.default: _sdpa_handler,
aten._scaled_dot_product_cudnn_attention.default: _sdpa_handler,
aten._scaled_dot_product_cudnn_attention_backward.default: _sdpa_handler,
}
exitsing_custom_ops = DTensor._op_dispatcher._custom_op_handlers
ArgsType = tuple[Any, ...]
KwargsType = dict[str, Any]
InputFnType = Callable[[nn.Module | None, ArgsType, KwargsType, DeviceMesh], Any]
OutputFnType = Callable[[nn.Module | None, Any, Any, DeviceMesh], Any]
_replaced_functions: dict[Callable, tuple[str, Callable]] = {}
def _distribute_function(
fn: Callable,
fn_module: types.ModuleType,
device_mesh: DeviceMesh,
input_fn: InputFnType,
output_fn: OutputFnType,
) -> None:
"""
A helper function to replace a function with a distributed version by
using the monkey patching approach.
This function is for the CP internal usage only.
"""
def wrapper(
target_fn: Callable, input_fn: InputFnType, output_fn: OutputFnType
) -> Callable:
def inner_fn(*args: ArgsType, **kwargs: KwargsType) -> Any:
args, kwargs = input_fn(None, args, kwargs, device_mesh)
outputs = target_fn(*args, **kwargs)
return output_fn(None, (args, kwargs), outputs, device_mesh)
return inner_fn
global _replaced_functions
if fn in _replaced_functions:
return
wrapper_fn = wrapper(fn, input_fn, output_fn)
setattr(fn_module, fn.__name__, wrapper_fn)
_replaced_functions[wrapper_fn] = (fn.__name__, fn)
def _restore_function(fn: Callable, fn_module: types.ModuleType) -> None:
"""Restore the function that is replaced by _distribute_function."""
if fn not in _replaced_functions:
return
original_name, original_fn = _replaced_functions[fn]
setattr(fn_module, original_name, original_fn)
def _enable_cp_dtensor_dispatcher() -> None:
"""Enables DTensor dispatcher to dispatch SDPA to CP."""
DTensor._op_dispatcher._custom_op_handlers = {
**exitsing_custom_ops,
**custom_ops,
}
def _disable_cp_dtensor_dispatcher() -> None:
"""Disables DTensor dispatcher to dispatch SDPA to CP."""
DTensor._op_dispatcher._custom_op_handlers = exitsing_custom_ops
def _enable_context_parallel_dispatcher_impl(seq_dim: int, mesh: DeviceMesh) -> None:
sdpa_cp = _ContextParallel(
seq_dim=seq_dim,
attention_type=_ContextParallel.AttentionType.SDPA,
)
if _dispatch_mode == _DispatchMode.MONKEY_PATCH:
_distribute_function(
F.scaled_dot_product_attention,
F,
mesh,
sdpa_cp.sdpa_input_fn,
sdpa_cp.sdpa_output_fn,
)
_enable_cp_dtensor_dispatcher()
elif _dispatch_mode == _DispatchMode.MODULE_WRAPPER:
_enable_cp_dtensor_dispatcher()
else:
raise ValueError(f"Unknown dispatch mode: {_dispatch_mode}")
def _disable_context_parallel_dispatcher_impl() -> None:
if _dispatch_mode == _DispatchMode.MONKEY_PATCH:
_restore_function(F.scaled_dot_product_attention, F)
elif _dispatch_mode == _DispatchMode.MODULE_WRAPPER:
pass
else:
raise NotImplementedError(f"Unknown dispatch mode: {_dispatch_mode}")
_disable_cp_dtensor_dispatcher()
_compiled_create_block_mask = None
def _context_parallel_buffers(
mesh: DeviceMesh,
buffers: list[torch.Tensor | BlockMask],
buffer_seq_dims: list[int],
load_balancer: _LoadBalancer | None = None,
) -> list[torch.Tensor | BlockMask]:
"""
Shard the buffers along the sequence dimensions according to CP rules.
Args:
mesh (:class:`DeviceMesh`): the device mesh for the context parallelism.
buffers (List[torch.Tensor]): the buffers to be sharded.
seq_dims (List[int]): the sequence dimensions of ``buffers``. This list
must have the same length as ``buffers``.
load_balancer (Optional[:class:`_LoadBalancer`]): an optional `_LoadBalancer`
object. If this argument is `None`, it means the `buffers` need no
rearrangement before being sharded. If this argument is a `_LoadBalancer`
object, call its `_generate_indices(restore=False)` to generate the
rearrangement indices such that each shard of `buffer[rearrange_idx]` is
well-balanced (i.e., having close sparsities).
Returns:
List[torch.Tensor]: the sharded buffers.
Note:
For `_context_parallel_shard` we require a non-None `load_balancer` object to be
explicitly passed if load-balancing is needed.
"""
# generate the index tensor for rearranging the buffer if a load-balance
# is available
load_balance_indices = load_balancer._generate_indices() if load_balancer else None
assert load_balance_indices is None or load_balance_indices.ndim == 2, (
"load balance index expects shape (1, seq_len) or (B, seq_len) "
f"but got {load_balance_indices.shape}."
)
new_buffers = []
sharded_buffer: torch.Tensor | BlockMask
for buffer, seq_dim in zip(buffers, buffer_seq_dims):
if isinstance(buffer, torch.Tensor):
# TODO: the load balance doesn't perform error handling.
# NOTE: assuming batch dim is 0
if load_balance_indices is not None:
# TODO: we should expclitly ask users to unsqueeze the batch dim.
# But this is a BC breaking ask.
# However, what we have done today is also not very safe.
idx_batch_size = load_balance_indices.size(0)
data_batch_size = buffer.size(0) if seq_dim > 0 else 1
if idx_batch_size != 1 and idx_batch_size != data_batch_size:
raise ValueError(
"Cannot rearrange buffer: "
f"load_balance_indices has shape {load_balance_indices.shape}, "
f"but buffer has shape {buffer.shape}."
)
if seq_dim == 0:
buffer = torch.index_select(
buffer, dim=0, index=load_balance_indices[0]
)
else:
indices = load_balance_indices
if idx_batch_size == 1:
size = [data_batch_size] + list(indices.size())[1:]
indices = indices.expand(*size)
for i in range(data_batch_size):
buffer[i] = torch.index_select(
buffer[i], dim=seq_dim - 1, index=indices[i]
)
# use DTensor to shard the buffer on sequence dimension, retain the local tensor
sharded_buffer = distribute_tensor(
buffer, mesh, [Shard(seq_dim)], src_data_rank=None
).to_local()
elif isinstance(buffer, BlockMask):
sharded_buffer = _create_cp_block_mask(
mask_mod=buffer.mask_mod,
B=buffer.kv_num_blocks.shape[0],
H=buffer.kv_num_blocks.shape[1],
Q_LEN=buffer.seq_lengths[0],
KV_LEN=buffer.seq_lengths[1],
device_mesh=mesh,
load_balancer=load_balancer,
)
else:
raise ValueError(f"Unknown buffer type: {type(buffer)}")
new_buffers.append(sharded_buffer)
return new_buffers
def _create_cp_block_mask(
mask_mod: _mask_mod_signature,
B: int,
H: int,
Q_LEN: int,
KV_LEN: int,
device_mesh: DeviceMesh,
load_balancer: _LoadBalancer | None = None,
) -> BlockMask:
"""
Creates a specialized BlockMask for Context Parallel FlexAttention.
This function creates a BlockMask that enables computation of attention results
for sharded Q attending to global KV. The mask appropriately handles the query
index offset required when each rank operates on a shard of the query sequence
while accessing the full key-value sequence.
The function internally rewrites the provided mask_mod function to translate local
query indices to global query indices, ensuring that the masking logic is applied
correctly across the distributed computation.
Args:
mask_mod (Callable): Mask function that operates on global attention indices.
B (int): Batch size.
H (int): Number of query heads.
Q_LEN (int): Global sequence length of the query.
KV_LEN (int): Global sequence length of the key/value.
device_mesh (DeviceMesh): Device mesh used for context parallelism.
load_balancer (Optional[:class:`_LoadBalancer`]): The load-balancer used to rearrange
QKV before sharding. This will be used to modify the block_mask generated.
Returns:
BlockMask: A block mask configured for the local query shard that can be used
with flex_attention() for the given cp_mesh.
Raises:
NotImplementedError: If Q_LEN is not divisible by (CP world size * BLOCK_SIZE).
Warning:
Currently requires Q_LEN to be divisible by CP mesh world size * BLOCK_SIZE
(BLOCK_SIZE defaults to 128). This constraint exists because the BlockMask
must handle both padding and offsets correctly. For example, if Q_LEN is 384,
CP world size is 2, and BLOCK_SIZE is 128, the local Q_LEN would be 192. In
such cases, both rank0 and rank1 would have paddings in their local BlockMasks.
Support for padding in this scenario is planned for future work.
"""
from torch.nn.attention.flex_attention import _DEFAULT_SPARSE_BLOCK_SIZE
if Q_LEN % (device_mesh.size() * _DEFAULT_SPARSE_BLOCK_SIZE) != 0:
raise NotImplementedError(
f"Q_LEN {Q_LEN} is not divisible by CP mesh world size {device_mesh.size()} * "
f"BLOCK_SIZE {_DEFAULT_SPARSE_BLOCK_SIZE}. This is not supported yet. "
)
global _compiled_create_block_mask
if _compiled_create_block_mask is None:
_compiled_create_block_mask = torch.compile(
create_block_mask, dynamic=False, fullgraph=True
)
compiled_create_block_mask = _compiled_create_block_mask
def _rewrite_mask_mod(
mask_mod: _mask_mod_signature,
rank: int,
block_size: int,
local_q_size: int,
qkv_rearrange_indices: torch.Tensor | None = None,
) -> _mask_mod_signature:
assert qkv_rearrange_indices is None or qkv_rearrange_indices.ndim == 2, (
"load balance index expects shape (1, seq_len) or (B, seq_len) "
f"but got {qkv_rearrange_indices.shape}."
)
def qkv_idx_restore(
b: torch.Tensor, idx_post_rearrange: torch.Tensor
) -> torch.Tensor:
if qkv_rearrange_indices is not None:
if (
qkv_rearrange_indices.size(0) == 1
): # identical load-balance in batch
idx_pre_rearrange = qkv_rearrange_indices[0][idx_post_rearrange]
else:
idx_pre_rearrange = qkv_rearrange_indices[b][idx_post_rearrange]
else:
idx_pre_rearrange = idx_post_rearrange
return idx_pre_rearrange
def local_q_idx_to_q_idx(local_q_idx: torch.Tensor) -> torch.Tensor:
# calculate local block_idx and block_offset
local_blk_idx, local_blk_offset = (
local_q_idx // block_size,
local_q_idx % block_size,
)
# NOTE: load balancing is not used
local_num_blocks = local_q_size // block_size
blk_idx = local_num_blocks * rank + local_blk_idx
return blk_idx * block_size + local_blk_offset
return lambda b, h, q_idx, kv_idx: mask_mod(
b,
h,
qkv_idx_restore(b, local_q_idx_to_q_idx(q_idx)),
qkv_idx_restore(b, kv_idx),
)
cp_rank = device_mesh.get_local_rank()
cp_group_size = device_mesh.size()
load_balancer = load_balancer or _create_default_load_balancer(
Q_LEN, cp_group_size, device_mesh.device_type
)
Q_SHARD_LEN = Q_LEN // cp_group_size
block_size = _DEFAULT_SPARSE_BLOCK_SIZE
rearrange_indices = (
load_balancer._generate_indices(restore=False) if load_balancer else None
)
block_mask = compiled_create_block_mask(
_rewrite_mask_mod(
mask_mod,
cp_rank,
block_size,
Q_SHARD_LEN,
qkv_rearrange_indices=rearrange_indices,
),
B,
H,
Q_SHARD_LEN,
KV_LEN,
device=device_mesh.device_type,
BLOCK_SIZE=(block_size, block_size),
)
return block_mask
#####################
# Experimental APIs
#####################
| _AllGatherRotater |
python | huggingface__transformers | src/transformers/models/eomt/image_processing_eomt_fast.py | {
"start": 2219,
"end": 20751
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"shortest_edge": 640, "longest_edge": 640}
default_to_square = False
do_resize = True
do_rescale = True
do_normalize = True
do_split_image = False
do_pad = False
ignore_index = None
valid_kwargs = EomtImageProcessorKwargs
def __init__(self, **kwargs: Unpack[EomtImageProcessorKwargs]):
super().__init__(**kwargs)
def _split_image(self, images: torch.Tensor, size: dict, image_indices: int) -> tuple[list, list]:
"""Slices an image into overlapping patches for semantic segmentation."""
patches, patch_offsets = [], []
_, _, height, width = images.shape
patch_size = size["shortest_edge"]
longer_side = max(height, width)
num_patches = math.ceil(longer_side / patch_size)
total_overlap = num_patches * patch_size - longer_side
overlap_per_patch = total_overlap / (num_patches - 1) if num_patches > 1 else 0
for i in range(num_patches):
start = int(i * (patch_size - overlap_per_patch))
end = start + patch_size
if height > width:
batch_patch = images[:, :, start:end, :]
else:
batch_patch = images[:, :, :, start:end]
for batch_idx, single in enumerate(torch.unbind(batch_patch, dim=0)):
patches.append(single)
patch_offsets.append([image_indices[batch_idx], start, end])
return patches, patch_offsets
def _pad(self, images: torch.Tensor, size: dict) -> torch.Tensor:
"""Pads the image to the target size using zero padding."""
_, _, height, width = images.shape
target_height, target_width = get_target_size(size)
pad_h = max(0, target_height - height)
pad_w = max(0, target_width - width)
padding = (0, pad_w, 0, pad_h)
padded_images = torch.nn.functional.pad(images, padding, mode="constant", value=0.0)
return padded_images
@auto_docstring
def preprocess(
self,
images: ImageInput,
segmentation_maps: Optional[list[torch.Tensor]] = None,
instance_id_to_semantic_id: Optional[dict[int, int]] = None,
**kwargs: Unpack[EomtImageProcessorKwargs],
) -> BatchFeature:
r"""
segmentation_maps (`ImageInput`, *optional*):
The segmentation maps to preprocess for corresponding images.
instance_id_to_semantic_id (`list[dict[int, int]]` or `dict[int, int]`, *optional*):
A mapping between object instance ids and class ids.
"""
return super().preprocess(images, segmentation_maps, instance_id_to_semantic_id, **kwargs)
def _preprocess_image_like_inputs(
self,
images: ImageInput,
segmentation_maps: Optional[ImageInput],
instance_id_to_semantic_id: Optional[dict[int, int]],
do_convert_rgb: bool,
input_data_format: ChannelDimension,
device: Optional[Union[str, "torch.device"]] = None,
**kwargs: Unpack[EomtImageProcessorKwargs],
) -> BatchFeature:
"""
Preprocess image-like inputs.
"""
images = self._prepare_image_like_inputs(
images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
)
ignore_index = kwargs.pop("ignore_index", None)
images_kwargs = kwargs.copy()
processed_images, patch_offsets = self._preprocess(images, **images_kwargs)
outputs = BatchFeature({"pixel_values": processed_images})
if segmentation_maps is not None:
processed_segmentation_maps = self._prepare_image_like_inputs(
images=segmentation_maps,
expected_ndims=2,
do_convert_rgb=False,
input_data_format=ChannelDimension.FIRST,
)
segmentation_maps_kwargs = kwargs.copy()
segmentation_maps_kwargs.update(
{
"do_normalize": False,
"do_rescale": False,
# Nearest interpolation is used for segmentation maps instead of BILINEAR.
"interpolation": F.InterpolationMode.NEAREST_EXACT,
}
)
processed_segmentation_maps, _ = self._preprocess(
images=processed_segmentation_maps, **segmentation_maps_kwargs
)
processed_segmentation_maps = processed_segmentation_maps.squeeze(1).to(torch.int64)
# Convert to list of binary masks and labels
mask_labels, class_labels = [], []
for idx, segmentation_map in enumerate(processed_segmentation_maps):
if isinstance(instance_id_to_semantic_id, list):
instance_id = instance_id_to_semantic_id[idx]
else:
instance_id = instance_id_to_semantic_id
# Use instance2class_id mapping per image
masks, classes = convert_segmentation_map_to_binary_masks(
segmentation_map,
instance_id,
ignore_index=ignore_index,
)
mask_labels.append(torch.from_numpy(masks))
class_labels.append(torch.from_numpy(classes))
# we cannot batch them since they don't share a common class size
outputs["mask_labels"] = mask_labels
outputs["class_labels"] = class_labels
if patch_offsets:
outputs["patch_offsets"] = [torch.tensor(offsets) for offsets in patch_offsets]
return outputs
def _preprocess(
self,
images: list["torch.Tensor"],
do_resize: bool,
size: SizeDict,
interpolation: Optional["F.InterpolationMode"],
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
do_split_image: bool,
do_pad: bool,
image_mean: Optional[Union[float, list[float]]],
image_std: Optional[Union[float, list[float]]],
disable_grouping: Optional[bool],
return_tensors: Optional[Union[str, TensorType]],
**kwargs,
):
"""Preprocesses the input images and masks if provided."""
processed_images, patch_offsets = [], []
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
resized_images_grouped = {}
for shape, stacked_images in grouped_images.items():
if do_resize:
stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation)
resized_images_grouped[shape] = stacked_images
images = reorder_images(resized_images_grouped, grouped_images_index)
# Group images by size for batched resizing, Needed in case do_resize is False.
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
processed_images_grouped = {}
for shape, stacked_images in grouped_images.items():
original_indices = [
original_idx for original_idx, (img_shape, _) in grouped_images_index.items() if img_shape == shape
]
if do_split_image:
patches, offsets = self._split_image(stacked_images, size, original_indices)
processed_images.extend(patches)
patch_offsets.extend(offsets)
if do_pad:
stacked_images = self._pad(stacked_images, size)
processed_images_grouped[shape] = stacked_images
if do_split_image:
images, patch_offsets = reorder_patches_and_offsets(processed_images, patch_offsets)
if do_pad:
images = reorder_images(processed_images_grouped, grouped_images_index)
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
processed_images_grouped = {}
for shape, stacked_images in grouped_images.items():
stacked_images = self.rescale_and_normalize(
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
)
processed_images_grouped[shape] = stacked_images
images = reorder_images(processed_images_grouped, grouped_images_index)
processed_images = torch.stack(images, dim=0) if return_tensors else images
return processed_images, patch_offsets
def merge_image_patches(
self,
segmentation_logits: torch.Tensor,
patch_offsets: list[tuple[int, int, int]],
target_sizes: list[tuple[int, int]],
size: dict[str, int],
) -> list[torch.Tensor]:
"""
Reconstructs full-size semantic segmentation logits from patch predictions.
Args:
segmentation_logits (`torch.Tensor`):
A tensor of shape `(num_patches, num_classes, patch_height, patch_width)` representing predicted logits
for each image patch.
patch_offsets (`list[tuple[int, int, int]]`):
A list of tuples where each tuple contains:
- `image_index` (int): Index of the original image this patch belongs to.
- `start` (int): Start pixel index of the patch along the long dimension (height or width).
- `end` (int): End pixel index of the patch along the long dimension.
target_sizes (`list[tuple[int, int]]`):
list of original (height, width) dimensions for each image before preprocessing.
size (`dict[str, int]`):
A size dict which was used to resize.
"""
num_classes = segmentation_logits.shape[1]
aggregated_logits = []
patch_counts = []
for image_size in target_sizes:
height, width = get_size_with_aspect_ratio(image_size, size["shortest_edge"], size["longest_edge"])
aggregated_logits.append(torch.zeros((num_classes, height, width), device=segmentation_logits.device))
patch_counts.append(torch.zeros((num_classes, height, width), device=segmentation_logits.device))
# Stitch patches back into full-sized logit maps
for patch_idx, (image_idx, patch_start, patch_end) in enumerate(patch_offsets):
if target_sizes[image_idx][0] > target_sizes[image_idx][1]:
aggregated_logits[image_idx][:, patch_start:patch_end, :] += segmentation_logits[patch_idx]
patch_counts[image_idx][:, patch_start:patch_end, :] += 1
else:
aggregated_logits[image_idx][:, :, patch_start:patch_end] += segmentation_logits[patch_idx]
patch_counts[image_idx][:, :, patch_start:patch_end] += 1
# Normalize and resize logits to original image size
reconstructed_logits = []
for idx, (logit_sum, count) in enumerate(zip(aggregated_logits, patch_counts)):
averaged_logits = logit_sum / count.clamp(min=1)
resized_logits = torch.nn.functional.interpolate(
averaged_logits[None, ...],
size=target_sizes[idx],
mode="bilinear",
align_corners=False,
)[0]
reconstructed_logits.append(resized_logits)
return reconstructed_logits
def unpad_image(
self,
segmentation_logits: torch.Tensor,
target_sizes: list[tuple[int, int]],
size: dict[str, int],
) -> list[torch.Tensor]:
"""Restores panoptic segmentation logits to their original image resolutions."""
resized_logits = []
for idx, original_size in enumerate(target_sizes):
target_height, target_width = get_size_with_aspect_ratio(
original_size, size["shortest_edge"], size["longest_edge"]
)
cropped_logits = segmentation_logits[idx][:, :target_height, :target_width]
upsampled_logits = torch.nn.functional.interpolate(
cropped_logits[None, ...], size=original_size, mode="bilinear", align_corners=False
)[0]
resized_logits.append(upsampled_logits)
return resized_logits
def post_process_semantic_segmentation(
self,
outputs,
target_sizes: list[tuple[int, int]],
size: Optional[dict[str, int]] = None,
) -> np.ndarray:
"""Post-processes model outputs into final semantic segmentation prediction."""
size = size if size is not None else self.size
masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
patch_offsets = outputs.patch_offsets
output_size = get_target_size(size)
masks_queries_logits = torch.nn.functional.interpolate(
masks_queries_logits,
size=output_size,
mode="bilinear",
)
# Remove the null class `[..., :-1]`
masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
segmentation_logits = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
output_logits = self.merge_image_patches(segmentation_logits, patch_offsets, target_sizes, size)
preds = [logit.argmax(dim=0) for logit in output_logits]
return preds
def post_process_panoptic_segmentation(
self,
outputs,
target_sizes: list[tuple[int, int]],
threshold: float = 0.8,
mask_threshold: float = 0.5,
overlap_mask_area_threshold: float = 0.8,
stuff_classes: Optional[list[int]] = None,
size: Optional[dict[str, int]] = None,
):
"""Post-processes model outputs into final panoptic segmentation prediction."""
size = size if size is not None else self.size
masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
batch_size = class_queries_logits.shape[0]
num_labels = class_queries_logits.shape[-1] - 1
output_size = get_target_size(size)
masks_queries_logits = torch.nn.functional.interpolate(
masks_queries_logits,
size=output_size,
mode="bilinear",
)
mask_probs_batch = self.unpad_image(masks_queries_logits, target_sizes, size)
pred_scores_batch, pred_labels_batch = class_queries_logits.softmax(dim=-1).max(-1)
results: list = []
for i in range(batch_size):
mask_probs, pred_scores, pred_labels = remove_low_and_no_objects(
mask_probs_batch[i], pred_scores_batch[i], pred_labels_batch[i], threshold, num_labels
)
# No mask found
if mask_probs.shape[0] <= 0:
height, width = target_sizes[i] if target_sizes is not None else mask_probs.shape[1:]
segmentation = torch.zeros((height, width)) - 1
results.append({"segmentation": segmentation, "segments_info": []})
continue
segmentation, segments = compute_segments(
mask_probs=mask_probs,
pred_scores=pred_scores,
pred_labels=pred_labels,
stuff_classes=stuff_classes,
mask_threshold=mask_threshold,
overlap_mask_area_threshold=overlap_mask_area_threshold,
target_size=target_sizes[i] if target_sizes is not None else None,
)
results.append({"segmentation": segmentation, "segments_info": segments})
return results
@filter_out_non_signature_kwargs()
def post_process_instance_segmentation(
self,
outputs,
target_sizes: list[tuple[int, int]],
threshold: float = 0.8,
size: Optional[dict[str, int]] = None,
):
"""Post-processes model outputs into Instance Segmentation Predictions."""
size = size if size is not None else self.size
masks_queries_logits = outputs.masks_queries_logits
class_queries_logits = outputs.class_queries_logits
output_size = get_target_size(size)
masks_queries_logits = torch.nn.functional.interpolate(
masks_queries_logits,
size=output_size,
mode="bilinear",
)
mask_probs_batch = self.unpad_image(masks_queries_logits, target_sizes, size)
device = masks_queries_logits.device
batch_size = class_queries_logits.shape[0]
num_queries = class_queries_logits.shape[-2]
results = []
for i in range(batch_size):
mask_pred = mask_probs_batch[i]
mask_class = class_queries_logits[i]
# Remove the null class `[..., :-1]`
scores, pred_classes = mask_class.softmax(dim=-1)[..., :-1].max(-1)
pred_masks = (mask_pred > 0).float()
# Calculate average mask prob
mask_scores = (mask_pred.sigmoid().flatten(1) * pred_masks.flatten(1)).sum(1) / (
pred_masks.flatten(1).sum(1) + 1e-6
)
pred_scores = scores * mask_scores
segmentation = torch.zeros(target_sizes[i], device=device) - 1
instance_maps, segments = [], []
current_segment_id = 0
for j in range(num_queries):
score = pred_scores[j].item()
if not torch.all(pred_masks[j] == 0) and score >= threshold:
segmentation[pred_masks[j] == 1] = current_segment_id
segments.append(
{
"id": current_segment_id,
"label_id": pred_classes[j].item(),
"score": round(score, 6),
}
)
current_segment_id += 1
instance_maps.append(pred_masks[j])
results.append({"segmentation": segmentation, "segments_info": segments})
return results
__all__ = ["EomtImageProcessorFast"]
| EomtImageProcessorFast |
python | django-import-export__django-import-export | tests/core/tests/test_base_formats.py | {
"start": 5625,
"end": 7468
} | class ____(TestCase):
def setUp(self):
self.format = base_formats.CSV()
self.dataset = tablib.Dataset(headers=["id", "username"])
self.dataset.append(("1", "x"))
def test_import_dos(self):
filename = os.path.join(
os.path.dirname(__file__), os.path.pardir, "exports", "books-dos.csv"
)
with open(filename, self.format.get_read_mode()) as in_stream:
actual = in_stream.read()
expected = "id,name,author_email\n1,Some book,test@example.com\n"
self.assertEqual(actual, expected)
def test_import_mac(self):
filename = os.path.join(
os.path.dirname(__file__), os.path.pardir, "exports", "books-mac.csv"
)
with open(filename, self.format.get_read_mode()) as in_stream:
actual = in_stream.read()
expected = "id,name,author_email\n1,Some book,test@example.com\n"
self.assertEqual(actual, expected)
def test_import_unicode(self):
# importing csv UnicodeEncodeError 347
filename = os.path.join(
os.path.dirname(__file__), os.path.pardir, "exports", "books-unicode.csv"
)
with open(filename, self.format.get_read_mode()) as in_stream:
data = force_str(in_stream.read())
base_formats.CSV().create_dataset(data)
def test_export_data(self):
res = self.format.export_data(self.dataset)
self.assertEqual("id,username\r\n1,x\r\n", res)
def test_get_extension(self):
self.assertEqual("csv", self.format.get_extension())
def test_content_type(self):
self.assertEqual("text/csv", self.format.get_content_type())
def test_can_import(self):
self.assertTrue(self.format.can_import())
def test_can_export(self):
self.assertTrue(self.format.can_export())
| CSVTest |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/toys/user_computed_data_versions/external_system.py | {
"start": 625,
"end": 674
} | class ____(TypedDict):
key: str
| SourceAssetInfo |
python | py-pdf__pypdf | pypdf/_text_extraction/_layout_mode/_font.py | {
"start": 345,
"end": 7067
} | class ____:
"""
A font object formatted for use during "layout" mode text extraction
Attributes:
subtype (str): font subtype
space_width (int | float): width of a space character
encoding (str | Dict[int, str]): font encoding
char_map (dict): character map
font_dictionary (dict): font dictionary
width_map (Dict[str, int]): mapping of characters to widths
interpretable (bool): Default True. If False, the font glyphs cannot
be translated to characters, e.g. Type3 fonts that do not define
a '/ToUnicode' mapping.
"""
subtype: str
space_width: Union[int, float]
encoding: Union[str, dict[int, str]]
char_map: dict[Any, Any]
font_dictionary: dict[Any, Any]
width_map: dict[str, int] = field(default_factory=dict, init=False)
interpretable: bool = True
def __post_init__(self) -> None:
# Type3 fonts that do not specify a "/ToUnicode" mapping cannot be
# reliably converted into character codes unless all named chars
# in /CharProcs map to a standard adobe glyph. See §9.10.2 of the
# PDF 1.7 standard.
if self.subtype == "/Type3" and "/ToUnicode" not in self.font_dictionary:
self.interpretable = all(
cname in adobe_glyphs
for cname in self.font_dictionary.get("/CharProcs") or []
)
if not self.interpretable: # save some overhead if font is not interpretable
return
# TrueType fonts have a /Widths array mapping character codes to widths
if isinstance(self.encoding, dict) and "/Widths" in self.font_dictionary:
first_char = self.font_dictionary.get("/FirstChar", 0)
self.width_map = {
self.encoding.get(idx + first_char, chr(idx + first_char)): width
for idx, width in enumerate(self.font_dictionary["/Widths"])
}
# CID fonts have a /W array mapping character codes to widths stashed in /DescendantFonts
if "/DescendantFonts" in self.font_dictionary:
d_font: dict[Any, Any]
for d_font_idx, d_font in enumerate(
self.font_dictionary["/DescendantFonts"]
):
while isinstance(d_font, IndirectObject):
d_font = d_font.get_object()
self.font_dictionary["/DescendantFonts"][d_font_idx] = d_font
ord_map = {
ord(_target): _surrogate
for _target, _surrogate in self.char_map.items()
if isinstance(_target, str)
}
# /W width definitions have two valid formats which can be mixed and matched:
# (1) A character start index followed by a list of widths, e.g.
# `45 [500 600 700]` applies widths 500, 600, 700 to characters 45-47.
# (2) A character start index, a character stop index, and a width, e.g.
# `45 65 500` applies width 500 to characters 45-65.
skip_count = 0
_w = d_font.get("/W", [])
for idx, w_entry in enumerate(_w):
w_entry = w_entry.get_object()
if skip_count:
skip_count -= 1
continue
if not isinstance(w_entry, (int, float)): # pragma: no cover
# We should never get here due to skip_count above. Add a
# warning and or use reader's "strict" to force an ex???
continue
# check for format (1): `int [int int int int ...]`
w_next_entry = _w[idx + 1].get_object()
if isinstance(w_next_entry, Sequence):
start_idx, width_list = w_entry, w_next_entry
self.width_map.update(
{
ord_map[_cidx]: _width
for _cidx, _width in zip(
range(
cast(int, start_idx),
cast(int, start_idx) + len(width_list),
1,
),
width_list,
)
if _cidx in ord_map
}
)
skip_count = 1
# check for format (2): `int int int`
elif isinstance(w_next_entry, (int, float)) and isinstance(
_w[idx + 2].get_object(), (int, float)
):
start_idx, stop_idx, const_width = (
w_entry,
w_next_entry,
_w[idx + 2].get_object(),
)
self.width_map.update(
{
ord_map[_cidx]: const_width
for _cidx in range(
cast(int, start_idx), cast(int, stop_idx + 1), 1
)
if _cidx in ord_map
}
)
skip_count = 2
else:
# Note: this doesn't handle the case of out of bounds (reaching the end of the width definitions
# while expecting more elements). This raises an IndexError which is sufficient.
raise ParseError(
f"Invalid font width definition. Next elements: {w_entry}, {w_next_entry}, {_w[idx + 2]}"
) # pragma: no cover
if not self.width_map and "/BaseFont" in self.font_dictionary:
for key in STANDARD_WIDTHS:
if self.font_dictionary["/BaseFont"].startswith(f"/{key}"):
self.width_map = STANDARD_WIDTHS[key]
break
def word_width(self, word: str) -> float:
"""Sum of character widths specified in PDF font for the supplied word"""
return sum(
[self.width_map.get(char, self.space_width * 2) for char in word], 0.0
)
@staticmethod
def to_dict(font_instance: "Font") -> dict[str, Any]:
"""Dataclass to dict for json.dumps serialization."""
return {
k: getattr(font_instance, k) for k in font_instance.__dataclass_fields__
}
| Font |
python | redis__redis-py | redis/maint_notifications.py | {
"start": 10736,
"end": 13539
} | class ____(MaintenanceNotification):
"""
Notification for when a Redis cluster node has completed a failover.
This notification is received when a node has finished the failover process
during cluster maintenance operations or after handling node failures.
Args:
id (int): Unique identifier for this notification
"""
DEFAULT_TTL = 5
def __init__(self, id: int):
super().__init__(id, NodeFailedOverNotification.DEFAULT_TTL)
def __repr__(self) -> str:
expiry_time = self.creation_time + self.ttl
remaining = max(0, expiry_time - time.monotonic())
return (
f"{self.__class__.__name__}("
f"id={self.id}, "
f"ttl={self.ttl}, "
f"creation_time={self.creation_time}, "
f"expires_at={expiry_time}, "
f"remaining={remaining:.1f}s, "
f"expired={self.is_expired()}"
f")"
)
def __eq__(self, other) -> bool:
"""
Two NodeFailedOverNotification notifications are considered equal if they have the same
id and are of the same type.
"""
if not isinstance(other, NodeFailedOverNotification):
return False
return self.id == other.id and type(self) is type(other)
def __hash__(self) -> int:
"""
Return a hash value for the notification to allow
instances to be used in sets and as dictionary keys.
Returns:
int: Hash value based on notification type and id
"""
return hash((self.__class__.__name__, int(self.id)))
def _is_private_fqdn(host: str) -> bool:
"""
Determine if an FQDN is likely to be internal/private.
This uses heuristics based on RFC 952 and RFC 1123 standards:
- .local domains (RFC 6762 - Multicast DNS)
- .internal domains (common internal convention)
- Single-label hostnames (no dots)
- Common internal TLDs
Args:
host (str): The FQDN to check
Returns:
bool: True if the FQDN appears to be internal/private
"""
host_lower = host.lower().rstrip(".")
# Single-label hostnames (no dots) are typically internal
if "." not in host_lower:
return True
# Common internal/private domain patterns
internal_patterns = [
r"\.local$", # mDNS/Bonjour domains
r"\.internal$", # Common internal convention
r"\.corp$", # Corporate domains
r"\.lan$", # Local area network
r"\.intranet$", # Intranet domains
r"\.private$", # Private domains
]
for pattern in internal_patterns:
if re.search(pattern, host_lower):
return True
# If none of the internal patterns match, assume it's external
return False
| NodeFailedOverNotification |
python | ray-project__ray | python/ray/util/metrics.py | {
"start": 1395,
"end": 5820
} | class ____:
"""The parent class of custom metrics.
Ray's custom metrics APIs are rooted from this class and share
the same public methods.
"""
def __init__(
self,
name: str,
description: str = "",
tag_keys: Optional[Tuple[str, ...]] = None,
):
# Metrics with invalid names will be discarded and will not be collected
# by Prometheus.
self._discard_metric = _is_invalid_metric_name(name)
self._name = name
self._description = description
# The default tags key-value pair.
self._default_tags = {}
# Keys of tags.
self._tag_keys = tag_keys or tuple()
# The Cython metric class. This should be set in the child class.
self._metric = None
if not isinstance(self._tag_keys, tuple):
raise TypeError(
"tag_keys should be a tuple type, got: " f"{type(self._tag_keys)}"
)
for key in self._tag_keys:
if not isinstance(key, str):
raise TypeError(f"Tag keys must be str, got {type(key)}.")
if ":" in self._name:
warnings.warn(
f"Metric name {self._name} contains a : character, which is no longer allowed. "
f"Please migrate to the new metric name format. "
f"This will be an error in the future.",
FutureWarning,
)
def set_default_tags(self, default_tags: Dict[str, str]):
"""Set default tags of metrics.
Example:
>>> from ray.util.metrics import Counter
>>> # Note that set_default_tags returns the instance itself.
>>> counter = Counter("name", tag_keys=("a",))
>>> counter2 = counter.set_default_tags({"a": "b"})
>>> assert counter is counter2
>>> # this means you can instantiate it in this way.
>>> counter = Counter("name", tag_keys=("a",)).set_default_tags({"a": "b"})
Args:
default_tags: Default tags that are
used for every record method.
Returns:
Metric: it returns the instance itself.
"""
for key, val in default_tags.items():
if key not in self._tag_keys:
raise ValueError(f"Unrecognized tag key {key}.")
if not isinstance(val, str):
raise TypeError(f"Tag values must be str, got {type(val)}.")
self._default_tags = default_tags
return self
def _record(
self,
value: Union[int, float],
tags: Optional[Dict[str, str]] = None,
) -> None:
"""Record the metric point of the metric.
Tags passed in will take precedence over the metric's default tags.
Args:
value: The value to be recorded as a metric point.
"""
if self._discard_metric:
return
assert self._metric is not None
final_tags = self._get_final_tags(tags)
self._validate_tags(final_tags)
self._metric.record(value, tags=final_tags)
def _get_final_tags(self, tags):
if not tags:
return self._default_tags
for val in tags.values():
if not isinstance(val, str):
raise TypeError(f"Tag values must be str, got {type(val)}.")
return {**self._default_tags, **tags}
def _validate_tags(self, final_tags):
missing_tags = []
for tag_key in self._tag_keys:
# Prefer passed tags over default tags.
if tag_key not in final_tags:
missing_tags.append(tag_key)
# Strict validation: if any required tag_keys are missing, raise error
if missing_tags:
raise ValueError(f"Missing value for tag key(s): {','.join(missing_tags)}.")
@property
def info(self) -> Dict[str, Any]:
"""Return the information of this metric.
Example:
>>> from ray.util.metrics import Counter
>>> counter = Counter("name", description="desc")
>>> print(counter.info)
{'name': 'name', 'description': 'desc', 'tag_keys': (), 'default_tags': {}}
"""
return {
"name": self._name,
"description": self._description,
"tag_keys": self._tag_keys,
"default_tags": self._default_tags,
}
@DeveloperAPI
| Metric |
python | django__django | tests/serializers/models/data.py | {
"start": 1659,
"end": 1758
} | class ____(models.Model):
data = models.PositiveBigIntegerField(null=True)
| PositiveBigIntegerData |
python | kamyu104__LeetCode-Solutions | Python/unique-paths.py | {
"start": 33,
"end": 481
} | class ____(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def nCr(n, r): # Time: O(n), Space: O(1)
if n-r < r:
r = n-r
c = 1
for k in xrange(1, r+1):
c *= n-k+1
c //= k
return c
return nCr((m-1)+(n-1), n-1)
# Time: O(m * n)
# Space: O(min(m, n))
| Solution |
python | encode__django-rest-framework | tests/test_throttling.py | {
"start": 953,
"end": 1172
} | class ____(BaseThrottle):
def allow_request(self, request, view):
if not hasattr(self.__class__, 'called'):
self.__class__.called = True
return True
return False
| NonTimeThrottle |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 64945,
"end": 65823
} | class ____(DefinedFunction):
r"""
Returns the Kronecker symbol `(a / n)`.
Examples
========
>>> from sympy.functions.combinatorial.numbers import kronecker_symbol
>>> kronecker_symbol(45, 77)
-1
>>> kronecker_symbol(13, -120)
1
See Also
========
jacobi_symbol, legendre_symbol
References
==========
.. [1] https://en.wikipedia.org/wiki/Kronecker_symbol
"""
is_integer = True
is_prime = False
@classmethod
def eval(cls, a, n):
if a.is_integer is False:
raise TypeError("a should be an integer")
if n.is_integer is False:
raise TypeError("n should be an integer")
if a is S.One or n is S.One:
return S.One
if a.is_Integer is True and n.is_Integer is True:
return S(kronecker(as_int(a), as_int(n)))
| kronecker_symbol |
python | etianen__django-reversion | tests/test_app/tests/test_middleware.py | {
"start": 328,
"end": 892
} | class ____(TestModelMixin, TestBase):
def testCreateRevision(self):
response = self.client.post("/test-app/save-obj/")
obj = TestModel.objects.get(pk=response.content)
self.assertSingleRevision((obj,))
def testCreateRevisionError(self):
with self.assertRaises(Exception):
self.client.post("/test-app/save-obj-error/")
self.assertNoRevision()
def testCreateRevisionGet(self):
self.client.get("/test-app/create-revision/")
self.assertNoRevision()
@use_middleware
| RevisionMiddlewareTest |
python | python__mypy | mypy/util.py | {
"start": 4250,
"end": 10023
} | class ____(Exception):
"""Exception raised when a file cannot be decoded due to an unknown encoding type.
Essentially a wrapper for the LookupError raised by `bytearray.decode`
"""
def decode_python_encoding(source: bytes) -> str:
"""Read the Python file with while obeying PEP-263 encoding detection.
Returns the source as a string.
"""
# check for BOM UTF-8 encoding and strip it out if present
if source.startswith(b"\xef\xbb\xbf"):
encoding = "utf8"
source = source[3:]
else:
# look at first two lines and check if PEP-263 coding is present
encoding, _ = find_python_encoding(source)
try:
source_text = source.decode(encoding)
except LookupError as lookuperr:
raise DecodeError(str(lookuperr)) from lookuperr
return source_text
def read_py_file(path: str, read: Callable[[str], bytes]) -> list[str] | None:
"""Try reading a Python file as list of source lines.
Return None if something goes wrong.
"""
try:
source = read(path)
except OSError:
return None
else:
try:
source_lines = decode_python_encoding(source).splitlines()
except DecodeError:
return None
return source_lines
def trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]:
"""Trim a line of source code to fit into max_len.
Show 'min_width' characters on each side of 'col' (an error location). If either
start or end is trimmed, this is indicated by adding '...' there.
A typical result looks like this:
...some_variable = function_to_call(one_arg, other_arg) or...
Return the trimmed string and the column offset to adjust error location.
"""
if max_len < 2 * min_width + 1:
# In case the window is too tiny it is better to still show something.
max_len = 2 * min_width + 1
# Trivial case: line already fits in.
if len(line) <= max_len:
return line, 0
# If column is not too large so that there is still min_width after it,
# the line doesn't need to be trimmed at the start.
if col + min_width < max_len:
return line[:max_len] + "...", 0
# Otherwise, if the column is not too close to the end, trim both sides.
if col < len(line) - min_width - 1:
offset = col - max_len + min_width + 1
return "..." + line[offset : col + min_width + 1] + "...", offset - 3
# Finally, if the column is near the end, just trim the start.
return "..." + line[-max_len:], len(line) - max_len - 3
def get_mypy_comments(source: str) -> list[tuple[int, str]]:
PREFIX = "# mypy: "
# Don't bother splitting up the lines unless we know it is useful
if PREFIX not in source:
return []
lines = source.split("\n")
results = []
for i, line in enumerate(lines):
if line.startswith(PREFIX):
results.append((i + 1, line[len(PREFIX) :]))
return results
JUNIT_HEADER_TEMPLATE: Final = """<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="{errors}" failures="{failures}" name="mypy" skips="0" tests="{tests}" time="{time:.3f}">
"""
JUNIT_TESTCASE_FAIL_TEMPLATE: Final = """ <testcase classname="mypy" file="{filename}" line="1" name="{name}" time="{time:.3f}">
<failure message="mypy produced messages">{text}</failure>
</testcase>
"""
JUNIT_ERROR_TEMPLATE: Final = """ <testcase classname="mypy" file="mypy" line="1" name="mypy-py{ver}-{platform}" time="{time:.3f}">
<error message="mypy produced errors">{text}</error>
</testcase>
"""
JUNIT_TESTCASE_PASS_TEMPLATE: Final = """ <testcase classname="mypy" file="mypy" line="1" name="mypy-py{ver}-{platform}" time="{time:.3f}">
</testcase>
"""
JUNIT_FOOTER: Final = """</testsuite>
"""
def _generate_junit_contents(
dt: float,
serious: bool,
messages_by_file: dict[str | None, list[str]],
version: str,
platform: str,
) -> str:
from xml.sax.saxutils import escape
if serious:
failures = 0
errors = len(messages_by_file)
else:
failures = len(messages_by_file)
errors = 0
xml = JUNIT_HEADER_TEMPLATE.format(
errors=errors,
failures=failures,
time=dt,
# If there are no messages, we still write one "test" indicating success.
tests=len(messages_by_file) or 1,
)
if not messages_by_file:
xml += JUNIT_TESTCASE_PASS_TEMPLATE.format(time=dt, ver=version, platform=platform)
else:
for filename, messages in messages_by_file.items():
if filename is not None:
xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format(
text=escape("\n".join(messages)),
filename=filename,
time=dt,
name="mypy-py{ver}-{platform} {filename}".format(
ver=version, platform=platform, filename=filename
),
)
else:
xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format(
text=escape("\n".join(messages)),
filename="mypy",
time=dt,
name=f"mypy-py{version}-{platform}",
)
xml += JUNIT_FOOTER
return xml
def write_junit_xml(
dt: float,
serious: bool,
messages_by_file: dict[str | None, list[str]],
path: str,
version: str,
platform: str,
) -> None:
xml = _generate_junit_contents(dt, serious, messages_by_file, version, platform)
# creates folders if needed
xml_dirs = os.path.dirname(os.path.abspath(path))
os.makedirs(xml_dirs, exist_ok=True)
with open(path, "wb") as f:
f.write(xml.encode("utf-8"))
| DecodeError |
python | wandb__wandb | wandb/sdk/internal/context.py | {
"start": 893,
"end": 2518
} | class ____:
_active_items: Dict[str, Context]
def __init__(self) -> None:
self._active_items = {}
def add_from_record(self, record: Record) -> Optional[Context]:
context_id = context_id_from_record(record)
if not context_id:
return None
context_obj = self.add(context_id)
# TODO(debug_context) see above
# context_obj._debug_record = record
return context_obj
def add(self, context_id: str) -> Context:
assert context_id
context_obj = Context()
self._active_items[context_id] = context_obj
return context_obj
def get(self, context_id: str) -> Optional[Context]:
item = self._active_items.get(context_id)
return item
def release(self, context_id: str) -> None:
if not context_id:
return
_ = self._active_items.pop(context_id, None)
def cancel(self, context_id: str) -> bool:
item = self.get(context_id)
if item:
item.cancel()
return True
return False
# TODO(debug_context) see above
# def _debug_print_orphans(self, print_to_stdout: bool) -> None:
# for context_id, context in self._active_items.items():
# record = context._debug_record
# record_type = record.WhichOneof("record_type") if record else "unknown"
# message = (
# f"Context: {context_id} {context.cancel_event.is_set()} {record_type}"
# )
# logger.warning(message)
# if print_to_stdout:
# print(message)
| ContextKeeper |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_between.py | {
"start": 559,
"end": 780
} | class ____(ValueError):
def __init__(self, column_type: str):
message = f"ColumnValuesBetween metrics cannot be computed on column of type {column_type}."
super().__init__(message)
| InvalidColumnTypeError |
python | dagster-io__dagster | .buildkite/dagster-buildkite/dagster_buildkite/steps/tox.py | {
"start": 484,
"end": 3683
} | class ____:
"""Represents a tox environment factor for configuration.
Args:
factor: The tox factor name (e.g., "pytest", "integration")
splits: Number of parallel splits to generate for this factor (default: 1)
"""
factor: str
splits: int = 1
_COMMAND_TYPE_TO_EMOJI_MAP = {
"pytest": ":pytest:",
"miscellaneous": ":sparkle:",
}
def build_tox_step(
root_dir: str,
tox_env: str,
base_label: Optional[str] = None,
command_type: str = "miscellaneous",
python_version: Optional[AvailablePythonVersion] = None,
tox_file: Optional[str] = None,
extra_commands_pre: Optional[list[str]] = None,
extra_commands_post: Optional[list[str]] = None,
env_vars: Optional[list[str]] = None,
dependencies: Optional[list[str]] = None,
retries: Optional[int] = None,
timeout_in_minutes: Optional[int] = None,
queue: Optional[BuildkiteQueue] = None,
skip_reason: Optional[str] = None,
pytest_args: Optional[list[str]] = None,
) -> CommandStepConfiguration:
base_label = base_label or os.path.basename(root_dir)
emoji = _COMMAND_TYPE_TO_EMOJI_MAP[command_type]
label = f"{emoji} {base_label} {_tox_env_to_label_suffix(tox_env)}"
python_version = python_version or _resolve_python_version(tox_env)
header_message = f"{emoji} Running tox env: {tox_env}"
buildkite_section_header = make_buildkite_section_header(header_message)
tox_command_parts = filter(
None,
[
"tox",
f"-c {tox_file} " if tox_file else None,
"-vv", # extra-verbose
"-e",
tox_env,
"--" if pytest_args else None,
" ".join(pytest_args) if pytest_args else None,
],
)
tox_command = " ".join(tox_command_parts)
commands = [
*(extra_commands_pre or []),
f"cd {root_dir}",
f'pip install "{UV_PIN}"',
f"echo -e {shlex.quote(buildkite_section_header)}",
tox_command,
*(extra_commands_post or []),
]
step_builder = (
add_test_image(CommandStepBuilder(label), python_version, env_vars or [])
.run(*commands)
.with_timeout(timeout_in_minutes)
.with_retry(retries)
.depends_on(dependencies)
.skip_if(skip_reason)
)
if queue:
step_builder.on_queue(queue)
return step_builder.build()
def _tox_env_to_label_suffix(tox_env: str) -> str:
py_version, _, factor = tox_env.partition("-")
m = re.match(r"py(\d+)", py_version)
if m:
version_number = m[1]
number_str = f"{version_number[0]}.{version_number[1:]}"
if factor == "":
return number_str
return f"{factor} {number_str}"
else:
return ""
def _resolve_python_version(tox_env: str) -> AvailablePythonVersion:
factors = tox_env.split("-")
py_version_factor = next((f for f in factors if re.match(r"py\d+", f)), None)
if py_version_factor:
major, minor = int(py_version_factor[2]), int(py_version_factor[3:])
return AvailablePythonVersion.from_major_minor(major, minor)
else:
return AvailablePythonVersion.get_default()
| ToxFactor |
python | django-extensions__django-extensions | tests/test_templatetags.py | {
"start": 631,
"end": 1166
} | class ____(TestCase):
"""Test class for DebuggerTags."""
def setUp(self):
self.engine = engines["django"]
def test_pdb_filter(self):
"""Test for pdb filter."""
import pdb
pdb.set_trace = MagicMock(return_value=None)
template = self.engine.from_string(
"""
{% load debugger_tags %}
{{ test_object|pdb }}
"""
)
template.render({"test_object": "test_value"})
self.assertTrue(pdb.set_trace.called)
| DebuggerTagsTests |
python | numpy__numpy | numpy/_core/tests/test_array_coercion.py | {
"start": 4583,
"end": 6418
} | class ____:
@pytest.mark.parametrize("obj",
[object(), 1.2, 10**43, None, "string"],
ids=["object", "1.2", "10**43", "None", "string"])
def test_basic_stringlength(self, obj):
length = len(str(obj))
expected = np.dtype(f"S{length}")
assert np.array(obj, dtype="S").dtype == expected
assert np.array([obj], dtype="S").dtype == expected
# A nested array is also discovered correctly
arr = np.array(obj, dtype="O")
assert np.array(arr, dtype="S").dtype == expected
# Also if we use the dtype class
assert np.array(arr, dtype=type(expected)).dtype == expected
# Check that .astype() behaves identical
assert arr.astype("S").dtype == expected
# The DType class is accepted by `.astype()`
assert arr.astype(type(np.dtype("S"))).dtype == expected
@pytest.mark.parametrize("obj",
[object(), 1.2, 10**43, None, "string"],
ids=["object", "1.2", "10**43", "None", "string"])
def test_nested_arrays_stringlength(self, obj):
length = len(str(obj))
expected = np.dtype(f"S{length}")
arr = np.array(obj, dtype="O")
assert np.array([arr, arr], dtype="S").dtype == expected
@pytest.mark.parametrize("arraylike", arraylikes())
def test_unpack_first_level(self, arraylike):
# We unpack exactly one level of array likes
obj = np.array([None])
obj[0] = np.array(1.2)
# the length of the included item, not of the float dtype
length = len(str(obj[0]))
expected = np.dtype(f"S{length}")
obj = arraylike(obj)
# casting to string usually calls str(obj)
arr = np.array([obj], dtype="S")
assert arr.shape == (1, 1)
assert arr.dtype == expected
| TestStringDiscovery |
python | google__jax | jax/_src/custom_transpose.py | {
"start": 1535,
"end": 2247
} | class ____(lu.Store):
"""Stores an unchanging value. Checks empty reads and unequal overwrites."""
def store(self, val):
if self._val is not lu._EMPTY_STORE_VALUE and val != self._val:
raise lu.StoreException(
f"Store assignment mismatch, from {self._val} to {val}")
self._val = val
@util.curry
def transformation_with_aux(
gen, fun: lu.WrappedFun, *gen_static_args) -> tuple[lu.WrappedFun, Any]:
out_store = StoreEqual()
out_thunk = lambda: out_store.val
return fun.wrap(gen, gen_static_args, out_store), out_thunk
flatten_fun_nokwargs = transformation_with_aux(
api_util.flatten_fun_nokwargs.args[0])
### api
@custom_api_util.register_custom_decorator_type
| StoreEqual |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_snippets.py | {
"start": 20698,
"end": 21629
} | class ____(util.MdCase):
"""Test snippet file case."""
extension = [
'pymdownx.snippets',
]
extension_configs = {
'pymdownx.snippets': {
'base_path': [os.path.join(BASE, '_snippets')]
}
}
def test_top_level(self):
"""Test top level."""
self.check_markdown(
R'''
--8<-- "not-here.txt"
''',
'''
''',
True
)
def test_nested(self):
"""Test nested."""
self.check_markdown(
R'''
--8<-- "missing.txt"
''',
'''
''',
True
)
def test_missing_lines(self):
"""Test missing file with lines."""
self.check_markdown(
R'''
--8<-- ":3:4"
''',
'''
''',
True
)
| TestSnippetsGracefulMissing |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py | {
"start": 17771,
"end": 20707
} | class ____:
@staticmethod
def make_mock_awaitable(mock_obj, result=None):
f = Future()
f.set_result(result)
mock_obj.return_value = f
@pytest.fixture
def async_hook(self):
return GKEKubernetesAsyncHook(
cluster_url=CLUSTER_URL,
ssl_ca_cert=SSL_CA_CERT,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATE_CHAIN,
)
@pytest.mark.asyncio
@mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_conn"))
@mock.patch(GKE_STRING.format("async_client.CoreV1Api.read_namespaced_pod"))
async def test_get_pod(self, read_namespace_pod_mock, get_conn_mock, async_hook):
self.make_mock_awaitable(read_namespace_pod_mock)
await async_hook.get_pod(name=POD_NAME, namespace=POD_NAMESPACE)
get_conn_mock.assert_called_once_with()
read_namespace_pod_mock.assert_called_with(
name=POD_NAME,
namespace=POD_NAMESPACE,
)
@pytest.mark.asyncio
@mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_conn"))
@mock.patch(GKE_STRING.format("async_client.CoreV1Api.delete_namespaced_pod"))
async def test_delete_pod(self, delete_namespaced_pod, get_conn_mock, async_hook):
self.make_mock_awaitable(delete_namespaced_pod)
await async_hook.delete_pod(name=POD_NAME, namespace=POD_NAMESPACE)
get_conn_mock.assert_called_once_with()
delete_namespaced_pod.assert_called_with(
name=POD_NAME,
namespace=POD_NAMESPACE,
body=kubernetes.client.V1DeleteOptions(),
)
@pytest.mark.asyncio
@mock.patch(GKE_STRING.format("GKEKubernetesAsyncHook.get_conn"))
@mock.patch(GKE_STRING.format("async_client.CoreV1Api.read_namespaced_pod_log"))
async def test_read_logs(self, read_namespaced_pod_log, get_conn_mock, async_hook, caplog):
caplog.set_level(logging.INFO)
self.make_mock_awaitable(read_namespaced_pod_log, result="Test string #1\nTest string #2\n")
logs = await async_hook.read_logs(name=POD_NAME, namespace=POD_NAMESPACE)
get_conn_mock.assert_called_once_with()
read_namespaced_pod_log.assert_called_with(
name=POD_NAME,
namespace=POD_NAMESPACE,
follow=False,
timestamps=True,
container=None,
since_seconds=None,
)
assert "Test string #1" in logs
assert "Test string #2" in logs
@pytest_asyncio.fixture
async def async_gke_hook():
return GKEAsyncHook(
gcp_conn_id=GCP_CONN_ID,
location=GKE_ZONE,
impersonation_chain=IMPERSONATE_CHAIN,
)
@pytest_asyncio.fixture
async def mock_async_gke_cluster_client():
f = Future()
f.set_result(None)
client = mock.MagicMock(spec=ClusterManagerAsyncClient)
client.get_operation.return_value = f
return client
| TestGKEKubernetesAsyncHook |
python | kamyu104__LeetCode-Solutions | Python/count-valid-paths-in-a-tree.py | {
"start": 3657,
"end": 4489
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.size = [1]*n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
self.set[stk.pop()] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return False
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
self.set[x] = self.set[y]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
self.size[y] += self.size[x]
return True
def total(self, x):
return self.size[self.find_set(x)]
| UnionFind |
python | pytorch__pytorch | test/dynamo/test_generator.py | {
"start": 24948,
"end": 25970
} | class ____(GeneratorTestsBase):
def test_send(self):
def double():
x = yield
yield x * 2
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = double()
next(gen)
return gen.send(t)
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, t * 2)
@parametrize("fullgraph", [True, False])
def test_send_stop_iteration(self, fullgraph):
def double():
x = yield
yield x * 2
@torch.compile(backend="eager", fullgraph=fullgraph)
def fn(t):
gen = double()
next(gen)
a = gen.send(t)
b = gen.send(t) # should result in StopIteration
return a + b
t = torch.randn(2)
if fullgraph:
with self.assertRaisesRegex(Unsupported, "Observed exception"):
fn(t)
else:
with self.assertRaises(StopIteration):
fn(t)
| TestGeneratorSend |
python | modin-project__modin | versioneer.py | {
"start": 14658,
"end": 19336
} | class ____:
"""Container for Versioneer configuration parameters."""
VCS: str
style: str
tag_prefix: str
versionfile_source: str
versionfile_build: Optional[str]
parentdir_prefix: Optional[str]
verbose: Optional[bool]
def get_root() -> str:
"""Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py .
"""
root = os.path.realpath(os.path.abspath(os.getcwd()))
setup_py = os.path.join(root, "setup.py")
pyproject_toml = os.path.join(root, "pyproject.toml")
versioneer_py = os.path.join(root, "versioneer.py")
if not (
os.path.exists(setup_py)
or os.path.exists(pyproject_toml)
or os.path.exists(versioneer_py)
):
# allow 'python path/to/setup.py COMMAND'
root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
setup_py = os.path.join(root, "setup.py")
pyproject_toml = os.path.join(root, "pyproject.toml")
versioneer_py = os.path.join(root, "versioneer.py")
if not (
os.path.exists(setup_py)
or os.path.exists(pyproject_toml)
or os.path.exists(versioneer_py)
):
err = (
"Versioneer was unable to run the project root directory. "
"Versioneer requires setup.py to be executed from "
"its immediate directory (like 'python setup.py COMMAND'), "
"or in a way that lets it use sys.argv[0] to find the root "
"(like 'python path/to/setup.py COMMAND')."
)
raise VersioneerBadRootError(err)
try:
# Certain runtime workflows (setup.py install/develop in a setuptools
# tree) execute all dependencies in a single python process, so
# "versioneer" may be imported multiple times, and python's shared
# module-import table will cache the first one. So we can't use
# os.path.dirname(__file__), as that will find whichever
# versioneer.py was first imported, even in later projects.
my_path = os.path.realpath(os.path.abspath(__file__))
me_dir = os.path.normcase(os.path.splitext(my_path)[0])
vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
print(
"Warning: build in %s is using versioneer.py from %s"
% (os.path.dirname(my_path), versioneer_py)
)
except NameError:
pass
return root
def get_config_from_root(root: str) -> VersioneerConfig:
"""Read the project setup.cfg file to determine Versioneer config."""
# This might raise OSError (if setup.cfg is missing), or
# configparser.NoSectionError (if it lacks a [versioneer] section), or
# configparser.NoOptionError (if it lacks "VCS="). See the docstring at
# the top of versioneer.py for instructions on writing your setup.cfg .
root_pth = Path(root)
pyproject_toml = root_pth / "pyproject.toml"
setup_cfg = root_pth / "setup.cfg"
section: Union[Dict[str, Any], configparser.SectionProxy, None] = None
if pyproject_toml.exists() and have_tomllib:
try:
with open(pyproject_toml, "rb") as fobj:
pp = tomllib.load(fobj)
section = pp["tool"]["versioneer"]
except (tomllib.TOMLDecodeError, KeyError) as e:
print(f"Failed to load config from {pyproject_toml}: {e}")
print("Try to load it from setup.cfg")
if not section:
parser = configparser.ConfigParser()
with open(setup_cfg) as cfg_file:
parser.read_file(cfg_file)
parser.get("versioneer", "VCS") # raise error if missing
section = parser["versioneer"]
# `cast`` really shouldn't be used, but its simplest for the
# common VersioneerConfig users at the moment. We verify against
# `None` values elsewhere where it matters
cfg = VersioneerConfig()
cfg.VCS = section["VCS"]
cfg.style = section.get("style", "")
cfg.versionfile_source = cast(str, section.get("versionfile_source"))
cfg.versionfile_build = section.get("versionfile_build")
cfg.tag_prefix = cast(str, section.get("tag_prefix"))
if cfg.tag_prefix in ("''", '""', None):
cfg.tag_prefix = ""
cfg.parentdir_prefix = section.get("parentdir_prefix")
if isinstance(section, configparser.SectionProxy):
# Make sure configparser translates to bool
cfg.verbose = section.getboolean("verbose")
else:
cfg.verbose = section.get("verbose")
return cfg
| VersioneerConfig |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 6931,
"end": 7587
} | class ____(BaseModel):
action: ShellCallAction
"""The shell commands and limits that describe how to run the tool call."""
call_id: str
"""The unique ID of the function shell tool call generated by the model."""
type: Literal["shell_call"]
"""The type of the item. Always `function_shell_call`."""
id: Optional[str] = None
"""The unique ID of the function shell tool call.
Populated when this item is returned via API.
"""
status: Optional[Literal["in_progress", "completed", "incomplete"]] = None
"""The status of the shell call.
One of `in_progress`, `completed`, or `incomplete`.
"""
| ShellCall |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 58938,
"end": 60640
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
host: str,
port: int,
database: str,
username: str,
password: Optional[str] = None,
jdbc_url_params: Optional[str] = None,
ssl: Optional[bool] = None,
):
"""Airbyte Source for Clickhouse.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/clickhouse
Args:
name (str): The name of the destination.
host (str): The host endpoint of the Clickhouse cluster.
port (int): The port of the database.
database (str): The name of the database.
username (str): The username which is used to access the database.
password (Optional[str]): The password associated with this username.
jdbc_url_params (Optional[str]): Additional properties to pass to the JDBC URL string when connecting to the database formatted as 'key=value' pairs separated by the symbol '&'. (Eg. key1=value1&key2=value2&key3=value3). For more information read about JDBC URL parameters.
ssl (Optional[bool]): Encrypt data using SSL.
"""
self.host = check.str_param(host, "host")
self.port = check.int_param(port, "port")
self.database = check.str_param(database, "database")
self.username = check.str_param(username, "username")
self.password = check.opt_str_param(password, "password")
self.jdbc_url_params = check.opt_str_param(jdbc_url_params, "jdbc_url_params")
self.ssl = check.opt_bool_param(ssl, "ssl")
super().__init__("Clickhouse", name)
| ClickhouseSource |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_variables.py | {
"start": 1220,
"end": 3144
} | class ____:
@pytest.mark.parametrize(
("deserialize_json", "value", "expected_value"),
[
pytest.param(
False,
"my_value",
"my_value",
id="simple-value",
),
pytest.param(
True,
'{"key": "value", "number": 42, "flag": true}',
{"key": "value", "number": 42, "flag": True},
id="deser-object-value",
),
],
)
def test_var_get(self, deserialize_json, value, expected_value, mock_supervisor_comms):
var_result = VariableResult(key="my_key", value=value)
mock_supervisor_comms.send.return_value = var_result
var = Variable.get(key="my_key", deserialize_json=deserialize_json)
assert var is not None
assert var == expected_value
@pytest.mark.parametrize(
("key", "value", "description", "serialize_json"),
[
pytest.param(
"key",
"value",
"description",
False,
id="simple-value",
),
pytest.param(
"key2",
{"hi": "there", "hello": 42, "flag": True},
"description2",
True,
id="serialize-json-value",
),
],
)
def test_var_set(self, key, value, description, serialize_json, mock_supervisor_comms):
Variable.set(key=key, value=value, description=description, serialize_json=serialize_json)
expected_value = value
if serialize_json:
expected_value = json.dumps(value, indent=2)
mock_supervisor_comms.send.assert_called_once_with(
msg=PutVariable(
key=key, value=expected_value, description=description, serialize_json=serialize_json
),
)
| TestVariables |
python | pytorch__pytorch | torch/_inductor/sizevars.py | {
"start": 46184,
"end": 47285
} | class ____(V.WrapperHandler): # type: ignore[name-defined]
"""
A wrapper around .virtualize.ops that uses var range information to
simplify ModularIndexing/FloorDiv.
"""
def __init__(self, inner, var_ranges: VarRanges) -> None:
super().__init__(inner)
self.name = "SimplifyIndexing"
self._simplify: Callable[[Expr], Expr] = (
lambda index: V.graph.sizevars.simplify_with_ranges(index, var_ranges)
)
def load(self, name: str, index: sympy.Expr):
return self._inner.load(name, self._simplify(index))
def store(self, name, index, value, mode=None):
return self._inner.store(name, self._simplify(index), value, mode=mode)
def store_reduction(self, name, index, value):
return self._inner.store_reduction(name, self._simplify(index), value)
def index_expr(self, index, dtype):
return self._inner.index_expr(self._simplify(index), dtype)
def check_bounds(self, index, size, lower, upper):
return self._inner.check_bounds(self._simplify(index), size, lower, upper)
| SimplifyIndexing |
python | justquick__django-activity-stream | actstream/drf/serializers.py | {
"start": 3099,
"end": 3390
} | class ____(DEFAULT_SERIALIZER):
"""
Serializer for actstream.Follow models in the activity feeds
"""
user = get_grf()
follow_object = get_grf()
class Meta:
model = Follow
fields = 'id flag user follow_object started actor_only'.split()
| FollowSerializer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/mem_io_manager.py | {
"start": 228,
"end": 1135
} | class ____(IOManager):
"""I/O manager that stores and retrieves values in memory. After execution is complete, the values will
be garbage-collected. Note that this means that each run will not have access to values from previous runs.
"""
def __init__(self):
self.values: dict[tuple[object, ...], object] = {}
def handle_output(self, context: OutputContext, obj: object):
keys = tuple(context.get_identifier())
self.values[keys] = obj
def load_input(self, context: InputContext) -> object:
keys = tuple(context.get_identifier())
return self.values[keys]
@dagster_maintained_io_manager
@io_manager(description="Built-in IO manager that stores and retrieves values in memory.")
def mem_io_manager(_) -> InMemoryIOManager:
"""Built-in IO manager that stores and retrieves values in memory."""
return InMemoryIOManager()
| InMemoryIOManager |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 5024,
"end": 5364
} | class ____(CtrlNode):
"""Filters data by taking the mode (histogram-based) of a sliding window"""
nodeName = 'ModeFilter'
uiTemplate = [
('window', 'intSpin', {'value': 500, 'min': 1, 'max': 1000000}),
]
def processData(self, data):
return functions.modeFilter(data, self.ctrls['window'].value())
| Mode |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 36520,
"end": 37608
} | class ____(BaseAPIIntegrationTest):
def test_diff(self):
container = self.client.create_container(TEST_IMG, ['touch', '/test'])
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exitcode = self.client.wait(id)['StatusCode']
assert exitcode == 0
diff = self.client.diff(id)
test_diff = [x for x in diff if x.get('Path', None) == '/test']
assert len(test_diff) == 1
assert 'Kind' in test_diff[0]
assert test_diff[0]['Kind'] == 1
def test_diff_with_dict_instead_of_id(self):
container = self.client.create_container(TEST_IMG, ['touch', '/test'])
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exitcode = self.client.wait(id)['StatusCode']
assert exitcode == 0
diff = self.client.diff(container)
test_diff = [x for x in diff if x.get('Path', None) == '/test']
assert len(test_diff) == 1
assert 'Kind' in test_diff[0]
assert test_diff[0]['Kind'] == 1
| DiffTest |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 11936,
"end": 12946
} | class ____(URLPatternsTestCase, APITestCase):
included = [
path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
]
urlpatterns = [
path('v1/', include((included, 'v1'), namespace='v1')),
path('v2/', include((included, 'v2'), namespace='v2'))
]
def setUp(self):
super().setUp()
class MockQueryset:
def get(self, pk):
return 'object %s' % pk
self.field = serializers.HyperlinkedRelatedField(
view_name='namespaced',
queryset=MockQueryset()
)
request = factory.get('/')
request.versioning_scheme = NamespaceVersioning()
request.version = 'v1'
self.field._context = {'request': request}
def test_bug_2489(self):
assert self.field.to_internal_value('/v1/namespaced/3/') == 'object 3'
with pytest.raises(serializers.ValidationError):
self.field.to_internal_value('/v2/namespaced/3/')
| TestHyperlinkedRelatedField |
python | PrefectHQ__prefect | tests/test_settings.py | {
"start": 59000,
"end": 60674
} | class ____:
def test_temporary_settings(self):
assert PREFECT_TEST_MODE.value() is True
with temporary_settings(updates={PREFECT_TEST_MODE: False}) as new_settings:
assert PREFECT_TEST_MODE.value_from(new_settings) is False, (
"Yields the new settings"
)
assert PREFECT_TEST_MODE.value() is False
assert PREFECT_TEST_MODE.value() is True
def test_temporary_settings_does_not_mark_unset_as_set(self):
settings = get_current_settings()
set_keys = set(settings.model_dump(exclude_unset=True).keys())
with temporary_settings() as new_settings:
pass
new_set_keys = set(new_settings.model_dump(exclude_unset=True).keys())
assert new_set_keys == set_keys
def test_temporary_settings_can_restore_to_defaults_values(self):
with temporary_settings(updates={PREFECT_API_DATABASE_PORT: 9001}):
assert PREFECT_API_DATABASE_PORT.value() == 9001
with temporary_settings(restore_defaults={PREFECT_API_DATABASE_PORT}):
assert (
PREFECT_API_DATABASE_PORT.value()
== PREFECT_API_DATABASE_PORT.default()
)
def test_temporary_settings_restores_on_error(self):
assert PREFECT_TEST_MODE.value() is True
with pytest.raises(ValueError):
with temporary_settings(updates={PREFECT_TEST_MODE: False}):
raise ValueError()
assert os.environ["PREFECT_TESTING_TEST_MODE"] == "1", (
"Does not alter os environ."
)
assert PREFECT_TEST_MODE.value() is True
| TestTemporarySettings |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/string_lower_op_test.py | {
"start": 838,
"end": 1908
} | class ____(test.TestCase):
"""Test cases for tf.strings.lower."""
def test_string_lower(self):
strings = ["Pigs on The Wing", "aNimals"]
with self.cached_session():
output = string_ops.string_lower(strings)
output = self.evaluate(output)
self.assertAllEqual(output, [b"pigs on the wing", b"animals"])
def test_string_lower_2d(self):
strings = [["pigS on THE wIng", "aniMals"], [" hello ", "\n\tWorld! \r \n"]]
with self.cached_session():
output = string_ops.string_lower(strings)
output = self.evaluate(output)
self.assertAllEqual(output, [[b"pigs on the wing", b"animals"],
[b" hello ", b"\n\tworld! \r \n"]])
def test_string_upper_unicode(self):
strings = [["ÓÓSSCHLOË"]]
with self.cached_session():
output = string_ops.string_lower(strings, encoding="utf-8")
output = self.evaluate(output)
# output: "óósschloë"
self.assertAllEqual(output, [[b"\xc3\xb3\xc3\xb3sschlo\xc3\xab"]])
if __name__ == "__main__":
test.main()
| StringLowerOpTest |
python | pytorch__pytorch | test/dynamo/test_backward_higher_order_ops.py | {
"start": 1957,
"end": 2670
} | class ____(torch.nn.Module):
def forward(self, grad_1: "f32[2]"):
trace_wrapped: "f32[2]" = torch__dynamo__trace_wrapped_higher_order_op_self_invoke(grad_1); grad_1 = None
return trace_wrapped
""",
)
def test_invoke_make_bw(self):
x = torch.tensor([0.5, 0.5], requires_grad=True)
def fwd(x):
z = x * x
return z + z
res = fwd(x)
res.backward(torch.tensor([1.0, 1.0]))
out = make_fx(_multiply_invoke)(x.grad)
self.assertEqual(out(x.grad), torch.tensor([4.0, 4.0]))
actual = normalize_gm(out.print_readable(False))
self.assertExpectedInline(
actual,
"""\
| _multiply_invoke |
python | networkx__networkx | networkx/classes/tests/test_multigraph.py | {
"start": 205,
"end": 5848
} | class ____(BaseAttrGraphTester):
def test_has_edge(self):
G = self.K3
assert G.has_edge(0, 1)
assert not G.has_edge(0, -1)
assert G.has_edge(0, 1, 0)
assert not G.has_edge(0, 1, 1)
def test_get_edge_data(self):
G = self.K3
assert G.get_edge_data(0, 1) == {0: {}}
assert G[0][1] == {0: {}}
assert G[0][1][0] == {}
assert G.get_edge_data(10, 20) is None
assert G.get_edge_data(0, 1, 0) == {}
def test_adjacency(self):
G = self.K3
assert dict(G.adjacency()) == {
0: {1: {0: {}}, 2: {0: {}}},
1: {0: {0: {}}, 2: {0: {}}},
2: {0: {0: {}}, 1: {0: {}}},
}
def deepcopy_edge_attr(self, H, G):
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
G[1][2][0]["foo"].append(1)
assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
def shallow_copy_edge_attr(self, H, G):
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
G[1][2][0]["foo"].append(1)
assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
def graphs_equal(self, H, G):
assert G._adj == H._adj
assert G._node == H._node
assert G.graph == H.graph
assert G.name == H.name
if not G.is_directed() and not H.is_directed():
assert H._adj[1][2][0] is H._adj[2][1][0]
assert G._adj[1][2][0] is G._adj[2][1][0]
else: # at least one is directed
if not G.is_directed():
G._pred = G._adj
G._succ = G._adj
if not H.is_directed():
H._pred = H._adj
H._succ = H._adj
assert G._pred == H._pred
assert G._succ == H._succ
assert H._succ[1][2][0] is H._pred[2][1][0]
assert G._succ[1][2][0] is G._pred[2][1][0]
def same_attrdict(self, H, G):
# same attrdict in the edgedata
old_foo = H[1][2][0]["foo"]
H.adj[1][2][0]["foo"] = "baz"
assert G._adj == H._adj
H.adj[1][2][0]["foo"] = old_foo
assert G._adj == H._adj
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G._node == H._node
H.nodes[0]["foo"] = old_foo
assert G._node == H._node
def different_attrdict(self, H, G):
# used by graph_equal_but_different
old_foo = H[1][2][0]["foo"]
H.adj[1][2][0]["foo"] = "baz"
assert G._adj != H._adj
H.adj[1][2][0]["foo"] = old_foo
assert G._adj == H._adj
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G._node != H._node
H.nodes[0]["foo"] = old_foo
assert G._node == H._node
def test_to_undirected(self):
G = self.K3
self.add_attributes(G)
H = nx.MultiGraph(G)
self.is_shallow_copy(H, G)
H = G.to_undirected()
self.is_deepcopy(H, G)
def test_to_directed(self):
G = self.K3
self.add_attributes(G)
H = nx.MultiDiGraph(G)
self.is_shallow_copy(H, G)
H = G.to_directed()
self.is_deepcopy(H, G)
def test_number_of_edges_selfloops(self):
G = self.K3
G.add_edge(0, 0)
G.add_edge(0, 0)
G.add_edge(0, 0, key="parallel edge")
G.remove_edge(0, 0, key="parallel edge")
assert G.number_of_edges(0, 0) == 2
G.remove_edge(0, 0)
assert G.number_of_edges(0, 0) == 1
def test_edge_lookup(self):
G = self.Graph()
G.add_edge(1, 2, foo="bar")
G.add_edge(1, 2, "key", foo="biz")
assert edges_equal(G.edges[1, 2, 0], {"foo": "bar"})
assert edges_equal(G.edges[1, 2, "key"], {"foo": "biz"})
def test_edge_attr(self):
G = self.Graph()
G.add_edge(1, 2, key="k1", foo="bar")
G.add_edge(1, 2, key="k2", foo="baz")
assert isinstance(G.get_edge_data(1, 2), G.edge_key_dict_factory)
assert all(
isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
)
assert edges_equal(
G.edges(keys=True, data=True),
[(1, 2, "k1", {"foo": "bar"}), (1, 2, "k2", {"foo": "baz"})],
)
assert edges_equal(
G.edges(keys=True, data="foo"), [(1, 2, "k1", "bar"), (1, 2, "k2", "baz")]
)
def test_edge_attr4(self):
G = self.Graph()
G.add_edge(1, 2, key=0, data=7, spam="bar", bar="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
)
G[1][2][0]["data"] = 10 # OK to set data like this
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2][0]["data"] = 20
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
)
G.edges[1, 2, 0]["data"] = 21 # another spelling, "edge"
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2][0]["listdata"] = [20, 200]
G.adj[1][2][0]["weight"] = 20
assert edges_equal(
G.edges(data=True),
[
(
1,
2,
{
"data": 21,
"spam": "bar",
"bar": "foo",
"listdata": [20, 200],
"weight": 20,
},
)
],
)
| BaseMultiGraphTester |
python | doocs__leetcode | solution/0600-0699/0658.Find K Closest Elements/Solution2.py | {
"start": 0,
"end": 281
} | class ____:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr)
while r - l > k:
if x - arr[l] <= arr[r - 1] - x:
r -= 1
else:
l += 1
return arr[l:r]
| Solution |
python | google__pytype | pytype/rewrite/abstract/base.py | {
"start": 608,
"end": 2404
} | class ____(types.BaseValue, abc.ABC):
"""Base class for abstract values."""
# For convenience, we want the 'name' attribute to be available on all values.
# Setting it as a class attribute gives subclasses the most flexibility in how
# to define it.
name = ''
def __init__(self, ctx: ContextType):
self._ctx = ctx
@abc.abstractmethod
def __repr__(self):
...
@property
@abc.abstractmethod
def _attrs(self) -> tuple[Any, ...]:
"""This object's identifying attributes.
Used for equality comparisons and hashing. Should return a tuple of the
attributes needed to differentiate this object from others of the same type.
The attributes must be hashable. Do not include the type of `self` or
`self._ctx`.
"""
@property
def full_name(self):
return self.name
def __eq__(self, other):
return self.__class__ == other.__class__ and self._attrs == other._attrs
def __hash__(self):
return hash((self.__class__, self._ctx) + self._attrs)
def to_variable(self, name: str | None = None) -> variables.Variable[Self]:
return variables.Variable.from_value(self, name=name)
def get_attribute(self, name: str) -> Optional['BaseValue']:
del name # unused
return None
def set_attribute(self, name: str, value: 'BaseValue') -> None:
del name, value # unused
def instantiate(self) -> 'BaseValue':
"""Creates an instance of this value."""
raise ValueError(f'{self!r} is not instantiable')
def to_pytd_def(self) -> pytd.Node:
return self._ctx.pytd_converter.to_pytd_def(self)
def to_pytd_type(self) -> pytd.Type:
return self._ctx.pytd_converter.to_pytd_type(self)
def to_pytd_type_of_instance(self) -> pytd.Type:
return self._ctx.pytd_converter.to_pytd_type_of_instance(self)
| BaseValue |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-wordlift/llama_index/readers/wordlift/base.py | {
"start": 596,
"end": 819
} | class ____(WordLiftLoaderError):
"""Exception raised for errors in data transformation."""
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message)
| DataTransformError |
python | encode__starlette | tests/middleware/test_base.py | {
"start": 911,
"end": 1597
} | class ____(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
response = await call_next(request)
response.headers["Custom-Header"] = "Example"
return response
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage")
def exc(request: Request) -> None:
raise Exception("Exc")
def exc_stream(request: Request) -> StreamingResponse:
return StreamingResponse(_generate_faulty_stream())
def _generate_faulty_stream() -> Generator[bytes, None, None]:
yield b"Ok"
raise Exception("Faulty Stream")
| CustomMiddleware |
python | Lightning-AI__lightning | src/lightning/fabric/_graveyard/tpu.py | {
"start": 2823,
"end": 3243
} | class ____(XLAPrecision):
"""Legacy class.
Use :class:`~lightning.fabric.plugins.precision.xla.XLAPrecision` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation(
"The `XLABf16Precision` class is deprecated. Use `lightning.fabric.plugins.precision.XLAPrecision` instead."
)
super().__init__(precision="bf16-true")
| XLABf16Precision |
python | mlflow__mlflow | mlflow/pyfunc/__init__.py | {
"start": 26848,
"end": 46676
} | class ____:
"""
MLflow 'python function' model.
Wrapper around model implementation and metadata. This class is not meant to be constructed
directly. Instead, instances of this class are constructed and returned from
:py:func:`load_model() <mlflow.pyfunc.load_model>`.
``model_impl`` can be any Python object that implements the `Pyfunc interface
<https://mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#pyfunc-inference-api>`_, and is
returned by invoking the model's ``loader_module``.
``model_meta`` contains model metadata loaded from the MLmodel file.
"""
def __init__(
self,
model_meta: Model,
model_impl: Any,
predict_fn: str = "predict",
predict_stream_fn: str | None = None,
model_id: str | None = None,
):
if not hasattr(model_impl, predict_fn):
raise MlflowException(f"Model implementation is missing required {predict_fn} method.")
if not model_meta:
raise MlflowException("Model is missing metadata.")
self._model_meta = model_meta
self.__model_impl = model_impl
self._predict_fn = getattr(model_impl, predict_fn)
if predict_stream_fn:
if not hasattr(model_impl, predict_stream_fn):
raise MlflowException(
f"Model implementation is missing required {predict_stream_fn} method."
)
self._predict_stream_fn = getattr(model_impl, predict_stream_fn)
else:
self._predict_stream_fn = None
self._model_id = model_id
self._input_example = None
@property
@developer_stable
def _model_impl(self) -> Any:
"""
The underlying model implementation object.
NOTE: This is a stable developer API.
"""
return self.__model_impl
@property
def model_id(self) -> str | None:
"""
The model ID of the model.
Returns:
The model ID of the model.
"""
return self._model_id
def _update_dependencies_schemas_in_prediction_context(self, context: Context):
if self._model_meta and self._model_meta.metadata:
dependencies_schemas = self._model_meta.metadata.get("dependencies_schemas", {})
context.update(
dependencies_schemas={
dependency: json.dumps(schema)
for dependency, schema in dependencies_schemas.items()
}
)
@property
def input_example(self) -> Any | None:
"""
The input example provided when the model was saved.
"""
return self._input_example
@input_example.setter
def input_example(self, value: Any) -> None:
self._input_example = value
def predict(self, data: PyFuncInput, params: dict[str, Any] | None = None) -> PyFuncOutput:
context = _try_get_prediction_context() or Context()
with set_prediction_context(context):
if schema := _get_dependencies_schema_from_model(self._model_meta):
context.update(**schema)
if self.model_id:
context.update(model_id=self.model_id)
return self._predict(data, params)
def _predict(self, data: PyFuncInput, params: dict[str, Any] | None = None) -> PyFuncOutput:
"""
Generates model predictions.
If the model contains signature, enforce the input schema first before calling the model
implementation with the sanitized input. If the pyfunc model does not include model schema,
the input is passed to the model implementation as is. See `Model Signature Enforcement
<https://www.mlflow.org/docs/latest/models.html#signature-enforcement>`_ for more details.
Args:
data: LLM Model single input as one of pandas.DataFrame, numpy.ndarray,
scipy.sparse.(csc_matrix | csr_matrix), List[Any], or
Dict[str, numpy.ndarray].
For model signatures with tensor spec inputs
(e.g. the Tensorflow core / Keras model), the input data type must be one of
`numpy.ndarray`, `List[numpy.ndarray]`, `Dict[str, numpy.ndarray]` or
`pandas.DataFrame`. If data is of `pandas.DataFrame` type and the model
contains a signature with tensor spec inputs, the corresponding column values
in the pandas DataFrame will be reshaped to the required shape with 'C' order
(i.e. read / write the elements using C-like index order), and DataFrame
column values will be cast as the required tensor spec type. For Pyspark
DataFrame inputs, MLflow will only enforce the schema on a subset
of the data rows.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions as one of pandas.DataFrame, pandas.Series, numpy.ndarray or list.
"""
# fetch the schema from metadata to avoid signature change after model is loaded
self.input_schema = self.metadata.get_input_schema()
self.params_schema = self.metadata.get_params_schema()
# signature can only be inferred from type hints if the model is PythonModel
if self.metadata._is_signature_from_type_hint():
# we don't need to validate on data as data validation
# will be done during PythonModel's predict call
params = _enforce_params_schema(params, self.params_schema)
else:
data, params = _validate_prediction_input(
data, params, self.input_schema, self.params_schema, self.loader_module
)
if (
isinstance(data, pandas.DataFrame)
and self.metadata._is_type_hint_from_example()
and self.input_example is not None
):
data = _convert_dataframe_to_example_format(data, self.input_example)
params_arg = inspect.signature(self._predict_fn).parameters.get("params")
if params_arg and params_arg.kind != inspect.Parameter.VAR_KEYWORD:
return self._predict_fn(data, params=params)
_log_warning_if_params_not_in_predict_signature(_logger, params)
return self._predict_fn(data)
def predict_stream(
self, data: PyFuncLLMSingleInput, params: dict[str, Any] | None = None
) -> Iterator[PyFuncLLMOutputChunk]:
context = _try_get_prediction_context() or Context()
if schema := _get_dependencies_schema_from_model(self._model_meta):
context.update(**schema)
if self.model_id:
context.update(model_id=self.model_id)
# NB: The prediction context must be applied during iterating over the stream,
# hence, simply wrapping the self._predict_stream call with the context manager
# is not sufficient.
def _gen_with_context(*args, **kwargs):
with set_prediction_context(context):
yield from self._predict_stream(*args, **kwargs)
return _gen_with_context(data, params)
def _predict_stream(
self, data: PyFuncLLMSingleInput, params: dict[str, Any] | None = None
) -> Iterator[PyFuncLLMOutputChunk]:
"""
Generates streaming model predictions. Only LLM supports this method.
If the model contains signature, enforce the input schema first before calling the model
implementation with the sanitized input. If the pyfunc model does not include model schema,
the input is passed to the model implementation as is. See `Model Signature Enforcement
<https://www.mlflow.org/docs/latest/models.html#signature-enforcement>`_ for more details.
Args:
data: LLM Model single input as one of dict, str, bool, bytes, float, int, str type.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions as an iterator of chunks. The chunks in the iterator must be type of
dict or string. Chunk dict fields are determined by the model implementation.
"""
if self._predict_stream_fn is None:
raise MlflowException("This model does not support predict_stream method.")
self.input_schema = self.metadata.get_input_schema()
self.params_schema = self.metadata.get_params_schema()
data, params = _validate_prediction_input(
data, params, self.input_schema, self.params_schema, self.loader_module
)
data = _convert_llm_input_data(data)
if isinstance(data, list):
# `predict_stream` only accepts single input.
# but `enforce_schema` might convert single input into a list like `[single_input]`
# so extract the first element in the list.
if len(data) != 1:
raise MlflowException(
f"'predict_stream' requires single input, but it got input data {data}"
)
data = data[0]
if "params" in inspect.signature(self._predict_stream_fn).parameters:
return self._predict_stream_fn(data, params=params)
_log_warning_if_params_not_in_predict_signature(_logger, params)
return self._predict_stream_fn(data)
def unwrap_python_model(self):
"""
Unwrap the underlying Python model object.
This method is useful for accessing custom model functions, while still being able to
leverage the MLflow designed workflow through the `predict()` method.
Returns:
The underlying wrapped model object
.. code-block:: python
:test:
:caption: Example
import mlflow
# define a custom model
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return self.my_custom_function(model_input, params)
def my_custom_function(self, model_input, params=None):
# do something with the model input
return 0
some_input = 1
# save the model
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(name="model", python_model=MyModel())
# load the model
loaded_model = mlflow.pyfunc.load_model(model_uri=model_info.model_uri)
print(type(loaded_model)) # <class 'mlflow.pyfunc.model.PyFuncModel'>
unwrapped_model = loaded_model.unwrap_python_model()
print(type(unwrapped_model)) # <class '__main__.MyModel'>
# does not work, only predict() is exposed
# print(loaded_model.my_custom_function(some_input))
print(unwrapped_model.my_custom_function(some_input)) # works
print(loaded_model.predict(some_input)) # works
# works, but None is needed for context arg
print(unwrapped_model.predict(None, some_input))
"""
try:
python_model = self._model_impl.python_model
if python_model is None:
raise AttributeError("Expected python_model attribute not to be None.")
except AttributeError as e:
raise MlflowException("Unable to retrieve base model object from pyfunc.") from e
return python_model
def __eq__(self, other):
if not isinstance(other, PyFuncModel):
return False
return self._model_meta == other._model_meta
@property
def metadata(self) -> Model:
"""Model metadata."""
if self._model_meta is None:
raise MlflowException("Model is missing metadata.")
return self._model_meta
@property
def model_config(self):
"""Model's flavor configuration"""
return self._model_meta.flavors[FLAVOR_NAME].get(MODEL_CONFIG, {})
@property
def loader_module(self):
"""Model's flavor configuration"""
if self._model_meta.flavors.get(FLAVOR_NAME) is None:
return None
return self._model_meta.flavors[FLAVOR_NAME].get(MAIN)
def __repr__(self):
info = {}
if self._model_meta is not None:
if hasattr(self._model_meta, "run_id") and self._model_meta.run_id is not None:
info["run_id"] = self._model_meta.run_id
if (
hasattr(self._model_meta, "artifact_path")
and self._model_meta.artifact_path is not None
):
info["artifact_path"] = self._model_meta.artifact_path
info["flavor"] = self._model_meta.flavors[FLAVOR_NAME]["loader_module"]
return yaml.safe_dump({"mlflow.pyfunc.loaded_model": info}, default_flow_style=False)
def get_raw_model(self):
"""
Get the underlying raw model if the model wrapper implemented `get_raw_model` function.
"""
if hasattr(self._model_impl, "get_raw_model"):
return self._model_impl.get_raw_model()
raise NotImplementedError("`get_raw_model` is not implemented by the underlying model")
def _get_pip_requirements_from_model_path(model_path: str):
req_file_path = os.path.join(model_path, _REQUIREMENTS_FILE_NAME)
if not os.path.exists(req_file_path):
return []
return [req.req_str for req in _parse_requirements(req_file_path, is_constraint=False)]
@trace_disabled # Suppress traces while loading model
def load_model(
model_uri: str,
suppress_warnings: bool = False,
dst_path: str | None = None,
model_config: str | Path | dict[str, Any] | None = None,
) -> PyFuncModel:
"""
Load a model stored in Python function format.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
- ``models:/<model_name>/<model_version>``
- ``models:/<model_name>/<stage>``
- ``mlflow-artifacts:/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#
artifact-locations>`_.
suppress_warnings: If ``True``, non-fatal warning messages associated with the model
loading process will be suppressed. If ``False``, these warning messages will be
emitted.
dst_path: The local filesystem path to which to download the model artifact.
This directory must already exist. If unspecified, a local output
path will be created.
model_config: The model configuration to apply to the model. The configuration will
be available as the ``model_config`` property of the ``context`` parameter
in :func:`PythonModel.load_context() <mlflow.pyfunc.PythonModel.load_context>`
and :func:`PythonModel.predict() <mlflow.pyfunc.PythonModel.predict>`.
The configuration can be passed as a file path, or a dict with string keys.
.. Note:: Experimental: This parameter may change or be removed in a future
release without warning.
"""
lineage_header_info = None
if (
not _MLFLOW_IN_CAPTURE_MODULE_PROCESS.get()
) and databricks_utils.is_in_databricks_runtime():
entity_list = []
# Get notebook id and job id, pack them into lineage_header_info
if databricks_utils.is_in_databricks_notebook() and (
notebook_id := databricks_utils.get_notebook_id()
):
notebook_entity = Notebook(id=notebook_id)
entity_list.append(Entity(notebook=notebook_entity))
if databricks_utils.is_in_databricks_job() and (job_id := databricks_utils.get_job_id()):
job_entity = Job(id=job_id)
entity_list.append(Entity(job=job_entity))
lineage_header_info = LineageHeaderInfo(entities=entity_list) if entity_list else None
local_path = _download_artifact_from_uri(
artifact_uri=model_uri, output_path=dst_path, lineage_header_info=lineage_header_info
)
if not suppress_warnings:
model_requirements = _get_pip_requirements_from_model_path(local_path)
warn_dependency_requirement_mismatches(model_requirements)
model_meta = Model.load(os.path.join(local_path, MLMODEL_FILE_NAME))
if model_meta.metadata and model_meta.metadata.get(MLFLOW_MODEL_IS_EXTERNAL, False) is True:
raise MlflowException(
"This model's artifacts are external and are not stored in the model directory."
" This model cannot be loaded with MLflow.",
BAD_REQUEST,
)
conf = model_meta.flavors.get(FLAVOR_NAME)
if conf is None:
raise MlflowException(
f'Model does not have the "{FLAVOR_NAME}" flavor',
RESOURCE_DOES_NOT_EXIST,
)
model_py_version = conf.get(PY_VERSION)
if not suppress_warnings:
_warn_potentially_incompatible_py_version_if_necessary(model_py_version=model_py_version)
_add_code_from_conf_to_system_path(local_path, conf, code_key=CODE)
data_path = os.path.join(local_path, conf[DATA]) if (DATA in conf) else local_path
if isinstance(model_config, str):
model_config = _validate_and_get_model_config_from_file(model_config)
model_config = _get_overridden_pyfunc_model_config(
conf.get(MODEL_CONFIG, None), model_config, _logger
)
try:
if model_config:
model_impl = importlib.import_module(conf[MAIN])._load_pyfunc(data_path, model_config)
else:
model_impl = importlib.import_module(conf[MAIN])._load_pyfunc(data_path)
except ModuleNotFoundError as e:
# This error message is particularly for the case when the error is caused by module
# "databricks.feature_store.mlflow_model". But depending on the environment, the offending
# module might be "databricks", "databricks.feature_store" or full package. So we will
# raise the error with the following note if "databricks" presents in the error. All non-
# databricks module errors will just be re-raised.
if conf[MAIN] == _DATABRICKS_FS_LOADER_MODULE and e.name.startswith("databricks"):
raise MlflowException(
f"{e.msg}; "
"Note: mlflow.pyfunc.load_model is not supported for Feature Store models. "
"spark_udf() and predict() will not work as expected. Use "
"score_batch for offline predictions.",
BAD_REQUEST,
) from None
raise e
finally:
# clean up the dependencies schema which is set to global state after loading the model.
# This avoids the schema being used by other models loaded in the same process.
_clear_dependencies_schemas()
predict_fn = conf.get("predict_fn", "predict")
streamable = conf.get("streamable", False)
predict_stream_fn = conf.get("predict_stream_fn", "predict_stream") if streamable else None
pyfunc_model = PyFuncModel(
model_meta=model_meta,
model_impl=model_impl,
predict_fn=predict_fn,
predict_stream_fn=predict_stream_fn,
model_id=model_meta.model_id,
)
try:
model_input_example = model_meta.load_input_example(path=local_path)
pyfunc_model.input_example = model_input_example
except Exception as e:
_logger.debug(f"Failed to load input example from model metadata: {e}.")
return pyfunc_model
| PyFuncModel |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/device_op_overrides.py | {
"start": 191,
"end": 14719
} | class ____(DeviceOpOverrides):
"""
CUDA-specific codegen functions, see DeviceOpOverrides for details
"""
def import_get_raw_stream_as(self, name: str) -> str:
return f"from torch._C import _cuda_getCurrentRawStream as {name}"
def set_device(self, device_idx: int) -> str:
return f"torch.cuda.set_device({device_idx})"
def synchronize(self) -> str:
return "torch.cuda.synchronize()"
def device_guard(self, device_idx: int) -> str:
return f"torch.cuda._DeviceGuard({device_idx})"
def cpp_device_guard(self) -> str:
return "at::cuda::CUDAGuard"
def cpp_aoti_device_guard(self) -> str:
return "AOTICudaGuard"
def cpp_stream_guard(self) -> str:
return "at::cuda::CUDAStreamGuard"
def cpp_aoti_stream_guard(self) -> str:
return "AOTICudaStreamGuard"
def cpp_getStreamFromExternal(self) -> str:
return "at::cuda::getStreamFromExternal"
def kernel_header(self) -> str:
source_codes = """
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAStream.h>
#include <ATen/cuda/EmptyTensor.h>
"""
return source_codes
def kernel_driver(self) -> str:
source_codes = """
#define CUDA_DRIVER_CHECK(EXPR) \\
do { \\
CUresult code = EXPR; \\
const char *msg; \\
CUresult code_get_error = cuGetErrorString(code, &msg); \\
if (code_get_error != CUDA_SUCCESS) { \\
throw std::runtime_error( \\
std::string("CUDA driver error: ") + \\
std::string("invalid error code!")); \\
} \\
if (code != CUDA_SUCCESS) { \\
throw std::runtime_error( \\
std::string("CUDA driver error: ") + \\
std::string(msg)); \\
} \\
} while (0);
static inline CUfunction loadKernel(
std::string filePath,
const std::string &funcName,
uint32_t sharedMemBytes,
const std::optional<std::string> &cubinDir = std::nullopt) {
if (cubinDir) {
std::filesystem::path p1{*cubinDir};
std::filesystem::path p2{filePath};
filePath = (p1 / p2.filename()).string();
}
CUmodule mod;
CUfunction func;
CUDA_DRIVER_CHECK(cuModuleLoad(&mod, filePath.c_str()));
CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str()));
if (sharedMemBytes > 0) {
CUDA_DRIVER_CHECK(cuFuncSetAttribute(
func,
CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
sharedMemBytes
))
}
return func;
}
static inline CUfunction loadKernel(const void* start, const std::string &funcName, uint32_t sharedMemBytes) {
CUmodule mod;
CUfunction func;
CUDA_DRIVER_CHECK(cuModuleLoadData(&mod, start));
CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str()));
if (sharedMemBytes > 0) {
CUDA_DRIVER_CHECK(cuFuncSetAttribute(
func,
CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
sharedMemBytes
))
}
return func;
}
static inline void launchKernel(
CUfunction func,
uint32_t gridX,
uint32_t gridY,
uint32_t gridZ,
uint32_t numWarps,
uint32_t sharedMemBytes,
void* args[],
cudaStream_t stream) {
CUDA_DRIVER_CHECK(cuLaunchKernel(
func, gridX, gridY, gridZ, 32*numWarps, 1, 1, sharedMemBytes, stream, args, nullptr
));
}
"""
if torch.version.hip is not None:
# Adjusting the warp size to GPU supported wavefront size on AMD GPU
prop = torch.cuda.get_device_properties(torch.cuda.current_device())
source_codes = source_codes.replace(
"32*numWarps", str(prop.warp_size) + "*numWarps"
)
return source_codes
def tma_descriptor_helpers(self) -> str:
"""
CUDA helper functions for initializing TMA Descriptors on host side
"""
if torch.version.hip is not None:
raise RuntimeError("Host-side TMA descriptors not supported on HIP.")
# helper functions for initializing 1D and 2D TMA descriptors in C++. borrowed from the Triton code here:
# Old APIs (fill(1|2)DTMADescriptor):
# https://github.com/triton-lang/triton/blob/6af4f88591c85de079d8a36a4d7dba67918e2b39/third_party/nvidia/backend/driver.c#L283
# New APIs (fillTMADescriptor):
# https://github.com/triton-lang/triton/blob/main/third_party/nvidia/backend/driver.c#L283
return """
#if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12000
[[maybe_unused]] static void init1DTMADescriptor(
CUtensorMap* m,
void* globalAddress,
uint64_t dim,
uint32_t blockDim,
uint32_t elementSize) {
uint64_t dims[1] = {dim};
uint64_t globalStrides[1] = {dim * elementSize};
uint32_t tensorDims[1] = {blockDim};
uint32_t elementStrides[1] = {1};
CUtensorMapDataType type;
switch (elementSize) {
case 1:
type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
break;
case 2:
type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
break;
case 4:
type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
break;
default:
throw std::runtime_error("elementSize must be 1, 2, or 4");
}
if (elementSize * blockDim < 32) {
throw std::runtime_error("block size too small");
}
int rank = 1;
CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
m, type, rank, globalAddress, dims,
globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE,
CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE,
CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
}
[[maybe_unused]] static void init2DTMADescriptor(
CUtensorMap* m,
void* globalAddress,
uint64_t dim1,
uint64_t dim0,
uint32_t blockDim1,
uint32_t blockDim0,
uint32_t elementSize) {
uint64_t dims[2] = {dim0, dim1};
uint32_t tensorDims[2] = {blockDim0, blockDim1};
uint64_t globalStrides[2] = {dims[0] * elementSize,
dims[0] * dims[1] * elementSize};
uint32_t elementStrides[2] = {1, 1};
CUtensorMapDataType type;
switch (elementSize) {
case 1:
type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
break;
case 2:
type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
break;
case 4:
type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
break;
default:
throw std::runtime_error("elementSize must be 1, 2, or 4");
}
int rank = 2;
CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
uint32_t contigDimSizeInByte = elementSize * tensorDims[0];
if (contigDimSizeInByte >= 128) {
swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
} else if (contigDimSizeInByte >= 64) {
swizzle = CU_TENSOR_MAP_SWIZZLE_64B;
} else if (contigDimSizeInByte >= 32) {
swizzle = CU_TENSOR_MAP_SWIZZLE_32B;
} else {
throw std::runtime_error("block size too small");
}
if (contigDimSizeInByte > 128) {
tensorDims[0] = 128 / elementSize;
}
CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
m, type, rank, globalAddress, dims,
globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE,
swizzle, CU_TENSOR_MAP_L2_PROMOTION_L2_128B,
CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
}
[[maybe_unused]] static void initTMADescriptor(
CUtensorMap* m,
void* globalAddress,
int elemSize,
int rank,
uint32_t* blockSize,
uint64_t* shape,
uint64_t* stride
) {
uint32_t elementStrides[5] = {1, 1, 1, 1, 1};
uint32_t blockSizeInt[5];
uint64_t shapeInt[5];
uint64_t stridesLL[5];
// Reorder blockSize (reverse the order)
for (int i = 0; i < rank; ++i) {
blockSizeInt[rank - i - 1] = blockSize[i];
}
// Reorder shape (reverse the order)
for (int i = 0; i < rank; ++i) {
shapeInt[rank - i - 1] = shape[i];
}
// Reorder and calculate strides
for (int i = 0; i + 1 < rank; ++i) {
stridesLL[rank - i - 2] = elemSize * stride[i];
}
stridesLL[rank - 1] =
shapeInt[rank - 1] * (rank == 1 ? elemSize : stridesLL[rank - 2]);
CUtensorMapDataType type;
// In Triton this is computed ahead of time; but for simplicity
// in the PyTorch version we copied this code from the old
// TMA API handling (i.e. init2DTMADescriptor)
switch (elemSize) {
case 1:
type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
break;
case 2:
type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
break;
case 4:
type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
break;
default:
throw std::runtime_error("elemSize must be 1, 2, or 4");
}
// Calculate the size of the most contiguous dimension in bytes
CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
uint32_t contigDimSizeInByte = elemSize * blockSizeInt[0];
if (rank == 1) {
// rank 1 should not be swizzled
swizzle = CU_TENSOR_MAP_SWIZZLE_NONE;
} else if (contigDimSizeInByte >= 128) {
swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
} else if (contigDimSizeInByte >= 64) {
swizzle = CU_TENSOR_MAP_SWIZZLE_64B;
} else if (contigDimSizeInByte >= 32) {
swizzle = CU_TENSOR_MAP_SWIZZLE_32B;
} else {
throw std::runtime_error("block size too small");
}
CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
m, type, rank, globalAddress,
shapeInt, stridesLL, blockSizeInt, elementStrides,
CU_TENSOR_MAP_INTERLEAVE_NONE, (CUtensorMapSwizzle)swizzle,
CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
}
struct StableTMADescriptor {
CUtensorMap m;
uint32_t block_shape[5];
uint64_t global_shape[5];
uint64_t strides[5];
};
#endif
"""
def cpp_stream_type(self) -> str:
return "cudaStream_t"
def aoti_get_stream(self) -> str:
return "aoti_torch_get_current_cuda_stream"
def cpp_kernel_type(self) -> str:
return "CUfunction"
def cpp_device_ptr(self) -> str:
return "CUdeviceptr"
def cpp_scratch(
self, idx: int, workspace: TritonScratchWorkspace, prefix: Optional[str] = None
) -> Optional[tuple[list[str], str]]:
prefix = f"{prefix}_" if prefix else ""
var_name = f"{prefix}scratch_{idx}"
if workspace.size > 0:
size_array = f"int64_t {var_name}_size[] = {{{workspace.size}}};"
stride_array = f"int64_t {var_name}_stride[] = {{1}};"
device_type = "cached_torch_device_type_cuda"
device_idx = "device_idx_"
return (
[
f"{size_array}",
f"{stride_array}",
f"AtenTensorHandle {var_name}_handle;",
(
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided(1, {var_name}_size, {var_name}_stride, "
f"{workspace.generate_dtype_str()}, {device_type}, {device_idx}, &{var_name}_handle));"
),
f"RAIIAtenTensorHandle {var_name}_tensor({var_name}_handle);",
f"CUdeviceptr {var_name} = reinterpret_cast<CUdeviceptr>({var_name}_tensor.data_ptr());",
],
var_name,
)
else:
return [f"CUdeviceptr {var_name} = 0;"], var_name
register_device_op_overrides("cuda", CUDADeviceOpOverrides())
| CUDADeviceOpOverrides |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 1110,
"end": 1208
} | class ____(Exception):
"""Raised if the node could not perform a requested action."""
| Impossible |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 18170,
"end": 22861
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: WhisperConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = WhisperAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_heads,
dropout=config.attention_dropout,
is_decoder=True,
is_causal=True,
layer_idx=layer_idx,
config=config,
)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.encoder_attn = WhisperAttention(
self.embed_dim,
config.decoder_attention_heads,
dropout=config.attention_dropout,
is_decoder=True,
layer_idx=layer_idx,
config=config,
)
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[EncoderDecoderCache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = True,
cache_position: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
encoder_hidden_states (`torch.FloatTensor`):
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
past_key_values (`Cache`): cached past key and value projection states
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
"""
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
# Self Attention
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
past_key_values=past_key_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
cache_position=cache_position,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
# Cross-Attention Block
cross_attn_weights = None
if encoder_hidden_states is not None:
residual = hidden_states
hidden_states = self.encoder_attn_layer_norm(hidden_states)
hidden_states, cross_attn_weights = self.encoder_attn(
hidden_states=hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_attentions=output_attentions,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights, cross_attn_weights)
return outputs
@auto_docstring
| WhisperDecoderLayer |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 4413,
"end": 5831
} | class ____:
def test_1d(self):
a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
desired = 3. / (1./1 + 1./2 + 1./3)
check_equal_hmean(a, desired, rtol=1e-14)
a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
desired = 34.1417152147
check_equal_hmean(a, desired)
a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
desired = 31.8137186141
check_equal_hmean(a, desired)
@pytest.mark.skipif(not hasattr(np, 'float96'),
reason='cannot find float96 so skipping')
def test_1d_float96(self):
a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
desired_dt = np.asarray(3. / (1./1 + 1./2 + 1./3), dtype=np.float96)
check_equal_hmean(a, desired_dt, dtype=np.float96)
def test_2d(self):
a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]])
desired = ma.array([1, 2, 3, 4])
check_equal_hmean(a, desired, axis=0, rtol=1e-14)
desired = [4./(1/1.+1/2.+1/3.+1/4.), 2./(1/2.+1/3.), 2./(1/1.+1/4.)]
check_equal_hmean(a, desired, axis=-1, rtol=1e-14)
a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
desired = 38.6696271841
check_equal_hmean(np.ma.array(a), desired)
| TestHarMean |
python | getsentry__sentry | src/sentry/notifications/platform/types.py | {
"start": 3041,
"end": 5126
} | class ____:
subject: str
"""
The subject or title of the notification. It's expected that the receiver understand the
expected content of the notification based on this alone, and it will be the first thing
they see. This string should not contain any formatting, and will be displayed as is.
"""
body: list[NotificationBodyFormattingBlock]
"""
The full contents of the notification. Put the details of the notification here, but consider
keeping it concise and useful to the receiver.
"""
actions: list[NotificationRenderedAction] = field(default_factory=list)
"""
The list of actions that a receiver may take after having received the notification.
"""
chart: NotificationRenderedImage | None = None
"""
The image that will be displayed in the notification.
"""
footer: str | None = None
"""
Extra notification content that will appear after any actions, separate from the body. Optional,
and consider omitting if the extra data is not necessary for your notification to be useful.
This string should not contain any formatting, and will be displayed as is.
"""
# The following are optional, as omitting them will use a default email template which expects
# the required fields above to be present instead.
email_html_path: str | None = None
"""
The email HTML template file path. The associated NotificationData will be passed as context.
In general, try to avoid including different information in these Django Templates than appear
in the required fields, as it will make the contents of your notification vary from email to other
providers.
"""
email_text_path: str | None = None
"""
The email text template file path. The associated NotificationData will be passed as context.
In general, try to avoid including different information in these Django Templates than appear
in the required fields, as it will make the contents of your notification vary from email to other
providers.
"""
| NotificationRenderedTemplate |
python | getsentry__sentry | tests/sentry/utils/test_committers.py | {
"start": 4502,
"end": 5818
} | class ____(CommitTestCase):
def setUp(self) -> None:
super().setUp()
commit_1 = self.create_commit()
commit_2 = self.create_commit()
commit_3 = self.create_commit()
file_change_1 = self.create_commitfilechange(
filename="hello/app.py", type="A", commit=commit_1
)
file_change_2 = self.create_commitfilechange(
filename="hello/templates/app.html", type="A", commit=commit_2
)
file_change_3 = self.create_commitfilechange(
filename="hello/app.py", type="M", commit=commit_3
)
# ensuring its not just getting all filechanges
self.create_commitfilechange(filename="goodbye/app.py", type="A")
self.file_changes = [file_change_1, file_change_2, file_change_3]
self.commits = [commit_1, commit_2, commit_3]
self.path_name_set = {file_change.filename for file_change in self.file_changes}
def test_no_paths(self) -> None:
assert [] == _get_commit_file_changes(self.commits, set())
def test_no_valid_paths(self) -> None:
assert [] == _get_commit_file_changes(self.commits, {"/"})
def test_simple(self) -> None:
assert _get_commit_file_changes(self.commits, self.path_name_set) == self.file_changes
| GetCommitFileChangesTestCase |
python | bokeh__bokeh | src/bokeh/models/selectors.py | {
"start": 2165,
"end": 2547
} | class ____(Selector):
""" Represents a CSS class selector query. """
# explicit __init__ to support Init signatures
def __init__(self, query: Init[str] = Intrinsic, **kwargs: Any) -> None:
super().__init__(query=query, **kwargs)
query = Required(String, help="""
CSS class name without ``.`` prefix. Alternatively use ``ByCSS(".class")``.
""")
| ByClass |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-click/sphinx_click/ext.py | {
"start": 13360,
"end": 19285
} | class ____(rst.Directive):
has_content = False
required_arguments = 1
option_spec = {
"prog": directives.unchanged_required,
"nested": nested,
"commands": directives.unchanged,
"show-nested": directives.flag,
}
def _load_module(self, module_path: str) -> ty.Union[click.Command, click.Group]:
"""Load the module."""
try:
module_name, attr_name = module_path.split(":", 1)
except ValueError:
raise self.error(f'"{module_path}" is not of format "module:parser"')
try:
with mock(self.env.config.sphinx_click_mock_imports):
mod = __import__(module_name, globals(), locals(), [attr_name])
except (Exception, SystemExit) as exc:
err_msg = f'Failed to import "{attr_name}" from "{module_name}". '
if isinstance(exc, SystemExit):
err_msg += "The module appeared to call sys.exit()"
else:
err_msg += f"The following exception was raised:\n{traceback.format_exc()}"
raise self.error(err_msg)
if not hasattr(mod, attr_name):
raise self.error(f'Module "{module_name}" has no attribute "{attr_name}"')
parser = getattr(mod, attr_name)
if not isinstance(parser, (click.Command, click.Group)):
raise self.error(
f'"{type(parser)}" of type "{module_path}" is not click.Command or click.Group.'
'"click.BaseCommand"'
)
return parser
def _generate_nodes(
self,
name: str,
command: click.Command,
parent: ty.Optional[click.Context],
nested: NestedT,
commands: ty.Optional[ty.List[str]] = None, # noqa
semantic_group: bool = False,
) -> ty.List[nodes.section]: # noqa
"""Generate the relevant Sphinx nodes.
Format a `click.Group` or `click.Command`.
:param name: Name of command, as used on the command line
:param command: Instance of `click.Group` or `click.Command`
:param parent: Instance of `click.Context`, or None
:param nested: The granularity of subcommand details.
:param commands: Display only listed commands or skip the section if
empty
:param semantic_group: Display command as title and description for
`click.CommandCollection`.
:returns: A list of nested docutil nodes
"""
ctx = click.Context(command, info_name=name, parent=parent)
if command.hidden:
return []
# Title
section = nodes.section(
"",
nodes.title(text=name),
ids=[nodes.make_id(ctx.command_path)],
names=[nodes.fully_normalize_name(ctx.command_path)],
)
# Summary
source_name = ctx.command_path
result = statemachine.StringList()
ctx.meta["sphinx-click-env"] = self.env
if semantic_group:
lines = _format_description(ctx)
else:
lines = _format_command(ctx, nested, commands)
for line in lines:
LOG.debug(line)
result.append(line, source_name)
sphinx_nodes.nested_parse_with_titles(self.state, result, section)
# Subcommands
if nested == NESTED_FULL:
if isinstance(command, click.CommandCollection):
for source in command.sources:
section.extend(
self._generate_nodes(
source.name,
source,
parent=ctx,
nested=nested,
semantic_group=True,
)
)
else:
commands = _filter_commands(ctx, commands)
for command in commands:
parent = ctx if not semantic_group else ctx.parent
section.extend(
self._generate_nodes(command.name, command, parent=parent, nested=nested)
)
return [section]
def run(self) -> ty.Sequence[nodes.section]:
self.env = self.state.document.settings.env
command = self._load_module(self.arguments[0])
if "prog" not in self.options:
raise self.error(":prog: must be specified")
prog_name = self.options["prog"]
show_nested = "show-nested" in self.options
nested = self.options.get("nested")
if show_nested:
if nested:
raise self.error("':nested:' and ':show-nested:' are mutually exclusive")
else:
warnings.warn(
"':show-nested:' is deprecated; use ':nested: full'",
DeprecationWarning,
)
nested = NESTED_FULL if show_nested else NESTED_SHORT
commands = None
if self.options.get("commands"):
commands = [command.strip() for command in self.options["commands"].split(",")]
return self._generate_nodes(prog_name, command, None, nested, commands)
def setup(app: application.Sphinx) -> ty.Dict[str, ty.Any]: # noqa
# Need autodoc to support mocking modules
app.setup_extension("sphinx.ext.autodoc")
app.add_directive("click", ClickDirective)
app.add_event("sphinx-click-process-description")
app.add_event("sphinx-click-process-usage")
app.add_event("sphinx-click-process-options")
app.add_event("sphinx-click-process-arguments")
app.add_event("sphinx-click-process-envvars")
app.add_event("sphinx-click-process-epilog")
app.add_config_value(
"sphinx_click_mock_imports", lambda config: config.autodoc_mock_imports, "env"
)
return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
| ClickDirective |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/inheritance/simple_inheritance.py | {
"start": 0,
"end": 39
} | class ____:
"""parent class"""
| Parent |
python | huggingface__transformers | tests/models/metaclip_2/test_modeling_metaclip_2.py | {
"start": 1787,
"end": 5837
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
dropout=0.1,
attention_dropout=0.1,
initializer_range=0.02,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.is_training = is_training
self.hidden_size = hidden_size
self.projection_dim = projection_dim
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.dropout = dropout
self.attention_dropout = attention_dropout
self.initializer_range = initializer_range
self.scope = scope
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
num_patches = (image_size // patch_size) ** 2
self.seq_length = num_patches + 1
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
config = self.get_config()
return config, pixel_values
def get_config(self):
return MetaClip2VisionConfig(
image_size=self.image_size,
patch_size=self.patch_size,
num_channels=self.num_channels,
hidden_size=self.hidden_size,
projection_dim=self.projection_dim,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
dropout=self.dropout,
attention_dropout=self.attention_dropout,
initializer_range=self.initializer_range,
)
def create_and_check_model(self, config, pixel_values):
model = MetaClip2VisionModel(config=config)
model.to(torch_device)
model.eval()
with torch.no_grad():
result = model(pixel_values)
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
image_size = (self.image_size, self.image_size)
patch_size = (self.patch_size, self.patch_size)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_model_with_projection(self, config, pixel_values):
model = MetaClip2VisionModelWithProjection(config=config)
model.to(torch_device)
model.eval()
with torch.no_grad():
result = model(pixel_values)
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
image_size = (self.image_size, self.image_size)
patch_size = (self.patch_size, self.patch_size)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
self.parent.assertEqual(result.image_embeds.shape, (self.batch_size, self.projection_dim))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values = config_and_inputs
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
@parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION)
def test_eager_matches_sdpa_inference(self, *args):
return getattr(ModelTesterMixin, self._testMethodName)(self)
| MetaClip2VisionModelTester |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 3103,
"end": 4548
} | class ____(DynamicCache):
def __init__(self):
super().__init__()
self.linear_cache: list[torch.Tensor] = []
def set_linear_cache(self, layer_idx, linear_cache):
# There may be skipped layers, fill them with empty lists
for _ in range(len(self.linear_cache), layer_idx + 1):
self.linear_cache.append([])
self.linear_cache[layer_idx] = linear_cache
def get_linear_cache(self, layer_idx: int):
if layer_idx < len(self):
return self.linear_cache[layer_idx]
return None
def __len__(self):
return max(super().__len__(), len(self.linear_cache))
def batch_repeat_interleave(self, repeats: int):
for layer_idx in range(len(self)):
if self.linear_cache[layer_idx] != []:
self.linear_cache[layer_idx] = self.linear_cache[layer_idx].repeat_interleave(repeats, dim=0)
else:
self.layers[layer_idx].batch_repeat_interleave(repeats)
def batch_select_indices(self, indices: torch.Tensor):
for layer_idx in range(len(self)):
if self.linear_cache[layer_idx] != []:
self.linear_cache[layer_idx] = self.linear_cache[layer_idx][indices, ...]
else:
self.layers[layer_idx].batch_select_indices(indices)
def crop(self, max_length: int):
raise RuntimeError("MiniMaxCache doesnot support `crop` method")
| MiniMaxCache |
python | huggingface__transformers | src/transformers/models/mpnet/modeling_mpnet.py | {
"start": 19859,
"end": 20751
} | class ____(nn.Module):
"""MPNet Head for masked and permuted language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, features, **kwargs):
x = self.dense(features)
x = gelu(x)
x = self.layer_norm(x)
# project back to size of vocabulary with bias
x = self.decoder(x)
return x
@auto_docstring(
custom_intro="""
MPNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
output) e.g. for GLUE tasks.
"""
)
| MPNetLMHead |
python | pypa__pipenv | pipenv/vendor/pipdeptree/_models/package.py | {
"start": 737,
"end": 2491
} | class ____(ABC):
"""Abstract class for wrappers around objects that pip returns."""
UNKNOWN_LICENSE_STR = "(Unknown license)"
def __init__(self, project_name: str) -> None:
self.project_name = project_name
self.key = canonicalize_name(project_name)
def licenses(self) -> str:
try:
dist_metadata = metadata(self.key)
except PackageNotFoundError:
return self.UNKNOWN_LICENSE_STR
license_strs: list[str] = []
classifiers = dist_metadata.get_all("Classifier", [])
for classifier in classifiers:
line = str(classifier)
if line.startswith("License"):
license_str = line.split(":: ")[-1]
license_strs.append(license_str)
if len(license_strs) == 0:
return self.UNKNOWN_LICENSE_STR
return f'({", ".join(license_strs)})'
@abstractmethod
def render_as_root(self, *, frozen: bool) -> str:
raise NotImplementedError
@abstractmethod
def render_as_branch(self, *, frozen: bool) -> str:
raise NotImplementedError
@abstractmethod
def as_dict(self) -> dict[str, str]:
raise NotImplementedError
def render(
self,
parent: DistPackage | ReqPackage | None = None,
*,
frozen: bool = False,
) -> str:
render = self.render_as_branch if parent else self.render_as_root
return render(frozen=frozen)
@staticmethod
def as_frozen_repr(dist: Distribution) -> str:
return dist_to_frozen_repr(dist)
def __repr__(self) -> str:
return f'<{self.__class__.__name__}("{self.key}")>'
def __lt__(self, rhs: Package) -> bool:
return self.key < rhs.key
| Package |
python | fastapi__sqlmodel | docs_src/tutorial/select/tutorial002_py310.py | {
"start": 79,
"end": 1217
} | class ____(SQLModel, table=True): # (2)!
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True) # (3)!
def create_db_and_tables():
SQLModel.metadata.create_all(engine) # (4)!
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") # (5)!
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
with Session(engine) as session: # (6)!
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.commit()
def select_heroes():
with Session(engine) as session: # (7)!
statement = select(Hero) # (8)!
results = session.exec(statement) # (9)!
for hero in results: # (10)!
print(hero) # (11)!
# (12)!
def main():
create_db_and_tables()
create_heroes()
select_heroes() # (13)!
if __name__ == "__main__":
main()
| Hero |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/jax_to_torch.py | {
"start": 1461,
"end": 3703
} | class ____(ArrayConversion):
"""Wraps a Jax-based environment so that it can be interacted with PyTorch Tensors.
Actions must be provided as PyTorch Tensors and observations will be returned as PyTorch Tensors.
A vector version of the wrapper exists, :class:`gymnasium.wrappers.vector.JaxToTorch`.
Note:
For ``rendered`` this is returned as a NumPy array not a pytorch Tensor.
Example:
>>> import torch # doctest: +SKIP
>>> import gymnasium as gym # doctest: +SKIP
>>> env = gym.make("JaxEnv-vx") # doctest: +SKIP
>>> env = JaxtoTorch(env) # doctest: +SKIP
>>> obs, _ = env.reset(seed=123) # doctest: +SKIP
>>> type(obs) # doctest: +SKIP
<class 'torch.Tensor'>
>>> action = torch.tensor(env.action_space.sample()) # doctest: +SKIP
>>> obs, reward, terminated, truncated, info = env.step(action) # doctest: +SKIP
>>> type(obs) # doctest: +SKIP
<class 'torch.Tensor'>
>>> type(reward) # doctest: +SKIP
<class 'float'>
>>> type(terminated) # doctest: +SKIP
<class 'bool'>
>>> type(truncated) # doctest: +SKIP
<class 'bool'>
Change logs:
* v1.0.0 - Initially added
"""
def __init__(self, env: gym.Env, device: Device | None = None):
"""Wrapper class to change inputs and outputs of environment to PyTorch tensors.
Args:
env: The Jax-based environment to wrap
device: The device the torch Tensors should be moved to
"""
super().__init__(env=env, env_xp=jnp, target_xp=torch, target_device=device)
# TODO: Device was part of the public API, but should be removed in favor of _env_device and
# _target_device.
self.device: Device | None = device
| JaxToTorch |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/compiler.py | {
"start": 511,
"end": 10447
} | class ____(spack.package_base.PackageBase):
"""A Package mixin for all common logic for packages that implement compilers"""
# TODO: how do these play nicely with other tags
tags: Sequence[str] = ["compiler"]
#: Optional suffix regexes for searching for this type of compiler.
#: Suffixes are used by some frameworks, e.g. macports uses an '-mp-X.Y'
#: version suffix for gcc.
compiler_suffixes: List[str] = [r"-.*"]
#: Optional prefix regexes for searching for this compiler
compiler_prefixes: List[str] = []
#: Compiler argument(s) that produces version information
#: If multiple arguments, the earlier arguments must produce errors when invalid
compiler_version_argument: Union[str, Tuple[str, ...]] = "-dumpversion"
#: Regex used to extract version from compiler's output
compiler_version_regex: str = "(.*)"
#: Static definition of languages supported by this class
compiler_languages: Sequence[str] = ["c", "cxx", "fortran"]
#: Relative path to compiler wrappers
compiler_wrapper_link_paths: Dict[str, str] = {}
#: Optimization flags
opt_flags: Sequence[str] = []
#: Flags for generating debug information
debug_flags: Sequence[str] = []
def __init__(self, spec: "spack.spec.Spec"):
super().__init__(spec)
msg = f"Supported languages for {spec} are not a subset of possible supported languages"
msg += f" supports: {self.supported_languages}, valid values: {self.compiler_languages}"
assert set(self.supported_languages) <= set(self.compiler_languages), msg
@property
def supported_languages(self) -> Sequence[str]:
"""Dynamic definition of languages supported by this package"""
return self.compiler_languages
@classproperty
def compiler_names(cls) -> Sequence[str]:
"""Construct list of compiler names from per-language names"""
names = []
for language in cls.compiler_languages:
names.extend(getattr(cls, f"{language}_names"))
return names
@classproperty
def executables(cls) -> Sequence[str]:
"""Construct executables for external detection from names, prefixes, and suffixes."""
regexp_fmt = r"^({0}){1}({2})$"
prefixes = [""] + cls.compiler_prefixes
suffixes = [""] + cls.compiler_suffixes
if sys.platform == "win32":
ext = r"\.(?:exe|bat)"
suffixes += [suf + ext for suf in suffixes]
return [
regexp_fmt.format(prefix, re.escape(name), suffix)
for prefix, name, suffix in itertools.product(prefixes, cls.compiler_names, suffixes)
]
@classmethod
def determine_version(cls, exe: Path) -> str:
version_argument = cls.compiler_version_argument
if isinstance(version_argument, str):
version_argument = (version_argument,)
for va in version_argument:
try:
output = compiler_output(exe, version_argument=va)
match = re.search(cls.compiler_version_regex, output)
if match:
return ".".join(match.groups())
except spack.util.executable.ProcessError:
pass
except Exception as e:
tty.debug(
f"[{__file__}] Cannot detect a valid version for the executable "
f"{str(exe)}, for package '{cls.name}': {e}"
)
return ""
@classmethod
def compiler_bindir(cls, prefix: Path) -> Path:
"""Overridable method for the location of the compiler bindir within the prefix"""
return os.path.join(prefix, "bin")
@classmethod
def determine_compiler_paths(cls, exes: Sequence[Path]) -> Dict[str, Path]:
"""Compute the paths to compiler executables associated with this package
This is a helper method for ``determine_variants`` to compute the ``extra_attributes``
to include with each spec object."""
# There are often at least two copies (not symlinks) of each compiler executable in the
# same directory: one with a canonical name, e.g. "gfortran", and another one with the
# target prefix, e.g. "x86_64-pc-linux-gnu-gfortran". There also might be a copy of "gcc"
# with the version suffix, e.g. "x86_64-pc-linux-gnu-gcc-6.3.0". To ensure the consistency
# of values in the "paths" dictionary (i.e. we prefer all of them to reference copies
# with canonical names if possible), we iterate over the executables in the reversed sorted
# order:
# First pass over languages identifies exes that are perfect matches for canonical names
# Second pass checks for names with prefix/suffix
# Second pass is sorted by language name length because longer named languages
# e.g. cxx can often contain the names of shorter named languages
# e.g. c (e.g. clang/clang++)
paths = {}
exes = sorted(exes, reverse=True)
languages = {
lang: getattr(cls, f"{lang}_names")
for lang in sorted(cls.compiler_languages, key=len, reverse=True)
}
for exe in exes:
for lang, names in languages.items():
if os.path.basename(exe) in names:
paths[lang] = exe
break
else:
for lang, names in languages.items():
if any(name in os.path.basename(exe) for name in names):
paths[lang] = exe
break
return paths
@classmethod
def determine_variants(cls, exes: Sequence[Path], version_str: str) -> Tuple:
# path determination is separated so it can be reused in subclasses
return "", {"compilers": cls.determine_compiler_paths(exes=exes)}
#: Returns the argument needed to set the RPATH, or None if it does not exist
rpath_arg: Optional[str] = "-Wl,-rpath,"
#: Flag that needs to be used to pass an argument to the linker
linker_arg: str = "-Wl,"
#: Flag used to produce Position Independent Code
pic_flag: str = "-fPIC"
#: Flag used to get verbose output
verbose_flags: str = "-v"
#: Flag to activate OpenMP support
openmp_flag: str = "-fopenmp"
implicit_rpath_libs: List[str] = []
def standard_flag(self, *, language: str, standard: str) -> str:
"""Returns the flag used to enforce a given standard for a language"""
if language not in self.supported_languages:
raise CompilerError(f"{self.spec} does not provide the '{language}' language")
try:
return self._standard_flag(language=language, standard=standard)
except (KeyError, RuntimeError) as e:
raise CompilerError(
f"{self.spec} does not provide the '{language}' standard {standard}"
) from e
def _standard_flag(self, *, language: str, standard: str) -> str:
raise NotImplementedError("Must be implemented by derived classes")
def archspec_name(self) -> str:
"""Name that archspec uses to refer to this compiler"""
return self.spec.name
@property
def cc(self) -> Optional[str]:
assert self.spec.concrete, "cannot retrieve C compiler, spec is not concrete"
if self.spec.external:
return self.spec.extra_attributes.get("compilers", {}).get("c", None)
return self._cc_path()
def _cc_path(self) -> Optional[str]:
"""Returns the path to the C compiler, if the package was installed by Spack"""
return None
@property
def cxx(self) -> Optional[str]:
assert self.spec.concrete, "cannot retrieve C++ compiler, spec is not concrete"
if self.spec.external:
return self.spec.extra_attributes.get("compilers", {}).get("cxx", None)
return self._cxx_path()
def _cxx_path(self) -> Optional[str]:
"""Returns the path to the C++ compiler, if the package was installed by Spack"""
return None
@property
def fortran(self):
assert self.spec.concrete, "cannot retrieve Fortran compiler, spec is not concrete"
if self.spec.external:
return self.spec.extra_attributes.get("compilers", {}).get("fortran", None)
return self._fortran_path()
def _fortran_path(self) -> Optional[str]:
"""Returns the path to the Fortran compiler, if the package was installed by Spack"""
return None
@memoized
def _compiler_output(
compiler_path: Path, *, version_argument: str, ignore_errors: Tuple[int, ...] = ()
) -> str:
"""Returns the output from the compiler invoked with the given version argument.
Args:
compiler_path: path of the compiler to be invoked
version_argument: the argument used to extract version information
"""
compiler = spack.util.executable.Executable(compiler_path)
if not version_argument:
return compiler(
output=str, error=str, ignore_errors=ignore_errors, timeout=120, fail_on_error=True
)
return compiler(
version_argument,
output=str,
error=str,
ignore_errors=ignore_errors,
timeout=120,
fail_on_error=True,
)
def compiler_output(
compiler_path: Path, *, version_argument: str, ignore_errors: Tuple[int, ...] = ()
) -> str:
"""Wrapper for _get_compiler_version_output()."""
# This ensures that we memoize compiler output by *absolute path*,
# not just executable name. If we don't do this, and the path changes
# (e.g., during testing), we can get incorrect results.
if not os.path.isabs(compiler_path):
compiler_path = spack.util.executable.which_string(str(compiler_path), required=True)
return _compiler_output(
compiler_path, version_argument=version_argument, ignore_errors=ignore_errors
)
| CompilerPackage |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 7217,
"end": 7860
} | class ____:
"""
Helper mixin that implements "scopes handling" behaviour
"""
required_scopes = None
def get_scopes(self, *args, **kwargs):
"""
Return the scopes needed to access the resource
:param args: Support scopes injections from the outside (not yet implemented)
"""
if self.required_scopes is None:
raise ImproperlyConfigured(
"ProtectedResourceMixin requires either a definition of 'required_scopes'"
" or an implementation of 'get_scopes()'"
)
else:
return self.required_scopes
| ScopedResourceMixin |
python | readthedocs__readthedocs.org | readthedocs/builds/querysets.py | {
"start": 791,
"end": 5041
} | class ____(NoReprQuerySet, models.QuerySet):
"""Versions take into account their own privacy_level setting."""
use_for_related_fields = True
def __init__(self, *args, internal_only=False, external_only=False, **kwargs):
"""
Overridden to pass extra arguments from the manager.
Usage:
import functools
ManagerClass.from_queryset(
functools.partial(VersionQuerySet, internal_only=True)
)
:param bool internal_only: If this queryset is being used to query internal versions only.
:param bool external_only: If this queryset is being used to query external versions only.
"""
self.internal_only = internal_only
self.external_only = external_only
super().__init__(*args, **kwargs)
def _add_from_user_projects(self, queryset, user, admin=False, member=False):
"""Add related objects from projects where `user` is an `admin` or a `member`."""
if user and user.is_authenticated:
projects_pk = AdminPermission.projects(
user=user,
admin=admin,
member=member,
).values_list("pk", flat=True)
user_queryset = self.filter(project__in=projects_pk)
queryset = user_queryset | queryset
return queryset
def _public_only(self):
if self.internal_only:
# Since internal versions are already filtered,
# don't do anything special.
queryset = self.filter(privacy_level=constants.PUBLIC)
elif self.external_only:
# Since external versions are already filtered,
# don't filter them again.
queryset = self.filter(
project__external_builds_privacy_level=constants.PUBLIC,
)
else:
queryset = self.filter(privacy_level=constants.PUBLIC).exclude(type=EXTERNAL)
queryset |= self.filter(
type=EXTERNAL,
project__external_builds_privacy_level=constants.PUBLIC,
)
return queryset
def public(
self,
user=None,
only_active=True,
include_hidden=True,
only_built=False,
):
"""
Get all allowed versions.
.. note::
External versions use the `Project.external_builds_privacy_level`
field instead of its `privacy_level` field.
.. note::
Avoid filtering by reverse relationships in this method (like project),
and instead use project.builds or similar, so the same object is shared
between the results.
"""
queryset = self._public_only()
if user:
if user.is_superuser:
queryset = self.all()
else:
queryset = self._add_from_user_projects(queryset, user, admin=True, member=True)
if only_active:
queryset = queryset.filter(active=True)
if only_built:
queryset = queryset.filter(built=True)
if not include_hidden:
queryset = queryset.filter(hidden=False)
return queryset.distinct()
def api(self, user=None):
return self.public(user, only_active=False)
def api_v2(self, *args, **kwargs):
# API v2 is the same as API v3 for .org, but it's
# different for .com, this method is overridden there.
return self.api(*args, **kwargs)
def for_reindex(self):
"""
Get all versions that can be reindexed.
A version can be reindexed if:
- It's active and has been built at least once successfully.
Since that means that it has files to be indexed.
- Its project is not delisted or marked as spam.
- Its project has search indexing enabled.
"""
return (
self.filter(
active=True,
built=True,
builds__state=BUILD_STATE_FINISHED,
builds__success=True,
project__search_indexing_enabled=True,
)
.exclude(project__delisted=True)
.exclude(project__is_spam=True)
.distinct()
)
| VersionQuerySetBase |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 1942,
"end": 3026
} | class ____(Exception):
pass
def read_headers(fd):
response_line = fd.readline()
if not response_line:
raise ConnectionClosed
response_line = response_line.decode('latin-1')
headers = {}
while True:
line = fd.readline().strip()
if not line:
break
line = line.decode('latin-1')
try:
key, value = line.split(': ', 1)
except:
print('Failed to split: %r' % (line, ))
raise
assert key.lower() not in {x.lower() for x in headers}, 'Header %r:%r sent more than once: %r' % (key, value, headers)
headers[key] = value
return response_line, headers
def iread_chunks(fd):
while True:
line = fd.readline()
chunk_size = line.strip()
chunk_size = int(chunk_size, 16)
if chunk_size == 0:
crlf = fd.read(2)
assert crlf == b'\r\n', repr(crlf)
break
data = fd.read(chunk_size)
yield data
crlf = fd.read(2)
assert crlf == b'\r\n', repr(crlf)
| ConnectionClosed |
python | mitmproxy__pdoc | test/testdata/demopackage/subpackage/child_g.py | {
"start": 26,
"end": 180
} | class ____:
"""This class is defined in subpackage's child_g, but reexposed in the `demopackage.subpackage` namespace."""
def g(self):
pass
| G |
python | apache__airflow | airflow-core/tests/unit/serialization/serializers/test_serializers.py | {
"start": 2173,
"end": 2280
} | class ____(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=2)
| NoNameTZ |
python | walkccc__LeetCode | solutions/156. Binary Tree Upside Down/156.py | {
"start": 0,
"end": 372
} | class ____:
def upsideDownBinaryTree(self, root: TreeNode | None) -> TreeNode | None:
if not root or not root.left:
return root
newRoot = self.upsideDownBinaryTree(root.left)
root.left.left = root.right # 2's left = 3 (root's right)
root.left.right = root # 2's right = 1 (root)
root.left = None
root.right = None
return newRoot
| Solution |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 184386,
"end": 189107
} | class ____(RunnableSerializable[list[Input], list[Output]]):
"""RunnableEachBase class.
`Runnable` that calls another `Runnable` for each element of the input sequence.
Use only if creating a new `RunnableEach` subclass with different `__init__`
args.
See documentation for `RunnableEach` for more details.
"""
bound: Runnable[Input, Output]
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
@property
@override
def InputType(self) -> Any:
return list[self.bound.InputType] # type: ignore[name-defined]
@override
def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
return create_model_v2(
self.get_name("Input"),
root=(
list[self.bound.get_input_schema(config)], # type: ignore[misc]
None,
),
# create model needs access to appropriate type annotations to be
# able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
# self.__class__.__module__ handles the case when the Runnable is
# being sub-classed in a different module.
module_name=self.__class__.__module__,
)
@property
@override
def OutputType(self) -> type[list[Output]]:
return list[self.bound.OutputType] # type: ignore[name-defined]
@override
def get_output_schema(
self, config: RunnableConfig | None = None
) -> type[BaseModel]:
schema = self.bound.get_output_schema(config)
return create_model_v2(
self.get_name("Output"),
root=list[schema], # type: ignore[valid-type]
# create model needs access to appropriate type annotations to be
# able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
# self.__class__.__module__ handles the case when the Runnable is
# being sub-classed in a different module.
module_name=self.__class__.__module__,
)
@property
@override
def config_specs(self) -> list[ConfigurableFieldSpec]:
return self.bound.config_specs
@override
def get_graph(self, config: RunnableConfig | None = None) -> Graph:
return self.bound.get_graph(config)
@classmethod
@override
def is_lc_serializable(cls) -> bool:
"""Return `True` as this class is serializable."""
return True
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
"""
return ["langchain", "schema", "runnable"]
def _invoke(
self,
inputs: list[Input],
run_manager: CallbackManagerForChainRun,
config: RunnableConfig,
**kwargs: Any,
) -> list[Output]:
configs = [
patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
]
return self.bound.batch(inputs, configs, **kwargs)
@override
def invoke(
self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
) -> list[Output]:
return self._call_with_config(self._invoke, input, config, **kwargs)
async def _ainvoke(
self,
inputs: list[Input],
run_manager: AsyncCallbackManagerForChainRun,
config: RunnableConfig,
**kwargs: Any,
) -> list[Output]:
configs = [
patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
]
return await self.bound.abatch(inputs, configs, **kwargs)
@override
async def ainvoke(
self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
) -> list[Output]:
return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
@override
async def astream_events(
self,
input: Input,
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[StreamEvent]:
def _error_stream_event(message: str) -> StreamEvent:
raise NotImplementedError(message)
for _ in range(1):
yield _error_stream_event(
"RunnableEach does not support astream_events yet."
)
| RunnableEachBase |
python | django__django | tests/forms_tests/field_tests/test_base.py | {
"start": 1243,
"end": 1454
} | class ____(SimpleTestCase):
def test_disabled_field_has_changed_always_false(self):
disabled_field = Field(disabled=True)
self.assertFalse(disabled_field.has_changed("x", "y"))
| DisabledFieldTests |
python | python-poetry__poetry | src/poetry/config/config_source.py | {
"start": 334,
"end": 610
} | class ____(ABC):
@abstractmethod
def get_property(self, key: str) -> Any: ...
@abstractmethod
def add_property(self, key: str, value: Any) -> None: ...
@abstractmethod
def remove_property(self, key: str) -> None: ...
@dataclasses.dataclass
| ConfigSource |
python | ipython__ipython | IPython/core/display.py | {
"start": 13414,
"end": 13524
} | class ____(TextDisplayObject):
def _repr_pretty_(self, pp, cycle):
return pp.text(self.data)
| Pretty |
python | pypa__packaging | tests/test_tags.py | {
"start": 2879,
"end": 4166
} | class ____:
def test_lowercasing(self) -> None:
tag = tags.Tag("PY3", "None", "ANY")
assert tag.interpreter == "py3"
assert tag.abi == "none"
assert tag.platform == "any"
def test_equality(self) -> None:
args = "py3", "none", "any"
assert tags.Tag(*args) == tags.Tag(*args)
def test_equality_fails_with_non_tag(self) -> None:
assert not tags.Tag("py3", "none", "any") == "non-tag"
def test_hashing(self, example_tag: tags.Tag) -> None:
tags = {example_tag} # Should not raise TypeError.
assert example_tag in tags
def test_hash_equality(self, example_tag: tags.Tag) -> None:
equal_tag = tags.Tag("py3", "none", "any")
assert example_tag == equal_tag # Sanity check.
assert example_tag.__hash__() == equal_tag.__hash__()
def test_str(self, example_tag: tags.Tag) -> None:
assert str(example_tag) == "py3-none-any"
def test_repr(self, example_tag: tags.Tag) -> None:
assert repr(example_tag) == f"<py3-none-any @ {id(example_tag)}>"
def test_attribute_access(self, example_tag: tags.Tag) -> None:
assert example_tag.interpreter == "py3"
assert example_tag.abi == "none"
assert example_tag.platform == "any"
| TestTag |
python | django__django | django/contrib/postgres/fields/ranges.py | {
"start": 6093,
"end": 6291
} | class ____(RangeField):
base_field = models.DateField
range_type = DateRange
form_field = forms.DateRangeField
def db_type(self, connection):
return "daterange"
| DateRangeField |
python | readthedocs__readthedocs.org | readthedocs/oauth/models.py | {
"start": 761,
"end": 2208
} | class ____(models.Manager):
def get_or_create_installation(
self, *, installation_id, target_id, target_type, extra_data=None
):
"""
Get or create a GitHub app installation.
Only the installation_id is unique, the target_id and target_type could change,
but this should never happen.
"""
installation, created = self.get_or_create(
installation_id=installation_id,
defaults={
"target_id": target_id,
"target_type": target_type,
"extra_data": extra_data or {},
},
)
# NOTE: An installation can't change its target_id or target_type.
# This should never happen, unless this assumption is wrong.
if installation.target_id != target_id or installation.target_type != target_type:
log.exception(
"Installation target_id or target_type changed. This shouldn't happen -- look into it",
installation_id=installation.installation_id,
target_id=installation.target_id,
target_type=installation.target_type,
new_target_id=target_id,
new_target_type=target_type,
)
installation.target_id = target_id
installation.target_type = target_type
installation.save()
return installation, created
| GitHubAppInstallationManager |
python | ray-project__ray | python/ray/tune/trainable/trainable_fn_utils.py | {
"start": 414,
"end": 2163
} | class ____(TrainCheckpoint):
# NOTE: This is just a pass-through wrapper around `ray.train.Checkpoint`
# in order to detect whether the import module was correct `ray.tune.Checkpoint`.
pass
@PublicAPI(stability="stable")
@_warn_session_misuse()
def report(metrics: Dict, *, checkpoint: Optional[Checkpoint] = None) -> None:
"""Report metrics and optionally save and register a checkpoint to Ray Tune.
If a checkpoint is provided, it will be
:ref:`persisted to storage <persistent-storage-guide>`.
.. note::
Each invocation of this method will automatically increment the underlying
``training_iteration`` number. The physical meaning of this "iteration" is
defined by user depending on how often they call ``report``.
It does not necessarily map to one epoch.
Args:
metrics: The metrics you want to report.
checkpoint: The optional checkpoint you want to report.
"""
if checkpoint and not isinstance(checkpoint, Checkpoint):
if _v2_migration_warnings_enabled():
_log_deprecation_warning(
"The `Checkpoint` class should be imported from `ray.tune` "
"when passing it to `ray.tune.report` in a Tune function. "
"Please update your imports. "
f"{V2_MIGRATION_GUIDE_MESSAGE}"
)
get_session().report(metrics, checkpoint=checkpoint)
@PublicAPI(stability="stable")
@_warn_session_misuse()
def get_checkpoint() -> Optional[Checkpoint]:
"""Access the latest reported checkpoint to resume from if one exists."""
return get_session().loaded_checkpoint
def _in_tune_session() -> bool:
return get_session() and get_session().world_rank is None
| Checkpoint |
python | django-extensions__django-extensions | tests/testapp/jobs/daily/test_daily_job.py | {
"start": 120,
"end": 224
} | class ____(DailyJob):
help = "My sample daily job."
def execute(self):
DAILY_JOB_MOCK()
| Job |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py | {
"start": 100002,
"end": 125314
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_v1_only("b/124229375")
def testBasicRNNCell(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m = array_ops.zeros([1, 2])
cell = rnn_cell_impl.BasicRNNCell(2)
g, _ = cell(x, m)
self.assertEqual([
"root/basic_rnn_cell/%s:0" % rnn_cell_impl._WEIGHTS_VARIABLE_NAME,
"root/basic_rnn_cell/%s:0" % rnn_cell_impl._BIAS_VARIABLE_NAME
], [v.name for v in cell.trainable_variables])
self.assertFalse(cell.non_trainable_variables)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run([g], {
x: np.array([[1., 1.]]),
m: np.array([[0.1, 0.1]])
})
self.assertEqual(res[0].shape, (1, 2))
@test_util.run_v1_only("b/124229375")
def testBasicRNNCellNotTrainable(self):
with self.cached_session() as sess:
def not_trainable_getter(getter, *args, **kwargs):
kwargs["trainable"] = False
return getter(*args, **kwargs)
with variable_scope.variable_scope(
"root",
initializer=init_ops.constant_initializer(0.5),
custom_getter=not_trainable_getter):
x = array_ops.zeros([1, 2])
m = array_ops.zeros([1, 2])
cell = rnn_cell_impl.BasicRNNCell(2)
g, _ = cell(x, m)
self.assertFalse(cell.trainable_variables)
self.assertEqual([
"root/basic_rnn_cell/%s:0" % rnn_cell_impl._WEIGHTS_VARIABLE_NAME,
"root/basic_rnn_cell/%s:0" % rnn_cell_impl._BIAS_VARIABLE_NAME
], [v.name for v in cell.non_trainable_variables])
sess.run([variables_lib.global_variables_initializer()])
res = sess.run([g], {
x: np.array([[1., 1.]]),
m: np.array([[0.1, 0.1]])
})
self.assertEqual(res[0].shape, (1, 2))
@test_util.run_v1_only("b/124229375")
def testGRUCell(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m = array_ops.zeros([1, 2])
g, _ = rnn_cell_impl.GRUCell(2)(x, m)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run([g], {
x: np.array([[1., 1.]]),
m: np.array([[0.1, 0.1]])
})
# Smoke test
self.assertAllClose(res[0], [[0.175991, 0.175991]])
with variable_scope.variable_scope(
"other", initializer=init_ops.constant_initializer(0.5)):
# Test GRUCell with input_size != num_units.
x = array_ops.zeros([1, 3])
m = array_ops.zeros([1, 2])
g, _ = rnn_cell_impl.GRUCell(2)(x, m)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run([g], {
x: np.array([[1., 1., 1.]]),
m: np.array([[0.1, 0.1]])
})
# Smoke test
self.assertAllClose(res[0], [[0.156736, 0.156736]])
@test_util.run_v1_only("b/124229375")
def testBasicLSTMCell(self):
for dtype in [dtypes.float16, dtypes.float32]:
np_dtype = dtype.as_numpy_dtype
with self.session(graph=ops.Graph()) as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2], dtype=dtype)
m = array_ops.zeros([1, 8], dtype=dtype)
cell = rnn_cell_impl.MultiRNNCell(
[
rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False)
for _ in range(2)
],
state_is_tuple=False)
self.assertEqual(cell.dtype, None)
self.assertIn("cell-0", cell._trackable_children())
self.assertIn("cell-1", cell._trackable_children())
cell.get_config() # Should not throw an error
g, out_m = cell(x, m)
# Layer infers the input type.
self.assertEqual(cell.dtype, dtype.name)
expected_variable_names = [
"root/multi_rnn_cell/cell_0/basic_lstm_cell/%s:0" %
rnn_cell_impl._WEIGHTS_VARIABLE_NAME,
"root/multi_rnn_cell/cell_0/basic_lstm_cell/%s:0" %
rnn_cell_impl._BIAS_VARIABLE_NAME,
"root/multi_rnn_cell/cell_1/basic_lstm_cell/%s:0" %
rnn_cell_impl._WEIGHTS_VARIABLE_NAME,
"root/multi_rnn_cell/cell_1/basic_lstm_cell/%s:0" %
rnn_cell_impl._BIAS_VARIABLE_NAME
]
self.assertEqual(expected_variable_names,
[v.name for v in cell.trainable_variables])
self.assertFalse(cell.non_trainable_variables)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run([g, out_m], {
x: np.array([[1., 1.]]),
m: 0.1 * np.ones([1, 8])
})
self.assertEqual(len(res), 2)
variables = variables_lib.global_variables()
self.assertEqual(expected_variable_names, [v.name for v in variables])
# The numbers in results were not calculated, this is just a
# smoke test.
self.assertAllClose(res[0], np.array(
[[0.240, 0.240]], dtype=np_dtype), 1e-2)
expected_mem = np.array(
[[0.689, 0.689, 0.448, 0.448, 0.398, 0.398, 0.240, 0.240]],
dtype=np_dtype)
self.assertAllClose(res[1], expected_mem, 1e-2)
with variable_scope.variable_scope(
"other", initializer=init_ops.constant_initializer(0.5)):
# Test BasicLSTMCell with input_size != num_units.
x = array_ops.zeros([1, 3], dtype=dtype)
m = array_ops.zeros([1, 4], dtype=dtype)
g, out_m = rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False)(x, m)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run(
[g, out_m], {
x: np.array([[1., 1., 1.]], dtype=np_dtype),
m: 0.1 * np.ones([1, 4], dtype=np_dtype)
})
self.assertEqual(len(res), 2)
@test_util.run_v1_only("b/124229375")
def testBasicLSTMCellDimension0Error(self):
"""Tests that dimension 0 in both(x and m) shape must be equal."""
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
num_units = 2
state_size = num_units * 2
batch_size = 3
input_size = 4
x = array_ops.zeros([batch_size, input_size])
m = array_ops.zeros([batch_size - 1, state_size])
with self.assertRaises(ValueError):
g, out_m = rnn_cell_impl.BasicLSTMCell(
num_units, state_is_tuple=False)(x, m)
sess.run([variables_lib.global_variables_initializer()])
sess.run(
[g, out_m], {
x: 1 * np.ones([batch_size, input_size]),
m: 0.1 * np.ones([batch_size - 1, state_size])
})
def testBasicLSTMCellStateSizeError(self):
"""Tests that state_size must be num_units * 2."""
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
num_units = 2
state_size = num_units * 3 # state_size must be num_units * 2
batch_size = 3
input_size = 4
x = array_ops.zeros([batch_size, input_size])
m = array_ops.zeros([batch_size, state_size])
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
g, out_m = rnn_cell_impl.BasicLSTMCell(
num_units, state_is_tuple=False)(x, m)
sess.run([variables_lib.global_variables_initializer()])
sess.run(
[g, out_m], {
x: 1 * np.ones([batch_size, input_size]),
m: 0.1 * np.ones([batch_size, state_size])
})
@test_util.run_v1_only("b/124229375")
def testBasicLSTMCellStateTupleType(self):
with self.cached_session():
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m0 = (array_ops.zeros([1, 2]),) * 2
m1 = (array_ops.zeros([1, 2]),) * 2
cell = rnn_cell_impl.MultiRNNCell(
[rnn_cell_impl.BasicLSTMCell(2) for _ in range(2)],
state_is_tuple=True)
self.assertTrue(isinstance(cell.state_size, tuple))
self.assertTrue(
isinstance(cell.state_size[0], rnn_cell_impl.LSTMStateTuple))
self.assertTrue(
isinstance(cell.state_size[1], rnn_cell_impl.LSTMStateTuple))
# Pass in regular tuples
_, (out_m0, out_m1) = cell(x, (m0, m1))
self.assertTrue(isinstance(out_m0, rnn_cell_impl.LSTMStateTuple))
self.assertTrue(isinstance(out_m1, rnn_cell_impl.LSTMStateTuple))
# Pass in LSTMStateTuples
variable_scope.get_variable_scope().reuse_variables()
zero_state = cell.zero_state(1, dtypes.float32)
self.assertTrue(isinstance(zero_state, tuple))
self.assertTrue(isinstance(zero_state[0], rnn_cell_impl.LSTMStateTuple))
self.assertTrue(isinstance(zero_state[1], rnn_cell_impl.LSTMStateTuple))
_, (out_m0, out_m1) = cell(x, zero_state)
self.assertTrue(isinstance(out_m0, rnn_cell_impl.LSTMStateTuple))
self.assertTrue(isinstance(out_m1, rnn_cell_impl.LSTMStateTuple))
@test_util.run_v1_only("b/124229375")
def testBasicLSTMCellWithStateTuple(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m0 = array_ops.zeros([1, 4])
m1 = array_ops.zeros([1, 4])
cell = rnn_cell_impl.MultiRNNCell(
[
rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False)
for _ in range(2)
],
state_is_tuple=True)
g, (out_m0, out_m1) = cell(x, (m0, m1))
sess.run([variables_lib.global_variables_initializer()])
res = sess.run(
[g, out_m0, out_m1], {
x: np.array([[1., 1.]]),
m0: 0.1 * np.ones([1, 4]),
m1: 0.1 * np.ones([1, 4])
})
self.assertEqual(len(res), 3)
# The numbers in results were not calculated, this is just a smoke test.
# Note, however, these values should match the original
# version having state_is_tuple=False.
self.assertAllClose(res[0], [[0.24024698, 0.24024698]])
expected_mem0 = np.array(
[[0.68967271, 0.68967271, 0.44848421, 0.44848421]])
expected_mem1 = np.array(
[[0.39897051, 0.39897051, 0.24024698, 0.24024698]])
self.assertAllClose(res[1], expected_mem0)
self.assertAllClose(res[2], expected_mem1)
@test_util.run_v1_only("b/124229375")
def testLSTMCell(self):
with self.cached_session() as sess:
num_units = 8
num_proj = 6
state_size = num_units + num_proj
batch_size = 3
input_size = 2
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([batch_size, input_size])
m = array_ops.zeros([batch_size, state_size])
cell = rnn_cell_impl.LSTMCell(
num_units=num_units,
num_proj=num_proj,
forget_bias=1.0,
state_is_tuple=False)
output, state = cell(x, m)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run(
[output, state], {
x: np.array([[1., 1.], [2., 2.], [3., 3.]]),
m: 0.1 * np.ones((batch_size, state_size))
})
self.assertEqual(len(res), 2)
# The numbers in results were not calculated, this is mostly just a
# smoke test.
self.assertEqual(res[0].shape, (batch_size, num_proj))
self.assertEqual(res[1].shape, (batch_size, state_size))
# Different inputs so different outputs and states
for i in range(1, batch_size):
self.assertTrue(
float(np.linalg.norm((res[0][0, :] - res[0][i, :]))) > 1e-6)
self.assertTrue(
float(np.linalg.norm((res[1][0, :] - res[1][i, :]))) > 1e-6)
@test_util.run_v1_only("b/124229375")
def testLSTMCellVariables(self):
with self.cached_session():
num_units = 8
num_proj = 6
state_size = num_units + num_proj
batch_size = 3
input_size = 2
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([batch_size, input_size])
m = array_ops.zeros([batch_size, state_size])
cell = rnn_cell_impl.LSTMCell(
num_units=num_units,
num_proj=num_proj,
forget_bias=1.0,
state_is_tuple=False)
cell(x, m) # Execute to create variables
variables = variables_lib.global_variables()
self.assertEqual(variables[0].op.name, "root/lstm_cell/kernel")
self.assertEqual(variables[1].op.name, "root/lstm_cell/bias")
self.assertEqual(variables[2].op.name, "root/lstm_cell/projection/kernel")
@test_util.run_in_graph_and_eager_modes
def testWrapperCheckpointing(self):
for wrapper_type in [
rnn_cell_impl.DropoutWrapper,
rnn_cell_impl.ResidualWrapper,
lambda cell: rnn_cell_impl.MultiRNNCell([cell])]:
cell = rnn_cell_impl.BasicRNNCell(1)
wrapper = wrapper_type(cell)
wrapper(array_ops.ones([1, 1]),
state=wrapper.zero_state(batch_size=1, dtype=dtypes.float32))
self.evaluate([v.initializer for v in cell.variables])
checkpoint = trackable_utils.Checkpoint(wrapper=wrapper)
prefix = os.path.join(self.get_temp_dir(), "ckpt")
self.evaluate(cell._bias.assign([40.]))
save_path = checkpoint.save(prefix)
self.evaluate(cell._bias.assign([0.]))
checkpoint.restore(save_path).assert_consumed().run_restore_ops()
self.assertAllEqual([40.], self.evaluate(cell._bias))
@test_util.run_in_graph_and_eager_modes
def testResidualWrapper(self):
wrapper_type = rnn_cell_impl.ResidualWrapper
x = ops.convert_to_tensor(np.array([[1., 1., 1.]]))
m = ops.convert_to_tensor(np.array([[0.1, 0.1, 0.1]]))
base_cell = rnn_cell_impl.GRUCell(
3, kernel_initializer=init_ops.constant_initializer(0.5),
bias_initializer=init_ops.constant_initializer(0.5))
g, m_new = base_cell(x, m)
wrapper_object = wrapper_type(base_cell)
wrapper_object.get_config() # Should not throw an error
self.assertIn("cell", wrapper_object._trackable_children())
self.assertIs(wrapper_object._trackable_children()["cell"], base_cell)
g_res, m_new_res = wrapper_object(x, m)
self.evaluate([variables_lib.global_variables_initializer()])
res = self.evaluate([g, g_res, m_new, m_new_res])
# Residual connections
self.assertAllClose(res[1], res[0] + [1., 1., 1.])
# States are left untouched
self.assertAllClose(res[2], res[3])
@test_util.run_in_graph_and_eager_modes
def testResidualWrapperWithSlice(self):
wrapper_type = rnn_cell_impl.ResidualWrapper
x = ops.convert_to_tensor(np.array([[1., 1., 1., 1., 1.]]))
m = ops.convert_to_tensor(np.array([[0.1, 0.1, 0.1]]))
base_cell = rnn_cell_impl.GRUCell(
3, kernel_initializer=init_ops.constant_initializer(0.5),
bias_initializer=init_ops.constant_initializer(0.5))
g, m_new = base_cell(x, m)
def residual_with_slice_fn(inp, out):
inp_sliced = array_ops.slice(inp, [0, 0], [-1, 3])
return inp_sliced + out
g_res, m_new_res = wrapper_type(
base_cell, residual_with_slice_fn)(x, m)
self.evaluate([variables_lib.global_variables_initializer()])
res_g, res_g_res, res_m_new, res_m_new_res = self.evaluate(
[g, g_res, m_new, m_new_res])
# Residual connections
self.assertAllClose(res_g_res, res_g + [1., 1., 1.])
# States are left untouched
self.assertAllClose(res_m_new, res_m_new_res)
def testDeviceWrapper(self):
wrapper_type = rnn_cell_impl.DeviceWrapper
x = array_ops.zeros([1, 3])
m = array_ops.zeros([1, 3])
cell = rnn_cell_impl.GRUCell(3)
wrapped_cell = wrapper_type(cell, "/cpu:0")
wrapped_cell.get_config() # Should not throw an error
self.assertEqual(wrapped_cell._trackable_children()["cell"], cell)
outputs, _ = wrapped_cell(x, m)
self.assertIn("cpu:0", outputs.device.lower())
def _retrieve_cpu_gpu_stats(self, run_metadata):
cpu_stats = None
gpu_stats = None
step_stats = run_metadata.step_stats
for ds in step_stats.dev_stats:
if "cpu:0" in ds.device[-5:].lower():
cpu_stats = ds.node_stats
if "gpu:0" == ds.device[-5:].lower():
gpu_stats = ds.node_stats
return cpu_stats, gpu_stats
@test_util.run_v1_only("b/124229375")
def testDeviceWrapperDynamicExecutionNodesAreAllProperlyLocated(self):
if not test.is_gpu_available():
# Can't perform this test w/o a GPU
return
gpu_dev = test.gpu_device_name()
with self.session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 1, 3])
cell = rnn_cell_impl.DeviceWrapper(rnn_cell_impl.GRUCell(3), gpu_dev)
with ops.device("/cpu:0"):
outputs, _ = rnn.dynamic_rnn(
cell=cell, inputs=x, dtype=dtypes.float32)
run_metadata = config_pb2.RunMetadata()
opts = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
sess.run([variables_lib.global_variables_initializer()])
_ = sess.run(outputs, options=opts, run_metadata=run_metadata)
cpu_stats, gpu_stats = self._retrieve_cpu_gpu_stats(run_metadata)
self.assertFalse([s for s in cpu_stats if "gru_cell" in s.node_name])
self.assertTrue([s for s in gpu_stats if "gru_cell" in s.node_name])
@test_util.run_v1_only("b/124229375")
def testMultiRNNCell(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m = array_ops.zeros([1, 4])
multi_rnn_cell = rnn_cell_impl.MultiRNNCell(
[rnn_cell_impl.GRUCell(2) for _ in range(2)],
state_is_tuple=False)
_, ml = multi_rnn_cell(x, m)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run(ml, {
x: np.array([[1., 1.]]),
m: np.array([[0.1, 0.1, 0.1, 0.1]])
})
# The numbers in results were not calculated, this is just a smoke test.
self.assertAllClose(res, [[0.175991, 0.175991, 0.13248, 0.13248]])
self.assertEqual(len(multi_rnn_cell.weights), 2 * 4)
self.assertTrue(
[x.dtype == dtypes.float32 for x in multi_rnn_cell.weights])
@test_util.run_v1_only("b/124229375")
def testMultiRNNCellWithStateTuple(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m_bad = array_ops.zeros([1, 4])
m_good = (array_ops.zeros([1, 2]), array_ops.zeros([1, 2]))
# Test incorrectness of state
with self.assertRaisesRegex(ValueError, "Expected state .* a tuple"):
rnn_cell_impl.MultiRNNCell(
[rnn_cell_impl.GRUCell(2) for _ in range(2)],
state_is_tuple=True)(x, m_bad)
_, ml = rnn_cell_impl.MultiRNNCell(
[rnn_cell_impl.GRUCell(2) for _ in range(2)],
state_is_tuple=True)(x, m_good)
sess.run([variables_lib.global_variables_initializer()])
res = sess.run(
ml, {
x: np.array([[1., 1.]]),
m_good[0]: np.array([[0.1, 0.1]]),
m_good[1]: np.array([[0.1, 0.1]])
})
# The numbers in results were not calculated, this is just a
# smoke test. However, these numbers should match those of
# the test testMultiRNNCell.
self.assertAllClose(res[0], [[0.175991, 0.175991]])
self.assertAllClose(res[1], [[0.13248, 0.13248]])
def testDeviceWrapperSerialization(self):
wrapper_cls = rnn_cell_impl.DeviceWrapper
cell = rnn_cell_impl.LSTMCell(10)
wrapper = wrapper_cls(cell, "/cpu:0")
config = wrapper.get_config()
# Replace the cell in the config with real cell instance to work around the
# reverse keras dependency issue.
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
self.assertDictEqual(config, reconstructed_wrapper.get_config())
self.assertIsInstance(reconstructed_wrapper, wrapper_cls)
def testResidualWrapperSerialization(self):
wrapper_cls = rnn_cell_impl.ResidualWrapper
cell = rnn_cell_impl.LSTMCell(10)
wrapper = wrapper_cls(cell)
config = wrapper.get_config()
# Replace the cell in the config with real cell instance to work around the
# reverse keras dependency issue.
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
self.assertDictEqual(config, reconstructed_wrapper.get_config())
self.assertIsInstance(reconstructed_wrapper, wrapper_cls)
wrapper = wrapper_cls(cell, residual_fn=lambda i, o: i + i + o)
config = wrapper.get_config()
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
# Assert the reconstructed function will perform the math correctly.
self.assertEqual(reconstructed_wrapper._residual_fn(1, 2), 4)
def residual_fn(inputs, outputs):
return inputs * 3 + outputs
wrapper = wrapper_cls(cell, residual_fn=residual_fn)
config = wrapper.get_config()
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
# Assert the reconstructed function will perform the math correctly.
self.assertEqual(reconstructed_wrapper._residual_fn(1, 2), 5)
def testDropoutWrapperSerialization(self):
wrapper_cls = rnn_cell_impl.DropoutWrapper
cell = rnn_cell_impl.LSTMCell(10)
wrapper = wrapper_cls(cell)
config = wrapper.get_config()
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
self.assertDictEqual(config, reconstructed_wrapper.get_config())
self.assertIsInstance(reconstructed_wrapper, wrapper_cls)
wrapper = wrapper_cls(cell, dropout_state_filter_visitor=lambda s: True)
config = wrapper.get_config()
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
self.assertTrue(reconstructed_wrapper._dropout_state_filter(None))
def dropout_state_filter_visitor(unused_state):
return False
wrapper = wrapper_cls(
cell, dropout_state_filter_visitor=dropout_state_filter_visitor)
config = wrapper.get_config()
config_copy = config.copy()
config_copy["cell"] = rnn_cell_impl.LSTMCell.from_config(
config_copy["cell"]["config"])
reconstructed_wrapper = wrapper_cls.from_config(config_copy)
self.assertFalse(reconstructed_wrapper._dropout_state_filter(None))
def testSavedModel(self):
if test_util.is_gpu_available():
self.skipTest("b/175887901")
with self.cached_session():
root = autotrackable.AutoTrackable()
root.cell = rnn_cell_impl.LSTMCell(8)
@def_function.function(input_signature=[tensor.TensorSpec([3, 8])])
def call(x):
state = root.cell.zero_state(3, dtype=x.dtype)
y, _ = root.cell(x, state)
return y
root.call = call
expected = root.call(array_ops.zeros((3, 8)))
self.evaluate(variables_lib.global_variables_initializer())
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
save.save(root, save_dir)
loaded = load.load(save_dir)
self.evaluate(variables_lib.global_variables_initializer())
self.assertAllClose(
expected, loaded.call(array_ops.zeros((3, 8))))
@test_util.run_all_in_graph_and_eager_modes
@test_util.run_all_without_tensor_float_32(
"Uses an LSTMCell, which calls matmul")
| RNNCellTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_views.py | {
"start": 4078,
"end": 6440
} | class ____(TestCase):
def setUp(self):
self.user = new(User, username="test")
self.user.set_password("test")
self.user.save()
self.project = get(Project, slug="my-mainproject")
self.subproject = get(Project, slug="my-subproject")
self.project.add_subproject(self.subproject)
self.client.login(username="test", password="test")
def test_deny_delete_for_non_project_admins(self):
response = self.client.get(
"/dashboard/my-mainproject/subprojects/delete/my-subproject/",
)
self.assertEqual(response.status_code, 404)
self.assertTrue(
self.subproject in [r.child for r in self.project.subprojects.all()],
)
def test_admins_can_delete_subprojects(self):
self.project.users.add(self.user)
self.subproject.users.add(self.user)
# URL doesn't exist anymore, 404
response = self.client.get(
"/dashboard/my-mainproject/subprojects/delete/my-subproject/",
)
self.assertEqual(response.status_code, 404)
# This URL still doesn't accept GET, 405
response = self.client.get(
"/dashboard/my-mainproject/subprojects/my-subproject/delete/",
)
self.assertEqual(response.status_code, 405)
self.assertTrue(
self.subproject in [r.child for r in self.project.subprojects.all()],
)
# Test POST
response = self.client.post(
"/dashboard/my-mainproject/subprojects/my-subproject/delete/",
)
self.assertEqual(response.status_code, 302)
self.assertTrue(
self.subproject not in [r.child for r in self.project.subprojects.all()],
)
def test_project_admins_can_delete_subprojects_that_they_are_not_admin_of(
self,
):
self.project.users.add(self.user)
self.assertFalse(AdminPermission.is_admin(self.user, self.subproject))
response = self.client.post(
"/dashboard/my-mainproject/subprojects/my-subproject/delete/",
)
self.assertEqual(response.status_code, 302)
self.assertTrue(
self.subproject not in [r.child for r in self.project.subprojects.all()],
)
@mock.patch("readthedocs.projects.tasks.builds.update_docs_task", mock.MagicMock())
| SubprojectViewTests |
python | apache__airflow | providers/datadog/src/airflow/providers/datadog/hooks/datadog.py | {
"start": 1060,
"end": 7279
} | class ____(BaseHook, LoggingMixin):
"""
Uses datadog API to send metrics of practically anything measurable.
It's possible to track # of db records inserted/deleted, records read
from file and many other useful metrics.
Depends on the datadog API, which has to be deployed on the same server where
Airflow runs.
:param datadog_conn_id: The connection to datadog, containing metadata for api keys.
"""
conn_name_attr = "datadog_conn_id"
default_conn_name = "datadog_default"
conn_type = "datadog"
hook_name = "Datadog"
def __init__(self, datadog_conn_id: str = "datadog_default") -> None:
super().__init__()
conn = self.get_connection(datadog_conn_id)
self.api_key = conn.extra_dejson.get("api_key", None)
self.app_key = conn.extra_dejson.get("app_key", None)
self.api_host = conn.extra_dejson.get("api_host", None)
self.source_type_name = conn.extra_dejson.get("source_type_name", None)
# If the host is populated, it will use that hostname instead.
# for all metric submissions.
self.host = conn.host
if self.api_key is None:
raise AirflowException("api_key must be specified in the Datadog connection details")
self.log.info("Setting up api keys for Datadog")
initialize(api_key=self.api_key, app_key=self.app_key, api_host=self.api_host)
def validate_response(self, response: dict[str, Any]) -> None:
"""Validate Datadog response."""
if response["status"] != "ok":
self.log.error("Datadog returned: %s", response)
raise AirflowException("Error status received from Datadog")
def send_metric(
self,
metric_name: str,
datapoint: float | int,
tags: list[str] | None = None,
type_: str | None = None,
interval: int | None = None,
) -> dict[str, Any]:
"""
Send a single datapoint metric to Datadog.
:param metric_name: The name of the metric
:param datapoint: A single integer or float related to the metric
:param tags: A list of tags associated with the metric
:param type_: Type of your metric: gauge, rate, or count
:param interval: If the type of the metric is rate or count, define the corresponding interval
"""
response = api.Metric.send(
metric=metric_name, points=datapoint, host=self.host, tags=tags, type=type_, interval=interval
)
self.validate_response(response)
return response
def query_metric(self, query: str, from_seconds_ago: int, to_seconds_ago: int) -> dict[str, Any]:
"""
Query datadog for a metric, potentially with some function applied to it and return the result.
:param query: The datadog query to execute (see datadog docs)
:param from_seconds_ago: How many seconds ago to start querying for.
:param to_seconds_ago: Up to how many seconds ago to query for.
"""
now = int(time.time())
response = api.Metric.query(start=now - from_seconds_ago, end=now - to_seconds_ago, query=query)
self.validate_response(response)
return response
def post_event(
self,
title: str,
text: str,
aggregation_key: str | None = None,
alert_type: str | None = None,
date_happened: int | None = None,
handle: str | None = None,
priority: str | None = None,
related_event_id: int | None = None,
tags: list[str] | None = None,
device_name: list[str] | None = None,
) -> dict[str, Any]:
"""
Post an event to datadog (processing finished, potentially alerts, other issues).
Think about this as a means to maintain persistence of alerts, rather than alerting itself.
:param title: The title of the event
:param text: The body of the event (more information)
:param aggregation_key: Key that can be used to aggregate this event in a stream
:param alert_type: The alert type for the event, one of
["error", "warning", "info", "success"]
:param date_happened: POSIX timestamp of the event; defaults to now
:handle: User to post the event as; defaults to owner of the application key used
to submit.
:param handle: str
:param priority: Priority to post the event as. ("normal" or "low", defaults to "normal")
:param related_event_id: Post event as a child of the given event
:param tags: List of tags to apply to the event
:param device_name: device_name to post the event with
"""
response = api.Event.create(
title=title,
text=text,
aggregation_key=aggregation_key,
alert_type=alert_type,
date_happened=date_happened,
handle=handle,
priority=priority,
related_event_id=related_event_id,
tags=tags,
host=self.host,
device_name=device_name,
source_type_name=self.source_type_name,
)
self.validate_response(response)
return response
@classmethod
def get_connection_form_widgets(cls) -> dict[str, Any]:
"""Return connection widgets to add to connection form."""
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_babel import lazy_gettext
from wtforms import StringField
return {
"api_host": StringField(lazy_gettext("API endpoint"), widget=BS3TextFieldWidget()),
"api_key": StringField(lazy_gettext("API key"), widget=BS3TextFieldWidget()),
"app_key": StringField(lazy_gettext("Application key"), widget=BS3TextFieldWidget()),
"source_type_name": StringField(lazy_gettext("Source type name"), widget=BS3TextFieldWidget()),
}
@classmethod
def get_ui_field_behaviour(cls) -> dict[str, Any]:
"""Return custom field behaviour."""
return {
"hidden_fields": ["schema", "login", "password", "port", "extra"],
"relabeling": {"host": "Events host name"},
}
| DatadogHook |
python | google__jax | jax/_src/pallas/mosaic/lowering.py | {
"start": 5520,
"end": 6784
} | class ____:
dim_expr_to_placeholder: dict[shape_poly._DimExpr, int] = {}
placeholder_to_dim_expr: dict[int, shape_poly._DimExpr] = {}
def to_placeholder(self, dim_expr: Any) -> ir.Value:
if jax_core.is_constant_dim(dim_expr):
# avoid ints, these are not dynamic
return dim_expr
if dim_expr not in self.dim_expr_to_placeholder:
next_val = DIM_UPPER_BOUND - len(self.dim_expr_to_placeholder)
if next_val < DIM_LOWER_BOUND:
# In practice, even with the largest of programs, we see rarely see
# anything even close to this limit. It is arbitrary, and can be safely
# increased if needed.
raise ValueError(
"Too many dynamic shapes in the input. Mosaic currently only"
" supports up to 128 dynamic dimension values."
)
self.dim_expr_to_placeholder[dim_expr] = next_val
# Reverse mapping - this is consumed to generate a table that is either
# input<>placeholder or intermediary computation<>placeholder.
self.placeholder_to_dim_expr[next_val] = dim_expr
return self.dim_expr_to_placeholder[dim_expr]
DynamicShapeReplacementFn = Callable[
[tuple[jax_core.DimSize, ...]], tuple[int, ...]
]
@dataclasses.dataclass
| LoweringDynamicShapeEnv |
python | django__django | tests/test_runner/tests.py | {
"start": 10445,
"end": 14012
} | class ____(unittest.TestCase):
def test_simple_dependencies(self):
raw = [
("s1", ("s1_db", ["alpha"])),
("s2", ("s2_db", ["bravo"])),
("s3", ("s3_db", ["charlie"])),
]
dependencies = {
"alpha": ["charlie"],
"bravo": ["charlie"],
}
ordered = dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig, value in ordered]
self.assertIn("s1", ordered_sigs)
self.assertIn("s2", ordered_sigs)
self.assertIn("s3", ordered_sigs)
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1"))
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2"))
def test_chained_dependencies(self):
raw = [
("s1", ("s1_db", ["alpha"])),
("s2", ("s2_db", ["bravo"])),
("s3", ("s3_db", ["charlie"])),
]
dependencies = {
"alpha": ["bravo"],
"bravo": ["charlie"],
}
ordered = dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig, value in ordered]
self.assertIn("s1", ordered_sigs)
self.assertIn("s2", ordered_sigs)
self.assertIn("s3", ordered_sigs)
# Explicit dependencies
self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1"))
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2"))
# Implied dependencies
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1"))
def test_multiple_dependencies(self):
raw = [
("s1", ("s1_db", ["alpha"])),
("s2", ("s2_db", ["bravo"])),
("s3", ("s3_db", ["charlie"])),
("s4", ("s4_db", ["delta"])),
]
dependencies = {
"alpha": ["bravo", "delta"],
"bravo": ["charlie"],
"delta": ["charlie"],
}
ordered = dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig, aliases in ordered]
self.assertIn("s1", ordered_sigs)
self.assertIn("s2", ordered_sigs)
self.assertIn("s3", ordered_sigs)
self.assertIn("s4", ordered_sigs)
# Explicit dependencies
self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1"))
self.assertLess(ordered_sigs.index("s4"), ordered_sigs.index("s1"))
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2"))
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s4"))
# Implicit dependencies
self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1"))
def test_circular_dependencies(self):
raw = [
("s1", ("s1_db", ["alpha"])),
("s2", ("s2_db", ["bravo"])),
]
dependencies = {
"bravo": ["alpha"],
"alpha": ["bravo"],
}
with self.assertRaises(ImproperlyConfigured):
dependency_ordered(raw, dependencies=dependencies)
def test_own_alias_dependency(self):
raw = [("s1", ("s1_db", ["alpha", "bravo"]))]
dependencies = {"alpha": ["bravo"]}
with self.assertRaises(ImproperlyConfigured):
dependency_ordered(raw, dependencies=dependencies)
# reordering aliases shouldn't matter
raw = [("s1", ("s1_db", ["bravo", "alpha"]))]
with self.assertRaises(ImproperlyConfigured):
dependency_ordered(raw, dependencies=dependencies)
| DependencyOrderingTests |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 16297,
"end": 18337
} | class ____(TestCase, RowDeprecationTestMixin):
def setUp(self):
self.value = Decimal("11.111")
self.widget = widgets.DecimalWidget()
def test_clean(self):
self.assertEqual(self.widget.clean("11.111"), self.value)
self.assertEqual(self.widget.clean(11.111), self.value)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_clean_numeric_separators(self):
self.assertEqual(self.widget.clean("1,234.5"), Decimal("1234.5"))
@override_settings(LANGUAGE_CODE="ar", USE_THOUSAND_SEPARATOR=True)
def test_clean_numeric_separators_arabic(self):
self.assertEqual(self.widget.clean("1.234,5"), Decimal("1234.5"))
@override_settings(LANGUAGE_CODE="zh-hans", USE_THOUSAND_SEPARATOR=True)
def test_clean_numeric_separators_chinese_simplified(self):
self.assertEqual(self.widget.clean("1234.5"), Decimal("1234.5"))
@override_settings(LANGUAGE_CODE="fr", USE_THOUSAND_SEPARATOR=True)
def test_clean_numeric_separators_french(self):
self.assertEqual(self.widget.clean("1\xa0234,5"), Decimal("1234.5"))
def test_render_coerce_to_string_is_False(self):
self.widget = widgets.DecimalWidget(coerce_to_string=False)
self.assertEqual(self.widget.render(self.value), self.value)
def test_render(self):
self.assertEqual(self.widget.render(self.value), "11.111")
def test_render_invalid_type(self):
self.assertEqual(self.widget.render("1"), "")
def test_clean_string_zero(self):
self.assertEqual(self.widget.clean("0"), Decimal("0"))
self.assertEqual(self.widget.clean("0.0"), Decimal("0"))
def test_clean_empty_string(self):
self.assertEqual(self.widget.clean(""), None)
self.assertEqual(self.widget.clean(" "), None)
self.assertEqual(self.widget.clean("\r\n\t"), None)
@override_settings(LANGUAGE_CODE="fr-fr")
def test_locale_render_coerce_to_string_gte4(self):
self.assertEqual(self.widget.render(self.value), "11,111")
| DecimalWidgetTest |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/hoverlabel/_font.py | {
"start": 233,
"end": 17168
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.hoverlabel"
_path_str = "scattersmith.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scattersmith.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scattersmith.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattersmith.hoverlabel.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("family", arg, family)
self._set_property("familysrc", arg, familysrc)
self._set_property("lineposition", arg, lineposition)
self._set_property("linepositionsrc", arg, linepositionsrc)
self._set_property("shadow", arg, shadow)
self._set_property("shadowsrc", arg, shadowsrc)
self._set_property("size", arg, size)
self._set_property("sizesrc", arg, sizesrc)
self._set_property("style", arg, style)
self._set_property("stylesrc", arg, stylesrc)
self._set_property("textcase", arg, textcase)
self._set_property("textcasesrc", arg, textcasesrc)
self._set_property("variant", arg, variant)
self._set_property("variantsrc", arg, variantsrc)
self._set_property("weight", arg, weight)
self._set_property("weightsrc", arg, weightsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | pandas-dev__pandas | pandas/io/excel/_odswriter.py | {
"start": 595,
"end": 11519
} | class ____(ExcelWriter):
_engine = "odf"
_supported_extensions = (".ods",)
def __init__( # pyright: ignore[reportInconsistentConstructor]
self,
path: FilePath | WriteExcelBuffer | ExcelWriter,
engine: str | None = None,
date_format: str | None = None,
datetime_format: str | None = None,
mode: str = "w",
storage_options: StorageOptions | None = None,
if_sheet_exists: ExcelWriterIfSheetExists | None = None,
engine_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
from odf.opendocument import OpenDocumentSpreadsheet
if mode == "a":
raise ValueError("Append mode is not supported with odf!")
engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
self._book = OpenDocumentSpreadsheet(**engine_kwargs)
super().__init__(
path,
mode=mode,
storage_options=storage_options,
if_sheet_exists=if_sheet_exists,
engine_kwargs=engine_kwargs,
)
self._style_dict: dict[str, str] = {}
@property
def book(self) -> OpenDocumentSpreadsheet:
"""
Book instance of class odf.opendocument.OpenDocumentSpreadsheet.
This attribute can be used to access engine-specific features.
"""
return self._book
@property
def sheets(self) -> dict[str, Any]:
"""Mapping of sheet names to sheet objects."""
from odf.table import Table
result = {
sheet.getAttribute("name"): sheet
for sheet in self.book.getElementsByType(Table)
}
return result
def _save(self) -> None:
"""
Save workbook to disk.
"""
for sheet in self.sheets.values():
self.book.spreadsheet.addElement(sheet)
self.book.save(self._handles.handle)
def _write_cells(
self,
cells: list[ExcelCell],
sheet_name: str | None = None,
startrow: int = 0,
startcol: int = 0,
freeze_panes: tuple[int, int] | None = None,
autofilter_range: str | None = None,
) -> None:
"""
Write the frame cells using odf
"""
if autofilter_range:
raise ValueError("Autofilter is not supported with odf!")
from odf.table import (
Table,
TableCell,
TableRow,
)
from odf.text import P
sheet_name = self._get_sheet_name(sheet_name)
assert sheet_name is not None
if sheet_name in self.sheets:
wks = self.sheets[sheet_name]
else:
wks = Table(name=sheet_name)
self.book.spreadsheet.addElement(wks)
if validate_freeze_panes(freeze_panes):
freeze_panes = cast(tuple[int, int], freeze_panes)
self._create_freeze_panes(sheet_name, freeze_panes)
for _ in range(startrow):
wks.addElement(TableRow())
rows: DefaultDict = defaultdict(TableRow)
col_count: DefaultDict = defaultdict(int)
for cell in sorted(cells, key=lambda cell: (cell.row, cell.col)):
# only add empty cells if the row is still empty
if not col_count[cell.row]:
for _ in range(startcol):
rows[cell.row].addElement(TableCell())
# fill with empty cells if needed
for _ in range(cell.col - col_count[cell.row]):
rows[cell.row].addElement(TableCell())
col_count[cell.row] += 1
pvalue, tc = self._make_table_cell(cell)
rows[cell.row].addElement(tc)
col_count[cell.row] += 1
p = P(text=pvalue)
tc.addElement(p)
# add all rows to the sheet
if len(rows) > 0:
for row_nr in range(max(rows.keys()) + 1):
wks.addElement(rows[row_nr])
def _make_table_cell_attributes(self, cell: ExcelCell) -> dict[str, int | str]:
"""Convert cell attributes to OpenDocument attributes
Parameters
----------
cell : ExcelCell
Spreadsheet cell data
Returns
-------
attributes : Dict[str, Union[int, str]]
Dictionary with attributes and attribute values
"""
attributes: dict[str, int | str] = {}
style_name = self._process_style(cell.style)
if style_name is not None:
attributes["stylename"] = style_name
if cell.mergestart is not None and cell.mergeend is not None:
attributes["numberrowsspanned"] = max(1, cell.mergestart)
attributes["numbercolumnsspanned"] = cell.mergeend
return attributes
def _make_table_cell(self, cell: ExcelCell) -> tuple[object, Any]:
"""Convert cell data to an OpenDocument spreadsheet cell
Parameters
----------
cell : ExcelCell
Spreadsheet cell data
Returns
-------
pvalue, cell : Tuple[str, TableCell]
Display value, Cell value
"""
from odf.table import TableCell
attributes = self._make_table_cell_attributes(cell)
val, fmt = self._value_with_fmt(cell.val)
pvalue = value = val
if isinstance(val, bool):
value = str(val).lower()
pvalue = str(val).upper()
return (
pvalue,
TableCell(
valuetype="boolean",
booleanvalue=value,
attributes=attributes,
),
)
elif isinstance(val, datetime.datetime):
# Fast formatting
value = val.isoformat()
# Slow but locale-dependent
pvalue = val.strftime("%c")
return (
pvalue,
TableCell(valuetype="date", datevalue=value, attributes=attributes),
)
elif isinstance(val, datetime.date):
# Fast formatting
value = f"{val.year}-{val.month:02d}-{val.day:02d}"
# Slow but locale-dependent
pvalue = val.strftime("%x")
return (
pvalue,
TableCell(valuetype="date", datevalue=value, attributes=attributes),
)
elif isinstance(val, str):
return (
pvalue,
TableCell(
valuetype="string",
stringvalue=value,
attributes=attributes,
),
)
else:
return (
pvalue,
TableCell(
valuetype="float",
value=value,
attributes=attributes,
),
)
@overload
def _process_style(self, style: dict[str, Any]) -> str: ...
@overload
def _process_style(self, style: None) -> None: ...
def _process_style(self, style: dict[str, Any] | None) -> str | None:
"""Convert a style dictionary to an OpenDocument style sheet
Parameters
----------
style : Dict
Style dictionary
Returns
-------
style_key : str
Unique style key for later reference in sheet
"""
from odf.style import (
ParagraphProperties,
Style,
TableCellProperties,
TextProperties,
)
if style is None:
return None
style_key = json.dumps(style)
if style_key in self._style_dict:
return self._style_dict[style_key]
name = f"pd{len(self._style_dict) + 1}"
self._style_dict[style_key] = name
odf_style = Style(name=name, family="table-cell")
if "font" in style:
font = style["font"]
if font.get("bold", False):
odf_style.addElement(TextProperties(fontweight="bold"))
if "borders" in style:
borders = style["borders"]
for side, thickness in borders.items():
thickness_translation = {"thin": "0.75pt solid #000000"}
odf_style.addElement(
TableCellProperties(
attributes={f"border{side}": thickness_translation[thickness]}
)
)
if "alignment" in style:
alignment = style["alignment"]
horizontal = alignment.get("horizontal")
if horizontal:
odf_style.addElement(ParagraphProperties(textalign=horizontal))
vertical = alignment.get("vertical")
if vertical:
odf_style.addElement(TableCellProperties(verticalalign=vertical))
self.book.styles.addElement(odf_style)
return name
def _create_freeze_panes(
self, sheet_name: str, freeze_panes: tuple[int, int]
) -> None:
"""
Create freeze panes in the sheet.
Parameters
----------
sheet_name : str
Name of the spreadsheet
freeze_panes : tuple of (int, int)
Freeze pane location x and y
"""
from odf.config import (
ConfigItem,
ConfigItemMapEntry,
ConfigItemMapIndexed,
ConfigItemMapNamed,
ConfigItemSet,
)
config_item_set = ConfigItemSet(name="ooo:view-settings")
self.book.settings.addElement(config_item_set)
config_item_map_indexed = ConfigItemMapIndexed(name="Views")
config_item_set.addElement(config_item_map_indexed)
config_item_map_entry = ConfigItemMapEntry()
config_item_map_indexed.addElement(config_item_map_entry)
config_item_map_named = ConfigItemMapNamed(name="Tables")
config_item_map_entry.addElement(config_item_map_named)
config_item_map_entry = ConfigItemMapEntry(name=sheet_name)
config_item_map_named.addElement(config_item_map_entry)
config_item_map_entry.addElement(
ConfigItem(name="HorizontalSplitMode", type="short", text="2")
)
config_item_map_entry.addElement(
ConfigItem(name="VerticalSplitMode", type="short", text="2")
)
config_item_map_entry.addElement(
ConfigItem(
name="HorizontalSplitPosition", type="int", text=str(freeze_panes[0])
)
)
config_item_map_entry.addElement(
ConfigItem(
name="VerticalSplitPosition", type="int", text=str(freeze_panes[1])
)
)
config_item_map_entry.addElement(
ConfigItem(name="PositionRight", type="int", text=str(freeze_panes[0]))
)
config_item_map_entry.addElement(
ConfigItem(name="PositionBottom", type="int", text=str(freeze_panes[1]))
)
| ODSWriter |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/base.py | {
"start": 1090,
"end": 15804
} | class ____(
RunnableSerializable[dict, PromptValue], ABC, Generic[FormatOutputType]
):
"""Base class for all prompt templates, returning a prompt."""
input_variables: list[str]
"""A list of the names of the variables whose values are required as inputs to the
prompt.
"""
optional_variables: list[str] = Field(default=[])
"""A list of the names of the variables for placeholder or `MessagePlaceholder` that
are optional.
These variables are auto inferred from the prompt and user need not provide them.
"""
input_types: typing.Dict[str, Any] = Field(default_factory=dict, exclude=True) # noqa: UP006
"""A dictionary of the types of the variables the prompt template expects.
If not provided, all variables are assumed to be strings.
"""
output_parser: BaseOutputParser | None = None
"""How to parse the output of calling an LLM on this formatted prompt."""
partial_variables: Mapping[str, Any] = Field(default_factory=dict)
"""A dictionary of the partial variables the prompt template carries.
Partial variables populate the template so that you don't need to pass them in every
time you call the prompt.
"""
metadata: typing.Dict[str, Any] | None = None # noqa: UP006
"""Metadata to be used for tracing."""
tags: list[str] | None = None
"""Tags to be used for tracing."""
@model_validator(mode="after")
def validate_variable_names(self) -> Self:
"""Validate variable names do not include restricted names."""
if "stop" in self.input_variables:
msg = (
"Cannot have an input variable named 'stop', as it is used internally,"
" please rename."
)
raise ValueError(
create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
)
if "stop" in self.partial_variables:
msg = (
"Cannot have an partial variable named 'stop', as it is used "
"internally, please rename."
)
raise ValueError(
create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
)
overall = set(self.input_variables).intersection(self.partial_variables)
if overall:
msg = f"Found overlapping input and partial variables: {overall}"
raise ValueError(
create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
)
return self
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "prompt_template"]`
"""
return ["langchain", "schema", "prompt_template"]
@classmethod
def is_lc_serializable(cls) -> bool:
"""Return `True` as this class is serializable."""
return True
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
@cached_property
def _serialized(self) -> dict[str, Any]:
return dumpd(self)
@property
@override
def OutputType(self) -> Any:
"""Return the output type of the prompt."""
return StringPromptValue | ChatPromptValueConcrete
@override
def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
"""Get the input schema for the prompt.
Args:
config: Configuration for the prompt.
Returns:
The input schema for the prompt.
"""
# This is correct, but pydantic typings/mypy don't think so.
required_input_variables = {
k: (self.input_types.get(k, str), ...) for k in self.input_variables
}
optional_input_variables = {
k: (self.input_types.get(k, str), None) for k in self.optional_variables
}
return create_model_v2(
"PromptInput",
field_definitions={**required_input_variables, **optional_input_variables},
)
def _validate_input(self, inner_input: Any) -> dict:
if not isinstance(inner_input, dict):
if len(self.input_variables) == 1:
var_name = self.input_variables[0]
inner_input = {var_name: inner_input}
else:
msg = (
f"Expected mapping type as input to {self.__class__.__name__}. "
f"Received {type(inner_input)}."
)
raise TypeError(
create_message(
message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT
)
)
missing = set(self.input_variables).difference(inner_input)
if missing:
msg = (
f"Input to {self.__class__.__name__} is missing variables {missing}. "
f" Expected: {self.input_variables}"
f" Received: {list(inner_input.keys())}"
)
example_key = missing.pop()
msg += (
f"\nNote: if you intended {{{example_key}}} to be part of the string"
" and not a variable, please escape it with double curly braces like: "
f"'{{{{{example_key}}}}}'."
)
raise KeyError(
create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
)
return inner_input
def _format_prompt_with_error_handling(self, inner_input: dict) -> PromptValue:
inner_input_ = self._validate_input(inner_input)
return self.format_prompt(**inner_input_)
async def _aformat_prompt_with_error_handling(
self, inner_input: dict
) -> PromptValue:
inner_input_ = self._validate_input(inner_input)
return await self.aformat_prompt(**inner_input_)
@override
def invoke(
self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
) -> PromptValue:
"""Invoke the prompt.
Args:
input: Input to the prompt.
config: Configuration for the prompt.
Returns:
The output of the prompt.
"""
config = ensure_config(config)
if self.metadata:
config["metadata"] = {**config["metadata"], **self.metadata}
if self.tags:
config["tags"] += self.tags
return self._call_with_config(
self._format_prompt_with_error_handling,
input,
config,
run_type="prompt",
serialized=self._serialized,
)
@override
async def ainvoke(
self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
) -> PromptValue:
"""Async invoke the prompt.
Args:
input: Input to the prompt.
config: Configuration for the prompt.
Returns:
The output of the prompt.
"""
config = ensure_config(config)
if self.metadata:
config["metadata"].update(self.metadata)
if self.tags:
config["tags"].extend(self.tags)
return await self._acall_with_config(
self._aformat_prompt_with_error_handling,
input,
config,
run_type="prompt",
serialized=self._serialized,
)
@abstractmethod
def format_prompt(self, **kwargs: Any) -> PromptValue:
"""Create `PromptValue`.
Args:
**kwargs: Any arguments to be passed to the prompt template.
Returns:
The output of the prompt.
"""
async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
"""Async create `PromptValue`.
Args:
**kwargs: Any arguments to be passed to the prompt template.
Returns:
The output of the prompt.
"""
return self.format_prompt(**kwargs)
def partial(self, **kwargs: str | Callable[[], str]) -> BasePromptTemplate:
"""Return a partial of the prompt template.
Args:
**kwargs: Partial variables to set.
Returns:
A partial of the prompt template.
"""
prompt_dict = self.__dict__.copy()
prompt_dict["input_variables"] = list(
set(self.input_variables).difference(kwargs)
)
prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
return type(self)(**prompt_dict)
def _merge_partial_and_user_variables(self, **kwargs: Any) -> dict[str, Any]:
# Get partial params:
partial_kwargs = {
k: v if not callable(v) else v() for k, v in self.partial_variables.items()
}
return {**partial_kwargs, **kwargs}
@abstractmethod
def format(self, **kwargs: Any) -> FormatOutputType:
"""Format the prompt with the inputs.
Args:
**kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
```python
prompt.format(variable1="foo")
```
"""
async def aformat(self, **kwargs: Any) -> FormatOutputType:
"""Async format the prompt with the inputs.
Args:
**kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
```python
await prompt.aformat(variable1="foo")
```
"""
return self.format(**kwargs)
@property
def _prompt_type(self) -> str:
"""Return the prompt type key."""
raise NotImplementedError
def dict(self, **kwargs: Any) -> dict:
"""Return dictionary representation of prompt.
Args:
**kwargs: Any additional arguments to pass to the dictionary.
Returns:
Dictionary representation of the prompt.
"""
prompt_dict = super().model_dump(**kwargs)
with contextlib.suppress(NotImplementedError):
prompt_dict["_type"] = self._prompt_type
return prompt_dict
def save(self, file_path: Path | str) -> None:
"""Save the prompt.
Args:
file_path: Path to directory to save prompt to.
Raises:
ValueError: If the prompt has partial variables.
ValueError: If the file path is not json or yaml.
NotImplementedError: If the prompt type is not implemented.
Example:
```python
prompt.save(file_path="path/prompt.yaml")
```
"""
if self.partial_variables:
msg = "Cannot save prompt with partial variables."
raise ValueError(msg)
# Fetch dictionary to save
prompt_dict = self.dict()
if "_type" not in prompt_dict:
msg = f"Prompt {self} does not support saving."
raise NotImplementedError(msg)
# Convert file to Path object.
save_path = Path(file_path)
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
if save_path.suffix == ".json":
with save_path.open("w", encoding="utf-8") as f:
json.dump(prompt_dict, f, indent=4)
elif save_path.suffix.endswith((".yaml", ".yml")):
with save_path.open("w", encoding="utf-8") as f:
yaml.dump(prompt_dict, f, default_flow_style=False)
else:
msg = f"{save_path} must be json or yaml"
raise ValueError(msg)
def _get_document_info(doc: Document, prompt: BasePromptTemplate[str]) -> dict:
base_info = {"page_content": doc.page_content, **doc.metadata}
missing_metadata = set(prompt.input_variables).difference(base_info)
if len(missing_metadata) > 0:
required_metadata = [
iv for iv in prompt.input_variables if iv != "page_content"
]
msg = (
f"Document prompt requires documents to have metadata variables: "
f"{required_metadata}. Received document with missing metadata: "
f"{list(missing_metadata)}."
)
raise ValueError(
create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
)
return {k: base_info[k] for k in prompt.input_variables}
def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
"""Format a document into a string based on a prompt template.
First, this pulls information from the document from two sources:
1. `page_content`:
This takes the information from the `document.page_content` and assigns it to a
variable named `page_content`.
2. `metadata`:
This takes information from `document.metadata` and assigns it to variables of
the same name.
Those variables are then passed into the `prompt` to produce a formatted string.
Args:
doc: `Document`, the `page_content` and `metadata` will be used to create
the final string.
prompt: `BasePromptTemplate`, will be used to format the `page_content`
and `metadata` into the final string.
Returns:
String of the document formatted.
Example:
```python
from langchain_core.documents import Document
from langchain_core.prompts import PromptTemplate
doc = Document(page_content="This is a joke", metadata={"page": "1"})
prompt = PromptTemplate.from_template("Page {page}: {page_content}")
format_document(doc, prompt)
>>> "Page 1: This is a joke"
```
"""
return prompt.format(**_get_document_info(doc, prompt))
async def aformat_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
"""Async format a document into a string based on a prompt template.
First, this pulls information from the document from two sources:
1. `page_content`:
This takes the information from the `document.page_content` and assigns it to a
variable named `page_content`.
2. `metadata`:
This takes information from `document.metadata` and assigns it to variables of
the same name.
Those variables are then passed into the `prompt` to produce a formatted string.
Args:
doc: `Document`, the `page_content` and `metadata` will be used to create
the final string.
prompt: `BasePromptTemplate`, will be used to format the `page_content`
and `metadata` into the final string.
Returns:
String of the document formatted.
"""
return await prompt.aformat(**_get_document_info(doc, prompt))
| BasePromptTemplate |
python | huggingface__transformers | src/transformers/models/idefics/modeling_idefics.py | {
"start": 2114,
"end": 3782
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
hidden_size)` is output.
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
input) to speed up sequential decoding.
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
"""
last_hidden_state: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
image_hidden_states: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for Idefics causal language model (or autoregressive) outputs.
"""
)
| IdeficsBaseModelOutputWithPast |
python | tensorflow__tensorflow | tensorflow/python/framework/python_api_dispatcher_test.py | {
"start": 10421,
"end": 13612
} | class ____(test_util.TensorFlowTestCase):
def check_signatures(self, checker, canon_expected_pairs):
for (canon_args, expected) in canon_expected_pairs:
with self.subTest(f'{canon_args} -> {expected}'):
self.assertEqual(checker.CheckCanonicalizedArgs(canon_args), expected)
def testSimpleSignature(self):
int_checker = dispatch.MakeInstanceChecker(int)
rt_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor)
checker = dispatch.PySignatureChecker([(0, int_checker), (2, rt_checker)])
rt = ragged_factory_ops.constant([[1, 2], [3]])
self.check_signatures(checker, [
((1, 2, rt), True),
((1, 2, 3), False),
((1, 2), False), ((), False),
((5, 'x', rt, None), True),
(([5], 'x', rt, None), False),
((5, 'x', [rt], None), False),
]) # pyformat: disable
self.assertEqual(
repr(checker), '<PySignatureChecker args[0]:int, args[2]:RaggedTensor>')
def testUnion(self):
rt_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor)
tensor_checker = dispatch.MakeInstanceChecker(tensor.Tensor)
rt_or_tensor = dispatch.MakeUnionChecker([rt_checker, tensor_checker])
checker = dispatch.PySignatureChecker([(0, rt_or_tensor),
(1, rt_or_tensor)])
t = constant_op.constant([[1, 2], [3, 4]])
rt = ragged_factory_ops.constant([[1, 2], [3]])
self.check_signatures(checker, [
((t, t), False),
((t, rt), True),
((rt, t), True),
((rt, rt), True),
((rt, [rt]), False),
((rt, rt, 1, 2, None), True),
]) # pyformat: disable
self.assertEqual(
repr(checker),
'<PySignatureChecker args[0]:Union[RaggedTensor, Tensor], '
'args[1]:Union[RaggedTensor, Tensor]>')
def testList(self):
rt_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor)
rt_list_checker = dispatch.MakeListChecker(rt_checker)
checker = dispatch.PySignatureChecker([(0, rt_list_checker)])
rt = ragged_factory_ops.constant([[1, 2], [3]])
self.check_signatures(checker, [
(([rt],), True),
(([],), False),
((rt,), False),
(([rt, rt+3, rt*2],), True),
(([rt, rt.values, rt*2],), False),
]) # pyformat: disable
self.assertEqual(
repr(checker), '<PySignatureChecker args[0]:List[RaggedTensor]>')
def testSortByCost(self):
a = dispatch.MakeInstanceChecker(int)
b = dispatch.MakeInstanceChecker(float)
c = dispatch.MakeUnionChecker([a, b])
d = dispatch.MakeListChecker(a)
e = dispatch.MakeListChecker(c)
checker = dispatch.PySignatureChecker([(0, e), (1, c), (2, d), (3, a)])
# Note: `repr(checker)` lists the args in the order they will be checked.
self.assertEqual(
repr(checker), '<PySignatureChecker '
'args[3]:int, ' # a: cost=1
'args[1]:Union[int, float], ' # c: cost=3
'args[2]:List[int], ' # d: cost=10
'args[0]:List[Union[int, float]]>' # e: cost=30
) # pyformat: disable
@test_util.run_all_in_graph_and_eager_modes
| PythonSignatureCheckerTest |
python | django__django | tests/aggregation_regress/tests.py | {
"start": 71422,
"end": 71882
} | class ____(TestCase):
def test_ticket_24748(self):
t1 = SelfRefFK.objects.create(name="t1")
SelfRefFK.objects.create(name="t2", parent=t1)
SelfRefFK.objects.create(name="t3", parent=t1)
self.assertQuerySetEqual(
SelfRefFK.objects.annotate(num_children=Count("children")).order_by("name"),
[("t1", 2), ("t2", 0), ("t3", 0)],
lambda x: (x.name, x.num_children),
)
| SelfReferentialFKTests |
python | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 8819,
"end": 9164
} | class ____(TypedDict, total=False):
diff: Required[str]
"""Unified diff content to apply when creating the file."""
path: Required[str]
"""Path of the file to create relative to the workspace root."""
type: Required[Literal["create_file"]]
"""The operation type. Always `create_file`."""
| ApplyPatchCallOperationCreateFile |
python | doocs__leetcode | solution/3500-3599/3516.Find Closest Person/Solution.py | {
"start": 0,
"end": 172
} | class ____:
def findClosest(self, x: int, y: int, z: int) -> int:
a = abs(x - z)
b = abs(y - z)
return 0 if a == b else (1 if a < b else 2)
| Solution |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 78134,
"end": 79815
} | class ____(Operation):
def __init__(self, k=0, *, name=None):
super().__init__(name=name)
self.k = k
def call(self, x):
return backend.numpy.diagflat(x, k=self.k)
def compute_output_spec(self, x):
x_shape = x.shape
if len(x_shape) == 0:
flat_size = 1
elif len(x_shape) == 1:
flat_size = x_shape[0] if x_shape[0] is not None else None
else:
flat_size = None
for s in x_shape:
if s is None:
flat_size = None
break
elif flat_size is None:
flat_size = s
else:
flat_size *= s
if flat_size is None:
output_shape = [None, None]
else:
output_shape = [
flat_size + int(np.abs(self.k)),
flat_size + int(np.abs(self.k)),
]
return KerasTensor(output_shape, dtype=x.dtype)
@keras_export(["keras.ops.diagflat", "keras.ops.numpy.diagflat"])
def diagflat(x, k=0):
"""Create a two-dimensional array with the flattened input on
the k-th diagonal.
Args:
x: Input tensor to be flattened and placed on the diagonal.
k: The diagonal to place the flattened input. Defaults to `0`.
Use `k > 0` for diagonals above the main diagonal,
and `k < 0` for diagonals below the main diagonal.
Returns:
A 2-D tensor with the flattened input on the specified diagonal.
"""
if any_symbolic_tensors((x,)):
return Diagflat(k=k).symbolic_call(x)
return backend.numpy.diagflat(x, k=k)
| Diagflat |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_abc_methods.py | {
"start": 120,
"end": 282
} | class ____:
"""Abstract Base Class """
__metaclass__ = abc.ABCMeta
@property
@abc.abstractmethod
def prop(self):
""" Abstract """
| Parent |
python | doocs__leetcode | solution/3200-3299/3292.Minimum Number of Valid Strings to Form Target II/Solution.py | {
"start": 0,
"end": 486
} | class ____:
__slots__ = ["mod", "h", "p"]
def __init__(self, s: List[str], base: int, mod: int):
self.mod = mod
self.h = [0] * (len(s) + 1)
self.p = [1] * (len(s) + 1)
for i in range(1, len(s) + 1):
self.h[i] = (self.h[i - 1] * base + ord(s[i - 1])) % mod
self.p[i] = (self.p[i - 1] * base) % mod
def query(self, l: int, r: int) -> int:
return (self.h[r] - self.h[l - 1] * self.p[r - l + 1]) % self.mod
| Hashing |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 9624,
"end": 9993
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=101, name="SERVICEHOOK_EDIT", api_name="servicehook.edit")
def render(self, audit_log_entry: AuditLogEntry) -> str:
full_url = audit_log_entry.data.get("url")
return f'edited the service hook for "{truncatechars(full_url, 64)}"'
| ServiceHookEditAuditLogEvent |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_slug.py | {
"start": 1807,
"end": 4371
} | class ____(ColumnMapExpectation):
"""Expect value to be valid slug."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_slug": [
"valid_pages",
"for_your_information",
"tour_info",
"football_match_result",
"history_of_2000s",
],
"some_of_them": [
"valid_pages",
"for_your_information",
"tour_info",
"result/football_match",
"history_of_2000+",
],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "all_slug"},
"out": {
"success": True,
},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "some_of_them", "mostly": 0.8},
"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_slug"
# 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",
"tags": [
"hackathon-22",
"experimental",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@szecsip", # Don't forget to add your github handle here!
],
}
if __name__ == "__main__":
ExpectColumnValuesToBeSlug().print_diagnostic_checklist()
| ExpectColumnValuesToBeSlug |
python | django__django | tests/file_storage/tests.py | {
"start": 42868,
"end": 43670
} | class ____(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir)
self.thread = threading.Thread(target=self.save_file, args=["conflict"])
def save_file(self, name):
name = self.storage.save(name, SlowFile(b"Data"))
def test_race_condition(self):
self.thread.start()
self.save_file("conflict")
self.thread.join()
files = sorted(os.listdir(self.storage_dir))
self.assertEqual(files[0], "conflict")
self.assertRegex(files[1], "conflict_%s" % FILE_SUFFIX_REGEX)
@unittest.skipIf(
sys.platform == "win32", "Windows only partially supports umasks and chmod."
)
| FileSaveRaceConditionTest |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 71185,
"end": 145119
} | class ____(mixins.ConfigMethodMixin):
"""Mixin for top-level chart objects such as Chart, LayeredChart, etc."""
_class_is_valid_at_instantiation: bool = False
data: Any
def to_dict( # noqa: C901
self,
validate: bool = True,
*,
format: Literal["vega-lite", "vega"] = "vega-lite",
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Convert the chart to a dictionary suitable for JSON export.
Parameters
----------
validate : bool, optional
If True (default), then validate the result against the schema.
format : {"vega-lite", "vega"}, optional
The chart specification format.
The `"vega"` format relies on the active Vega-Lite compiler plugin, which
by default requires the vl-convert-python package.
ignore : list[str], optional
A list of keys to ignore.
context : dict[str, Any], optional
A context dictionary.
Raises
------
SchemaValidationError :
If ``validate`` and the result does not conform to the schema.
Notes
-----
- ``ignore``, ``context`` are usually not needed to be specified as a user.
- *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`.
"""
# Validate format
if format not in {"vega-lite", "vega"}:
msg = f'The format argument must be either "vega-lite" or "vega". Received {format!r}'
raise ValueError(msg)
# We make use of three context markers:
# - 'data' points to the data that should be referenced for column type
# inference.
# - 'top_level' is a boolean flag that is assumed to be true; if it's
# true then a "$schema" arg is added to the dict.
# - 'datasets' is a dict of named datasets that should be inserted
# in the top-level object
# - 'pre_transform' whether data transformations should be pre-evaluated
# if the current data transformer supports it (currently only used when
# the "vegafusion" transformer is enabled)
# note: not a deep copy because we want datasets and data arguments to
# be passed by reference
context = context.copy() if context else {}
context.setdefault("datasets", {})
is_top_level = context.get("top_level", True)
copy = _top_schema_base(self).copy(deep=False)
original_data = getattr(copy, "data", Undefined)
if not utils.is_undefined(original_data):
try:
data = nw.from_native(original_data, eager_or_interchange_only=True)
except TypeError:
# Non-narwhalifiable type supported by Altair, such as dict
data = original_data
copy.data = _prepare_data(data, context)
context["data"] = data
# remaining to_dict calls are not at top level
context["top_level"] = False
vegalite_spec: Any = _top_schema_base(super(TopLevelMixin, copy)).to_dict(
validate=validate, ignore=ignore, context=dict(context, pre_transform=False)
)
# TODO: following entries are added after validation. Should they be validated?
if is_top_level:
# since this is top-level we add $schema if it's missing
if "$schema" not in vegalite_spec:
vegalite_spec["$schema"] = SCHEMA_URL
if func := theme.get():
vegalite_spec = utils.update_nested(func(), vegalite_spec, copy=True)
else:
msg = (
f"Expected a theme to be set but got {None!r}.\n"
f"Call `themes.enable('default')` to reset the `ThemeRegistry`."
)
raise TypeError(msg)
# update datasets
if context["datasets"]:
vegalite_spec.setdefault("datasets", {}).update(context["datasets"])
if context.get("pre_transform", True) and _using_vegafusion():
if format == "vega-lite":
msg = (
'When the "vegafusion" data transformer is enabled, the \n'
"to_dict() and to_json() chart methods must be called with "
'format="vega". \n'
"For example: \n"
' >>> chart.to_dict(format="vega")\n'
' >>> chart.to_json(format="vega")'
)
raise ValueError(msg)
else:
return _compile_with_vegafusion(vegalite_spec)
elif format == "vega":
plugin = vegalite_compilers.get()
if plugin is None:
msg = "No active vega-lite compiler plugin found"
raise ValueError(msg)
return plugin(vegalite_spec)
else:
return vegalite_spec
def to_json(
self,
validate: bool = True,
indent: int | str | None = 2,
sort_keys: bool = True,
*,
format: Literal["vega-lite", "vega"] = "vega-lite",
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
**kwargs: Any,
) -> str:
"""
Convert a chart to a JSON string.
Parameters
----------
validate : bool, optional
If True (default), then validate the result against the schema.
indent : int, optional
The number of spaces of indentation to use. The default is 2.
sort_keys : bool, optional
If True (default), sort keys in the output.
format : {"vega-lite", "vega"}, optional
The chart specification format.
The `"vega"` format relies on the active Vega-Lite compiler plugin, which
by default requires the vl-convert-python package.
ignore : list[str], optional
A list of keys to ignore.
context : dict[str, Any], optional
A context dictionary.
**kwargs
Additional keyword arguments are passed to ``json.dumps()``
Raises
------
SchemaValidationError :
If ``validate`` and the result does not conform to the schema.
Notes
-----
- ``ignore``, ``context`` are usually not needed to be specified as a user.
- *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`.
"""
if ignore is None:
ignore = []
if context is None:
context = {}
spec = self.to_dict(
validate=validate, format=format, ignore=ignore, context=context
)
return json.dumps(spec, indent=indent, sort_keys=sort_keys, **kwargs)
def to_html(
self,
base_url: str = "https://cdn.jsdelivr.net/npm",
output_div: str = "vis",
embed_options: dict | None = None,
json_kwds: dict | None = None,
fullhtml: bool = True,
requirejs: bool = False,
inline: bool = False,
**kwargs: Any,
) -> str:
"""
Embed a Vega/Vega-Lite spec into an HTML page.
Parameters
----------
base_url : string (optional)
The base url from which to load the javascript libraries.
output_div : string (optional)
The id of the div element where the plot will be shown.
embed_options : dict (optional)
Dictionary of options to pass to the vega-embed script. Default
entry is {'mode': mode}.
json_kwds : dict (optional)
Dictionary of keywords to pass to json.dumps().
fullhtml : boolean (optional)
If True (default) then return a full html page. If False, then return
an HTML snippet that can be embedded into an HTML page.
requirejs : boolean (optional)
If False (default) then load libraries from base_url using <script>
tags. If True, then load libraries using requirejs
inline: bool (optional)
If False (default), the required JavaScript libraries are loaded
from a CDN location in the resulting html file.
If True, the required JavaScript libraries are inlined into the resulting
html file so that it will work without an internet connection.
The vl-convert-python package is required if True.
**kwargs :
additional kwargs passed to spec_to_html.
Returns
-------
output : string
an HTML string for rendering the chart.
"""
if inline:
kwargs["template"] = "inline"
return utils.spec_to_html(
self.to_dict(),
mode="vega-lite",
vegalite_version=VEGALITE_VERSION,
vegaembed_version=VEGAEMBED_VERSION,
vega_version=VEGA_VERSION,
base_url=base_url,
output_div=output_div,
embed_options=embed_options,
json_kwds=json_kwds,
fullhtml=fullhtml,
requirejs=requirejs,
**kwargs,
)
def to_url(self, *, fullscreen: bool = False, validate: bool = True) -> str:
"""
Convert a chart to a URL that opens the chart specification in the Vega chart editor.
The chart specification (including any inline data) is encoded in the URL.
This method requires that the vl-convert-python package is installed.
Parameters
----------
fullscreen : bool
If True, editor will open chart in fullscreen mode. Default False
validate : boolean
If True, then validate the input against the schema.
"""
from altair.utils._importers import import_vl_convert
vlc = import_vl_convert()
if _using_vegafusion():
return vlc.vega_to_url(
self.to_dict(format="vega", validate=validate), fullscreen=fullscreen
)
else:
return vlc.vegalite_to_url(
self.to_dict(validate=validate), fullscreen=fullscreen
)
def open_editor(self, *, fullscreen: bool = False, validate: bool = True) -> None:
"""
Opens the chart specification in the Vega chart editor using the default browser.
Parameters
----------
fullscreen : bool
If True, editor will open chart in fullscreen mode. Default False
validate : boolean
If True, then validate the input against the schema.
"""
import webbrowser
webbrowser.open(self.to_url(fullscreen=fullscreen, validate=validate))
def save(
self,
fp: str | Path | IO,
format: Literal["json", "html", "png", "svg", "pdf"] | None = None,
override_data_transformer: bool = True,
scale_factor: float = 1.0,
mode: str | None = None,
vegalite_version: str = VEGALITE_VERSION,
vega_version: str = VEGA_VERSION,
vegaembed_version: str = VEGAEMBED_VERSION,
embed_options: dict | None = None,
json_kwds: dict | None = None,
engine: str | None = None,
inline: bool = False,
**kwargs: Any,
) -> None:
"""
Save a chart to file in a variety of formats.
Supported formats are json, html, png, svg, pdf; the last three require
the vl-convert-python package to be installed.
Parameters
----------
fp : string filename or file-like object
file in which to write the chart.
format : string (optional)
the format to write: one of ['json', 'html', 'png', 'svg', 'pdf'].
If not specified, the format will be determined from the filename.
override_data_transformer : `boolean` (optional)
If True (default), then the save action will be done with
the MaxRowsError disabled. If False, then do not change the data
transformer.
scale_factor : float (optional)
scale_factor to use to change size/resolution of png or svg output
mode : string (optional)
Must be 'vega-lite'. If not specified, then infer the mode from
the '$schema' property of the spec, or the ``opt`` dictionary.
If it's not specified in either of those places, then use 'vega-lite'.
vegalite_version : string (optional)
For html output, the version of vegalite.js to use
vega_version : string (optional)
For html output, the version of vega.js to use
vegaembed_version : string (optional)
For html output, the version of vegaembed.js to use
embed_options : dict (optional)
The vegaEmbed options dictionary. Default is {}
(See https://github.com/vega/vega-embed for details)
json_kwds : dict (optional)
Additional keyword arguments are passed to the output method
associated with the specified format.
engine: string {'vl-convert'}
the conversion engine to use for 'png', 'svg', and 'pdf' formats
inline: bool (optional)
If False (default), the required JavaScript libraries are loaded
from a CDN location in the resulting html file.
If True, the required JavaScript libraries are inlined into the resulting
html file so that it will work without an internet connection.
The vl-convert-python package is required if True.
**kwargs :
additional kwargs passed to spec_to_mimebundle.
"""
if _ := kwargs.pop("webdriver", None):
utils.deprecated_warn(
"The webdriver argument is not relevant for the new vl-convert engine which replaced altair_saver. "
"The argument will be removed in a future release.",
version="5.0.0",
)
from altair.utils.save import save
kwds: dict[str, Any] = dict(
chart=self,
fp=fp,
format=format,
scale_factor=scale_factor,
mode=mode,
vegalite_version=vegalite_version,
vega_version=vega_version,
vegaembed_version=vegaembed_version,
embed_options=embed_options,
json_kwds=json_kwds,
engine=engine,
inline=inline,
**kwargs,
)
# By default we override the data transformer. This makes it so
# that save() will succeed even for large datasets that would
# normally trigger a MaxRowsError
if override_data_transformer:
with data_transformers.disable_max_rows():
save(**kwds)
else:
save(**kwds)
# Fallback for when rendering fails; the full repr is too long to be
# useful in nearly all cases.
def __repr__(self) -> str:
return f"alt.{self.__class__.__name__}(...)"
# Layering and stacking
def __add__(self, other: ChartType) -> LayerChart:
if not is_chart_type(other):
msg = "Only Chart objects can be layered."
raise ValueError(msg)
return layer(t.cast("ChartType", self), other)
def __and__(self, other: ChartType) -> VConcatChart:
if not is_chart_type(other):
msg = "Only Chart objects can be concatenated."
raise ValueError(msg)
# Too difficult to type check this
return vconcat(t.cast("ChartType", self), other)
def __or__(self, other: ChartType) -> HConcatChart | ConcatChart:
if not is_chart_type(other):
msg = "Only Chart objects can be concatenated."
raise ValueError(msg)
elif isinstance(self, ConcatChart):
return concat(self, other)
else:
return hconcat(t.cast("ChartType", self), other)
def repeat(
self,
repeat: Optional[list[str]] = Undefined,
row: Optional[list[str]] = Undefined,
column: Optional[list[str]] = Undefined,
layer: Optional[list[str]] = Undefined,
columns: Optional[int] = Undefined,
**kwargs: Any,
) -> RepeatChart:
"""
Return a RepeatChart built from the chart.
Fields within the chart can be set to correspond to the row or
column using `alt.repeat('row')` and `alt.repeat('column')`.
Parameters
----------
repeat : list
a list of data column names to be repeated. This cannot be
used along with the ``row``, ``column`` or ``layer`` argument.
row : list
a list of data column names to be mapped to the row facet
column : list
a list of data column names to be mapped to the column facet
layer : list
a list of data column names to be layered. This cannot be
used along with the ``row``, ``column`` or ``repeat`` argument.
columns : int
the maximum number of columns before wrapping. Only referenced
if ``repeat`` is specified.
**kwargs :
additional keywords passed to RepeatChart.
Returns
-------
chart : RepeatChart
a repeated chart.
"""
repeat_specified = repeat is not Undefined
rowcol_specified = row is not Undefined or column is not Undefined
layer_specified = layer is not Undefined
if repeat_specified and rowcol_specified:
msg = "repeat argument cannot be combined with row/column argument."
raise ValueError(msg)
elif repeat_specified and layer_specified:
msg = "repeat argument cannot be combined with layer argument."
raise ValueError(msg)
repeat_arg: list[str] | LayerRepeatMapping | RepeatMapping
if repeat_specified:
assert isinstance(repeat, list)
repeat_arg = repeat
elif layer_specified:
repeat_arg = core.LayerRepeatMapping(layer=layer, row=row, column=column)
else:
repeat_arg = core.RepeatMapping(row=row, column=column)
return RepeatChart(
spec=t.cast("ChartType", self), repeat=repeat_arg, columns=columns, **kwargs
)
def properties(self, **kwargs: Any) -> Self:
"""
Set top-level properties of the Chart.
Argument names and types are the same as class initialization.
"""
copy = _top_schema_base(self).copy(deep=False)
for key, val in kwargs.items():
if key == "selection" and isinstance(val, Parameter):
# TODO: Can this be removed
# For backward compatibility with old selection interface.
setattr(copy, key, {val.name: val.selection})
else:
# Don't validate data, because it hasn't been processed.
if key != "data":
_top_schema_base(self).validate_property(key, val)
setattr(copy, key, val)
return t.cast("Self", copy)
def project(
self,
type: Optional[
ProjectionType_T | ProjectionType | ExprRef | Parameter
] = Undefined,
center: Optional[list[float] | Vector2number | ExprRef | Parameter] = Undefined,
clipAngle: Optional[float | ExprRef | Parameter] = Undefined,
clipExtent: Optional[
list[list[float]] | Vector2Vector2number | ExprRef | Parameter
] = Undefined,
coefficient: Optional[float | ExprRef | Parameter] = Undefined,
distance: Optional[float | ExprRef | Parameter] = Undefined,
fraction: Optional[float | ExprRef | Parameter] = Undefined,
lobes: Optional[float | ExprRef | Parameter] = Undefined,
parallel: Optional[float | ExprRef | Parameter] = Undefined,
precision: Optional[float | ExprRef | Parameter] = Undefined,
radius: Optional[float | ExprRef | Parameter] = Undefined,
ratio: Optional[float | ExprRef | Parameter] = Undefined,
reflectX: Optional[bool | ExprRef | Parameter] = Undefined,
reflectY: Optional[bool | ExprRef | Parameter] = Undefined,
rotate: Optional[
list[float] | Vector2number | Vector3number | ExprRef | Parameter
] = Undefined,
scale: Optional[float | ExprRef | Parameter] = Undefined,
spacing: Optional[float | Vector2number | ExprRef | Parameter] = Undefined,
tilt: Optional[float | ExprRef | Parameter] = Undefined,
translate: Optional[
list[float] | Vector2number | ExprRef | Parameter
] = Undefined,
**kwds: Any,
) -> Self:
"""
Add a geographic projection to the chart.
This is generally used either with ``mark_geoshape`` or with the
``latitude``/``longitude`` encodings.
Available projection types are
['albers', 'albersUsa', 'azimuthalEqualArea', 'azimuthalEquidistant',
'conicConformal', 'conicEqualArea', 'conicEquidistant', 'equalEarth', 'equirectangular',
'gnomonic', 'identity', 'mercator', 'orthographic', 'stereographic', 'transverseMercator']
Parameters
----------
type : str
The cartographic projection to use. This value is case-insensitive, for example
`"albers"` and `"Albers"` indicate the same projection type. You can find all valid
projection types [in the
documentation](https://vega.github.io/vega-lite/docs/projection.html#projection-types).
**Default value:** `equalEarth`
center : List(float)
Sets the projection's center to the specified center, a two-element array of
longitude and latitude in degrees.
**Default value:** `[0, 0]`
clipAngle : float
Sets the projection's clipping circle radius to the specified angle in degrees. If
`null`, switches to [antimeridian](http://bl.ocks.org/mbostock/3788999) cutting
rather than small-circle clipping.
clipExtent : List(List(float))
Sets the projection's viewport clip extent to the specified bounds in pixels. The
extent bounds are specified as an array `[[x0, y0], [x1, y1]]`, where `x0` is the
left-side of the viewport, `y0` is the top, `x1` is the right and `y1` is the
bottom. If `null`, no viewport clipping is performed.
coefficient : float
The coefficient parameter for the ``hammer`` projection.
**Default value:** ``2``
distance : float
For the ``satellite`` projection, the distance from the center of the sphere to the
point of view, as a proportion of the sphere's radius. The recommended maximum clip
angle for a given ``distance`` is acos(1 / distance) converted to degrees. If tilt
is also applied, then more conservative clipping may be necessary.
**Default value:** ``2.0``
fraction : float
The fraction parameter for the ``bottomley`` projection.
**Default value:** ``0.5``, corresponding to a sin(ψ) where ψ = π/6.
lobes : float
The number of lobes in projections that support multi-lobe views: ``berghaus``,
``gingery``, or ``healpix``. The default value varies based on the projection type.
parallel : float
For conic projections, the `two standard parallels
<https://en.wikipedia.org/wiki/Map_projection#Conic>`__ that define the map layout.
The default depends on the specific conic projection used.
precision : float
Sets the threshold for the projection's [adaptive
resampling](http://bl.ocks.org/mbostock/3795544) to the specified value in pixels.
This value corresponds to the [Douglas-Peucker
distance](http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm).
If precision is not specified, returns the projection's current resampling
precision which defaults to `√0.5 ≅ 0.70710…`.
radius : float
The radius parameter for the ``airy`` or ``gingery`` projection. The default value
varies based on the projection type.
ratio : float
The ratio parameter for the ``hill``, ``hufnagel``, or ``wagner`` projections. The
default value varies based on the projection type.
reflectX : boolean
Sets whether or not the x-dimension is reflected (negated) in the output.
reflectY : boolean
Sets whether or not the y-dimension is reflected (negated) in the output.
rotate : List(float)
Sets the projection's three-axis rotation to the specified angles, which must be a
two- or three-element array of numbers [`lambda`, `phi`, `gamma`] specifying the
rotation angles in degrees about each spherical axis. (These correspond to yaw,
pitch and roll.)
**Default value:** `[0, 0, 0]`
scale : float
The projection's scale (zoom) factor, overriding automatic fitting. The default
scale is projection-specific. The scale factor corresponds linearly to the distance
between projected points; however, scale factor values are not equivalent across
projections.
spacing : float
The spacing parameter for the ``lagrange`` projection.
**Default value:** ``0.5``
tilt : float
The tilt angle (in degrees) for the ``satellite`` projection.
**Default value:** ``0``.
translate : List(float)
The projection's translation offset as a two-element array ``[tx, ty]``,
overriding automatic fitting.
"""
projection = core.Projection(
center=center,
clipAngle=clipAngle,
clipExtent=clipExtent,
coefficient=coefficient,
distance=distance,
fraction=fraction,
lobes=lobes,
parallel=parallel,
precision=precision,
radius=radius,
ratio=ratio,
reflectX=reflectX,
reflectY=reflectY,
rotate=rotate,
scale=scale,
spacing=spacing,
tilt=tilt,
translate=translate,
type=type,
**kwds,
)
return self.properties(projection=projection)
def _add_transform(self, *transforms: Transform) -> Self:
"""Copy the chart and add specified transforms to chart.transform."""
copy = _top_schema_base(self).copy(deep=["transform"])
if copy.transform is Undefined:
copy.transform = []
copy.transform.extend(transforms)
return t.cast("Self", copy)
def transform_aggregate(
self,
aggregate: Optional[list[AggregatedFieldDef]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
**kwds: dict[str, Any] | str,
) -> Self:
"""
Add an :class:`AggregateTransform` to the schema.
Parameters
----------
aggregate : List(:class:`AggregatedFieldDef`)
Array of objects that define fields to aggregate.
groupby : List(string)
The data fields to group by. If not specified, a single group containing all data
objects will be used.
**kwds : Union[TypingDict[str, Any], str]
additional keywords are converted to aggregates using standard
shorthand parsing.
Returns
-------
self : Chart object
returns chart to allow for chaining
Examples
--------
The aggregate transform allows you to specify transforms directly using
the same shorthand syntax as used in encodings:
>>> import altair as alt
>>> chart1 = alt.Chart().transform_aggregate(
... mean_acc="mean(Acceleration)", groupby=["Origin"]
... )
>>> print(chart1.transform[0].to_json()) # doctest: +NORMALIZE_WHITESPACE
{
"aggregate": [
{
"as": "mean_acc",
"field": "Acceleration",
"op": "mean"
}
],
"groupby": [
"Origin"
]
}
It also supports including AggregatedFieldDef instances or dicts directly,
so you can create the above transform like this:
>>> chart2 = alt.Chart().transform_aggregate(
... [alt.AggregatedFieldDef(field="Acceleration", op="mean", **{"as": "mean_acc"})],
... groupby=["Origin"],
... )
>>> chart2.transform == chart1.transform
True
See Also
--------
alt.AggregateTransform : underlying transform object
"""
if aggregate is Undefined:
aggregate = []
for key, val in kwds.items():
parsed = utils.parse_shorthand(val)
dct = {
"as": key,
"field": parsed.get("field", Undefined),
"op": parsed.get("aggregate", Undefined),
}
assert isinstance(aggregate, list)
aggregate.append(core.AggregatedFieldDef(**dct))
return self._add_transform(
core.AggregateTransform(aggregate=aggregate, groupby=groupby)
)
def transform_bin(
self,
as_: Optional[str | FieldName | list[str | FieldName]] = Undefined,
field: Optional[str | FieldName] = Undefined,
bin: Literal[True] | BinParams = True,
**kwargs: Any,
) -> Self:
"""
Add a :class:`BinTransform` to the schema.
Parameters
----------
as_ : anyOf(string, List(string))
The output fields at which to write the start and end bin values.
bin : anyOf(boolean, :class:`BinParams`)
An object indicating bin properties, or simply ``true`` for using default bin
parameters.
field : string
The data field to bin.
Returns
-------
self : Chart object
returns chart to allow for chaining
Examples
--------
>>> import altair as alt
>>> chart = alt.Chart().transform_bin("x_binned", "x")
>>> chart.transform[0]
BinTransform({
as: 'x_binned',
bin: True,
field: 'x'
})
>>> chart = alt.Chart().transform_bin("x_binned", "x", bin=alt.Bin(maxbins=10))
>>> chart.transform[0]
BinTransform({
as: 'x_binned',
bin: BinParams({
maxbins: 10
}),
field: 'x'
})
See Also
--------
alt.BinTransform : underlying transform object
"""
if as_ is not Undefined:
if "as" in kwargs:
msg = "transform_bin: both 'as_' and 'as' passed as arguments."
raise ValueError(msg)
kwargs["as"] = as_
kwargs["bin"] = bin
kwargs["field"] = field
return self._add_transform(core.BinTransform(**kwargs))
def transform_calculate(
self,
as_: Optional[str | FieldName] = Undefined,
calculate: Optional[str | Expr | Expression] = Undefined,
**kwargs: str | Expr | Expression,
) -> Self:
"""
Add a :class:`CalculateTransform` to the schema.
Parameters
----------
as_ : string
The field for storing the computed formula value.
calculate : string or alt.expr.Expression
An `expression <https://vega.github.io/vega-lite/docs/types.html#expression>`__
string. Use the variable ``datum`` to refer to the current data object.
**kwargs
transforms can also be passed by keyword argument; see Examples
Returns
-------
self : Chart object
returns chart to allow for chaining
Examples
--------
>>> import altair as alt
>>> from altair import datum, expr
>>> chart = alt.Chart().transform_calculate(y=2 * expr.sin(datum.x))
>>> chart.transform[0]
CalculateTransform({
as: 'y',
calculate: (2 * sin(datum.x))
})
It's also possible to pass the ``CalculateTransform`` arguments directly:
>>> kwds = {"as_": "y", "calculate": "2 * sin(datum.x)"}
>>> chart = alt.Chart().transform_calculate(**kwds)
>>> chart.transform[0]
CalculateTransform({
as: 'y',
calculate: '2 * sin(datum.x)'
})
As the first form is easier to write and understand, that is the
recommended method.
See Also
--------
alt.CalculateTransform : underlying transform object
"""
calc_as: Optional[str | FieldName | Expr | Expression]
if as_ is Undefined:
calc_as = kwargs.pop("as", Undefined)
elif "as" in kwargs:
msg = "transform_calculate: both 'as_' and 'as' passed as arguments."
raise ValueError(msg)
else:
calc_as = as_
if calc_as is not Undefined or calculate is not Undefined:
dct: dict[str, Any] = {"as": calc_as, "calculate": calculate}
self = self._add_transform(core.CalculateTransform(**dct))
for a, calculate in kwargs.items():
dct = {"as": a, "calculate": calculate}
self = self._add_transform(core.CalculateTransform(**dct))
return self
def transform_density(
self,
density: str | FieldName,
as_: Optional[list[str | FieldName]] = Undefined,
bandwidth: Optional[float] = Undefined,
counts: Optional[bool] = Undefined,
cumulative: Optional[bool] = Undefined,
extent: Optional[list[float]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
maxsteps: Optional[int] = Undefined,
minsteps: Optional[int] = Undefined,
steps: Optional[int] = Undefined,
resolve: Optional[ResolveMode_T] = Undefined,
) -> Self:
"""
Add a :class:`DensityTransform` to the spec.
Parameters
----------
density : str
The data field for which to perform density estimation.
as_ : [str, str]
The output fields for the sample value and corresponding density estimate.
**Default value:** ``["value", "density"]``
bandwidth : float
The bandwidth (standard deviation) of the Gaussian kernel. If unspecified or set to
zero, the bandwidth value is automatically estimated from the input data using
Scott's rule.
counts : boolean
A boolean flag indicating if the output values should be probability estimates
(false) or smoothed counts (true).
**Default value:** ``false``
cumulative : boolean
A boolean flag indicating whether to produce density estimates (false) or cumulative
density estimates (true).
**Default value:** ``false``
extent : List([float, float])
A [min, max] domain from which to sample the distribution. If unspecified, the
extent will be determined by the observed minimum and maximum values of the density
value field.
groupby : List(str)
The data fields to group by. If not specified, a single group containing all data
objects will be used.
maxsteps : int
The maximum number of samples to take along the extent domain for plotting the
density. **Default value:** ``200``
minsteps : int
The minimum number of samples to take along the extent domain for plotting the
density. **Default value:** ``25``
steps : int
The exact number of samples to take along the extent domain for plotting the
density. If specified, overrides both minsteps and maxsteps to set an exact number
of uniform samples. Potentially useful in conjunction with a fixed extent to ensure
consistent sample points for stacked densities.
resolve : Literal['independent', 'shared']
Indicates how parameters for multiple densities should be resolved. If
``"independent"``, each density may have its own domain extent and dynamic number of
curve sample steps. If ``"shared"``, the KDE transform will ensure that all
densities are defined over a shared domain and curve steps, enabling stacking.
**Default value:** ``"shared"``
"""
return self._add_transform(
core.DensityTransform(
density=density,
bandwidth=bandwidth,
counts=counts,
cumulative=cumulative,
extent=extent,
groupby=groupby,
maxsteps=maxsteps,
minsteps=minsteps,
steps=steps,
resolve=resolve,
**{"as": as_},
)
)
def transform_impute(
self,
impute: str | FieldName,
key: str | FieldName,
frame: Optional[list[int | None]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
keyvals: Optional[list[Any] | ImputeSequence] = Undefined,
method: Optional[ImputeMethod_T | ImputeMethod] = Undefined,
value: Optional[Any] = Undefined,
) -> Self:
"""
Add an :class:`ImputeTransform` to the schema.
Parameters
----------
impute : string
The data field for which the missing values should be imputed.
key : string
A key field that uniquely identifies data objects within a group.
Missing key values (those occurring in the data but not in the current group) will
be imputed.
frame : List(anyOf(None, int))
A frame specification as a two-element array used to control the window over which
the specified method is applied. The array entries should either be a number
indicating the offset from the current data object, or null to indicate unbounded
rows preceding or following the current data object. For example, the value ``[-5,
5]`` indicates that the window should include five objects preceding and five
objects following the current object.
**Default value:** : ``[null, null]`` indicating that the window includes all
objects.
groupby : List(string)
An optional array of fields by which to group the values.
Imputation will then be performed on a per-group basis.
keyvals : anyOf(List(Mapping(required=[])), :class:`ImputeSequence`)
Defines the key values that should be considered for imputation.
An array of key values or an object defining a `number sequence
<https://vega.github.io/vega-lite/docs/impute.html#sequence-def>`__.
If provided, this will be used in addition to the key values observed within the
input data. If not provided, the values will be derived from all unique values of
the ``key`` field. For ``impute`` in ``encoding``, the key field is the x-field if
the y-field is imputed, or vice versa.
If there is no impute grouping, this property *must* be specified.
method : :class:`ImputeMethod`
The imputation method to use for the field value of imputed data objects.
One of ``value``, ``mean``, ``median``, ``max`` or ``min``.
**Default value:** ``"value"``
value : Mapping(required=[])
The field value to use when the imputation ``method`` is ``"value"``.
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.ImputeTransform : underlying transform object
"""
return self._add_transform(
core.ImputeTransform(
impute=impute,
key=key,
frame=frame,
groupby=groupby,
keyvals=keyvals,
method=method,
value=value,
)
)
def transform_joinaggregate(
self,
joinaggregate: Optional[list[JoinAggregateFieldDef]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
**kwargs: str,
) -> Self:
"""
Add a :class:`JoinAggregateTransform` to the schema.
Parameters
----------
joinaggregate : List(:class:`JoinAggregateFieldDef`)
The definition of the fields in the join aggregate, and what calculations to use.
groupby : List(string)
The data fields for partitioning the data objects into separate groups. If
unspecified, all data points will be in a single group.
**kwargs
joinaggregates can also be passed by keyword argument; see Examples.
Returns
-------
self : Chart object
returns chart to allow for chaining
Examples
--------
>>> import altair as alt
>>> chart = alt.Chart().transform_joinaggregate(x="sum(y)")
>>> chart.transform[0]
JoinAggregateTransform({
joinaggregate: [JoinAggregateFieldDef({
as: 'x',
field: 'y',
op: 'sum'
})]
})
See Also
--------
alt.JoinAggregateTransform : underlying transform object
"""
if joinaggregate is Undefined:
joinaggregate = []
for key, val in kwargs.items():
parsed = utils.parse_shorthand(val)
dct = {
"as": key,
"field": parsed.get("field", Undefined),
"op": parsed.get("aggregate", Undefined),
}
assert isinstance(joinaggregate, list)
joinaggregate.append(core.JoinAggregateFieldDef(**dct))
return self._add_transform(
core.JoinAggregateTransform(joinaggregate=joinaggregate, groupby=groupby)
)
def transform_extent(
self, extent: str | FieldName, param: str | ParameterName
) -> Self:
"""
Add a :class:`ExtentTransform` to the spec.
Parameters
----------
extent : str
The field of which to get the extent.
param : str
The name of the output parameter which will be created by
the extent transform.
Returns
-------
self : Chart object
returns chart to allow for chaining
"""
return self._add_transform(core.ExtentTransform(extent=extent, param=param))
def transform_filter(
self,
predicate: Optional[_PredicateType] = Undefined,
*more_predicates: _ComposablePredicateType,
empty: Optional[bool] = Undefined,
**constraints: _FieldEqualType,
) -> Self:
"""
Add a :class:`FilterTransform` to the spec.
The resulting predicate is an ``&`` reduction over ``predicate`` and optional ``*``, ``**``, arguments.
Parameters
----------
predicate
A selection or test predicate. ``str`` input will be treated as a test operand.
*more_predicates
Additional predicates, restricted to types supporting ``&``.
empty
For selection parameters, the predicate of empty selections returns ``True`` by default.
Override this behavior, with ``empty=False``.
.. note::
When ``predicate`` is a ``Parameter`` that is used more than once,
``self.transform_filter(..., empty=...)`` provides granular control for each occurrence.
**constraints
Specify `Field Equal Predicate`_'s.
Shortcut for ``alt.datum.field_name == value``, see examples for usage.
Warns
-----
AltairDeprecationWarning
If called using ``filter`` as a keyword argument.
See Also
--------
alt.when : Uses a similar syntax for defining conditional values.
Notes
-----
- Directly inspired by the syntax used in `polars.DataFrame.filter`_.
.. _Field Equal Predicate:
https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate
.. _polars.DataFrame.filter:
https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.filter.html
Examples
--------
Setting up a common chart::
import altair as alt
from altair import datum
from altair.datasets import data
source = data.population.url
chart = (
alt.Chart(source)
.mark_line()
.encode(
x="age:O",
y="sum(people):Q",
color=alt.Color("year:O").legend(symbolType="square"),
)
)
chart
Singular predicates can be expressed via ``datum``::
chart.transform_filter(datum.year <= 1980)
We can also use selection parameters directly::
selection = alt.selection_point(encodings=["color"], bind="legend")
chart.transform_filter(selection).add_params(selection)
Or a field predicate::
between_1950_60 = alt.FieldRangePredicate(field="year", range=[1950, 1960])
chart.transform_filter(between_1950_60) | chart.transform_filter(~between_1950_60)
Predicates can be composed together using logical operands::
chart.transform_filter(between_1950_60 | (datum.year == 1850))
Predicates passed as positional arguments will be reduced with ``&``::
chart.transform_filter(datum.year > 1980, datum.age != 90)
Using keyword-argument ``constraints`` can simplify compositions like::
verbose_composition = chart.transform_filter((datum.year == 2000) & (datum.sex == 1))
chart.transform_filter(year=2000, sex=1)
"""
if depr_filter := t.cast("Any", constraints.pop("filter", None)):
utils.deprecated_warn(
"Passing `filter` as a keyword is ambiguous.\n\n"
"Use a positional argument for `<5.5.0` behavior.\n"
"Or, `alt.datum['filter'] == ...` if referring to a column named 'filter'.",
version="5.5.0",
)
if utils.is_undefined(predicate):
predicate = depr_filter
else:
more_predicates = *more_predicates, depr_filter
cond = _parse_when(predicate, *more_predicates, empty=empty, **constraints)
return self._add_transform(core.FilterTransform(filter=cond.get("test", cond)))
def transform_flatten(
self,
flatten: list[str | FieldName],
as_: Optional[list[str | FieldName]] = Undefined,
) -> Self:
"""
Add a :class:`FlattenTransform` to the schema.
Parameters
----------
flatten : List(string)
An array of one or more data fields containing arrays to flatten.
If multiple fields are specified, their array values should have a parallel
structure, ideally with the same length.
If the lengths of parallel arrays do not match,
the longest array will be used with ``null`` values added for missing entries.
as : List(string)
The output field names for extracted array values.
**Default value:** The field name of the corresponding array field
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.FlattenTransform : underlying transform object
"""
return self._add_transform(
core.FlattenTransform(flatten=flatten, **{"as": as_})
)
def transform_fold(
self,
fold: list[str | FieldName],
as_: Optional[list[str | FieldName]] = Undefined,
) -> Self:
"""
Add a :class:`FoldTransform` to the spec.
Parameters
----------
fold : List(string)
An array of data fields indicating the properties to fold.
as : [string, string]
The output field names for the key and value properties produced by the fold
transform. Default: ``["key", "value"]``
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
Chart.transform_pivot : pivot transform - opposite of fold.
alt.FoldTransform : underlying transform object
"""
return self._add_transform(core.FoldTransform(fold=fold, **{"as": as_}))
def transform_loess(
self,
on: str | FieldName,
loess: str | FieldName,
as_: Optional[list[str | FieldName]] = Undefined,
bandwidth: Optional[float] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
) -> Self:
"""
Add a :class:`LoessTransform` to the spec.
Parameters
----------
on : str
The data field of the independent variable to use a predictor.
loess : str
The data field of the dependent variable to smooth.
as_ : [str, str]
The output field names for the smoothed points generated by the loess transform.
**Default value:** The field names of the input x and y values.
bandwidth : float
A bandwidth parameter in the range ``[0, 1]`` that determines the amount of
smoothing. **Default value:** ``0.3``
groupby : List(str)
The data fields to group by. If not specified, a single group containing all data
objects will be used.
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
Chart.transform_regression: regression transform
alt.LoessTransform : underlying transform object
"""
return self._add_transform(
core.LoessTransform(
loess=loess, on=on, bandwidth=bandwidth, groupby=groupby, **{"as": as_}
)
)
def transform_lookup(
self,
lookup: Optional[str] = Undefined,
from_: Optional[LookupData | LookupSelection] = Undefined,
as_: Optional[str | FieldName | list[str | FieldName]] = Undefined,
default: Optional[str] = Undefined,
**kwargs: Any,
) -> Self:
"""
Add a :class:`DataLookupTransform` or :class:`SelectionLookupTransform` to the chart.
Parameters
----------
lookup : string
Key in primary data source.
from_ : anyOf(:class:`LookupData`, :class:`LookupSelection`)
Secondary data reference.
as_ : anyOf(string, List(string))
The output fields on which to store the looked up data values.
For data lookups, this property may be left blank if ``from_.fields``
has been specified (those field names will be used); if ``from_.fields``
has not been specified, ``as_`` must be a string.
For selection lookups, this property is optional: if unspecified,
looked up values will be stored under a property named for the selection;
and if specified, it must correspond to ``from_.fields``.
default : string
The default value to use if lookup fails. **Default value:** ``null``
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.DataLookupTransform : underlying transform object
alt.SelectionLookupTransform : underlying transform object
"""
if as_ is not Undefined:
if "as" in kwargs:
msg = "transform_lookup: both 'as_' and 'as' passed as arguments."
raise ValueError(msg)
kwargs["as"] = as_
if from_ is not Undefined:
if "from" in kwargs:
msg = "transform_lookup: both 'from_' and 'from' passed as arguments."
raise ValueError(msg)
kwargs["from"] = from_
kwargs["lookup"] = lookup
kwargs["default"] = default
return self._add_transform(core.LookupTransform(**kwargs))
def transform_pivot(
self,
pivot: str | FieldName,
value: str | FieldName,
groupby: Optional[list[str | FieldName]] = Undefined,
limit: Optional[int] = Undefined,
op: Optional[AggregateOp_T | AggregateOp] = Undefined,
) -> Self:
"""
Add a :class:`PivotTransform` to the chart.
Parameters
----------
pivot : str
The data field to pivot on. The unique values of this field become new field names
in the output stream.
value : str
The data field to populate pivoted fields. The aggregate values of this field become
the values of the new pivoted fields.
groupby : List(str)
The optional data fields to group by. If not specified, a single group containing
all data objects will be used.
limit : int
An optional parameter indicating the maximum number of pivoted fields to generate.
The default ( ``0`` ) applies no limit. The pivoted ``pivot`` names are sorted in
ascending order prior to enforcing the limit.
**Default value:** ``0``
op : Literal['argmax', 'argmin', 'average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
The aggregation operation to apply to grouped ``value`` field values.
**Default value:** ``sum``
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
Chart.transform_fold : fold transform - opposite of pivot.
alt.PivotTransform : underlying transform object
"""
return self._add_transform(
core.PivotTransform(
pivot=pivot, value=value, groupby=groupby, limit=limit, op=op
)
)
def transform_quantile(
self,
quantile: str | FieldName,
as_: Optional[list[str | FieldName]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
probs: Optional[list[float]] = Undefined,
step: Optional[float] = Undefined,
) -> Self:
"""
Add a :class:`QuantileTransform` to the chart.
Parameters
----------
quantile : str
The data field for which to perform quantile estimation.
as : [str, str]
The output field names for the probability and quantile values.
groupby : List(str)
The data fields to group by. If not specified, a single group containing all data
objects will be used.
probs : List(float)
An array of probabilities in the range (0, 1) for which to compute quantile values.
If not specified, the *step* parameter will be used.
step : float
A probability step size (default 0.01) for sampling quantile values. All values from
one-half the step size up to 1 (exclusive) will be sampled. This parameter is only
used if the *probs* parameter is not provided. **Default value:** ``["prob", "value"]``
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.QuantileTransform : underlying transform object
"""
return self._add_transform(
core.QuantileTransform(
quantile=quantile,
groupby=groupby,
probs=probs,
step=step,
**{"as": as_},
)
)
def transform_regression(
self,
on: str | FieldName,
regression: str | FieldName,
as_: Optional[list[str | FieldName]] = Undefined,
extent: Optional[list[float]] = Undefined,
groupby: Optional[list[str | FieldName]] = Undefined,
method: Optional[
Literal["linear", "log", "exp", "pow", "quad", "poly"]
] = Undefined,
order: Optional[int] = Undefined,
params: Optional[bool] = Undefined,
) -> Self:
"""
Add a :class:`RegressionTransform` to the chart.
Parameters
----------
on : str
The data field of the independent variable to use a predictor.
regression : str
The data field of the dependent variable to predict.
as_ : [str, str]
The output field names for the smoothed points generated by the regression
transform. **Default value:** The field names of the input x and y values.
extent : [float, float]
A [min, max] domain over the independent (x) field for the starting and ending
points of the generated trend line.
groupby : List(str)
The data fields to group by. If not specified, a single group containing all data
objects will be used.
method : enum('linear', 'log', 'exp', 'pow', 'quad', 'poly')
The functional form of the regression model. One of ``"linear"``, ``"log"``,
``"exp"``, ``"pow"``, ``"quad"``, or ``"poly"``. **Default value:** ``"linear"``
order : int
The polynomial order (number of coefficients) for the 'poly' method.
**Default value:** ``3``
params : boolean
A boolean flag indicating if the transform should return the regression model
parameters (one object per group), rather than trend line points.
The resulting objects include a ``coef`` array of fitted coefficient values
(starting with the intercept term and then including terms of increasing order)
and an ``rSquared`` value (indicating the total variance explained by the model).
**Default value:** ``false``
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
Chart.transform_loess : LOESS transform
alt.RegressionTransform : underlying transform object
"""
return self._add_transform(
core.RegressionTransform(
regression=regression,
on=on,
extent=extent,
groupby=groupby,
method=method,
order=order,
params=params,
**{"as": as_},
)
)
def transform_sample(self, sample: int = 1000) -> Self:
"""
Add a :class:`SampleTransform` to the schema.
Parameters
----------
sample : int
The maximum number of data objects to include in the sample. Default: 1000.
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.SampleTransform : underlying transform object
"""
return self._add_transform(core.SampleTransform(sample))
def transform_stack(
self,
as_: str | FieldName | list[str],
stack: str | FieldName,
groupby: list[str | FieldName],
offset: Optional[StackOffset_T] = Undefined,
sort: Optional[list[SortField]] = Undefined,
) -> Self:
"""
Add a :class:`StackTransform` to the schema.
Parameters
----------
as_ : anyOf(string, List(string))
Output field names. This can be either a string or an array of strings with
two elements denoting the name for the fields for stack start and stack end
respectively.
If a single string(eg."val") is provided, the end field will be "val_end".
stack : string
The field which is stacked.
groupby : List(string)
The data fields to group by.
offset : enum('zero', 'center', 'normalize')
Mode for stacking marks. Default: 'zero'.
sort : List(:class:`SortField`)
Field that determines the order of leaves in the stacked charts.
Returns
-------
self : Chart object
returns chart to allow for chaining
See Also
--------
alt.StackTransform : underlying transform object
"""
return self._add_transform(
core.StackTransform(
stack=stack, groupby=groupby, offset=offset, sort=sort, **{"as": as_}
)
)
def transform_timeunit(
self,
as_: Optional[str | FieldName] = Undefined,
field: Optional[str | FieldName] = Undefined,
timeUnit: Optional[MultiTimeUnit_T | SingleTimeUnit_T | TimeUnit] = Undefined,
**kwargs: str,
) -> Self:
"""
Add a :class:`TimeUnitTransform` to the schema.
Parameters
----------
as_ : string
The output field to write the timeUnit value.
field : string
The data field to apply time unit.
timeUnit : str or :class:`TimeUnit`
The timeUnit.
**kwargs
transforms can also be passed by keyword argument; see Examples
Returns
-------
self : Chart object
returns chart to allow for chaining
Examples
--------
>>> import altair as alt
>>> from altair import datum, expr
>>> chart = alt.Chart().transform_timeunit(month="month(date)")
>>> chart.transform[0]
TimeUnitTransform({
as: 'month',
field: 'date',
timeUnit: 'month'
})
It's also possible to pass the ``TimeUnitTransform`` arguments directly;
this is most useful in cases where the desired field name is not a
valid python identifier:
>>> kwds = {"as": "month", "timeUnit": "month", "field": "The Month"}
>>> chart = alt.Chart().transform_timeunit(**kwds)
>>> chart.transform[0]
TimeUnitTransform({
as: 'month',
field: 'The Month',
timeUnit: 'month'
})
As the first form is easier to write and understand, that is the
recommended method.
See Also
--------
alt.TimeUnitTransform : underlying transform object
"""
if as_ is Undefined:
as_ = kwargs.pop("as", Undefined)
elif "as" in kwargs:
msg = "transform_timeunit: both 'as_' and 'as' passed as arguments."
raise ValueError(msg)
if as_ is not Undefined:
dct: dict[str, Any] = {"as": as_, "timeUnit": timeUnit, "field": field}
self = self._add_transform(core.TimeUnitTransform(**dct))
for as_, shorthand in kwargs.items():
dct = utils.parse_shorthand(
shorthand,
parse_timeunits=True,
parse_aggregates=False,
parse_types=False,
)
dct.pop("type", None)
dct["as"] = as_
if "timeUnit" not in dct:
msg = f"'{shorthand}' must include a valid timeUnit"
raise ValueError(msg)
self = self._add_transform(core.TimeUnitTransform(**dct))
return self
def transform_window(
self,
window: Optional[list[WindowFieldDef]] = Undefined,
frame: Optional[list[int | None]] = Undefined,
groupby: Optional[list[str]] = Undefined,
ignorePeers: Optional[bool] = Undefined,
sort: Optional[list[SortField | dict[str, str]]] = Undefined,
**kwargs: str,
) -> Self:
"""
Add a :class:`WindowTransform` to the schema.
Parameters
----------
window : List(:class:`WindowFieldDef`)
The definition of the fields in the window, and what calculations to use.
frame : List(anyOf(None, int))
A frame specification as a two-element array indicating how the sliding window
should proceed. The array entries should either be a number indicating the offset
from the current data object, or null to indicate unbounded rows preceding or
following the current data object. The default value is ``[null, 0]``, indicating
that the sliding window includes the current object and all preceding objects. The
value ``[-5, 5]`` indicates that the window should include five objects preceding
and five objects following the current object. Finally, ``[null, null]`` indicates
that the window frame should always include all data objects. The only operators
affected are the aggregation operations and the ``first_value``, ``last_value``, and
``nth_value`` window operations. The other window operations are not affected by
this.
**Default value:** : ``[null, 0]`` (includes the current object and all preceding
objects)
groupby : List(string)
The data fields for partitioning the data objects into separate windows. If
unspecified, all data points will be in a single group.
ignorePeers : boolean
Indicates if the sliding window frame should ignore peer values. (Peer values are
those considered identical by the sort criteria). The default is false, causing the
window frame to expand to include all peer values. If set to true, the window frame
will be defined by offset values only. This setting only affects those operations
that depend on the window frame, namely aggregation operations and the first_value,
last_value, and nth_value window operations.
**Default value:** ``false``
sort : List(:class:`SortField`)
A sort field definition for sorting data objects within a window. If two data
objects are considered equal by the comparator, they are considered "peer" values of
equal rank. If sort is not specified, the order is undefined: data objects are
processed in the order they are observed and none are considered peers (the
ignorePeers parameter is ignored and treated as if set to ``true`` ).
**kwargs
transforms can also be passed by keyword argument; see Examples
Examples
--------
A cumulative line chart
>>> import altair as alt
>>> import numpy as np
>>> import pandas as pd
>>> data = pd.DataFrame({"x": np.arange(100), "y": np.random.randn(100)})
>>> chart = (
... alt.Chart(data)
... .mark_line()
... .encode(x="x:Q", y="ycuml:Q")
... .transform_window(ycuml="sum(y)")
... )
>>> chart.transform[0]
WindowTransform({
window: [WindowFieldDef({
as: 'ycuml',
field: 'y',
op: 'sum'
})]
})
"""
w = window if isinstance(window, list) else []
if kwargs:
for as_, shorthand in kwargs.items():
kwds: dict[str, Any] = {"as": as_}
kwds.update(
utils.parse_shorthand(
shorthand,
parse_aggregates=False,
parse_window_ops=True,
parse_timeunits=False,
parse_types=False,
)
)
w.append(core.WindowFieldDef(**kwds))
return self._add_transform(
core.WindowTransform(
window=w or Undefined,
frame=frame,
groupby=groupby,
ignorePeers=ignorePeers,
sort=sort,
)
)
# Display-related methods
def _repr_mimebundle_(self, *args, **kwds) -> MimeBundleType | None: # type:ignore[return] # noqa: ANN002, ANN003
"""Return a MIME bundle for display in Jupyter frontends."""
# Catch errors explicitly to get around issues in Jupyter frontend
# see https://github.com/ipython/ipython/issues/11038
try:
dct = self.to_dict(context={"pre_transform": False})
except Exception:
utils.display_traceback(in_ipython=True)
return {}
else:
if renderer := renderers.get():
return renderer(dct)
def display(
self,
renderer: Optional[Literal["canvas", "svg"]] = Undefined,
theme: Optional[str] = Undefined,
actions: Optional[bool | dict] = Undefined,
**kwargs: Any,
) -> None:
"""
Display chart in Jupyter notebook or JupyterLab.
Parameters are passed as options to vega-embed within supported frontends.
See https://github.com/vega/vega-embed#options for details.
Parameters
----------
renderer : string ('canvas' or 'svg')
The renderer to use
theme : string
The Vega theme name to use; see https://github.com/vega/vega-themes
actions : bool or dict
Specify whether action links ("Open In Vega Editor", etc.) are
included in the view.
**kwargs :
Additional parameters are also passed to vega-embed as options.
"""
from IPython.display import display
if renderer is not Undefined:
kwargs["renderer"] = renderer
if theme is not Undefined:
kwargs["theme"] = theme
if actions is not Undefined:
kwargs["actions"] = actions
if kwargs:
options = renderers.options.copy()
options["embed_options"] = options.get("embed_options", {}).copy()
options["embed_options"].update(kwargs)
with renderers.enable(**options):
display(self)
else:
display(self)
@utils.deprecated(version="4.1.0", alternative="show")
def serve(
self,
ip="127.0.0.1", # noqa: ANN001
port=8888, # noqa: ANN001
n_retries=50, # noqa: ANN001
files=None, # noqa: ANN001
jupyter_warning=True, # noqa: ANN001
open_browser=True, # noqa: ANN001
http_server=None, # noqa: ANN001
**kwargs, # noqa: ANN003
) -> None:
"""'serve' is deprecated. Use 'show' instead."""
from altair.utils.server import serve
html = io.StringIO()
self.save(html, format="html", **kwargs)
html.seek(0)
serve(
html.read(),
ip=ip,
port=port,
n_retries=n_retries,
files=files,
jupyter_warning=jupyter_warning,
open_browser=open_browser,
http_server=http_server,
)
def show(self) -> None:
"""Display the chart using the active renderer."""
if renderers.active == "browser":
# Opens browser window as side-effect.
# We use a special case here so that IPython is not required
self._repr_mimebundle_()
else:
# Mime-bundle based renderer, requires running in an IPython session
from IPython.display import display
display(self)
@utils.use_signature(core.Resolve)
def _set_resolve(self, **kwargs: Any): # noqa: ANN202
"""Copy the chart and update the resolve property with kwargs."""
if not hasattr(self, "resolve"):
msg = f"{self.__class__} object has no attribute 'resolve'"
raise ValueError(msg)
copy = _top_schema_base(self).copy(deep=["resolve"])
if copy.resolve is Undefined:
copy.resolve = core.Resolve()
for key, val in kwargs.items():
copy.resolve[key] = val
return copy
@utils.use_signature(core.AxisResolveMap)
def resolve_axis(self, *args: Any, **kwargs: Any) -> Self:
check = _top_schema_base(self)
r = check._set_resolve(axis=core.AxisResolveMap(*args, **kwargs))
return t.cast("Self", r)
@utils.use_signature(core.LegendResolveMap)
def resolve_legend(self, *args: Any, **kwargs: Any) -> Self:
check = _top_schema_base(self)
r = check._set_resolve(legend=core.LegendResolveMap(*args, **kwargs))
return t.cast("Self", r)
@utils.use_signature(core.ScaleResolveMap)
def resolve_scale(self, *args: Any, **kwargs: Any) -> Self:
check = _top_schema_base(self)
r = check._set_resolve(scale=core.ScaleResolveMap(*args, **kwargs))
return t.cast("Self", r)
| TopLevelMixin |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 12587,
"end": 14176
} | class ____(greentest.TestCase):
def test_weakref(self):
# Event objects should allow weakrefs
e = Event()
r = weakref.ref(e)
self.assertIs(e, r())
del e
del r
def test_wait_while_notifying(self):
# If someone calls wait() on an Event that is
# ready, and notifying other waiters, that new
# waiter still runs at the end, but this does not
# require a trip around the event loop.
# See https://github.com/gevent/gevent/issues/1520
event = Event()
results = []
def wait_then_append(arg):
event.wait()
results.append(arg)
gevent.spawn(wait_then_append, 1)
gevent.spawn(wait_then_append, 2)
gevent.idle()
self.assertEqual(2, event.linkcount())
check = gevent.get_hub().loop.check()
check.start(results.append, 4)
event.set()
wait_then_append(3)
self.assertEqual(results, [1, 2, 3])
# Note that the check event DID NOT run.
check.stop()
check.close()
def test_gevent_wait_twice_when_already_set(self):
event = Event()
event.set()
# First one works fine.
result = gevent.wait([event])
self.assertEqual(result, [event])
# Second one used to fail with an AssertionError,
# now it passes
result = gevent.wait([event])
self.assertEqual(result, [event])
del AbstractGenericGetTestCase
del AbstractGenericWaitTestCase
if __name__ == '__main__':
greentest.main()
| TestEventBasics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.