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 | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 78328,
"end": 81852
} | class ____(TestCase):
# Ref: https://github.com/pytorch/pytorch/issues/87191
def test_op_isinstance_of_reduceop(self):
for reduce_op in (
c10d.ReduceOp.SUM,
c10d.ReduceOp.AVG,
c10d.ReduceOp.PRODUCT,
c10d.ReduceOp.MIN,
c10d.ReduceOp.MAX,
c10d.ReduceOp.BAND,
c10d.ReduceOp.BOR,
c10d.ReduceOp.BXOR,
):
self.assertTrue(isinstance(reduce_op, c10d.ReduceOp))
for scale in (torch.tensor(1.0), 2.0):
self.assertTrue(
isinstance(dist._make_nccl_premul_sum(scale), c10d.ReduceOp)
)
# Ref: https://github.com/pytorch/pytorch/pull/87303#discussion_r1002879700
def test_reduceop_copyable(self):
for reduce_op in (
c10d.ReduceOp.SUM,
c10d.ReduceOp.AVG,
c10d.ReduceOp.PRODUCT,
c10d.ReduceOp.MIN,
c10d.ReduceOp.MAX,
c10d.ReduceOp.BAND,
c10d.ReduceOp.BOR,
c10d.ReduceOp.BXOR,
):
self.assertEqual(copy.copy(reduce_op), reduce_op)
self.assertEqual(copy.deepcopy(reduce_op), reduce_op)
self.assertEqual(copy.copy(c10d.ReduceOp(reduce_op)), reduce_op)
self.assertEqual(copy.deepcopy(c10d.ReduceOp(reduce_op)), reduce_op)
for scale in (torch.tensor(1.0), 2.0):
reduce_op = dist._make_nccl_premul_sum(scale)
self.assertEqual(copy.copy(reduce_op), reduce_op)
self.assertEqual(copy.deepcopy(reduce_op), reduce_op)
def test_reduceop_pickle(self):
for reduce_op in (
c10d.ReduceOp.SUM,
c10d.ReduceOp.AVG,
c10d.ReduceOp.PRODUCT,
c10d.ReduceOp.MIN,
c10d.ReduceOp.MAX,
c10d.ReduceOp.BAND,
c10d.ReduceOp.BOR,
c10d.ReduceOp.BXOR,
):
pickle.loads(pickle.dumps(reduce_op))
orig = c10d.ReduceOp(reduce_op)
self.assertEqual(pickle.loads(pickle.dumps(orig)), orig)
for scale in (torch.tensor(1.0), 2.0):
reduce_op = dist._make_nccl_premul_sum(scale)
self.assertEqual(pickle.loads(pickle.dumps(reduce_op)), reduce_op)
# Ref: https://github.com/pytorch/pytorch/issues/90072
def test_reduceop_equal(self):
not_reduceop = "abc"
for reduce_op in (
c10d.ReduceOp.SUM,
c10d.ReduceOp.AVG,
c10d.ReduceOp.PRODUCT,
c10d.ReduceOp.MIN,
c10d.ReduceOp.MAX,
c10d.ReduceOp.BAND,
c10d.ReduceOp.BOR,
c10d.ReduceOp.BXOR,
):
reduce_op_obj = c10d.ReduceOp(reduce_op)
# this calls `ReduceOp.__eq__(self, other)`
self.assertEqual(reduce_op_obj, reduce_op_obj)
self.assertEqual(reduce_op_obj, reduce_op)
self.assertNotEqual(reduce_op_obj, not_reduceop)
self.assertNotEqual(reduce_op, not_reduceop)
# TODO(crcrpar): This needs to be `assertEqual` for the associativity even though
# the comparison of `RedOpType` and `ReduceOp` sounds less likely to happen compared
# to that of `ReduceOp` and `RedOptype`.
# this calls `RedOpType.__eq__(self, other)`
self.assertNotEqual(reduce_op, reduce_op_obj)
self.assertFalse(None in (reduce_op, reduce_op_obj))
self.assertFalse(not_reduceop in (reduce_op, reduce_op_obj))
| ReduceOpTest |
python | pytorch__pytorch | torch/distributions/wishart.py | {
"start": 892,
"end": 13919
} | class ____(ExponentialFamily):
r"""
Creates a Wishart distribution parameterized by a symmetric positive definite matrix :math:`\Sigma`,
or its Cholesky decomposition :math:`\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top`
Example:
>>> # xdoctest: +SKIP("FIXME: scale_tril must be at least two-dimensional")
>>> m = Wishart(torch.Tensor([2]), covariance_matrix=torch.eye(2))
>>> m.sample() # Wishart distributed with mean=`df * I` and
>>> # variance(x_ij)=`df` for i != j and variance(x_ij)=`2 * df` for i == j
Args:
df (float or Tensor): real-valued parameter larger than the (dimension of Square matrix) - 1
covariance_matrix (Tensor): positive-definite covariance matrix
precision_matrix (Tensor): positive-definite precision matrix
scale_tril (Tensor): lower-triangular factor of covariance, with positive-valued diagonal
Note:
Only one of :attr:`covariance_matrix` or :attr:`precision_matrix` or
:attr:`scale_tril` can be specified.
Using :attr:`scale_tril` will be more efficient: all computations internally
are based on :attr:`scale_tril`. If :attr:`covariance_matrix` or
:attr:`precision_matrix` is passed instead, it is only used to compute
the corresponding lower triangular matrices using a Cholesky decomposition.
'torch.distributions.LKJCholesky' is a restricted Wishart distribution.[1]
**References**
[1] Wang, Z., Wu, Y. and Chu, H., 2018. `On equivalence of the LKJ distribution and the restricted Wishart distribution`.
[2] Sawyer, S., 2007. `Wishart Distributions and Inverse-Wishart Sampling`.
[3] Anderson, T. W., 2003. `An Introduction to Multivariate Statistical Analysis (3rd ed.)`.
[4] Odell, P. L. & Feiveson, A. H., 1966. `A Numerical Procedure to Generate a SampleCovariance Matrix`. JASA, 61(313):199-203.
[5] Ku, Y.-C. & Bloomfield, P., 2010. `Generating Random Wishart Matrices with Fractional Degrees of Freedom in OX`.
"""
support = constraints.positive_definite
has_rsample = True
_mean_carrier_measure = 0
@property
def arg_constraints(self):
return {
"covariance_matrix": constraints.positive_definite,
"precision_matrix": constraints.positive_definite,
"scale_tril": constraints.lower_cholesky,
"df": constraints.greater_than(self.event_shape[-1] - 1),
}
def __init__(
self,
df: Union[Tensor, Number],
covariance_matrix: Optional[Tensor] = None,
precision_matrix: Optional[Tensor] = None,
scale_tril: Optional[Tensor] = None,
validate_args: Optional[bool] = None,
) -> None:
assert (covariance_matrix is not None) + (scale_tril is not None) + (
precision_matrix is not None
) == 1, (
"Exactly one of covariance_matrix or precision_matrix or scale_tril may be specified."
)
param = next(
p
for p in (covariance_matrix, precision_matrix, scale_tril)
if p is not None
)
if param.dim() < 2:
raise ValueError(
"scale_tril must be at least two-dimensional, with optional leading batch dimensions"
)
if isinstance(df, _Number):
batch_shape = torch.Size(param.shape[:-2])
self.df = torch.tensor(df, dtype=param.dtype, device=param.device)
else:
batch_shape = torch.broadcast_shapes(param.shape[:-2], df.shape)
self.df = df.expand(batch_shape)
event_shape = param.shape[-2:]
if self.df.le(event_shape[-1] - 1).any():
raise ValueError(
f"Value of df={df} expected to be greater than ndim - 1 = {event_shape[-1] - 1}."
)
if scale_tril is not None:
# pyrefly: ignore [read-only]
self.scale_tril = param.expand(batch_shape + (-1, -1))
elif covariance_matrix is not None:
# pyrefly: ignore [read-only]
self.covariance_matrix = param.expand(batch_shape + (-1, -1))
elif precision_matrix is not None:
# pyrefly: ignore [read-only]
self.precision_matrix = param.expand(batch_shape + (-1, -1))
if self.df.lt(event_shape[-1]).any():
warnings.warn(
"Low df values detected. Singular samples are highly likely to occur for ndim - 1 < df < ndim.",
stacklevel=2,
)
super().__init__(batch_shape, event_shape, validate_args=validate_args)
self._batch_dims = [-(x + 1) for x in range(len(self._batch_shape))]
if scale_tril is not None:
self._unbroadcasted_scale_tril = scale_tril
elif covariance_matrix is not None:
self._unbroadcasted_scale_tril = torch.linalg.cholesky(covariance_matrix)
else: # precision_matrix is not None
self._unbroadcasted_scale_tril = _precision_to_scale_tril(precision_matrix)
# Chi2 distribution is needed for Bartlett decomposition sampling
self._dist_chi2 = torch.distributions.chi2.Chi2(
df=(
self.df.unsqueeze(-1)
- torch.arange(
self._event_shape[-1],
dtype=self._unbroadcasted_scale_tril.dtype,
device=self._unbroadcasted_scale_tril.device,
).expand(batch_shape + (-1,))
)
)
def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Wishart, _instance)
batch_shape = torch.Size(batch_shape)
cov_shape = batch_shape + self.event_shape
new._unbroadcasted_scale_tril = self._unbroadcasted_scale_tril.expand(cov_shape)
new.df = self.df.expand(batch_shape)
new._batch_dims = [-(x + 1) for x in range(len(batch_shape))]
if "covariance_matrix" in self.__dict__:
new.covariance_matrix = self.covariance_matrix.expand(cov_shape)
if "scale_tril" in self.__dict__:
new.scale_tril = self.scale_tril.expand(cov_shape)
if "precision_matrix" in self.__dict__:
new.precision_matrix = self.precision_matrix.expand(cov_shape)
# Chi2 distribution is needed for Bartlett decomposition sampling
new._dist_chi2 = torch.distributions.chi2.Chi2(
df=(
new.df.unsqueeze(-1)
- torch.arange(
self.event_shape[-1],
dtype=new._unbroadcasted_scale_tril.dtype,
device=new._unbroadcasted_scale_tril.device,
).expand(batch_shape + (-1,))
)
)
super(Wishart, new).__init__(batch_shape, self.event_shape, validate_args=False)
new._validate_args = self._validate_args
return new
@lazy_property
def scale_tril(self) -> Tensor:
return self._unbroadcasted_scale_tril.expand(
self._batch_shape + self._event_shape
)
@lazy_property
def covariance_matrix(self) -> Tensor:
return (
self._unbroadcasted_scale_tril
@ self._unbroadcasted_scale_tril.transpose(-2, -1)
).expand(self._batch_shape + self._event_shape)
@lazy_property
def precision_matrix(self) -> Tensor:
identity = torch.eye(
self._event_shape[-1],
device=self._unbroadcasted_scale_tril.device,
dtype=self._unbroadcasted_scale_tril.dtype,
)
return torch.cholesky_solve(identity, self._unbroadcasted_scale_tril).expand(
self._batch_shape + self._event_shape
)
@property
def mean(self) -> Tensor:
return self.df.view(self._batch_shape + (1, 1)) * self.covariance_matrix
@property
def mode(self) -> Tensor:
factor = self.df - self.covariance_matrix.shape[-1] - 1
factor[factor <= 0] = nan
return factor.view(self._batch_shape + (1, 1)) * self.covariance_matrix
@property
def variance(self) -> Tensor:
V = self.covariance_matrix # has shape (batch_shape x event_shape)
diag_V = V.diagonal(dim1=-2, dim2=-1)
return self.df.view(self._batch_shape + (1, 1)) * (
V.pow(2) + torch.einsum("...i,...j->...ij", diag_V, diag_V)
)
def _bartlett_sampling(self, sample_shape=torch.Size()):
p = self._event_shape[-1] # has singleton shape
# Implemented Sampling using Bartlett decomposition
noise = _clamp_above_eps(
self._dist_chi2.rsample(sample_shape).sqrt()
).diag_embed(dim1=-2, dim2=-1)
i, j = torch.tril_indices(p, p, offset=-1)
noise[..., i, j] = torch.randn(
torch.Size(sample_shape) + self._batch_shape + (int(p * (p - 1) / 2),),
dtype=noise.dtype,
device=noise.device,
)
chol = self._unbroadcasted_scale_tril @ noise
return chol @ chol.transpose(-2, -1)
def rsample(
self, sample_shape: _size = torch.Size(), max_try_correction=None
) -> Tensor:
r"""
.. warning::
In some cases, sampling algorithm based on Bartlett decomposition may return singular matrix samples.
Several tries to correct singular samples are performed by default, but it may end up returning
singular matrix samples. Singular samples may return `-inf` values in `.log_prob()`.
In those cases, the user should validate the samples and either fix the value of `df`
or adjust `max_try_correction` value for argument in `.rsample` accordingly.
"""
if max_try_correction is None:
max_try_correction = 3 if torch._C._get_tracing_state() else 10
sample_shape = torch.Size(sample_shape)
sample = self._bartlett_sampling(sample_shape)
# Below part is to improve numerical stability temporally and should be removed in the future
is_singular = self.support.check(sample)
if self._batch_shape:
is_singular = is_singular.amax(self._batch_dims)
if torch._C._get_tracing_state():
# Less optimized version for JIT
for _ in range(max_try_correction):
sample_new = self._bartlett_sampling(sample_shape)
sample = torch.where(is_singular, sample_new, sample)
is_singular = ~self.support.check(sample)
if self._batch_shape:
is_singular = is_singular.amax(self._batch_dims)
else:
# More optimized version with data-dependent control flow.
if is_singular.any():
warnings.warn("Singular sample detected.", stacklevel=2)
for _ in range(max_try_correction):
sample_new = self._bartlett_sampling(is_singular[is_singular].shape)
sample[is_singular] = sample_new
is_singular_new = ~self.support.check(sample_new)
if self._batch_shape:
is_singular_new = is_singular_new.amax(self._batch_dims)
is_singular[is_singular.clone()] = is_singular_new
if not is_singular.any():
break
return sample
def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
nu = self.df # has shape (batch_shape)
p = self._event_shape[-1] # has singleton shape
return (
-nu
* (
p * _log_2 / 2
+ self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1)
.log()
.sum(-1)
)
- torch.mvlgamma(nu / 2, p=p)
+ (nu - p - 1) / 2 * torch.linalg.slogdet(value).logabsdet
- torch.cholesky_solve(value, self._unbroadcasted_scale_tril)
.diagonal(dim1=-2, dim2=-1)
.sum(dim=-1)
/ 2
)
def entropy(self):
nu = self.df # has shape (batch_shape)
p = self._event_shape[-1] # has singleton shape
return (
(p + 1)
* (
p * _log_2 / 2
+ self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1)
.log()
.sum(-1)
)
+ torch.mvlgamma(nu / 2, p=p)
- (nu - p - 1) / 2 * _mvdigamma(nu / 2, p=p)
+ nu * p / 2
)
@property
def _natural_params(self) -> tuple[Tensor, Tensor]:
nu = self.df # has shape (batch_shape)
p = self._event_shape[-1] # has singleton shape
return -self.precision_matrix / 2, (nu - p - 1) / 2
# pyrefly: ignore [bad-override]
def _log_normalizer(self, x, y):
p = self._event_shape[-1]
return (y + (p + 1) / 2) * (
-torch.linalg.slogdet(-2 * x).logabsdet + _log_2 * p
) + torch.mvlgamma(y + (p + 1) / 2, p=p)
| Wishart |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 10251,
"end": 10290
} | class ____(Protocol): ...
| _SetterProtocol |
python | crytic__slither | slither/detectors/attributes/incorrect_solc.py | {
"start": 636,
"end": 5525
} | class ____(AbstractDetector):
"""
Check if an old version of solc is used
"""
ARGUMENT = "solc-version"
HELP = "Incorrect Solidity version"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
LANGUAGE = "solidity"
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-versions-of-solidity"
WIKI_TITLE = "Incorrect versions of Solidity"
# region wiki_description
WIKI_DESCRIPTION = """
`solc` frequently releases new compiler versions. Using an old version prevents access to new Solidity security checks.
We also recommend avoiding complex `pragma` statement."""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Deploy with a recent version of Solidity (at least 0.8.0) with no known severe issues.
Use a simple pragma version that allows any of these versions.
Consider using the latest version of Solidity for testing."""
# endregion wiki_recommendation
COMPLEX_PRAGMA_TXT = "is too complex"
OLD_VERSION_TXT = (
"is an outdated solc version. Use a more recent version (at least 0.8.0), if possible."
)
LESS_THAN_TXT = "uses lesser than"
BUGGY_VERSION_TXT = (
"contains known severe issues (https://solidity.readthedocs.io/en/latest/bugs.html)"
)
# Indicates the allowed versions. Must be formatted in increasing order.
ALLOWED_VERSIONS = ["0.8.0"]
def _check_version(self, version: Tuple[str, str, str, str, str]) -> Optional[str]:
op = version[0]
if op and op not in [">", ">=", "^"]:
return self.LESS_THAN_TXT
version_number = ".".join(version[2:])
if version_number in bugs_by_version and len(bugs_by_version[version_number]):
bugs = "\n".join([f"\t- {bug}" for bug in bugs_by_version[version_number]])
return self.BUGGY_VERSION_TXT + f"\n{bugs}"
return None
def _check_pragma(self, version: str) -> Optional[str]:
versions = PATTERN.findall(version)
if len(versions) == 1:
version = versions[0]
return self._check_version(version)
if len(versions) == 2:
version_left = versions[0]
version_right = versions[1]
# Only allow two elements if the second one is
# <0.5.0 or <0.6.0
if version_right not in [
("<", "", "0", "5", "0"),
("<", "", "0", "6", "0"),
("<", "", "0", "7", "0"),
]:
return self.COMPLEX_PRAGMA_TXT
return self._check_version(version_left)
return self.COMPLEX_PRAGMA_TXT
def _detect(self) -> List[Output]:
"""
Detects pragma statements that allow for outdated solc versions.
:return: Returns the relevant JSON data for the findings.
"""
# Detect all version related pragmas and check if they are disallowed.
results = []
pragma = self.compilation_unit.pragma_directives
disallowed_pragmas = {}
for p in pragma:
# Skip any pragma directives which do not refer to version
if len(p.directive) < 1 or p.directive[0] != "solidity":
continue
reason = self._check_pragma(p.version)
if reason is None:
continue
if p.version in disallowed_pragmas and reason in disallowed_pragmas[p.version]:
disallowed_pragmas[p.version][reason].append(p)
else:
disallowed_pragmas[p.version] = {reason: [p]}
# If we found any disallowed pragmas, we output our findings.
if len(disallowed_pragmas.keys()):
for p, reasons in disallowed_pragmas.items():
info: DETECTOR_INFO = []
for r, vers in reasons.items():
info += [f"Version constraint {p} {r}.\nIt is used by:\n"]
for ver in vers:
info += ["\t- ", ver, "\n"]
json = self.generate_result(info)
results.append(json)
if list(map(int, self.compilation_unit.solc_version.split("."))) < list(
map(int, self.ALLOWED_VERSIONS[-1].split("."))
):
info = [
"solc-",
self.compilation_unit.solc_version,
" ",
self.OLD_VERSION_TXT,
"\n",
]
json = self.generate_result(info)
# TODO: Once crytic-compile adds config file info, add a source mapping element pointing to
# the line in the config that specifies the problematic version of solc
results.append(json)
return results
@staticmethod
def _format(slither, result):
custom_format(slither, result)
| IncorrectSolc |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/dtensor_util_test.py | {
"start": 3371,
"end": 4586
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout.Mesh(['batch'], global_ids, local_ids,
test_util.create_device_list((2,), device))
for device in ['TPU', 'GPU', 'CPU']
}
self.mesh = self.configTestMesh(mesh_dict)
def test_unsupported_methods(self):
strategy = mirrored_strategy.MirroredStrategy(mesh=self.mesh)
replica_context = dtensor_util.DTensorReplicaContext(strategy)
expected_error = replica_context._UNSUPPORTED_ERROR_MSG
self.assertEqual(replica_context.num_replicas_in_sync, 2)
self.assertEqual(replica_context.replica_id_in_sync_group, 0)
with self.assertRaisesRegex(NotImplementedError, expected_error):
replica_context.merge_call(None)
with self.assertRaisesRegex(NotImplementedError, expected_error):
replica_context.all_reduce(reduce_util.ReduceOp.SUM, None)
with self.assertRaisesRegex(NotImplementedError, expected_error):
replica_context.all_gather([], 0)
if __name__ == '__main__':
test.main()
| DTensorReplicaContextTest |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/models/metadata.py | {
"start": 1319,
"end": 1443
} | class ____(PydanticDelayValidationMixin, PydanticDictMixin, ConnectorMetadataDefinitionV0):
pass
| PartialMetadataDefinition |
python | ipython__ipython | IPython/core/history.py | {
"start": 4908,
"end": 5958
} | class ____(LoggingConfigurable):
"""An abstract class for History Accessors"""
def get_tail(
self,
n: int = 10,
raw: bool = True,
output: bool = False,
include_latest: bool = False,
) -> Iterable[tuple[int, int, InOrInOut]]:
raise NotImplementedError
def search(
self,
pattern: str = "*",
raw: bool = True,
search_raw: bool = True,
output: bool = False,
n: Optional[int] = None,
unique: bool = False,
) -> Iterable[tuple[int, int, InOrInOut]]:
raise NotImplementedError
def get_range(
self,
session: int,
start: int = 1,
stop: Optional[int] = None,
raw: bool = True,
output: bool = False,
) -> Iterable[tuple[int, int, InOrInOut]]:
raise NotImplementedError
def get_range_by_str(
self, rangestr: str, raw: bool = True, output: bool = False
) -> Iterable[tuple[int, int, InOrInOut]]:
raise NotImplementedError
| HistoryAccessorBase |
python | getsentry__sentry | src/sentry/integrations/on_call/metrics.py | {
"start": 1155,
"end": 1820
} | class ____(IntegrationEventLifecycleMetric):
"""
An instance to be recorded of a user interacting with Sentry through an on-call app.
"""
interaction_type: OnCallInteractionType
spec: OnCallSpec
# Optional attributes to populate extras
user: User | RpcUser | None = None
organization: Organization | RpcOrganization | None = None
def get_integration_domain(self) -> IntegrationDomain:
return IntegrationDomain.ON_CALL_SCHEDULING
def get_integration_name(self) -> str:
return self.spec.provider_slug
def get_interaction_type(self) -> str:
return str(self.interaction_type)
| OnCallInteractionEvent |
python | pytorch__pytorch | torch/utils/_pytree.py | {
"start": 23497,
"end": 23760
} | class ____(Generic[T]):
idx: int
def __str__(self) -> str:
return f"[{self.idx!r}]"
def get(self, sequence: Sequence[T]) -> T:
return sequence[self.idx]
K = TypeVar("K", bound=Hashable)
@dataclasses.dataclass(frozen=True)
| SequenceKey |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_index_returned.py | {
"start": 580,
"end": 720
} | class ____:
""" __index__ returns a dict """
def __index__(self): # [invalid-index-returned]
return {'1': '1'}
| FirstBadIndex |
python | pytorch__pytorch | test/dynamo/cpython/3_13/seq_tests.py | {
"start": 667,
"end": 1813
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
r = importlib.import_module(name)
# Redirect the module in sys.modules
sys.modules[fullname] = r
# Return a module spec from the found module
return importlib.util.find_spec(name)
except ImportError:
return None
return None
# Add the custom finder to sys.meta_path
sys.meta_path.insert(0, RedirectImportFinder())
# ======= END DYNAMO PATCH =======
"""
Tests common to tuple, list and UserList.UserList
"""
import unittest
import sys
import pickle
from test import support
from test.support import ALWAYS_EQ, NEVER_EQ
# Various iterables
# This is used for checking the constructor (here and in test_deque.py)
def iterfunc(seqn):
'Regular generator'
for i in seqn:
yield i
| RedirectImportFinder |
python | huggingface__transformers | tests/models/video_llava/test_modeling_video_llava.py | {
"start": 6671,
"end": 16492
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `VideoLlavaForConditionalGeneration`.
"""
all_model_classes = (
(
VideoLlavaModel,
VideoLlavaForConditionalGeneration,
)
if is_torch_available()
else ()
)
test_resize_embeddings = True
_is_composite = True
def setUp(self):
self.model_tester = VideoLlavaVisionText2TextModelTester(self)
common_properties = ["image_token_index", "video_token_index", "vision_feature_layer", "image_seq_length"]
self.config_tester = ConfigTester(
self, config_class=VideoLlavaConfig, has_text_modality=False, common_properties=common_properties
)
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
@unittest.skip(
"VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
)
def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
pass
@run_test_using_subprocess
def test_mixed_input(self):
config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
curr_inputs = copy.deepcopy(inputs)
model = model_class(config).to(torch_device).eval()
# test that the forward does not fail
with torch.no_grad():
_ = model(**curr_inputs)
# if we remove some images from inputs leaving only one
# image number mismatch error should raise
curr_inputs["pixel_values_images"] = curr_inputs["pixel_values_images"][:1]
with self.assertRaises(ValueError):
_ = model(**curr_inputs)
def test_video_only_input(self):
config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
curr_inputs = copy.deepcopy(inputs)
model = model_class(config).to(torch_device).eval()
# replace image token id with dummy id
# Error will be raised as num-image-tokens and num-of-image-embeds mismatch
curr_inputs["input_ids"][:, : self.model_tester.num_image_tokens] = 2
with self.assertRaises(ValueError):
_ = model(**curr_inputs)
curr_inputs["pixel_values_images"] = None
_ = model(**curr_inputs)
def test_image_only_input(self):
config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
curr_inputs = copy.deepcopy(inputs)
model = model_class(config).to(torch_device).eval()
# set dummy id, which is not video token id
# Error will be raised as num-video-tokens and num-of-video-embeds mismatch
curr_inputs["input_ids"][
:,
self.model_tester.num_image_tokens : self.model_tester.num_image_tokens
+ self.model_tester.num_video_tokens,
] = 2
with self.assertRaises(ValueError):
_ = model(**curr_inputs)
curr_inputs["pixel_values_videos"] = None
_ = model(**curr_inputs)
def test_batching_equivalence(self):
def recursive_check(batched_object, single_row_object, model_name, key):
if isinstance(batched_object, (list, tuple)):
for batched_object_value, single_row_object_value in zip(batched_object, single_row_object):
recursive_check(batched_object_value, single_row_object_value, model_name, key)
# do not compare returned loss (0-dim tensor) / codebook ids (int) / caching objects
elif batched_object is None or not isinstance(batched_object, torch.Tensor):
return
elif batched_object.dim() == 0:
return
else:
batched_row = batched_object[:1]
self.assertFalse(
torch.isnan(batched_row).any(), f"Batched output has `nan` in {model_name} for key={key}"
)
self.assertFalse(
torch.isinf(batched_row).any(), f"Batched output has `inf` in {model_name} for key={key}"
)
self.assertFalse(
torch.isnan(single_row_object).any(), f"Single row output has `nan` in {model_name} for key={key}"
)
self.assertFalse(
torch.isinf(single_row_object).any(), f"Single row output has `inf` in {model_name} for key={key}"
)
self.assertTrue(
(torch.max(torch.abs(batched_row - single_row_object))) <= 1e-03,
msg=(
f"Batched and Single row outputs are not equal in {model_name} for key={key}. "
f"Difference={torch.max(torch.abs(batched_row - single_row_object))}."
),
)
config, batched_input = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
config.output_hidden_states = True
model_name = model_class.__name__
batched_input_prepared = self._prepare_for_class(batched_input, model_class)
model = model_class(config).to(torch_device).eval()
single_row_input = {}
for key, value in batched_input_prepared.items():
single_row_input[key] = value[:1]
with torch.no_grad():
model_batched_output = model(**batched_input_prepared)
model_row_output = model(**single_row_input)
for key in model_batched_output:
# we can't test videos as their output shapes are linked to number of frames
# and we don't have to as it is a CLIP model and can be tested from `ClipModelTester` class
if key == "video_hidden_states":
continue
recursive_check(model_batched_output[key], model_row_output[key], model_name, key)
def test_mismatching_num_image_tokens(self):
"""
Tests that VLMs through an error with explicit message saying what is wrong
when number of images don't match number of image tokens in the text.
Also we need to test multi-image cases when one prompr has multiple image tokens.
"""
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config).to(torch_device)
model.eval()
curr_input_dict = copy.deepcopy(input_dict)
_ = model(**curr_input_dict) # successful forward with no modifications
# remove one image but leave the image token in text
curr_input_dict["pixel_values_images"] = curr_input_dict["pixel_values_images"][-1:, ...]
with self.assertRaises(ValueError):
_ = model(**curr_input_dict)
# simulate multi-image case by concatenating inputs where each has exactly one image/image-token
input_ids = curr_input_dict["input_ids"][:1]
pixel_values = curr_input_dict["pixel_values_images"][:1]
input_ids = torch.cat([input_ids, input_ids], dim=0)
# one image and two image tokens raise an error
with self.assertRaises(ValueError):
_ = model(input_ids=input_ids, pixel_values_images=pixel_values)
# two images and two image tokens don't raise an error
pixel_values = torch.cat([pixel_values, pixel_values], dim=0)
_ = model(input_ids=input_ids, pixel_values_images=pixel_values)
@parameterized.expand(
[
(-1,),
([-1],),
([-1, -2],),
],
)
def test_vision_feature_layers(self, vision_feature_layer):
"""
Test that we can use either one vision feature layer, or a list of
vision feature layers.
"""
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.vision_feature_layer = vision_feature_layer
num_feature_layers = 1 if isinstance(vision_feature_layer, int) else len(vision_feature_layer)
hidden_size = config.vision_config.hidden_size
expected_features = hidden_size * num_feature_layers
for model_class in self.all_model_classes:
model = model_class(config).to(torch_device)
# We should have the right number of input features,
# and should be able to run a forward pass without exploding
base_model = getattr(model, "model", model)
assert base_model.multi_modal_projector.linear_1.in_features == expected_features
model(**input_dict)
@require_torch
| VideoLlavaForConditionalGenerationModelTest |
python | kamyu104__LeetCode-Solutions | Python/find-minimum-in-rotated-sorted-array.py | {
"start": 32,
"end": 436
} | class ____(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 0, len(nums)
target = nums[-1]
while left < right:
mid = left + (right - left) / 2
if nums[mid] <= target:
right = mid
else:
left = mid + 1
return nums[left]
| Solution |
python | plotly__plotly.py | plotly/graph_objs/funnelarea/legendgrouptitle/_font.py | {
"start": 233,
"end": 9942
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnelarea.legendgrouptitle"
_path_str = "funnelarea.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@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
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = 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
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = 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')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = 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
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = 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]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = 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']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = 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']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = 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']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = 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')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
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.
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.
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.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.funnelarea.leg
endgrouptitle.Font`
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.
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.
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.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
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.funnelarea.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.funnelarea.legendgrouptitle.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | pytorch__pytorch | test/jit/test_hooks_modules.py | {
"start": 2208,
"end": 2452
} | class ____(torch.nn.Module):
def __init__(self, name):
super().__init__()
self.name = name
def forward(self, input: Tuple[int]):
input_access = input[0] # noqa: F841
return (1,)
| SubmoduleForwardTupleInput |
python | getsentry__sentry | src/sentry/snuba/metrics/naming_layer/mri.py | {
"start": 8575,
"end": 10203
} | class ____(Enum):
USER = "s:spans/user@none"
DURATION = "d:spans/duration@millisecond"
COUNT_PER_ROOT_PROJECT = "c:spans/count_per_root_project@none"
SELF_TIME = "d:spans/exclusive_time@millisecond"
SELF_TIME_LIGHT = "d:spans/exclusive_time_light@millisecond"
# Measurement-based metrics
AI_TOTAL_TOKENS = "c:spans/ai.total_tokens.used@none"
AI_TOTAL_COST = "c:spans/ai.total_cost@usd"
CACHE_ITEM_SIZE = "d:spans/cache.item_size@byte"
DECODED_RESPONSE_CONTENT_LENGTH = "d:spans/http.decoded_response_content_length@byte"
MESSAGE_RECEIVE_LATENCY = "g:spans/messaging.message.receive.latency@millisecond"
MOBILE_FRAMES_DELAY = "g:spans/mobile.frames_delay@second"
MOBILE_FROZEN_FRAMES = "g:spans/mobile.frozen_frames@none"
MOBILE_SLOW_FRAMES = "g:spans/mobile.slow_frames@none"
MOBILE_TOTAL_FRAMES = "g:spans/mobile.total_frames@none"
RESPONSE_CONTENT_LENGTH = "d:spans/http.response_content_length@byte"
RESPONSE_TRANSFER_SIZE = "d:spans/http.response_transfer_size@byte"
WEB_VITALS_INP = "d:spans/webvital.inp@millisecond"
WEB_VITALS_SCORE_INP = "d:spans/webvital.score.inp@ratio"
WEB_VITALS_SCORE_TOTAL = "d:spans/webvital.score.total@ratio"
WEB_VITALS_SCORE_WEIGHT = "d:spans/webvital.score.weight.inp@ratio"
# Derived
ALL = "e:spans/all@none"
ALL_LIGHT = "e:spans_light/all@none"
HTTP_ERROR_COUNT = "e:spans/http_error_count@none"
HTTP_ERROR_RATE = "e:spans/http_error_rate@ratio"
HTTP_ERROR_COUNT_LIGHT = "e:spans/http_error_count_light@none"
HTTP_ERROR_RATE_LIGHT = "e:spans/http_error_rate_light@ratio"
| SpanMRI |
python | great-expectations__great_expectations | great_expectations/core/config_provider.py | {
"start": 6441,
"end": 7675
} | class ____(_AbstractConfigurationProvider):
"""
Responsible for the management of a user's GX Cloud credentials.
See `GXCloudConfig` for more information. Note that this is only registered on the primary
config provider when in a Cloud-backed environment.
"""
def __init__(self, cloud_config: GXCloudConfig) -> None:
self._cloud_config = cloud_config
@override
def get_values(self) -> Dict[str, str]:
from great_expectations.data_context.cloud_constants import (
GXCloudEnvironmentVariable,
)
base_url = self._cloud_config.base_url
access_token = self._cloud_config.access_token
organization_id = self._cloud_config.organization_id
cloud_values: Dict[str, str] = {
GXCloudEnvironmentVariable.BASE_URL: base_url,
GXCloudEnvironmentVariable.ACCESS_TOKEN: access_token,
}
# organization_id is nullable so we conditionally include it in the output
if organization_id:
cloud_values.update(
{
GXCloudEnvironmentVariable.ORGANIZATION_ID: organization_id,
}
)
return cloud_values
| _CloudConfigurationProvider |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataplex.py | {
"start": 2557,
"end": 2702
} | class ____(AirflowException):
"""Raised when no result found after specified amount of seconds."""
| AirflowDataQualityScanResultTimeoutException |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 12657,
"end": 12700
} | class ____(gevent.Greenlet):
pass
| Subclass |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 44072,
"end": 44854
} | class ____(BaseAsyncRealtimeConnectionResource):
async def clear(self, *, event_id: str | Omit = omit) -> None:
"""**WebRTC Only:** Emit to cut off the current audio response.
This will trigger the server to
stop generating audio and emit a `output_audio_buffer.cleared` event. This
event should be preceded by a `response.cancel` client event to stop the
generation of the current response.
[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).
"""
await self._connection.send(
cast(RealtimeClientEventParam, strip_not_given({"type": "output_audio_buffer.clear", "event_id": event_id}))
)
| AsyncRealtimeOutputAudioBufferResource |
python | PyCQA__isort | isort/utils.py | {
"start": 103,
"end": 404
} | class ____:
def __init__(self, config_file: str = "", config_data: dict[str, Any] | None = None) -> None:
if not config_data:
config_data = {}
self.nodes: dict[str, TrieNode] = {}
self.config_info: tuple[str, dict[str, Any]] = (config_file, config_data)
| TrieNode |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/throughput_monitor.py | {
"start": 1485,
"end": 10985
} | class ____(Callback):
r"""Computes and logs throughput with the :class:`~lightning.fabric.utilities.throughput.Throughput`
Example::
class MyModel(LightningModule):
def setup(self, stage):
with torch.device("meta"):
model = MyModel()
def sample_forward():
batch = torch.randn(..., device="meta")
return model(batch)
self.flops_per_batch = measure_flops(model, sample_forward, loss_fn=torch.Tensor.sum)
logger = ...
throughput = ThroughputMonitor(batch_size_fn=lambda batch: batch.size(0))
trainer = Trainer(max_steps=1000, log_every_n_steps=10, callbacks=throughput, logger=logger)
model = MyModel()
trainer.fit(model)
Notes:
- It assumes that the batch size is the same during all iterations.
- It will try to access a ``flops_per_batch`` attribute on your ``LightningModule`` on every iteration.
We suggest using the :func:`~lightning.fabric.utilities.throughput.measure_flops` function for this.
You might want to compute it differently each time based on your setup.
Args:
batch_size_fn: A function to compute the number of samples given a batch.
length_fn: A function to compute the number of items in a sample given a batch.
\**kwargs: See available parameters in
:class:`~lightning.fabric.utilities.throughput.Throughput`
"""
def __init__(
self, batch_size_fn: Callable[[Any], int], length_fn: Optional[Callable[[Any], int]] = None, **kwargs: Any
) -> None:
super().__init__()
self.kwargs = kwargs
self.batch_size_fn = batch_size_fn
self.length_fn = length_fn
self.available_flops: Optional[int] = None
self._throughputs: dict[RunningStage, Throughput] = {}
self._t0s: dict[RunningStage, float] = {}
self._lengths: dict[RunningStage, int] = {}
self._samples: dict[RunningStage, int] = {}
self._batches: dict[RunningStage, int] = {}
@override
def setup(self, trainer: "Trainer", pl_module: "LightningModule", stage: str) -> None:
dtype = _plugin_to_compute_dtype(trainer.precision_plugin)
self.available_flops = get_available_flops(trainer.strategy.root_device, dtype)
if stage == TrainerFn.FITTING and trainer.enable_validation:
# `fit` includes validation inside
throughput = Throughput(available_flops=self.available_flops, world_size=trainer.world_size, **self.kwargs)
self._throughputs[RunningStage.VALIDATING] = throughput
throughput = Throughput(available_flops=self.available_flops, world_size=trainer.world_size, **self.kwargs)
stage = trainer.state.stage
assert stage is not None
self._throughputs[stage] = throughput
def _start(self, trainer: "Trainer") -> None:
stage = trainer.state.stage
assert stage is not None
reset_needed = trainer.state.fn == TrainerFn.FITTING or stage not in self._samples
if reset_needed:
self._throughputs[stage].reset()
self._lengths[stage] = 0
self._samples[stage] = 0
self._batches[stage] = 0
self._t0s[stage] = time.perf_counter()
@torch.inference_mode() # in case `length_fn` or `batch_size_fn` computes grads
def _update(self, trainer: "Trainer", pl_module: "LightningModule", batch: Any, iter_num: int) -> None:
stage = trainer.state.stage
assert stage is not None
throughput = self._throughputs[stage]
if trainer.strategy.root_device.type == "cuda":
# required or else perf_counter() won't be correct
torch.cuda.synchronize()
elapsed = time.perf_counter() - self._t0s[stage]
if self.length_fn is not None:
self._lengths[stage] += self.length_fn(batch)
if hasattr(pl_module, "flops_per_batch"):
flops_per_batch = pl_module.flops_per_batch
else:
rank_zero_warn(
"When using the `ThroughputMonitor`, you need to define a `flops_per_batch` attribute or property"
f" in {type(pl_module).__name__} to compute the FLOPs."
)
flops_per_batch = None
self._samples[stage] += self.batch_size_fn(batch)
self._batches[stage] += 1
throughput.update(
time=elapsed,
batches=self._batches[stage],
# this assumes that all iterations used the same batch size
samples=self._samples[stage],
lengths=None if self.length_fn is None else self._lengths[stage],
flops=flops_per_batch, # type: ignore[arg-type]
)
def _compute(self, trainer: "Trainer", iter_num: Optional[int] = None) -> None:
if not trainer._logger_connector.should_update_logs:
return
stage = trainer.state.stage
assert stage is not None
throughput = self._throughputs[stage]
metrics = throughput.compute()
# prefix with the stage to avoid collisions
metrics = {f"{stage.value}{throughput.separator}{k}": v for k, v in metrics.items()}
trainer._logger_connector.log_metrics(metrics, step=iter_num) # type: ignore[arg-type]
@override
@rank_zero_only
def on_train_start(self, trainer: "Trainer", *_: Any) -> None:
self._start(trainer)
@override
@rank_zero_only
def on_train_batch_end(
self, trainer: "Trainer", pl_module: "LightningModule", outputs: Any, batch: Any, *_: Any
) -> None:
self._update(trainer, pl_module, batch, trainer.fit_loop.total_batch_idx + 1)
# log only when gradient accumulation is over. this ensures that we only measure when the effective batch has
# finished and the `optimizer.step()` time is included
if not trainer.fit_loop._should_accumulate():
self._compute(trainer)
@override
@rank_zero_only
def on_validation_start(self, trainer: "Trainer", *_: Any) -> None:
if trainer.sanity_checking:
return
self._start(trainer)
@override
@rank_zero_only
def on_validation_batch_end(
self, trainer: "Trainer", pl_module: "LightningModule", outputs: Any, batch: Any, *_: Any, **__: Any
) -> None:
if trainer.sanity_checking:
return
iter_num = trainer._evaluation_loop.batch_progress.total.ready
self._update(trainer, pl_module, batch, iter_num)
self._compute(trainer, iter_num)
@override
@rank_zero_only
def on_validation_end(self, trainer: "Trainer", *_: Any) -> None:
if trainer.sanity_checking or trainer.state.fn != TrainerFn.FITTING:
return
train_times = self._throughputs[RunningStage.TRAINING]._time
val_times = self._throughputs[RunningStage.VALIDATING]._time
train_elapsed = train_times[-1] if train_times else 0.0
val_elapsed = val_times[-1] if val_times else 0.0
# add the validation time to the training time before continuing to avoid sinking the training throughput
training_finished = self._t0s[RunningStage.TRAINING] + train_elapsed
time_between_train_and_val = self._t0s[RunningStage.VALIDATING] - training_finished
val_time = val_elapsed
self._t0s[RunningStage.TRAINING] += time_between_train_and_val + val_time
@override
@rank_zero_only
def on_test_start(self, trainer: "Trainer", *_: Any) -> None:
self._start(trainer)
@override
@rank_zero_only
def on_test_batch_end(
self, trainer: "Trainer", pl_module: "LightningModule", outputs: Any, batch: Any, *_: Any, **__: Any
) -> None:
iter_num = trainer._evaluation_loop.batch_progress.total.ready
self._update(trainer, pl_module, batch, iter_num)
self._compute(trainer, iter_num)
@override
@rank_zero_only
def on_predict_start(self, trainer: "Trainer", *_: Any) -> None:
self._start(trainer)
@override
@rank_zero_only
def on_predict_batch_end(
self, trainer: "Trainer", pl_module: "LightningModule", outputs: Any, batch: Any, *_: Any, **__: Any
) -> None:
iter_num = trainer.predict_loop.batch_progress.total.ready
self._update(trainer, pl_module, batch, iter_num)
self._compute(trainer, iter_num)
def _plugin_to_compute_dtype(plugin: Union[FabricPrecision, Precision]) -> torch.dtype:
# TODO: integrate this into the precision plugins
if not isinstance(plugin, Precision):
return fabric_plugin_to_compute_dtype(plugin)
if isinstance(plugin, BitsandbytesPrecision):
return plugin.dtype
if isinstance(plugin, HalfPrecision):
return plugin._desired_input_dtype
if isinstance(plugin, MixedPrecision):
return torch.bfloat16 if plugin.precision == "bf16-mixed" else torch.half
if isinstance(plugin, DoublePrecision):
return torch.double
if isinstance(plugin, (XLAPrecision, DeepSpeedPrecision)):
return plugin._desired_dtype
if isinstance(plugin, TransformerEnginePrecision):
return torch.int8
if isinstance(plugin, FSDPPrecision):
return plugin.mixed_precision_config.reduce_dtype or torch.float32
if isinstance(plugin, Precision):
return torch.float32
raise NotImplementedError(plugin)
| ThroughputMonitor |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 86038,
"end": 86404
} | class ____(BaseModel, extra="forbid"):
batch: "Batch" = Field(..., description="")
shard_key: Optional["ShardKeySelector"] = Field(default=None, description="")
update_filter: Optional["Filter"] = Field(
default=None,
description="If specified, only points that match this filter will be updated, others will be inserted",
)
| PointsBatch |
python | huggingface__transformers | src/transformers/models/ijepa/modeling_ijepa.py | {
"start": 1178,
"end": 3146
} | class ____(nn.Module):
"""
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
"""
def __init__(self, config: IJepaConfig):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
num_channels, hidden_size = config.num_channels, config.hidden_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.num_patches = num_patches
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
batch_size, num_channels, height, width = pixel_values.shape
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
f" Expected {self.num_channels} but got {num_channels}."
)
if not interpolate_pos_encoding:
if height != self.image_size[0] or width != self.image_size[1]:
raise ValueError(
f"Input image size ({height}*{width}) doesn't match model"
f" ({self.image_size[0]}*{self.image_size[1]})."
)
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
return embeddings
| IJepaPatchEmbeddings |
python | getsentry__sentry | src/sentry/rules/actions/notify_event_service.py | {
"start": 4518,
"end": 8270
} | class ____(EventAction):
"""Used for notifying a *specific* plugin/sentry app with a generic webhook payload."""
id = "sentry.rules.actions.notify_event_service.NotifyEventServiceAction"
label = "Send a notification via {service}"
prompt = "Send a notification via an integration"
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.form_fields = {
"service": {
"type": "choice",
"choices": [[i.slug, self.transform_title(i.title)] for i in self.get_services()],
}
}
def transform_title(self, title: str) -> str:
if title in PLUGINS_WITH_FIRST_PARTY_EQUIVALENTS:
return f"(Legacy) {title}"
return title
def after(
self, event: GroupEvent, notification_uuid: str | None = None
) -> Generator[CallbackFuture]:
service = self.get_option("service")
extra: dict[str, object] = {"event_id": event.event_id}
if not service:
self.logger.info("rules.fail.is_configured", extra=extra)
return
plugin = None
app = app_service.get_sentry_app_by_slug(slug=service)
if app:
metrics.incr(
"notifications.sent",
instance=app.slug,
tags={
"issue_type": event.group.issue_type.slug,
},
skip_internal=False,
)
yield self.future(notify_sentry_app, sentry_app=app)
try:
plugin = plugins.get(service)
except KeyError:
if not app:
# If we can't find the sentry app OR plugin,
# we've removed the plugin no need to error, just skip.
extra["plugin"] = service
self.logger.info("rules.fail.plugin_does_not_exist", extra=extra)
return
if plugin:
extra["plugin"] = service
if not plugin.is_enabled(self.project):
extra["project_id"] = self.project.id
self.logger.info("rules.fail.is_enabled", extra=extra)
return
group = event.group
if not plugin.should_notify(group=group, event=event):
extra["group_id"] = group.id
self.logger.info("rule.fail.should_notify", extra=extra)
return
extra["organization_id"] = self.project.organization_id
extra["project_id"] = self.project.id
self.logger.info("rules.plugin_notification_sent", extra=extra)
metrics.incr(
"notifications.sent",
instance=plugin.slug,
tags={
"issue_type": event.group.issue_type.slug,
},
skip_internal=False,
)
yield self.future(plugin.rule_notify)
def get_sentry_app_services(self) -> Sequence[RpcSentryAppService]:
return app_service.find_alertable_services(organization_id=self.project.organization_id)
def get_plugins(self) -> Sequence[PluginService]:
from sentry.plugins.bases.notify import NotificationPlugin
results = []
for plugin in plugins.for_project(self.project, version=1):
if not isinstance(plugin, NotificationPlugin):
continue
results.append(PluginService(plugin))
return results
def get_services(self) -> Sequence[Any]:
return [*self.get_plugins(), *self.get_sentry_app_services()]
def get_form_instance(self) -> NotifyEventServiceForm:
return NotifyEventServiceForm(self.data, services=self.get_services())
| NotifyEventServiceAction |
python | urllib3__urllib3 | test/with_dummyserver/test_no_ssl.py | {
"start": 676,
"end": 1146
} | class ____(HTTPSHypercornDummyServerTestCase, TestWithoutSSL):
def test_simple(self) -> None:
with urllib3.HTTPSConnectionPool(
self.host, self.port, cert_reqs="NONE"
) as pool:
with pytest.warns(InsecureRequestWarning):
try:
pool.request("GET", "/")
except urllib3.exceptions.SSLError as e:
assert "SSL module is not available" in str(e)
| TestHTTPSWithoutSSL |
python | readthedocs__readthedocs.org | readthedocs/api/v3/tests/test_subprojects.py | {
"start": 302,
"end": 14571
} | class ____(APIEndpointMixin):
def setUp(self):
super().setUp()
self._create_subproject()
def test_projects_subprojects_list_anonymous_user(self):
url = reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
)
expected_response = self._get_response_dict("projects-subprojects-list")
empty_response = self._get_response_dict("projects-list-empty")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), empty_response)
def test_projects_subprojects_list(self):
url = reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
)
expected_response = self._get_response_dict("projects-subprojects-list")
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
expected_response["results"][0]["child"]["privacy_level"] = PRIVATE
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
def test_projects_subprojects_list_other_user(self):
url = reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
)
expected_response = self._get_response_dict("projects-subprojects-list")
empty_response = self._get_response_dict("projects-list-empty")
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.others_token.key}")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), empty_response)
def test_projects_subprojects_detail_anonymous_user(self):
url = reverse(
"projects-subprojects-detail",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
"alias_slug": self.project_relationship.alias,
},
)
expected_response = self._get_response_dict("projects-subprojects-detail")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_projects_subprojects_detail(self):
url = reverse(
"projects-subprojects-detail",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
"alias_slug": self.project_relationship.alias,
},
)
expected_response = self._get_response_dict("projects-subprojects-detail")
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
expected_response["child"]["privacy_level"] = PRIVATE
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
def test_projects_subprojects_detail_other_user(self):
url = reverse(
"projects-subprojects-detail",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
"alias_slug": self.project_relationship.alias,
},
)
expected_response = self._get_response_dict("projects-subprojects-detail")
self.client.logout()
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.others_token.key}")
# Subproject is public
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(response.json(), expected_response)
# Subproject is private
Project.objects.filter(slug=self.subproject.slug).update(privacy_level=PRIVATE)
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_projects_subprojects_list_post(self):
newproject = self._create_new_project()
self.organization.projects.add(newproject)
self.assertEqual(self.project.subprojects.count(), 1)
url = reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
)
data = {
"child": newproject.slug,
"alias": "subproject-alias",
}
self.client.logout()
response = self.client.post(url, data)
self.assertEqual(response.status_code, 401)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.others_token.key}")
response = self.client.post(url, data)
self.assertEqual(response.status_code, 403)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.post(url, data)
self.assertEqual(response.status_code, 201)
self.assertEqual(self.project.subprojects.count(), 2)
self.assertDictEqual(
response.json(),
self._get_response_dict("projects-subprojects-list_POST"),
)
def test_projects_subprojects_list_post_with_others_as_child(self):
self.assertEqual(self.project.subprojects.count(), 1)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": self.others_project.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertEqual(self.project.subprojects.count(), 1)
def test_projects_subprojects_list_post_with_subproject_of_itself(self):
newproject = self._create_new_project()
self.assertEqual(newproject.subprojects.count(), 0)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": newproject.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": newproject.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertIn(
"Project with slug=new-project is not valid as subproject",
response.json()["child"][0],
)
self.assertEqual(newproject.subprojects.count(), 0)
def test_projects_subprojects_list_post_with_child_already_superproject(self):
newproject = self._create_new_project()
self.assertEqual(newproject.subprojects.count(), 0)
self.assertTrue(self.project.subprojects.exists())
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": self.project.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": newproject.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertIn(
"Project with slug=project is not valid as subproject",
response.json()["child"][0],
)
self.assertEqual(newproject.subprojects.count(), 0)
def test_projects_subprojects_list_post_with_child_already_subproject(self):
newproject = self._create_new_project()
self.assertEqual(newproject.subprojects.count(), 0)
self.assertTrue(self.subproject.superprojects.exists())
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": self.subproject.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": newproject.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertIn(
"Project with slug=subproject is not valid as subproject",
response.json()["child"][0],
)
self.assertEqual(newproject.subprojects.count(), 0)
def test_projects_subprojects_list_post_nested_subproject(self):
newproject = self._create_new_project()
self.assertEqual(self.project.subprojects.count(), 1)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": newproject.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.subproject.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertIn(
"Subproject nesting is not supported",
response.json()["non_field_errors"],
)
self.assertEqual(self.project.subprojects.count(), 1)
def test_projects_subprojects_list_post_unique_alias(self):
newproject = self._create_new_project()
self.assertEqual(self.project.subprojects.count(), 1)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": newproject.slug,
"alias": "subproject", # this alias is already set for another subproject
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
},
),
data,
)
self.assertEqual(response.status_code, 400)
self.assertIn(
"A subproject with this alias already exists",
response.json()["alias"],
)
self.assertEqual(self.project.subprojects.count(), 1)
def test_projects_subprojects_list_post_with_others_as_parent(self):
self.assertEqual(self.others_project.subprojects.count(), 0)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
data = {
"child": self.project.slug,
"alias": "subproject-alias",
}
response = self.client.post(
reverse(
"projects-subprojects-list",
kwargs={
"parent_lookup_parent__slug": self.others_project.slug,
},
),
data,
)
self.assertEqual(response.status_code, 403)
self.assertEqual(self.others_project.subprojects.count(), 0)
def test_projects_subprojects_detail_delete(self):
url = reverse(
"projects-subprojects-detail",
kwargs={
"parent_lookup_parent__slug": self.project.slug,
"alias_slug": self.project_relationship.alias,
},
)
self.client.logout()
response = self.client.delete(url)
self.assertEqual(response.status_code, 401)
self.assertEqual(self.project.subprojects.count(), 1)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.delete(url)
self.assertEqual(response.status_code, 204)
self.assertEqual(self.project.subprojects.count(), 0)
def test_projects_subprojects_detail_delete_others_project(self):
newproject = self._create_new_project()
project_relationship = self.others_project.add_subproject(newproject)
self.assertEqual(self.others_project.subprojects.count(), 1)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.delete(
reverse(
"projects-subprojects-detail",
kwargs={
"parent_lookup_parent__slug": self.others_project.slug,
"alias_slug": project_relationship.alias,
},
),
)
self.assertEqual(response.status_code, 403)
self.assertEqual(self.project.subprojects.count(), 1)
| SubprojectsEndpointTests |
python | huggingface__transformers | src/transformers/models/speecht5/configuration_speecht5.py | {
"start": 19002,
"end": 23466
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SpeechT5HifiGanModel`]. It is used to instantiate
a SpeechT5 HiFi-GAN vocoder model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the SpeechT5
[microsoft/speecht5_hifigan](https://huggingface.co/microsoft/speecht5_hifigan) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
model_in_dim (`int`, *optional*, defaults to 80):
The number of frequency bins in the input log-mel spectrogram.
sampling_rate (`int`, *optional*, defaults to 16000):
The sampling rate at which the output audio will be generated, expressed in hertz (Hz).
upsample_initial_channel (`int`, *optional*, defaults to 512):
The number of input channels into the upsampling network.
upsample_rates (`tuple[int]` or `list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
A tuple of integers defining the stride of each 1D convolutional layer in the upsampling network. The
length of *upsample_rates* defines the number of convolutional layers and has to match the length of
*upsample_kernel_sizes*.
upsample_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[8, 8, 8, 8]`):
A tuple of integers defining the kernel size of each 1D convolutional layer in the upsampling network. The
length of *upsample_kernel_sizes* defines the number of convolutional layers and has to match the length of
*upsample_rates*.
resblock_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[3, 7, 11]`):
A tuple of integers defining the kernel sizes of the 1D convolutional layers in the multi-receptive field
fusion (MRF) module.
resblock_dilation_sizes (`tuple[tuple[int]]` or `list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
multi-receptive field fusion (MRF) module.
initializer_range (`float`, *optional*, defaults to 0.01):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
leaky_relu_slope (`float`, *optional*, defaults to 0.1):
The angle of the negative slope used by the leaky ReLU activation.
normalize_before (`bool`, *optional*, defaults to `True`):
Whether or not to normalize the spectrogram before vocoding using the vocoder's learned mean and variance.
Example:
```python
>>> from transformers import SpeechT5HifiGan, SpeechT5HifiGanConfig
>>> # Initializing a "microsoft/speecht5_hifigan" style configuration
>>> configuration = SpeechT5HifiGanConfig()
>>> # Initializing a model (with random weights) from the "microsoft/speecht5_hifigan" style configuration
>>> model = SpeechT5HifiGan(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "hifigan"
def __init__(
self,
model_in_dim=80,
sampling_rate=16000,
upsample_initial_channel=512,
upsample_rates=[4, 4, 4, 4],
upsample_kernel_sizes=[8, 8, 8, 8],
resblock_kernel_sizes=[3, 7, 11],
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
initializer_range=0.01,
leaky_relu_slope=0.1,
normalize_before=True,
**kwargs,
):
self.model_in_dim = model_in_dim
self.sampling_rate = sampling_rate
self.upsample_initial_channel = upsample_initial_channel
self.upsample_rates = upsample_rates
self.upsample_kernel_sizes = upsample_kernel_sizes
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.initializer_range = initializer_range
self.leaky_relu_slope = leaky_relu_slope
self.normalize_before = normalize_before
super().__init__(**kwargs)
__all__ = ["SpeechT5Config", "SpeechT5HifiGanConfig"]
| SpeechT5HifiGanConfig |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 22730,
"end": 40227
} | class ____(object):
""" Each Bottle object represents a single, distinct web application and
consists of routes, callbacks, plugins, resources and configuration.
Instances are callable WSGI applications.
:param catchall: If true (default), handle all exceptions. Turn off to
let debugging middleware handle exceptions.
"""
def __init__(self, catchall=True, autojson=True):
#: A :class:`ConfigDict` for app specific configuration.
self.config = ConfigDict()
self.config._on_change = functools.partial(self.trigger_hook, 'config')
self.config.meta_set('autojson', 'validate', bool)
self.config.meta_set('catchall', 'validate', bool)
self.config['catchall'] = catchall
self.config['autojson'] = autojson
#: A :class:`ResourceManager` for application files
self.resources = ResourceManager()
self.routes = [] # List of installed :class:`Route` instances.
self.router = Router() # Maps requests to :class:`Route` instances.
self.error_handler = {}
# Core plugins
self.plugins = [] # List of installed plugins.
if self.config['autojson']:
self.install(JSONPlugin())
self.install(TemplatePlugin())
#: If true, most exceptions are caught and returned as :exc:`HTTPError`
catchall = DictProperty('config', 'catchall')
__hook_names = 'before_request', 'after_request', 'app_reset', 'config'
__hook_reversed = 'after_request'
@cached_property
def _hooks(self):
return dict((name, []) for name in self.__hook_names)
def add_hook(self, name, func):
''' Attach a callback to a hook. Three hooks are currently implemented:
before_request
Executed once before each request. The request context is
available, but no routing has happened yet.
after_request
Executed once after each request regardless of its outcome.
app_reset
Called whenever :meth:`Bottle.reset` is called.
'''
if name in self.__hook_reversed:
self._hooks[name].insert(0, func)
else:
self._hooks[name].append(func)
def remove_hook(self, name, func):
''' Remove a callback from a hook. '''
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True
def trigger_hook(self, __name, *args, **kwargs):
''' Trigger a hook and return a list of results. '''
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
def hook(self, name):
""" Return a decorator that attaches a callback to a hook. See
:meth:`add_hook` for details."""
def decorator(func):
self.add_hook(name, func)
return func
return decorator
def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :class:`Bottle` or a WSGI application.
All other parameters are passed to the underlying :meth:`route` call.
'''
if isinstance(app, basestring):
depr('Parameter order of Bottle.mount() changed.', True) # 0.10
segments = [p for p in prefix.split('/') if p]
if not segments: raise ValueError('Empty path prefix.')
path_depth = len(segments)
def mountpoint_wrapper():
try:
request.path_shift(path_depth)
rs = HTTPResponse([])
def start_response(status, headerlist, exc_info=None):
if exc_info:
try:
_raise(*exc_info)
finally:
exc_info = None
rs.status = status
for name, value in headerlist: rs.add_header(name, value)
return rs.body.append
body = app(request.environ, start_response)
if body and rs.body: body = itertools.chain(rs.body, body)
rs.body = body or rs.body
return rs
finally:
request.path_shift(-path_depth)
options.setdefault('skip', True)
options.setdefault('method', 'PROXY')
options.setdefault('mountpoint', {'prefix': prefix, 'target': app})
options['callback'] = mountpoint_wrapper
self.route('/%s/<:re:.*>' % '/'.join(segments), **options)
if not prefix.endswith('/'):
self.route('/' + '/'.join(segments), **options)
def merge(self, routes):
''' Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle):
routes = routes.routes
for route in routes:
self.add_route(route)
def install(self, plugin):
''' Add a plugin to the list of plugins and prepare it for being
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API.
'''
if hasattr(plugin, 'setup'): plugin.setup(self)
if not callable(plugin) and not hasattr(plugin, 'apply'):
raise TypeError("Plugins must be callable or implement .apply()")
self.plugins.append(plugin)
self.reset()
return plugin
def uninstall(self, plugin):
''' Uninstall plugins. Pass an instance to remove a specific plugin, a type
object to remove all plugins that match that type, a string to remove
all plugins with a matching ``name`` attribute or ``True`` to remove all
plugins. Return the list of removed plugins. '''
removed, remove = [], plugin
for i, plugin in list(enumerate(self.plugins))[::-1]:
if remove is True or remove is plugin or remove is type(plugin) \
or getattr(plugin, 'name', True) == remove:
removed.append(plugin)
del self.plugins[i]
if hasattr(plugin, 'close'): plugin.close()
if removed: self.reset()
return removed
def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.routes
elif isinstance(route, Route): routes = [route]
else: routes = [self.routes[route]]
for route in routes: route.reset()
if DEBUG:
for route in routes: route.prepare()
self.trigger_hook('app_reset')
def close(self):
''' Close the application and all installed plugins. '''
for plugin in self.plugins:
if hasattr(plugin, 'close'): plugin.close()
self.stopped = True
def run(self, **kwargs):
''' Calls :func:`run` with the same parameters. '''
run(self, **kwargs)
def match(self, environ):
""" Search for a matching route and return a (:class:`Route` , urlargs)
tuple. The second value is a dictionary with parameters extracted
from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
return self.router.match(environ)
def get_url(self, routename, **kargs):
""" Return a string that matches a named route """
scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
location = self.router.build(routename, **kargs).lstrip('/')
return urljoin(urljoin('/', scriptname), location)
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare()
def route(self, path=None, method='GET', callback=None, name=None,
apply=None, skip=None, **config):
""" A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path or a list of paths to listen to. If no
path is specified, it is automatically generated from the
signature of the function.
:param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
methods to listen to. (default: `GET`)
:param callback: An optional shortcut to avoid the decorator
syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
:param name: The name for this route. (default: None)
:param apply: A decorator or plugin or a list of plugins. These are
applied to the route callback in addition to installed plugins.
:param skip: A list of plugins, plugin classes or names. Matching
plugins are not installed to this route. ``True`` skips all.
Any additional keyword arguments are stored as route-specific
configuration and passed to plugins (see :meth:`Plugin.apply`).
"""
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
def decorator(callback):
# TODO: Documentation and tests
if isinstance(callback, basestring): callback = load(callback)
for rule in makelist(path) or yieldroutes(callback):
for verb in makelist(method):
verb = verb.upper()
route = Route(self, rule, verb, callback, name=name,
plugins=plugins, skiplist=skiplist, **config)
self.add_route(route)
return callback
return decorator(callback) if callback else decorator
def get(self, path=None, method='GET', **options):
""" Equals :meth:`route`. """
return self.route(path, method, **options)
def post(self, path=None, method='POST', **options):
""" Equals :meth:`route` with a ``POST`` method parameter. """
return self.route(path, method, **options)
def put(self, path=None, method='PUT', **options):
""" Equals :meth:`route` with a ``PUT`` method parameter. """
return self.route(path, method, **options)
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options)
def error(self, code=500):
""" Decorator: Register an output handler for a HTTP error code"""
def wrapper(handler):
self.error_handler[int(code)] = handler
return handler
return wrapper
def default_error_handler(self, res):
return tob(template(ERROR_PAGE_TEMPLATE, e=res))
def _handle(self, environ):
path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind()
try:
self.trigger_hook('before_request')
route, args = self.router.match(environ)
environ['route.handle'] = route
environ['bottle.route'] = route
environ['route.url_args'] = args
return route.call(**args)
finally:
self.trigger_hook('after_request')
except HTTPResponse:
return _e()
except RouteReset:
route.reset()
return self._handle(environ)
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
stacktrace = format_exc()
environ['wsgi.errors'].write(stacktrace)
return HTTPError(500, "Internal Server Error", _e(), stacktrace)
def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty output is done here
if not out:
if 'Content-Length' not in response:
response['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. Mixed lists are NOT supported
if isinstance(out, (tuple, list))\
and isinstance(out[0], (bytes, unicode)):
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
# Encode unicode strings
if isinstance(out, unicode):
out = out.encode(response.charset)
# Byte Strings are just returned
if isinstance(out, bytes):
if 'Content-Length' not in response:
response['Content-Length'] = len(out)
return [out]
# HTTPError or HTTPException (recursive, because they may wrap anything)
# TODO: Handle these explicitly in handle() or make them iterable.
if isinstance(out, HTTPError):
out.apply(response)
out = self.error_handler.get(out.status_code, self.default_error_handler)(out)
return self._cast(out)
if isinstance(out, HTTPResponse):
out.apply(response)
return self._cast(out.body)
# File-like objects.
if hasattr(out, 'read'):
if 'wsgi.file_wrapper' in request.environ:
return request.environ['wsgi.file_wrapper'](out)
elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
return WSGIFileWrapper(out)
# Handle Iterables. We peek into them to detect their inner type.
try:
iout = iter(out)
first = next(iout)
while not first:
first = next(iout)
except StopIteration:
return self._cast('')
except HTTPResponse:
first = _e()
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
first = HTTPError(500, 'Unhandled exception', _e(), format_exc())
# These are the inner types allowed in iterator or generator objects.
if isinstance(first, HTTPResponse):
return self._cast(first)
elif isinstance(first, bytes):
new_iter = itertools.chain([first], iout)
elif isinstance(first, unicode):
encoder = lambda x: x.encode(response.charset)
new_iter = imap(encoder, itertools.chain([first], iout))
else:
msg = 'Unsupported response type: %s' % type(first)
return self._cast(HTTPError(500, msg))
if hasattr(out, 'close'):
new_iter = _closeiter(new_iter, out.close)
return new_iter
def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasattr(out, 'close'): out.close()
out = []
start_response(response._status_line, response.headerlist)
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
err = '<h1>Critical error while processing request: %s</h1>' \
% html_escape(environ.get('PATH_INFO', '/'))
if DEBUG:
err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
'<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
% (html_escape(repr(_e())), html_escape(format_exc()))
environ['wsgi.errors'].write(err)
headers = [('Content-Type', 'text/html; charset=UTF-8')]
start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
return [tob(err)]
def __call__(self, environ, start_response):
''' Each instance of :class:'Bottle' is a WSGI application. '''
return self.wsgi(environ, start_response)
###############################################################################
# HTTP and WSGI Tools ##########################################################
###############################################################################
| Bottle |
python | jina-ai__jina | tests/unit/serve/runtimes/worker/test_worker_request_handler.py | {
"start": 766,
"end": 945
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
doc.text = 'changed document'
return docs
| MergeChangeDocsExecutor |
python | getsentry__sentry | src/sentry/core/endpoints/scim/utils.py | {
"start": 4875,
"end": 5033
} | class ____(TypedDict):
schemas: list[str]
totalResults: int
startIndex: int
itemsPerPage: int
@extend_schema(tags=["SCIM"])
| SCIMListBaseResponse |
python | pytorch__pytorch | torch/_inductor/codegen/triton_combo_kernel.py | {
"start": 6126,
"end": 6377
} | class ____:
partitions: list[list[BaseSchedulerNode]]
cur_partition: list[BaseSchedulerNode]
cur_count: int
def finalize(self) -> None:
if self.cur_partition:
self.partitions.append(self.cur_partition)
| PartitionState |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/annotation/hoverlabel/_font.py | {
"start": 235,
"end": 10073
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.annotation.hoverlabel"
_path_str = "layout.scene.annotation.hoverlabel.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@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
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = 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
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = 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')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = 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
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = 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]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = 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']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = 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']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = 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']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = 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')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
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.
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.
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.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets the hover label text font. By default uses the global
hover font and size, with color from `hoverlabel.bordercolor`.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.scene.a
nnotation.hoverlabel.Font`
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.
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.
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.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
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.layout.scene.annotation.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.scene.annotation.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("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 940,
"end": 1074
} | class ____:
"""The top occurrence of a text property."""
count: Optional[int]
value: Optional[str]
@dataclass
| TopOccurrence |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 14710,
"end": 14776
} | class ____(PyObjectPtr):
_typename = 'PyVarObject'
| PyVarObjectPtr |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-us-census/components.py | {
"start": 5621,
"end": 7031
} | class ____(SchemaLoader):
"""
The US Census website hosts many APIs: https://www.census.gov/data/developers/data-sets.html
These APIs return data in a non standard format.
We create the JSON schemas dynamically by reading the first "row" of data we get.
In this implementation all records are of type "string", but this function could
be changed to try and infer the data type based on the values it finds.
"""
config: Config
def get_json_schema(self) -> Mapping[str, Any]:
query_params = self.config.get("query_params")
if query_params:
parts = query_params.split("&")
parameters = []
for part in parts:
key, value = part.split("=", 1)
if key == "get":
parameters += value.split(",")
elif key == "for":
parameters.append(value.split(":")[0])
else:
parameters.append(key)
json_schema = {k: {"type": "string"} for k in parameters}
else:
json_schema = {"{ @context: https://project-open-data.cio.gov/v1.1/schema/catalog.jsonld": {"type": "string"}}
return {
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": True,
"type": "object",
"properties": json_schema,
}
| USCensusSchema |
python | pdm-project__pdm | src/pdm/pytest.py | {
"start": 16925,
"end": 21114
} | class ____:
"""
Store a command execution result.
"""
exit_code: int
"""The execution exit code"""
stdout: str
"""The execution `stdout` output"""
stderr: str
"""The execution `stderr` output"""
exception: Exception | None = None
"""If set, the exception raised on execution"""
@property
def output(self) -> str:
"""The execution `stdout` output (`stdout` alias)"""
return self.stdout
@property
def outputs(self) -> str:
"""The execution `stdout` and `stderr` outputs concatenated"""
return self.stdout + self.stderr
def print(self) -> None:
"""A debugging facility"""
print("# exit code:", self.exit_code)
print("# stdout:", self.stdout, sep="\n")
print("# stderr:", self.stderr, sep="\n")
if TYPE_CHECKING:
class PDMCallable(Protocol):
"""The PDM fixture callable signature"""
def __call__(
self,
args: str | list[str],
strict: bool = False,
input: str | None = None,
obj: Project | None = None,
env: Mapping[str, str] | None = None,
cleanup: bool = True,
**kwargs: Any,
) -> RunResult:
"""
Args:
args: the command arguments as a single lexable string or a strings array
strict: raise an exception on failure instead of returning if enabled
input: an optional string to be submitted too `stdin`
obj: an optional existing `Project`.
env: override the environment variables with those
Returns:
The command result
"""
...
@pytest.fixture
def pdm(core: Core, monkeypatch: pytest.MonkeyPatch) -> PDMCallable:
"""
A fixture allowing to execute PDM commands
Returns:
A `pdm` fixture command.
"""
# Hide the spinner text from testing output to not break existing tests
monkeypatch.setattr("pdm.termui.DummySpinner._show", lambda self: None)
def caller(
args: str | list[str],
strict: bool = False,
input: str | None = None,
obj: Project | None = None,
env: Mapping[str, str] | None = None,
cleanup: bool = True,
**kwargs: Any,
) -> RunResult:
__tracebackhide__ = True
stdin = StringIO(input)
stdout = StringIO()
stderr = StringIO()
exit_code: int = 0
exception: Exception | None = None
args = args.split() if isinstance(args, str) else args
with monkeypatch.context() as m:
old_env = os.environ.copy()
m.setattr("sys.stdin", stdin)
m.setattr("sys.stdout", stdout)
m.setattr("sys.stderr", stderr)
for key, value in (env or {}).items():
m.setenv(key, value)
try:
core.main(args, "pdm", obj=obj, **kwargs)
except SystemExit as e:
exit_code = cast(int, e.code)
except Exception as e:
exit_code = 1
exception = e
finally:
os.environ.clear()
os.environ.update(old_env)
if cleanup:
core.exit_stack.close()
result = RunResult(exit_code, stdout.getvalue(), stderr.getvalue(), exception)
if strict and result.exit_code != 0:
if result.exception:
raise result.exception.with_traceback(result.exception.__traceback__)
raise RuntimeError(f"Call command {args} failed({result.exit_code}): {result.stderr}")
return result
return caller
VENV_BACKENDS = ["virtualenv", "venv"]
@pytest.fixture(params=VENV_BACKENDS)
def venv_backends(project: Project, request: SubRequest) -> None:
"""A fixture iterating over `venv` backends"""
project.project_config["venv.backend"] = request.param
project.project_config["venv.prompt"] = "{project_name}-{python_version}"
project.project_config["python.use_venv"] = True
shutil.rmtree(project.root / "__pypackages__", ignore_errors=True)
| RunResult |
python | Lightning-AI__lightning | src/lightning/pytorch/_graveyard/hpu.py | {
"start": 809,
"end": 1216
} | class ____:
def __init__(self, *_: Any, **__: Any) -> None:
raise NotImplementedError(
"The `HPUParallelStrategy` class has been removed. Please contact developer@lightning.ai"
)
def setup(self, *_: Any, **__: Any) -> None:
raise NotImplementedError
def get_device_stats(self, *_: Any, **__: Any) -> dict:
raise NotImplementedError
| HPUParallelStrategy |
python | getsentry__sentry | tests/sentry/web/frontend/test_mailgun_inbound_webhook.py | {
"start": 499,
"end": 4981
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
with assume_test_silo_mode(SiloMode.REGION):
self.event = self.store_event(data={"event_id": "a" * 32}, project_id=self.project.id)
self.mailto = group_id_to_email(self.group.pk)
def test_invalid_signature(self) -> None:
with self.options({"mail.mailgun-api-key": "a" * 32}):
resp = self.client.post(
reverse("sentry-mailgun-inbound-hook"),
{
"recipient": self.mailto,
"sender": self.user.email,
"body-plain": body_plain,
"signature": "",
"token": "",
"timestamp": "",
},
)
assert resp.status_code == 200
qs = ControlOutbox.objects.filter(category=OutboxCategory.ISSUE_COMMENT_UPDATE)
assert qs.exists() is False
def test_missing_api_key(self) -> None:
resp = self.client.post(
reverse("sentry-mailgun-inbound-hook"),
{
"recipient": self.mailto,
"sender": self.user.email,
"body-plain": body_plain,
"signature": "",
"token": "",
"timestamp": "",
},
)
assert resp.status_code == 500
qs = ControlOutbox.objects.filter(category=OutboxCategory.ISSUE_COMMENT_UPDATE)
assert qs.exists() is False
def test_missing_body_plain(self) -> None:
token = "a" * 50
timestamp = "1422513193"
signature = "e018afea61a8eeb2f309972385b123e376079462895ebd1ede5391fb7680b6db"
with self.options({"mail.mailgun-api-key": token}):
resp = self.client.post(
reverse("sentry-mailgun-inbound-hook"),
{
"recipient": self.mailto,
"sender": self.user.email,
"signature": signature,
"token": token,
"timestamp": timestamp,
},
)
assert resp.status_code == 200
qs = ControlOutbox.objects.filter(category=OutboxCategory.ISSUE_COMMENT_UPDATE)
assert qs.exists() is False
def test_success(self) -> None:
token = "a" * 50
timestamp = "1422513193"
signature = "414a4705e6c12a39905748549f9135fbe8b739a5b12b2349ee40f31d3ee12f83"
with self.options({"mail.mailgun-api-key": "a" * 32}):
resp = self.client.post(
reverse("sentry-mailgun-inbound-hook"),
{
"recipient": self.mailto,
"sender": self.user.email,
"body-plain": body_plain,
"signature": signature,
"token": token,
"timestamp": timestamp,
},
)
assert resp.status_code == 201
assert ControlOutbox.objects.filter(category=OutboxCategory.ISSUE_COMMENT_UPDATE).exists()
with outbox_runner():
pass
with assume_test_silo_mode(SiloMode.REGION):
activity = Activity.objects.get(group_id=self.group.id, user_id=self.user.id)
assert activity.data == {"text": body_plain}
def test_success_no_duplicates(self) -> None:
token = "a" * 50
timestamp = "1422513193"
signature = "414a4705e6c12a39905748549f9135fbe8b739a5b12b2349ee40f31d3ee12f83"
with self.options({"mail.mailgun-api-key": "a" * 32}):
for _ in range(2):
resp = self.client.post(
reverse("sentry-mailgun-inbound-hook"),
{
"recipient": self.mailto,
"sender": self.user.email,
"body-plain": body_plain,
"signature": signature,
"token": token,
"timestamp": timestamp,
},
)
assert resp.status_code == 201
assert (
ControlOutbox.objects.filter(category=OutboxCategory.ISSUE_COMMENT_UPDATE).count() == 2
)
with outbox_runner():
pass
with assume_test_silo_mode(SiloMode.REGION):
qs = Activity.objects.filter(group_id=self.group.id, user_id=self.user.id)
assert qs.count() == 1
| TestMailgunInboundWebhookView |
python | openai__gym | tests/wrappers/test_atari_preprocessing.py | {
"start": 197,
"end": 914
} | class ____:
"""A testing implementation for the ALE object in atari games."""
grayscale_obs_space = Box(low=0, high=255, shape=(210, 160), dtype=np.uint8, seed=1)
rgb_obs_space = Box(low=0, high=255, shape=(210, 160, 3), dtype=np.uint8, seed=1)
def lives(self) -> int:
"""Returns the number of lives in the atari game."""
return 1
def getScreenGrayscale(self, buffer: np.ndarray):
"""Updates the buffer with a random grayscale observation."""
buffer[...] = self.grayscale_obs_space.sample()
def getScreenRGB(self, buffer: np.ndarray):
"""Updates the buffer with a random rgb observation."""
buffer[...] = self.rgb_obs_space.sample()
| AleTesting |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 25809,
"end": 26227
} | class ____(DagsterError):
"""Indicates that a stored value can't be deserialized because the definition needed to interpret
it has changed.
"""
# Not a subclass of DagsterError, since DagsterError is treated as a framework error and bypasses
# user error driven handling such as retries. This error is raised when user code in a pipes
# execution raises an error.
| DagsterDefinitionChangedDeserializationError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/pseudoGeneric3.py | {
"start": 188,
"end": 735
} | class ____(metaclass=abc.ABCMeta):
def __init__(self, value=None):
self._cache = {"value": value}
@property
def cache(self):
return self._cache
@cache.deleter
def cache(self):
self._cache = {key: None for key in self._cache}
def __getattr__(self, attr):
cache = self.cache
if attr in cache:
return cache[attr]
else:
return self.__getattribute__(attr)
b1 = ClassB("test")
reveal_type(b1.value, expected_text="Unknown | Any | None")
del b1.cache
| ClassB |
python | kamyu104__LeetCode-Solutions | Python/guess-the-number-using-bitwise-questions-i.py | {
"start": 52,
"end": 243
} | class ____(object):
def findNumber(self):
"""
:rtype: int
"""
return reduce(lambda accu, x: accu|x, (1<<i for i in xrange(30) if commonSetBits(1<<i)))
| Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 57488,
"end": 58737
} | class ____(BaseModel):
class Config:
extra = Extra.allow
type: Literal["SelectiveAuthenticator"]
authenticator_selection_path: List[str] = Field(
...,
description="Path of the field in config with selected authenticator name",
examples=[["auth"], ["auth", "type"]],
title="Authenticator Selection Path",
)
authenticators: Dict[
str,
Union[
ApiKeyAuthenticator,
BasicHttpAuthenticator,
BearerAuthenticator,
CustomAuthenticator,
OAuthAuthenticator,
JwtAuthenticator,
NoAuth,
SessionTokenAuthenticator,
LegacySessionTokenAuthenticator,
],
] = Field(
...,
description="Authenticators to select from.",
examples=[
{
"authenticators": {
"token": "#/definitions/ApiKeyAuthenticator",
"oauth": "#/definitions/OAuthAuthenticator",
"jwt": "#/definitions/JwtAuthenticator",
}
}
],
title="Authenticators",
)
parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
| SelectiveAuthenticator |
python | openai__openai-python | src/openai/types/shared_params/response_format_json_object.py | {
"start": 224,
"end": 398
} | class ____(TypedDict, total=False):
type: Required[Literal["json_object"]]
"""The type of response format being defined. Always `json_object`."""
| ResponseFormatJSONObject |
python | getsentry__sentry | src/sentry/seer/explorer/client.py | {
"start": 837,
"end": 13356
} | class ____:
"""
A simple client for Seer Explorer, our general debugging agent.
This provides a class-based interface for Sentry developers to build agentic features
with full Sentry context.
Example usage:
```python
from sentry.seer.explorer.client import SeerExplorerClient
from pydantic import BaseModel
# SIMPLE USAGE
client = SeerExplorerClient(organization, user)
run_id = client.start_run("Analyze trace XYZ and find performance issues")
state = client.get_run(run_id)
# WITH ARTIFACTS
class BugAnalysis(BaseModel):
issue_count: int
severity: str
recommendations: list[str]
client = SeerExplorerClient(organization, user, artifact_schema=BugAnalysis)
run_id = client.start_run("Analyze recent 500 errors")
state = client.get_run(run_id, blocking=True)
# Artifact is automatically reconstructed as BugAnalysis instance at runtime
if state.artifact:
artifact = cast(BugAnalysis, state.artifact)
print(f"Found {artifact.issue_count} issues")
# WITH CUSTOM TOOLS
from sentry.seer.explorer.custom_tool_utils import ExplorerTool, ExplorerToolParam, StringType
class DeploymentStatusTool(ExplorerTool):
@classmethod
def get_description(cls):
return "Check if a service is deployed in an environment"
@classmethod
def get_params(cls):
return [
ExplorerToolParam(
name="environment",
description="Environment name (e.g., 'production', 'staging')",
type=StringType(),
),
ExplorerToolParam(
name="service",
description="Service name",
type=StringType(),
),
]
@classmethod
def execute(cls, organization, **kwargs):
return "deployed" if check_deployment(organization, kwargs["environment"], kwargs["service"]) else "not deployed"
client = SeerExplorerClient(
organization,
user,
custom_tools=[DeploymentStatusTool]
)
run_id = client.start_run("Check if payment-service is deployed in production")
```
Args:
organization: Sentry organization
user: User for permission checks and user-specific context (can be User, AnonymousUser, or None)
category_key: Optional category key for filtering/grouping runs (e.g., "bug-fixer", "trace-analyzer"). Must be provided together with category_value. Makes it easy to retrieve runs for your feature later.
category_value: Optional category value for filtering/grouping runs (e.g., issue ID, trace ID). Must be provided together with category_key. Makes it easy to retrieve a specific run for your feature later.
artifact_schema: Optional Pydantic model to generate a structured artifact at the end of the run
custom_tools: Optional list of `ExplorerTool` objects to make available as tools to the agent. Each tool must inherit from ExplorerTool and implement get_params() and execute(). Tools are automatically given access to the organization context. Tool classes must be module-level (not nested classes).
intelligence_level: Optionally set the intelligence level of the agent. Higher intelligence gives better result quality at the cost of significantly higher latency and cost.
is_interactive: Enable full interactive, human-like features of the agent. Only enable if you support *all* available interactions in Seer. An example use of this is the explorer chat in Sentry UI.
"""
def __init__(
self,
organization: Organization,
user: User | AnonymousUser | None = None,
category_key: str | None = None,
category_value: str | None = None,
artifact_schema: type[BaseModel] | None = None,
custom_tools: list[type[ExplorerTool]] | None = None,
intelligence_level: Literal["low", "medium", "high"] = "medium",
is_interactive: bool = False,
):
self.organization = organization
self.user = user
self.artifact_schema = artifact_schema
self.custom_tools = custom_tools or []
self.intelligence_level = intelligence_level
self.category_key = category_key
self.category_value = category_value
self.is_interactive = is_interactive
# Validate that category_key and category_value are provided together
if category_key == "" or category_value == "":
raise ValueError("category_key and category_value cannot be empty strings")
if bool(category_key) != bool(category_value):
raise ValueError("category_key and category_value must be provided together")
# Validate access on init
has_access, error = has_seer_explorer_access_with_detail(organization, user)
if not has_access:
raise SeerPermissionError(error or "Access denied")
def start_run(
self,
prompt: str,
on_page_context: str | None = None,
) -> int:
"""
Start a new Seer Explorer session.
Args:
prompt: The initial task/query for the agent
on_page_context: Optional context from the user's screen
Returns:
int: The run ID that can be used to fetch results or continue the conversation
Raises:
requests.HTTPError: If the Seer API request fails
"""
path = "/v1/automation/explorer/chat"
payload: dict[str, Any] = {
"organization_id": self.organization.id,
"query": prompt,
"run_id": None,
"insert_index": None,
"on_page_context": on_page_context,
"user_org_context": collect_user_org_context(self.user, self.organization),
"intelligence_level": self.intelligence_level,
"is_interactive": self.is_interactive,
}
# Add artifact schema if provided
if self.artifact_schema:
payload["artifact_schema"] = self.artifact_schema.schema()
# Extract and add custom tool definitions
if self.custom_tools:
payload["custom_tools"] = [
extract_tool_schema(tool).dict() for tool in self.custom_tools
]
if self.category_key and self.category_value:
payload["category_key"] = self.category_key
payload["category_value"] = self.category_value
body = orjson.dumps(payload, option=orjson.OPT_NON_STR_KEYS)
response = requests.post(
f"{settings.SEER_AUTOFIX_URL}{path}",
data=body,
headers={
"content-type": "application/json;charset=utf-8",
**sign_with_seer_secret(body),
},
)
response.raise_for_status()
result = response.json()
return result["run_id"]
def continue_run(
self,
run_id: int,
prompt: str,
insert_index: int | None = None,
on_page_context: str | None = None,
) -> int:
"""
Continue an existing Seer Explorer session. This allows you to add follow-up queries to an ongoing conversation.
Args:
run_id: The run ID from start_run()
prompt: The follow-up task/query for the agent
insert_index: Optional index to insert the message at
on_page_context: Optional context from the user's screen
Returns:
int: The run ID (same as input)
Raises:
requests.HTTPError: If the Seer API request fails
"""
path = "/v1/automation/explorer/chat"
payload: dict[str, Any] = {
"organization_id": self.organization.id,
"query": prompt,
"run_id": run_id,
"insert_index": insert_index,
"on_page_context": on_page_context,
"is_interactive": self.is_interactive,
}
body = orjson.dumps(payload, option=orjson.OPT_NON_STR_KEYS)
response = requests.post(
f"{settings.SEER_AUTOFIX_URL}{path}",
data=body,
headers={
"content-type": "application/json;charset=utf-8",
**sign_with_seer_secret(body),
},
)
response.raise_for_status()
result = response.json()
return result["run_id"]
def get_run(
self,
run_id: int,
blocking: bool = False,
poll_interval: float = 2.0,
poll_timeout: float = 600.0,
) -> SeerRunState:
"""
Get the status/result of a Seer Explorer session.
If artifact_schema was provided in the constructor and an artifact was generated,
it will be automatically reconstructed as a typed Pydantic instance.
Args:
run_id: The run ID returned from start_run()
blocking: If True, blocks until the run completes (with polling)
poll_interval: Seconds between polls when blocking=True
poll_timeout: Maximum seconds to wait when blocking=True
Returns:
SeerRunState: State object with blocks, status, and optionally reconstructed artifact
Raises:
requests.HTTPError: If the Seer API request fails
TimeoutError: If polling exceeds poll_timeout when blocking=True
"""
if blocking:
state = poll_until_done(run_id, self.organization, poll_interval, poll_timeout)
else:
state = fetch_run_status(run_id, self.organization)
# Automatically parse raw_artifact into typed artifact if schema was provided
if state.raw_artifact and self.artifact_schema:
try:
state.artifact = self.artifact_schema.parse_obj(state.raw_artifact)
state.raw_artifact = None # clear now that it's not needed
except ValidationError as e:
# Log but don't fail - keep artifact as None
state.artifact = None
sentry_sdk.capture_exception(e, level="warning")
return state
def get_runs(
self,
category_key: str | None = None,
category_value: str | None = None,
offset: int | None = None,
limit: int | None = None,
) -> list[ExplorerRun]:
"""
Get a list of Seer Explorer runs for the organization with optional filters.
This function supports flexible filtering by user_id (from client), category_key,
or category_value. At least one filter should be provided to avoid returning all runs.
Args:
category_key: Optional category key to filter by (e.g., "bug-fixer")
category_value: Optional category value to filter by (e.g., "issue-123")
offset: Optional offset for pagination
limit: Optional limit for pagination
Returns:
list[ExplorerRun]: List of runs matching the filters, sorted by most recent first
Raises:
requests.HTTPError: If the Seer API request fails
"""
path = "/v1/automation/explorer/runs"
payload: dict[str, Any] = {
"organization_id": self.organization.id,
}
# Add optional filters
if self.user and hasattr(self.user, "id"):
payload["user_id"] = self.user.id
if category_key is not None:
payload["category_key"] = category_key
if category_value is not None:
payload["category_value"] = category_value
if offset is not None:
payload["offset"] = offset
if limit is not None:
payload["limit"] = limit
body = orjson.dumps(payload, option=orjson.OPT_NON_STR_KEYS)
response = requests.post(
f"{settings.SEER_AUTOFIX_URL}{path}",
data=body,
headers={
"content-type": "application/json;charset=utf-8",
**sign_with_seer_secret(body),
},
)
response.raise_for_status()
result = response.json()
runs = [ExplorerRun(**run) for run in result.get("data", [])]
return runs
| SeerExplorerClient |
python | keras-team__keras | keras/src/backend/torch/optimizers/torch_parallel_optimizer.py | {
"start": 118,
"end": 822
} | class ____(BaseOptimizer):
@torch_utils.no_grad
def _backend_update_step(self, grads, trainable_variables, learning_rate):
self._parallel_update_step(
grads,
trainable_variables,
learning_rate,
)
@torch_utils.no_grad
def _backend_reset_gradient_accumulators(self):
acc_list = [
v.value for v in self._accumulated_gradients if v is not None
]
torch._foreach_mul_(acc_list, 0.0)
@torch_utils.no_grad
def _backend_increment_gradient_accumulators(self, grads, acc_grads):
acc_list = [v.value for v in acc_grads]
torch._foreach_add_(acc_list, grads, alpha=1.0)
| TorchParallelOptimizer |
python | django__django | tests/check_framework/test_security.py | {
"start": 20042,
"end": 21610
} | class ____(SimpleTestCase):
@override_settings(
MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
SECURE_REFERRER_POLICY=None,
)
def test_no_referrer_policy(self):
self.assertEqual(base.check_referrer_policy(None), [base.W022])
@override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None)
def test_no_referrer_policy_no_middleware(self):
"""
Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware
isn't in MIDDLEWARE.
"""
self.assertEqual(base.check_referrer_policy(None), [])
@override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"])
def test_with_referrer_policy(self):
tests = (
"strict-origin",
"strict-origin,origin",
"strict-origin, origin",
["strict-origin", "origin"],
("strict-origin", "origin"),
)
for value in tests:
with (
self.subTest(value=value),
override_settings(SECURE_REFERRER_POLICY=value),
):
self.assertEqual(base.check_referrer_policy(None), [])
@override_settings(
MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
SECURE_REFERRER_POLICY="invalid-value",
)
def test_with_invalid_referrer_policy(self):
self.assertEqual(base.check_referrer_policy(None), [base.E023])
def failure_view_with_invalid_signature():
pass
good_class_based_csrf_failure_view = View.as_view()
| CheckReferrerPolicyTest |
python | pytorch__pytorch | test/test_custom_ops.py | {
"start": 159830,
"end": 168114
} | class ____(CustomOpTestCaseBase):
def test_MiniOpTest(self):
for orig_test in ["test_mm", "test_nonzero"]:
for (
test
) in torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS:
expected_test = f"{test}__{orig_test}"
self.assertTrue(hasattr(MiniOpTest, expected_test), msg=expected_test)
def test_generate_repro_save_data(self):
from torch.testing._internal.optests.generate_tests import generate_repro
args = (torch.ones(2, 2),)
kwargs = {"mat2": torch.zeros(2, 2)}
actual = generate_repro(
"test_schema",
torch.ops.aten.sin.default,
args,
kwargs,
save_data=True,
dry_run=True,
)
actual = re.sub(r"torch.load\(\".*\.pt\"\)", 'torch.load("repro.pt")', actual)
self.assertExpectedInline(
actual,
"""\
# =========================================================
# BEGIN REPRO SCRIPT
# =========================================================
import torch
from torch.testing._internal.optests import opcheck
# Make sure you have loaded the library that contains the op
# via an import or torch.ops.load_library(...)
op = torch.ops.aten.sin.default
args, kwargs = torch.load("repro.pt")
opcheck(op, args, kwargs, test_utils="test_schema")
# =========================================================
# END REPRO SCRIPT
# =========================================================
""",
)
def test_generate_repro_no_save_data(self):
from torch.testing._internal.optests.generate_tests import generate_repro
args = (torch.ones(2, 2),)
kwargs = {"mat2": torch.zeros(2, 2)}
actual = generate_repro(
"test_schema",
torch.ops.aten.sin.default,
args,
kwargs,
save_data=False,
dry_run=True,
)
self.assertExpectedInline(
actual,
"""\
# =========================================================
# BEGIN REPRO SCRIPT
# =========================================================
import torch
from torch.testing._internal.optests import opcheck
# Make sure you have loaded the library that contains the op
# via an import or torch.ops.load_library(...)
op = torch.ops.aten.sin.default
# If you rerun your test with PYTORCH_OPCHECK_PRINT_BETTER_REPRO=1
# we will fill them in same (args, kwargs) as in your test
args = () # args to the operator
kwargs = {} # kwargs to the operator
opcheck(op, args, kwargs, test_utils="test_schema")
# =========================================================
# END REPRO SCRIPT
# =========================================================
""",
)
def test_failures_dict_validation(self):
from torch.testing._internal.optests.generate_tests import (
FailuresDict,
validate_failures_dict_structure,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch_dynamic__test_delayed_error": {
"comment": "",
"status": "success",
}
}
}
with self.assertRaisesRegex(RuntimeError, "got status=success"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch__test_delayed_error": {
"comment": "",
"status": "xfail",
},
}
}
with self.assertRaisesRegex(RuntimeError, "should begin with one of"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch_dynamic__test_delayed_error_nopenopenope": {
"comment": "",
"status": "xfail",
},
}
}
with self.assertRaisesRegex(RuntimeError, "does not exist on the TestCase"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
def test_dont_generate_decorator(self):
self.assertTrue(hasattr(MiniOpTest, "test_dont_generate"))
self.assertFalse(hasattr(MiniOpTest, "test_schema__test_dont_generate"))
def test_opcheck(self):
x = torch.randn(3, requires_grad=True)
with self.assertRaisesRegex(ValueError, "OpOverload"):
torch.library.opcheck(torch.sin, (x,))
with self.assertRaisesRegex(ValueError, "test_utils to be subset of"):
torch.library.opcheck(torch.ops.aten.sin.default, (x,), test_utils="blah")
result = torch.library.opcheck(torch.ops.aten.sin.default, (x,))
self.assertEqual(
result,
{
"test_schema": "SUCCESS",
"test_autograd_registration": "SUCCESS",
"test_faketensor": "SUCCESS",
"test_aot_dispatch_dynamic": "SUCCESS",
},
)
result = torch.library.opcheck(
torch.ops.aten.sin.default, (x,), test_utils="test_schema"
)
self.assertEqual(result, {"test_schema": "SUCCESS"})
result = torch.library.opcheck(
torch.ops.aten.sin.default,
(x,),
test_utils=["test_schema", "test_faketensor"],
)
self.assertEqual(
result,
{
"test_schema": "SUCCESS",
"test_faketensor": "SUCCESS",
},
)
def test_opcheck_customopdef(self):
sample_inputs = [
(torch.randn(3),),
(torch.randn(3, requires_grad=True),),
]
if torch.cuda.is_available():
sample_inputs.extend(
[
(torch.randn(3, device="cuda"),),
(torch.randn(3, device="cuda", requires_grad=True),),
]
)
for args in sample_inputs:
torch.library.opcheck(custom_op_db.numpy_cube, args)
def test_is_inside_opcheck_mode(self):
self.assertFalse(optests.is_inside_opcheck_mode())
with optests.generate_tests.OpCheckMode(
["foo"], "bar", lambda x: x, None, "baz", "brr"
):
self.assertTrue(optests.is_inside_opcheck_mode())
def test_opcheck_bad_op(self):
op = op_with_incorrect_schema(self, "foo")
x = torch.randn(3)
with self.assertRaisesRegex(Exception, "is not defined to alias output"):
torch.library.opcheck(op, (x,))
result = torch.library.opcheck(op, (x,), raise_exception=False)
self.assertTrue(isinstance(result["test_schema"], RuntimeError))
del result["test_schema"]
self.assertEqual(
result,
{
"test_autograd_registration": "SUCCESS",
"test_faketensor": "SUCCESS",
"test_aot_dispatch_dynamic": "SUCCESS",
},
)
def test_opcheck_does_not_require_extra_deps(self):
# torch.testing._internal.common_utils comes with a lot of additional
# test-time dependencies. Since opcheck is public API, it should be
# usable only with pytorch install-time dependencies.
cmd = [
sys.executable,
"-c",
"import torch; import sys; \
x = torch.randn(3, requires_grad=True); \
torch.library.opcheck(torch.ops.aten.sin.default, (x,)); \
assert 'expecttest' not in sys.modules; \
assert 'torch.testing._internal.common_utils' not in sys.modules",
]
subprocess.check_output(cmd, shell=False)
| TestGenerateOpcheckTests |
python | sqlalchemy__sqlalchemy | test/ext/test_hybrid.py | {
"start": 35325,
"end": 38564
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def _fixture(self):
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
_value = Column("value", String)
@hybrid.hybrid_method
def value(self, x):
"This is an instance-level docstring"
return int(self._value) + x
@value.expression
def value(cls, value):
"This is a class-level docstring"
return func.foo(cls._value, value) + value
@hybrid.hybrid_method
def other_value(self, x):
"This is an instance-level docstring"
return int(self._value) + x
@other_value.expression
def other_value(cls, value):
return func.foo(cls._value, value) + value
return A
def test_call(self):
A = self._fixture()
a1 = A(_value=10)
eq_(a1.value(7), 17)
def test_expression(self):
A = self._fixture()
self.assert_compile(A.value(5), "foo(a.value, :foo_1) + :foo_2")
def test_info(self):
A = self._fixture()
inspect(A).all_orm_descriptors.value.info["some key"] = "some value"
eq_(
inspect(A).all_orm_descriptors.value.info,
{"some key": "some value"},
)
def test_aliased_expression(self):
A = self._fixture()
self.assert_compile(
aliased(A).value(5), "foo(a_1.value, :foo_1) + :foo_2"
)
def test_query(self):
A = self._fixture()
sess = fixture_session()
self.assert_compile(
sess.query(A).filter(A.value(5) == "foo"),
"SELECT a.id AS a_id, a.value AS a_value "
"FROM a WHERE foo(a.value, :foo_1) + :foo_2 = :param_1",
)
def test_aliased_query(self):
A = self._fixture()
sess = fixture_session()
a1 = aliased(A)
self.assert_compile(
sess.query(a1).filter(a1.value(5) == "foo"),
"SELECT a_1.id AS a_1_id, a_1.value AS a_1_value "
"FROM a AS a_1 WHERE foo(a_1.value, :foo_1) + :foo_2 = :param_1",
)
def test_query_col(self):
A = self._fixture()
sess = fixture_session()
self.assert_compile(
sess.query(A.value(5)),
"SELECT foo(a.value, :foo_1) + :foo_2 AS anon_1 FROM a",
)
def test_aliased_query_col(self):
A = self._fixture()
sess = fixture_session()
self.assert_compile(
sess.query(aliased(A).value(5)),
"SELECT foo(a_1.value, :foo_1) + :foo_2 AS anon_1 FROM a AS a_1",
)
def test_docstring(self):
A = self._fixture()
eq_(A.value.__doc__, "This is a class-level docstring")
eq_(A.other_value.__doc__, "This is an instance-level docstring")
a1 = A(_value=10)
# a1.value is still a method, so it has a
# docstring
eq_(a1.value.__doc__, "This is an instance-level docstring")
eq_(a1.other_value.__doc__, "This is an instance-level docstring")
| MethodExpressionTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 347007,
"end": 347827
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateEnterpriseRepositoryProjectsSetting
"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "setting_value", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId")
"""The ID of the enterprise on which to set the repository projects
setting.
"""
setting_value = sgqlc.types.Field(sgqlc.types.non_null(EnterpriseEnabledDisabledSettingValue), graphql_name="settingValue")
"""The value for the repository projects setting on the enterprise."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UpdateEnterpriseRepositoryProjectsSettingInput |
python | pytorch__pytorch | torch/backends/__init__.py | {
"start": 1519,
"end": 2996
} | class ____:
def __init__(self, backend, op):
self.backend = backend
self.op = op
def __setattr__(self, name, value):
if name == "fp32_precision":
torch._C._set_fp32_precision_setter(self.backend, self.op, value)
elif name in ("backend", "op"):
super().__setattr__(name, value)
else:
raise AttributeError("Unknown attribute " + name)
def __getattr__(self, name):
if name == "fp32_precision":
return torch._C._get_fp32_precision_getter(self.backend, self.op)
else:
raise AttributeError("Unknown attribute " + name)
def set_flags(_fp32_precision="none"):
orig_flags = (torch._C._get_fp32_precision_getter("generic", "all"),)
if _fp32_precision is not None:
torch._C._set_fp32_precision_setter("generic", "all", _fp32_precision)
return orig_flags
@contextmanager
def flags(fp32_precision="none"):
with __allow_nonbracketed_mutation():
orig_flags = set_flags(fp32_precision)
try:
yield
finally:
with __allow_nonbracketed_mutation():
set_flags(*orig_flags)
def _get_fp32_precision_getter(backend, op):
def inner():
return torch._C._get_fp32_precision_getter(backend, op)
return inner
def _set_fp32_precision_setter(backend, op):
def inner(precision):
return torch._C._set_fp32_precision_setter(backend, op, precision)
return inner
| _FP32Precision |
python | redis__redis-py | redis/cluster.py | {
"start": 98366,
"end": 100914
} | class ____:
""" """
def __init__(self, parse_response, connection_pool, connection):
""" """
self.parse_response = parse_response
self.connection_pool = connection_pool
self.connection = connection
self.commands = []
def append(self, c):
""" """
self.commands.append(c)
def write(self):
"""
Code borrowed from Redis so it can be fixed
"""
connection = self.connection
commands = self.commands
# We are going to clobber the commands with the write, so go ahead
# and ensure that nothing is sitting there from a previous run.
for c in commands:
c.result = None
# build up all commands into a single request to increase network perf
# send all the commands and catch connection and timeout errors.
try:
connection.send_packed_command(
connection.pack_commands([c.args for c in commands])
)
except (ConnectionError, TimeoutError) as e:
for c in commands:
c.result = e
def read(self):
""" """
connection = self.connection
for c in self.commands:
# if there is a result on this command,
# it means we ran into an exception
# like a connection error. Trying to parse
# a response on a connection that
# is no longer open will result in a
# connection error raised by redis-py.
# but redis-py doesn't check in parse_response
# that the sock object is
# still set and if you try to
# read from a closed connection, it will
# result in an AttributeError because
# it will do a readline() call on None.
# This can have all kinds of nasty side-effects.
# Treating this case as a connection error
# is fine because it will dump
# the connection object back into the
# pool and on the next write, it will
# explicitly open the connection and all will be well.
if c.result is None:
try:
c.result = self.parse_response(connection, c.args[0], **c.options)
except (ConnectionError, TimeoutError) as e:
for c in self.commands:
c.result = e
return
except RedisError:
c.result = sys.exc_info()[1]
| NodeCommands |
python | pytorch__pytorch | torch/_dynamo/variables/torch.py | {
"start": 8065,
"end": 11033
} | class ____(VariableTracker):
"""common base for all torch.* functions, classes, modules and other things"""
@classmethod
def create_with_source(cls, value, source):
if inspect.isclass(value):
install_guard(source.make_guard(GuardBuilder.CLASS_MATCH))
elif inspect.ismodule(value):
install_guard(source.make_guard(GuardBuilder.MODULE_MATCH))
elif inspect.isfunction(value):
install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH))
elif inspect.isbuiltin(value) or isinstance(
value, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)
):
install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH))
elif is_wrapper_or_member_descriptor(value) or isinstance(
value, torch._dynamo.compiled_autograd.Op
):
# Dont need to guard on wrappers
pass
else:
install_guard(source.make_guard(GuardBuilder.FUNCTION_MATCH))
return cls(value, source=source)
def __init__(self, value, **kwargs) -> None:
super().__init__(**kwargs)
self.value = value
def reconstruct(self, codegen: "PyCodegen"):
try:
name = f"{self.value.__module__}.{self.value.__name__}"
except Exception:
name = f"torch_obj_{id(self.value)}"
unique_var_name = "__" + re.sub(r"[^a-zA-Z0-9_]+", "_", name)
codegen.extend_output(
codegen.setup_globally_cached(unique_var_name, self.value)
)
def as_proxy(self):
return self.value
def as_python_constant(self):
return self.value
def call_obj_hasattr(self, tx: "InstructionTranslator", name):
result = hasattr(self.value, name)
return variables.ConstantVariable.create(result)
def can_constant_fold_through(self):
if self.value in constant_fold_functions:
return True
if (
self.value is torch.autograd._profiler_enabled
and config.constant_fold_autograd_profiler_enabled
):
# The relevant flag is enabled only for export. One might wonder
# why?
#
# Actually we would like to not graph break even in the case of
# Dynamo. But there is a weird-unsolved bug with Kineto + Dynamo
# when there are distributed jobs that lead to NCCL timeouts. This
# bug is a rare edege case, but we have not been able to root cause
# it yet. See https://www.internalfb.com/sevmanager/view/560336 for
# more details.
#
# So is this safe for export? Yes, for export, we do not anticipate
# JIT tracing in distributed job training, and the weird edge-case
# interaction with Kineto is not a valid usecase. So, this is ok.
return True
return getattr(self.value, "__module__", None) == "math"
| BaseTorchVariable |
python | OmkarPathak__pygorithm | pygorithm/data_structures/tree.py | {
"start": 9317,
"end": 11111
} | class ____(object):
def __init__(self):
self.root = None
def insert(self, data):
"""
inserts a node in the tree
"""
if self.root:
return self.root.insert(data)
else:
self.root = BSTNode(data)
return True
def delete(self, data):
"""
deletes the node with the specified data from the tree
"""
if self.root is not None:
return self.root.delete(data)
def find(self, data):
if self.root:
return self.root.find(data)
else:
return False
def preorder(self):
"""
finding the preorder of the tree
"""
if self.root is not None:
return self.root.preorder(self.root)
def inorder(self):
"""
finding the inorder of the tree
"""
if self.root is not None:
return self.root.inorder(self.root)
def postorder(self):
"""
finding the postorder of the tree
"""
if self.root is not None:
return self.root.postorder(self.root)
def number_of_nodes(self, root):
"""
counting number of nodes
"""
# need testing
left_number = 0;
right_number = 0;
#number of nodes left side
if root.get_left():
left_number = self.number_of_nodes(root.get_left())
#numbeof nodes right side
if root.get_right():
right_number = self.number_of_nodes(root.get_right())
return left_number + right_number + 1
@staticmethod
def get_code():
"""
returns the code of the current class
"""
return inspect.getsource(BinarySearchTree)
| BinarySearchTree |
python | simonw__datasette | datasette/views/table.py | {
"start": 21686,
"end": 21846
} | class ____(TableInsertView):
name = "table-upsert"
async def post(self, request):
return await super().post(request, upsert=True)
| TableUpsertView |
python | gevent__gevent | src/greentest/3.11/test_socket.py | {
"start": 204677,
"end": 207387
} | class ____(SocketTCPTest, ThreadableTest):
cli = None
def __init__(self, methodName='runTest'):
SocketTCPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.source_port = socket_helper.find_unused_port()
def clientTearDown(self):
if self.cli is not None:
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
def _justAccept(self):
conn, addr = self.serv.accept()
conn.close()
testFamily = _justAccept
def _testFamily(self):
self.cli = socket.create_connection((HOST, self.port),
timeout=support.LOOPBACK_TIMEOUT)
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.family, 2)
testSourceAddress = _justAccept
def _testSourceAddress(self):
self.cli = socket.create_connection((HOST, self.port),
timeout=support.LOOPBACK_TIMEOUT,
source_address=('', self.source_port))
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.getsockname()[1], self.source_port)
# The port number being used is sufficient to show that the bind()
# call happened.
testTimeoutDefault = _justAccept
def _testTimeoutDefault(self):
# passing no explicit timeout uses socket's global default
self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(42)
try:
self.cli = socket.create_connection((HOST, self.port))
self.addCleanup(self.cli.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(self.cli.gettimeout(), 42)
testTimeoutNone = _justAccept
def _testTimeoutNone(self):
# None timeout means the same as sock.settimeout(None)
self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
self.cli = socket.create_connection((HOST, self.port), timeout=None)
self.addCleanup(self.cli.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(self.cli.gettimeout(), None)
testTimeoutValueNamed = _justAccept
def _testTimeoutValueNamed(self):
self.cli = socket.create_connection((HOST, self.port), timeout=30)
self.assertEqual(self.cli.gettimeout(), 30)
testTimeoutValueNonamed = _justAccept
def _testTimeoutValueNonamed(self):
self.cli = socket.create_connection((HOST, self.port), 30)
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.gettimeout(), 30)
| NetworkConnectionAttributesTest |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 8435,
"end": 9616
} | class ____(fixtures.TestBase):
def test_no_slots_dispatch(self):
class Target:
__slots__ = ()
class TargetEvents(event.Events):
_dispatch_target = Target
def event_one(self, x, y):
pass
def event_two(self, x):
pass
def event_three(self, x):
pass
t1 = Target()
with testing.expect_raises_message(
TypeError,
r"target .*Target.* doesn't have __dict__, should it "
"be defining _slots_dispatch",
):
event.listen(t1, "event_one", Mock())
def test_slots_dispatch(self):
class Target:
__slots__ = ("_slots_dispatch",)
class TargetEvents(event.Events):
_dispatch_target = Target
def event_one(self, x, y):
pass
def event_two(self, x):
pass
def event_three(self, x):
pass
t1 = Target()
m1 = Mock()
event.listen(t1, "event_one", m1)
t1.dispatch.event_one(2, 4)
eq_(m1.mock_calls, [call(2, 4)])
| SlotsEventsTest |
python | getsentry__sentry | src/sentry/api/endpoints/project_artifact_bundle_files.py | {
"start": 1728,
"end": 5440
} | class ____(ProjectEndpoint):
owner = ApiOwner.OWNERS_INGEST
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectReleasePermission,)
rate_limits = RateLimitConfig(
group="CLI", limit_overrides={"GET": SENTRY_RATELIMITER_GROUP_DEFAULTS["default"]}
)
def get(self, request: Request, project, bundle_id) -> Response:
"""
List files for a given project artifact bundle.
``````````````````````````````
Retrieve a list of files for a given artifact bundle.
:pparam string organization_id_or_slug: the id or slug of the organization the
artifact bundle belongs to.
:pparam string project_id_or_slug: the id or slug of the project the
artifact bundle belongs to.
:pparam string bundle_id: bundle_id of the artifact bundle to list files from.
"""
query = request.GET.get("query")
try:
artifact_bundle = ArtifactBundle.objects.filter(
organization_id=project.organization.id,
bundle_id=bundle_id,
projectartifactbundle__project_id=project.id,
)[0]
except IndexError:
return Response(
{
"error": f"The artifact bundle with {bundle_id} is not bound to this project or doesn't exist"
},
status=400,
)
try:
# We open the archive to fetch the number of files.
archive = ArtifactBundleArchive(artifact_bundle.file.getfile(), build_memory_map=False)
except Exception:
return Response(
{"error": f"The archive of artifact bundle {bundle_id} can't be opened"}
)
def serialize_results(r):
# Here we don't query with project_id under the assumption that the above's code checks for it. In case
# the get_release_associations method is going to be used in other places, a project_id check should
# still be performed to avoid any security problems.
associations = ArtifactBundle.get_release_associations(
project.organization.id, artifact_bundle
)
def format_date(date: datetime | None) -> str | None:
return None if date is None else date.isoformat()[:19] + "Z"
return serialize(
{
"bundleId": str(artifact_bundle.bundle_id),
"date": format_date(artifact_bundle.date_uploaded),
"dateModified": format_date(artifact_bundle.date_last_modified),
"fileCount": artifact_bundle.artifact_count,
"associations": associations,
"files": serialize(
# We need to convert the dictionary to a list in order to properly use the serializer.
r,
request.user,
ArtifactBundleFilesSerializer(archive),
),
},
request.user,
)
try:
return self.paginate(
request=request,
sources=[ArtifactBundleSource(archive.get_files_by_url_or_debug_id(query))],
paginator_cls=ChainPaginator,
max_offset=MAX_ARTIFACT_BUNDLE_FILES_OFFSET,
on_results=serialize_results,
)
finally:
# We must close the archive before returning the value, otherwise we will get an error.
archive.close()
| ProjectArtifactBundleFilesEndpoint |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 835232,
"end": 835988
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PinnedDiscussion."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PinnedDiscussionEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("PinnedDiscussion"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| PinnedDiscussionConnection |
python | bokeh__bokeh | src/bokeh/models/layouts.py | {
"start": 12723,
"end": 14539
} | class ____(HasProps):
""" Common properties for grid-like layouts. """
rows = Nullable(TracksSizing, default=None, help="""
Describes how the grid should maintain its rows' heights.
This maps to CSS grid's track sizing options. In particular the following
values are allowed:
* length, e.g. ``100px``, ``5.5em``
* percentage, e.g. ``33%``
* flex, e.g. 1fr
* enums, e.g. ``max-content``, ``min-content``, ``auto``, etc.
If a single value is provided, then it applies to all rows. A list of
values can be provided to size all rows, or a dictionary providing
sizing for individual rows.
See https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-rows
or https://w3c.github.io/csswg-drafts/css-grid/#track-sizing for details.
""")
cols = Nullable(TracksSizing, default=None, help="""
Describes how the grid should maintain its columns' widths.
This maps to CSS grid's track sizing options. In particular the following
values are allowed:
* length, e.g. ``100px``, ``5.5em``
* percentage, e.g. ``33%``
* flex, e.g. 1fr
* enums, e.g. ``max-content``, ``min-content``, ``auto``, etc.
If a single value is provided, then it applies to all columns. A list of
values can be provided to size all columns, or a dictionary providing
sizing for individual columns.
See https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns
or https://w3c.github.io/csswg-drafts/css-grid/#track-sizing for details.
""")
spacing = GridSpacing(default=0, help="""
The gap between children (in pixels).
Either a number, if spacing is the same for both dimensions, or a pair
of numbers indicating spacing in the vertical and horizontal dimensions
respectively.
""")
| GridCommon |
python | doocs__leetcode | solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.py | {
"start": 0,
"end": 398
} | class ____:
def robotWithString(self, s: str) -> str:
cnt = Counter(s)
ans = []
stk = []
mi = 'a'
for c in s:
cnt[c] -= 1
while mi < 'z' and cnt[mi] == 0:
mi = chr(ord(mi) + 1)
stk.append(c)
while stk and stk[-1] <= mi:
ans.append(stk.pop())
return ''.join(ans)
| Solution |
python | PrefectHQ__prefect | src/prefect/_internal/observability.py | {
"start": 195,
"end": 2911
} | class ____(BaseSettings):
"""
configuration for logfire observability integration.
"""
model_config = SettingsConfigDict(
env_prefix="PREFECT_LOGFIRE_",
extra="ignore",
)
enabled: bool = Field(
default=False,
description="whether to enable logfire observability",
)
write_token: str | None = Field(
default=None,
description="API token for writing to logfire. required when enabled=true.",
)
sampling_head_rate: float = Field(
default=0.1,
ge=0.0,
le=1.0,
description="fraction of traces to sample upfront (0.0-1.0). reduces total volume.",
)
sampling_level_threshold: str = Field(
default="warn",
description="minimum log level to always include (debug, info, warn, error). keeps all warnings/errors.",
)
sampling_duration_threshold: float = Field(
default=5.0,
ge=0.0,
description="minimum duration in seconds to always include. catches slow operations.",
)
sampling_background_rate: float = Field(
default=0.01,
ge=0.0,
le=1.0,
description="fraction of non-notable traces to keep anyway (0.0-1.0). maintains baseline visibility.",
)
def configure_logfire() -> Any | None:
"""
configure and return logfire instance with sampling, or None if disabled.
this function:
1. checks if logfire is enabled via PREFECT_LOGFIRE_ENABLED
2. validates PREFECT_LOGFIRE_WRITE_TOKEN is set
3. loads sampling configuration from env vars
4. configures logfire with sampling options
5. returns configured logfire module (or None if disabled)
can be called multiple times safely - logfire.configure is idempotent.
"""
# load logfire settings from env vars
settings = LogfireSettings()
if not settings.enabled:
return None
if settings.write_token is None:
raise ValueError(
"PREFECT_LOGFIRE_WRITE_TOKEN must be set when PREFECT_LOGFIRE_ENABLED is true"
)
try:
import logfire # pyright: ignore
except ImportError as exc:
raise ImportError(
"logfire is not installed. install it with: uv add logfire"
) from exc
# build sampling options
sampling_options = logfire.SamplingOptions.level_or_duration(
head=settings.sampling_head_rate,
level_threshold=settings.sampling_level_threshold,
duration_threshold=settings.sampling_duration_threshold,
background_rate=settings.sampling_background_rate,
)
logfire.configure(token=settings.write_token, sampling=sampling_options) # pyright: ignore
return logfire
| LogfireSettings |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/test_project/__init__.py | {
"start": 6937,
"end": 11646
} | class ____(RemoteSchedule):
def __init__(
self,
remote_schedule: RemoteSchedule,
container_image=None,
):
self._container_image = container_image
super().__init__(
remote_schedule._schedule_snap, # noqa: SLF001
remote_schedule.handle.repository_handle,
)
def get_remote_origin(self):
"""Hack! Inject origin that the k8s images will use. The k8s helm chart workspace uses a
gRPC server repo location origin. As a result the normal origin won't work, we need to
inject this one.
"""
return RemoteInstigatorOrigin(
repository_origin=RemoteRepositoryOrigin(
code_location_origin=GrpcServerCodeLocationOrigin(
host="user-code-deployment-1",
port=3030,
location_name="user-code-deployment-1",
),
repository_name="demo_execution_repo",
),
instigator_name=self.name,
)
@property
def selector_id(self): # pyright: ignore[reportIncompatibleVariableOverride]
"""Hack! Inject a selector that matches the one that the k8s helm chart will use."""
return create_snapshot_id(
InstigatorSelector(
"user-code-deployment-1", # pyright: ignore[reportCallIssue]
"demo_execution_repo",
self.name,
)
)
@contextmanager
def get_test_project_workspace(instance, container_image=None, filename=None):
filename = filename or "repo.py"
with in_process_test_workspace(
instance,
loadable_target_origin=LoadableTargetOrigin(
executable_path=sys.executable,
python_file=file_relative_path(__file__, f"test_jobs/{filename}"),
attribute="define_demo_execution_repo",
),
container_image=container_image,
) as workspace:
yield workspace
@contextmanager
def get_test_project_remote_job_hierarchy(instance, job_name, container_image=None, filename=None):
with get_test_project_workspace(instance, container_image, filename) as workspace:
location = workspace.get_code_location(workspace.code_location_names[0])
repo = location.get_repository("demo_execution_repo")
job = repo.get_full_job(job_name)
yield workspace, location, repo, job
@contextmanager
def get_test_project_remote_repo(instance, container_image=None, filename=None):
with get_test_project_workspace(instance, container_image, filename) as workspace:
location = workspace.get_code_location(workspace.code_location_names[0])
yield location, location.get_repository("demo_execution_repo")
@contextmanager
def get_test_project_workspace_and_remote_job(
instance, job_name, container_image=None, filename=None
):
with get_test_project_remote_job_hierarchy(instance, job_name, container_image, filename) as (
workspace,
_location,
_repo,
job,
):
yield workspace, job
@contextmanager
def get_test_project_remote_schedule(instance, schedule_name, container_image=None, filename=None):
with get_test_project_remote_repo(
instance, container_image=container_image, filename=filename
) as (_, repo):
yield repo.get_schedule(schedule_name)
def get_test_project_docker_image():
docker_repository = os.getenv("DAGSTER_DOCKER_REPOSITORY")
image_name = os.getenv("DAGSTER_DOCKER_IMAGE", "test-project")
docker_image_tag = os.getenv("DAGSTER_DOCKER_IMAGE_TAG")
if IS_BUILDKITE:
assert docker_image_tag is not None, (
"This test requires the environment variable DAGSTER_DOCKER_IMAGE_TAG to be set "
"to proceed"
)
assert docker_repository is not None, (
"This test requires the environment variable DAGSTER_DOCKER_REPOSITORY to be set "
"to proceed"
)
# This needs to be a domain name to avoid the k8s machinery automatically prefixing it with
# `docker.io/` and attempting to pull images from Docker Hub
if not docker_repository:
docker_repository = "dagster.io.priv"
if not docker_image_tag:
# Detect the python version we're running on
majmin = str(sys.version_info.major) + str(sys.version_info.minor)
docker_image_tag = "py{majmin}-{image_version}".format(
majmin=majmin, image_version="latest"
)
final_docker_image = f"{docker_repository}/{image_name}:{docker_image_tag}"
print(f"Using Docker image: {final_docker_image}") # noqa: T201
return final_docker_image
| ReOriginatedExternalScheduleForTest |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorRegistryDestinationDefinition.py | {
"start": 11196,
"end": 11519
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
__root__: Union[
ConnectorRegistrySourceDefinition, ConnectorRegistryDestinationDefinition
] = Field(
...,
description="Contains information about a release candidate version of a connector.",
)
| VersionReleaseCandidate |
python | numba__numba | numba/core/event.py | {
"start": 5206,
"end": 5998
} | class ____(abc.ABC):
"""Base class for all event listeners.
"""
@abc.abstractmethod
def on_start(self, event):
"""Called when there is a *START* event.
Parameters
----------
event : Event
"""
pass
@abc.abstractmethod
def on_end(self, event):
"""Called when there is a *END* event.
Parameters
----------
event : Event
"""
pass
def notify(self, event):
"""Notify this Listener with the given Event.
Parameters
----------
event : Event
"""
if event.is_start:
self.on_start(event)
elif event.is_end:
self.on_end(event)
else:
raise AssertionError("unreachable")
| Listener |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 55043,
"end": 56553
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def testDenseShape(self):
t_value = [[0, 42], [24, 0]]
self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(t_value)))
self.assertEqual(4, self.evaluate(array_ops.size(t_value)))
self.assertEqual(2, self.evaluate(array_ops.rank(t_value)))
t = constant_op.constant(t_value)
self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(t)))
self.assertEqual(4, self.evaluate(array_ops.size(t)))
self.assertEqual(2, self.evaluate(array_ops.rank(t)))
@test_util.run_in_graph_and_eager_modes
def testSparseShape(self):
sp_value = sparse_tensor.SparseTensorValue(
indices=((0, 1), (1, 0)), values=(42, 24), dense_shape=(2, 2))
self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(sp_value)))
self.assertEqual(4, self.evaluate(array_ops.size(sp_value)))
self.assertEqual(2, self.evaluate(array_ops.rank(sp_value)))
sp = sparse_tensor.SparseTensor.from_value(sp_value)
self.assertAllEqual((2, 2), self.evaluate(array_ops.shape(sp)))
self.assertEqual(4, self.evaluate(array_ops.size(sp)))
self.assertEqual(2, self.evaluate(array_ops.rank(sp)))
@test_util.run_in_graph_and_eager_modes
def testSizeDtype(self):
tensor = [1]
self.assertEqual(dtypes.int32, self.evaluate(array_ops.size(tensor)).dtype)
self.assertEqual(
dtypes.int64,
self.evaluate(array_ops.size(tensor, out_type=dtypes.int64)).dtype)
| ShapeSizeRankTest |
python | kamyu104__LeetCode-Solutions | Python/divide-players-into-teams-of-equal-skill.py | {
"start": 63,
"end": 492
} | class ____(object):
def dividePlayers(self, skill):
"""
:type skill: List[int]
:rtype: int
"""
target = sum(skill)//(len(skill)//2)
cnt = collections.Counter(skill)
result = 0
for k, v in cnt.iteritems():
if target-k not in cnt or cnt[target-k] != cnt[k]:
return -1
result += k*(target-k)*v
return result//2
| Solution |
python | tensorflow__tensorflow | tensorflow/compiler/tests/conv_node_name_test.py | {
"start": 1177,
"end": 4132
} | class ____(xla_test.XLATestCase):
"""Verify convolution node name match.
Verify convolution node names on TPU and CPU match with dilation > 1.
"""
def _verifyNodeNameMatch(self, layer, input_sizes, filter_sizes, strides,
dilations):
def _GetNodeNames(use_xla):
with self.session():
input_tensor = array_ops.placeholder(np.float32, shape=input_sizes)
if use_xla:
with self.device_scope():
# pylint: disable=protected-access
graph = ops.get_default_graph()
graph._set_control_flow_context(
control_flow_ops.XLAControlFlowContext())
# pylint: enable=protected-access
conv2d_op = layer(
filters=64,
kernel_size=filter_sizes,
dilation_rate=dilations,
padding="same")
_ = conv2d_op(input_tensor)
return [n.name for n in ops.get_default_graph().as_graph_def().node]
else:
with ops.device("CPU"):
conv2d_op = layer(
filters=64,
kernel_size=filter_sizes,
dilation_rate=dilations,
padding="same")
_ = conv2d_op(input_tensor)
names = [
n.name for n in ops.get_default_graph().as_graph_def().node
]
# filter out space to depth ops.
return [
name for name in names
if "space" not in name and "Space" not in name
]
xla_names = _GetNodeNames(use_xla=True)
no_xla_names = _GetNodeNames(use_xla=False)
# CPU path creates some additional nodes to handle dilations.
# TODO(b/138804006): Remove this when CPU & GPU support dilations.
filtered_no_xla_names = []
for name in no_xla_names:
if ("dilation_rate" in name or "filter_shape" in name or "stack" in name):
continue
else:
filtered_no_xla_names.append(name)
self.assertListEqual(xla_names, filtered_no_xla_names)
def testConv1DNodeNameMatch(self):
input_sizes = [8, 16, 3]
filter_sizes = [7]
strides = 1
dilations = [2]
layer = layers.Conv1D
self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides,
dilations)
def testConv2DNodeNameMatch(self):
input_sizes = [8, 16, 16, 3]
filter_sizes = [7, 7]
strides = 1
dilations = [2, 2]
layer = layers.Conv2D
self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides,
dilations)
def testConv3DNodeNameMatch(self):
input_sizes = [8, 16, 16, 16, 3]
filter_sizes = [7, 7, 7]
strides = 1
dilations = [2, 2, 2]
layer = layers.Conv3D
self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides,
dilations)
if __name__ == "__main__":
googletest.main()
| ConvolutionNodeNameTest |
python | doocs__leetcode | solution/1200-1299/1224.Maximum Equal Frequency/Solution.py | {
"start": 0,
"end": 578
} | class ____:
def maxEqualFreq(self, nums: List[int]) -> int:
cnt = Counter()
ccnt = Counter()
ans = mx = 0
for i, v in enumerate(nums, 1):
if v in cnt:
ccnt[cnt[v]] -= 1
cnt[v] += 1
mx = max(mx, cnt[v])
ccnt[cnt[v]] += 1
if mx == 1:
ans = i
elif ccnt[mx] * mx + ccnt[mx - 1] * (mx - 1) == i and ccnt[mx] == 1:
ans = i
elif ccnt[mx] * mx + 1 == i and ccnt[1] == 1:
ans = i
return ans
| Solution |
python | walkccc__LeetCode | solutions/1863. Sum of All Subset XOR Totals/1863.py | {
"start": 0,
"end": 256
} | class ____:
def subsetXORSum(self, nums: list[int]) -> int:
def dfs(i: int, xors: int) -> int:
if i == len(nums):
return xors
x = dfs(i + 1, xors)
y = dfs(i + 1, nums[i] ^ xors)
return x + y
return dfs(0, 0)
| Solution |
python | numba__numba | numba/tests/test_target_overloadselector.py | {
"start": 4624,
"end": 6226
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
# ensure all impls are loaded
cpu_target.target_context.refresh()
def create_overload_selector(self, kind):
os = OverloadSelector()
loader = RegistryLoader(builtin_registry)
for impl, sig in loader.new_registrations(kind):
os.append(impl, sig)
return os
def test_ambiguous_casts(self):
os = self.create_overload_selector(kind='casts')
all_types = set(t for sig, impl in os.versions for t in sig)
# ensure there are no ambiguous cast overloads
# note: using permutations to avoid testing cast to the same type
for sig in permutations(all_types, r=2):
try:
os.find(sig)
except NumbaNotImplementedError:
pass # ignore not implemented cast
def test_ambiguous_functions(self):
loader = RegistryLoader(builtin_registry)
selectors = defaultdict(OverloadSelector)
for impl, fn, sig in loader.new_registrations('functions'):
os = selectors[fn]
os.append(impl, sig)
for fn, os in selectors.items():
all_types = set(t for sig, impl in os.versions for t in sig)
# ensure there are no ambiguous overloads
for sig in product(all_types, all_types):
try:
os.find(sig)
except NumbaNotImplementedError:
pass # ignore not implemented cast
if __name__ == '__main__':
unittest.main()
| TestAmbiguousOverloads |
python | pypa__warehouse | tests/unit/oidc/test_services.py | {
"start": 1710,
"end": 27717
} | class ____:
def test_interface_matches(self):
assert verifyClass(
interfaces.IOIDCPublisherService, services.OIDCPublisherService
)
def test_verify_jwt_signature(self, monkeypatch):
issuer_url = "https://example.com"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher=pretend.stub(),
issuer_url=issuer_url,
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=pretend.stub(),
)
token = pretend.stub()
decoded = pretend.stub()
jwt = pretend.stub(decode=pretend.call_recorder(lambda t, **kwargs: decoded))
key = pretend.stub(key="fake-key")
monkeypatch.setattr(service, "_get_key_for_token", lambda t, i=issuer_url: key)
monkeypatch.setattr(services, "jwt", jwt)
assert service.verify_jwt_signature(token, issuer_url) == decoded
assert jwt.decode.calls == [
pretend.call(
token,
key=key,
algorithms=["RS256"],
options=dict(
verify_signature=True,
require=["iss", "iat", "exp", "aud"],
verify_iss=True,
verify_iat=True,
verify_exp=True,
verify_aud=True,
verify_nbf=True,
strict_aud=True,
),
issuer=issuer_url,
audience="fakeaudience",
leeway=30,
)
]
def test_verify_jwt_signature_get_key_for_token_fails(self, metrics, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url="https://none",
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=metrics,
)
token = pretend.stub()
jwt = pretend.stub(PyJWTError=PyJWTError)
monkeypatch.setattr(service, "_get_key_for_token", pretend.raiser(DecodeError))
monkeypatch.setattr(services, "jwt", jwt)
monkeypatch.setattr(
services.sentry_sdk,
"capture_message",
pretend.call_recorder(lambda s: None),
)
assert service.verify_jwt_signature(token, "https://none") is None
assert service.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.verify_jwt_signature.malformed_jwt",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
)
]
assert services.sentry_sdk.capture_message.calls == []
@pytest.mark.parametrize("exc", [PyJWTError, TypeError("foo")])
def test_verify_jwt_signature_fails(self, metrics, monkeypatch, exc):
issuer_url = "https://none"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=issuer_url,
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=metrics,
)
token = pretend.stub()
jwt = pretend.stub(decode=pretend.raiser(exc), PyJWTError=PyJWTError)
key = pretend.stub(key="fake-key")
monkeypatch.setattr(
service,
"_get_key_for_token",
pretend.call_recorder(lambda t, i=issuer_url: key),
)
monkeypatch.setattr(services, "jwt", jwt)
monkeypatch.setattr(
services.sentry_sdk,
"capture_message",
pretend.call_recorder(lambda s: None),
)
assert service.verify_jwt_signature(token, issuer_url) is None
assert service.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.verify_jwt_signature.invalid_signature",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
)
]
if exc != PyJWTError:
assert services.sentry_sdk.capture_message.calls == [
pretend.call(f"JWT backend raised generic error: {exc}")
]
else:
assert services.sentry_sdk.capture_message.calls == []
def test_find_publisher(self, metrics, monkeypatch):
issuer_url = "https://none"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=issuer_url,
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=metrics,
)
token = SignedClaims({"iss": issuer_url})
publisher = pretend.stub(verify_claims=pretend.call_recorder(lambda c, s: True))
find_publisher_by_issuer = pretend.call_recorder(lambda *a, **kw: publisher)
monkeypatch.setattr(
services, "find_publisher_by_issuer", find_publisher_by_issuer
)
assert service.find_publisher(token) == publisher
assert service.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.find_publisher.attempt",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
pretend.call(
"warehouse.oidc.find_publisher.ok",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
]
def test_find_publisher_issuer_lookup_fails(self, metrics, monkeypatch):
issuer_url = "https://none"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=issuer_url,
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=metrics,
)
find_publisher_by_issuer = pretend.raiser(errors.InvalidPublisherError("foo"))
monkeypatch.setattr(
services, "find_publisher_by_issuer", find_publisher_by_issuer
)
claims = SignedClaims({"iss": issuer_url})
with pytest.raises(errors.InvalidPublisherError):
service.find_publisher(claims)
assert service.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.find_publisher.attempt",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
pretend.call(
"warehouse.oidc.find_publisher.publisher_not_found",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
]
def test_find_publisher_verify_claims_fails(self, metrics, monkeypatch):
issuer_url = "https://none"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=issuer_url,
audience="fakeaudience",
cache_url=pretend.stub(),
metrics=metrics,
)
publisher = pretend.stub(
verify_claims=pretend.call_recorder(
pretend.raiser(errors.InvalidPublisherError)
)
)
find_publisher_by_issuer = pretend.call_recorder(lambda *a, **kw: publisher)
monkeypatch.setattr(
services, "find_publisher_by_issuer", find_publisher_by_issuer
)
claims = SignedClaims({"iss": issuer_url})
with pytest.raises(errors.InvalidPublisherError):
service.find_publisher(claims)
assert service.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.find_publisher.attempt",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
pretend.call(
"warehouse.oidc.find_publisher.publisher_not_found",
tags=["publisher:fakepublisher", "issuer_url:https://none"],
),
]
assert publisher.verify_claims.calls == [pretend.call(claims, service)]
def test_find_publisher_reuse_token_fails(self, monkeypatch, mockredis, metrics):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=pretend.stub(),
audience="fakeaudience",
cache_url="redis://fake.example.com",
metrics=metrics,
)
publisher = pretend.stub(
verify_claims=pretend.call_recorder(pretend.raiser(errors.ReusedTokenError))
)
find_publisher_by_issuer = pretend.call_recorder(lambda *a, **kw: publisher)
monkeypatch.setattr(
services, "find_publisher_by_issuer", find_publisher_by_issuer
)
expiration = int(
(
datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(minutes=15)
).timestamp()
)
claims = SignedClaims(
{
"iss": "foo",
"iat": 1516239022,
"nbf": 1516239022,
"exp": expiration,
"aud": "pypi",
"jti": "fake-token-identifier",
}
)
with pytest.raises(errors.ReusedTokenError):
service.find_publisher(claims, pending=False)
def test_get_keyset_not_cached(self, monkeypatch, mockredis):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url=pretend.stub(),
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=pretend.stub(),
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
keys, timeout = service._get_keyset("https://example.com")
assert not keys
assert timeout is False
def test_get_keyset_cached(self, monkeypatch, mockredis):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url=pretend.stub(),
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=pretend.stub(),
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
keyset = {"fake-key-id": {"foo": "bar"}}
service._store_keyset("https://example.com", keyset)
keys, timeout = service._get_keyset("https://example.com")
assert keys == keyset
assert timeout is True
def test_refresh_keyset_timeout(self, metrics, monkeypatch, mockredis):
issuer_url = "https://example.com"
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url=issuer_url,
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
keyset = {"fake-key-id": {"foo": "bar"}}
service._store_keyset(issuer_url, keyset)
keys = service._refresh_keyset(issuer_url)
assert keys == keyset
assert metrics.increment.calls == [
pretend.call(
"warehouse.oidc.refresh_keyset.timeout",
tags=["publisher:example", "issuer_url:https://example.com"],
)
]
def test_refresh_keyset_oidc_config_fails(self, metrics, monkeypatch, mockredis):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
requests = pretend.stub(
get=pretend.call_recorder(lambda url, timeout: pretend.stub(ok=False))
)
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda msg: pretend.stub())
)
monkeypatch.setattr(services, "requests", requests)
monkeypatch.setattr(services, "sentry_sdk", sentry_sdk)
keys = service._refresh_keyset("https://example.com")
assert keys == {}
assert metrics.increment.calls == []
assert requests.get.calls == [
pretend.call(
"https://example.com/.well-known/openid-configuration", timeout=5
)
]
assert sentry_sdk.capture_message.calls == [
pretend.call(
"OIDC publisher example failed to return configuration: "
"https://example.com/.well-known/openid-configuration"
)
]
def test_refresh_keyset_oidc_config_no_jwks_uri(
self, metrics, monkeypatch, mockredis
):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
requests = pretend.stub(
get=pretend.call_recorder(
lambda url, timeout: pretend.stub(ok=True, json=lambda: {})
)
)
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda msg: pretend.stub())
)
monkeypatch.setattr(services, "requests", requests)
monkeypatch.setattr(services, "sentry_sdk", sentry_sdk)
keys = service._refresh_keyset("https://example.com")
assert keys == {}
assert metrics.increment.calls == []
assert requests.get.calls == [
pretend.call(
"https://example.com/.well-known/openid-configuration", timeout=5
)
]
assert sentry_sdk.capture_message.calls == [
pretend.call(
"OIDC publisher example is returning malformed configuration "
"(no jwks_uri)"
)
]
def test_refresh_keyset_oidc_config_no_jwks_json(
self, metrics, monkeypatch, mockredis
):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
openid_resp = pretend.stub(
ok=True,
json=lambda: {
"jwks_uri": "https://example.com/.well-known/jwks.json",
},
)
jwks_resp = pretend.stub(ok=False)
def get(url, timeout=5):
if url == "https://example.com/.well-known/jwks.json":
return jwks_resp
else:
return openid_resp
requests = pretend.stub(get=pretend.call_recorder(get))
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda msg: pretend.stub())
)
monkeypatch.setattr(services, "requests", requests)
monkeypatch.setattr(services, "sentry_sdk", sentry_sdk)
keys = service._refresh_keyset("https://example.com")
assert keys == {}
assert metrics.increment.calls == []
assert requests.get.calls == [
pretend.call(
"https://example.com/.well-known/openid-configuration", timeout=5
),
pretend.call("https://example.com/.well-known/jwks.json", timeout=5),
]
assert sentry_sdk.capture_message.calls == [
pretend.call(
"OIDC publisher example failed to return JWKS JSON: "
"https://example.com/.well-known/jwks.json"
)
]
def test_refresh_keyset_oidc_config_no_jwks_keys(
self, metrics, monkeypatch, mockredis
):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
openid_resp = pretend.stub(
ok=True,
json=lambda: {
"jwks_uri": "https://example.com/.well-known/jwks.json",
},
)
jwks_resp = pretend.stub(ok=True, json=lambda: {})
def get(url, timeout=5):
if url == "https://example.com/.well-known/jwks.json":
return jwks_resp
else:
return openid_resp
requests = pretend.stub(get=pretend.call_recorder(get))
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda msg: pretend.stub())
)
monkeypatch.setattr(services, "requests", requests)
monkeypatch.setattr(services, "sentry_sdk", sentry_sdk)
keys = service._refresh_keyset("https://example.com")
assert keys == {}
assert metrics.increment.calls == []
assert requests.get.calls == [
pretend.call(
"https://example.com/.well-known/openid-configuration", timeout=5
),
pretend.call("https://example.com/.well-known/jwks.json", timeout=5),
]
assert sentry_sdk.capture_message.calls == [
pretend.call("OIDC publisher example returned JWKS JSON but no keys")
]
def test_refresh_keyset_successful(self, metrics, monkeypatch, mockredis):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
openid_resp = pretend.stub(
ok=True,
json=lambda: {
"jwks_uri": "https://example.com/.well-known/jwks.json",
},
)
jwks_resp = pretend.stub(
ok=True, json=lambda: {"keys": [{"kid": "fake-key-id", "foo": "bar"}]}
)
def get(url, timeout=5):
if url == "https://example.com/.well-known/jwks.json":
return jwks_resp
else:
return openid_resp
requests = pretend.stub(get=pretend.call_recorder(get))
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda msg: pretend.stub())
)
monkeypatch.setattr(services, "requests", requests)
monkeypatch.setattr(services, "sentry_sdk", sentry_sdk)
keys = service._refresh_keyset("https://example.com")
assert keys == {"fake-key-id": {"kid": "fake-key-id", "foo": "bar"}}
assert metrics.increment.calls == []
assert requests.get.calls == [
pretend.call(
"https://example.com/.well-known/openid-configuration", timeout=5
),
pretend.call("https://example.com/.well-known/jwks.json", timeout=5),
]
assert sentry_sdk.capture_message.calls == []
# Ensure that we also cached the updated keyset as part of refreshing.
keys, timeout = service._get_keyset("https://example.com")
assert keys == {"fake-key-id": {"kid": "fake-key-id", "foo": "bar"}}
assert timeout is True
def test_get_key_cached(self, metrics, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
keyset = {
"fake-key-id": {
"kid": "fake-key-id",
"n": "ZHVtbXkK",
"kty": "RSA",
"alg": "RS256",
"e": "AQAB",
"use": "sig",
"x5c": ["dummy"],
"x5t": "dummy",
}
}
monkeypatch.setattr(
service, "_get_keyset", lambda issuer_url=None: (keyset, True)
)
key = service._get_key("fake-key-id", "https://example.com")
assert isinstance(key, PyJWK)
assert key.key_id == "fake-key-id"
assert metrics.increment.calls == []
def test_get_key_uncached(self, metrics, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
keyset = {
"fake-key-id": {
"kid": "fake-key-id",
"n": "ZHVtbXkK",
"kty": "RSA",
"alg": "RS256",
"e": "AQAB",
"use": "sig",
"x5c": ["dummy"],
"x5t": "dummy",
}
}
monkeypatch.setattr(service, "_get_keyset", lambda issuer_url=None: ({}, False))
monkeypatch.setattr(service, "_refresh_keyset", lambda issuer_url=None: keyset)
key = service._get_key("fake-key-id", "https://example.com")
assert isinstance(key, PyJWK)
assert key.key_id == "fake-key-id"
assert metrics.increment.calls == []
def test_get_key_refresh_fails(self, metrics, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(service, "_get_keyset", lambda issuer_url=None: ({}, False))
monkeypatch.setattr(service, "_refresh_keyset", lambda issuer_url=None: {})
with pytest.raises(
jwt.PyJWTError,
match=r"Key ID 'fake-key-id' not found for issuer 'https://example.com'",
):
service._get_key("fake-key-id", "https://example.com")
assert metrics.increment.calls == [
pretend.call(
"warehouse.oidc.get_key.error",
tags=[
"publisher:example",
"key_id:fake-key-id",
"issuer_url:https://example.com",
],
)
]
def test_get_key_for_token(self, monkeypatch):
token = pretend.stub()
key = pretend.stub()
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=pretend.stub(),
)
monkeypatch.setattr(
service, "_get_key", pretend.call_recorder(lambda kid, i: key)
)
monkeypatch.setattr(
services.jwt,
"get_unverified_header",
pretend.call_recorder(lambda token: {"kid": "fake-key-id"}),
)
assert service._get_key_for_token(token, "https://example.com") == key
assert service._get_key.calls == [
pretend.call("fake-key-id", "https://example.com")
]
assert services.jwt.get_unverified_header.calls == [pretend.call(token)]
def test_reify_publisher(self, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="example",
issuer_url="https://example.com",
audience="fakeaudience",
cache_url="rediss://fake.example.com",
metrics=pretend.stub(),
)
publisher = pretend.stub()
pending_publisher = pretend.stub(
reify=pretend.call_recorder(lambda *a: publisher)
)
project = pretend.stub(
oidc_publishers=[],
)
assert service.reify_pending_publisher(pending_publisher, project) == publisher
assert pending_publisher.reify.calls == [pretend.call(service.db)]
assert project.oidc_publishers == [publisher]
def test_jwt_identifier_exists(self, metrics, mockredis, monkeypatch):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=pretend.stub(),
audience="fakeaudience",
cache_url="redis://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
assert service.jwt_identifier_exists("fake-jti-token") is False
def test_jwt_identifier_exists_find_duplicate(
self, metrics, mockredis, monkeypatch
):
service = services.OIDCPublisherService(
session=pretend.stub(),
publisher="fakepublisher",
issuer_url=pretend.stub(),
audience="fakeaudience",
cache_url="redis://fake.example.com",
metrics=metrics,
)
monkeypatch.setattr(services.redis, "StrictRedis", mockredis)
expiration = int(
(
datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(minutes=15)
).timestamp()
)
jwt_identifier = "6e67b1cb-2b8d-4be5-91cb-757edb2ec970"
service.store_jwt_identifier(jwt_identifier, expiration=expiration)
assert service.jwt_identifier_exists(jwt_identifier) is True
| TestOIDCPublisherService |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_freq_attr.py | {
"start": 140,
"end": 2176
} | class ____:
@pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []])
@pytest.mark.parametrize("freq", ["2D", Day(2), "48h", Hour(48)])
def test_freq_setter(self, values, freq):
# GH#20678
idx = TimedeltaIndex(values)
# can set to an offset, converting from string if necessary
idx._data.freq = freq
assert idx.freq == freq
assert isinstance(idx.freq, DateOffset)
# can reset to None
idx._data.freq = None
assert idx.freq is None
def test_with_freq_empty_requires_tick(self):
idx = TimedeltaIndex([])
off = MonthEnd(1)
msg = "TimedeltaArray/Index freq must be a Tick"
with pytest.raises(TypeError, match=msg):
idx._with_freq(off)
with pytest.raises(TypeError, match=msg):
idx._data._with_freq(off)
def test_freq_setter_errors(self):
# GH#20678
idx = TimedeltaIndex(["0 days", "2 days", "4 days"])
# setting with an incompatible freq
msg = (
"Inferred frequency 2D from passed values does not conform to "
"passed frequency 5D"
)
with pytest.raises(ValueError, match=msg):
idx._data.freq = "5D"
# setting with a non-fixed frequency
msg = r"<2 \* BusinessDays> is a non-fixed frequency"
with pytest.raises(ValueError, match=msg):
idx._data.freq = "2B"
# setting with non-freq string
with pytest.raises(ValueError, match="Invalid frequency"):
idx._data.freq = "foo"
def test_freq_view_safe(self):
# Setting the freq for one TimedeltaIndex shouldn't alter the freq
# for another that views the same data
tdi = TimedeltaIndex(["0 days", "2 days", "4 days"], freq="2D")
tda = tdi._data
tdi2 = TimedeltaIndex(tda)._with_freq(None)
assert tdi2.freq is None
# Original was not altered
assert tdi.freq == "2D"
assert tda.freq == "2D"
| TestFreq |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 304,
"end": 418
} | class ____(IntEnum):
SPECIFIC = 0
USER = 1
TEAM = 2
SENTRY_APP = 3
ISSUE_OWNERS = 4
| ActionTarget |
python | pytorch__pytorch | test/inductor/test_perf.py | {
"start": 2678,
"end": 9796
} | class ____(TestCase):
"""
Primarily used for sanity testing that the num_bytes_accessed metrics is correct.
"""
def test_pointwise(self):
def f(x):
return x.cos()
inp = (T(10),)
self.assertExpectedInline(count_numel(f, *inp), """20""")
def f(x, y):
return x + y
inp = (T(10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """30""")
def f(x, y):
return x + y
inp = (T(10, 10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """210""")
def f(x):
return x + x
inp = (T(10),)
self.assertExpectedInline(count_numel(f, *inp), """20""")
def f(x):
return x + x.t()
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """200""")
def f(a, b, c):
return a.cos(), b.sin() + c.sin()
inp = (T(10), T(10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """50""")
def test_reduction(self):
def f(x):
return x.sum(dim=1)
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """110""")
def f(x):
return x.sum(dim=0)
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """110""")
def test_extern(self):
def f(x):
return torch.mm(x, x)
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """200""")
def f(a, b):
return torch.mm(a, b)
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """300""")
def f(x):
x = x.cos()
x = torch.mm(x, x)
x = x.cos()
return x
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """600""")
def f(x):
a = x.cos()
b = x.sin()
x = torch.mm(a, b)
return x
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *inp), """600""")
def test_cat(self):
def f(a, b):
return torch.cat([a.sin(), b.sin()])
inp = (T(10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """40""")
def f(a, b):
return torch.cat([a, b])
inp = (T(10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """40""")
def f(a, b):
return torch.cat([a.cos(), b])
inp = (T(10), T(10))
self.assertExpectedInline(count_numel(f, *inp), """40""")
def f(a):
return torch.cat([a.cos(), a.sin()])
inp = (T(10),)
self.assertExpectedInline(count_numel(f, *inp), """30""")
def f(a, b):
return torch.cat([torch.mm(a, a), b.sin()])
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """400""")
def f(a, b, c):
return torch.cat((a + 1, b + 2, c + 3)) + 10
inp = (T(10, 10), T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """600""")
def f(a, b, c, d, e):
return torch.cat((a + 1, b + 2, c + 3, d + 4, e + 5)) + 10
inp = [T(10, 10) for _ in range(5)]
self.assertExpectedInline(count_numel(f, *inp), """1000""")
def f(a, b):
return torch.cat([a.sum(dim=0), b.sum(dim=0)]) + 10
inp = [T(10, 10, 10), T(10, 10, 10)]
self.assertExpectedInline(count_numel(f, *inp), """2600""")
def test_cat_pointwise(self):
def f(a, b):
return torch.cat([torch.softmax(a, dim=-1), torch.softmax(b, dim=-1)])
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """400""")
def f(a, b):
return torch.cat([torch.softmax(a, dim=-1), torch.softmax(b, dim=-1)]).cos()
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """680""")
# Should turn into pointwise even if only some of inputs are pointwise.
def f(a, b):
out = torch.cat([a.cos(), torch.mm(b, b)])
return out.cos()
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """600""")
# Should not turn into pointwise if all inputs are not pointwise
def f(a, b):
out = torch.cat([torch.mm(a, a), torch.mm(b, b)])
return out.cos()
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """800""")
def f(a, b):
out = torch.cat([a, b])
return out.cos()
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """400""")
def f(a, b):
b = b.cos()
return torch.cat([a, b])
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """400""")
def f(a, b):
a = a @ a
return torch.constant_pad_nd(torch.cat([a, b]), [2, 2], 0.5)
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """680""")
@patch.object(config, "split_cat_fx_passes", False)
@patch.object(
config,
"pre_grad_fusion_options",
{
"batch_linear": {},
"batch_linear_lhs": {},
"batch_layernorm": {},
"batch_tanh": {},
"batch_relu": {},
"batch_sigmoid": {},
},
)
@patch.object(config, "post_grad_fusion_options", {})
def test_cat_pointwise_many_complex_inputs(self):
def f(*inputs):
input = [torch.nn.functional.gelu(val) for val in inputs]
return torch.cat(input) + 10
inp = (T(10, 10) for _ in range(16))
self.assertExpectedInline(count_numel(f, *inp), """6400""")
@patch.object(config, "split_cat_fx_passes", False)
@patch.object(
config,
"pre_grad_fusion_options",
{
"batch_linear": {},
"batch_linear_lhs": {},
"batch_layernorm": {},
"batch_tanh": {},
"batch_relu": {},
"batch_sigmoid": {},
},
)
@patch.object(config, "post_grad_fusion_options", {})
def test_cat_pointwise_many_simple_inputs(self):
def f(*inputs):
input = [torch.nn.functional.relu(val) for val in inputs]
return torch.cat(input) + 10
inp = (T(10, 10) for _ in range(16))
self.assertExpectedInline(count_numel(f, *inp), """9600""")
@patch.object(config, "max_pointwise_cat_inputs", 0)
def test_cat_pointwise_config_option(self):
def f(a, b):
return torch.cat([a + 1, b + 2]) + 3
inp = (T(10, 10), T(10, 10))
self.assertExpectedInline(count_numel(f, *inp), """400""")
def test_index(self):
def f(a, b):
return a[b]
inp = (T(10), TI(10, mx=10))
self.assertExpectedInline(count_numel(f, *inp), """30""")
| NumBytesMetricTests |
python | spack__spack | lib/spack/spack/environment/environment.py | {
"start": 23368,
"end": 34314
} | class ____:
def __init__(
self,
base_path,
root,
projections={},
select=[],
exclude=[],
link=default_view_link,
link_type="symlink",
):
self.base = base_path
self.raw_root = root
self.root = spack.util.path.canonicalize_path(root, default_wd=base_path)
self.projections = projections
self.select = select
self.exclude = exclude
self.link_type = fsv.canonicalize_link_type(link_type)
self.link = link
def select_fn(self, spec):
return any(spec.satisfies(s) for s in self.select)
def exclude_fn(self, spec):
return not any(spec.satisfies(e) for e in self.exclude)
def update_root(self, new_path):
self.raw_root = new_path
self.root = spack.util.path.canonicalize_path(new_path, default_wd=self.base)
def __eq__(self, other):
return all(
[
self.root == other.root,
self.projections == other.projections,
self.select == other.select,
self.exclude == other.exclude,
self.link == other.link,
self.link_type == other.link_type,
]
)
def to_dict(self):
ret = syaml.syaml_dict([("root", self.raw_root)])
if self.projections:
ret["projections"] = self.projections
if self.select:
ret["select"] = self.select
if self.exclude:
ret["exclude"] = self.exclude
if self.link_type:
ret["link_type"] = self.link_type
if self.link != default_view_link:
ret["link"] = self.link
return ret
@staticmethod
def from_dict(base_path, d):
return ViewDescriptor(
base_path,
d["root"],
d.get("projections", {}),
d.get("select", []),
d.get("exclude", []),
d.get("link", default_view_link),
d.get("link_type", "symlink"),
)
@property
def _current_root(self):
if not islink(self.root):
return None
root = readlink(self.root)
if os.path.isabs(root):
return root
root_dir = os.path.dirname(self.root)
return os.path.join(root_dir, root)
def _next_root(self, specs):
content_hash = self.content_hash(specs)
root_dir = os.path.dirname(self.root)
root_name = os.path.basename(self.root)
return os.path.join(root_dir, "._%s" % root_name, content_hash)
def content_hash(self, specs):
d = syaml.syaml_dict(
[
("descriptor", self.to_dict()),
("specs", [(spec.dag_hash(), spec.prefix) for spec in sorted(specs)]),
]
)
contents = sjson.dump(d)
return spack.util.hash.b32_hash(contents)
def get_projection_for_spec(self, spec):
"""Get projection for spec. This function does not require the view
to exist on the filesystem."""
return self._view(self.root).get_projection_for_spec(spec)
def view(self, new: Optional[str] = None) -> fsv.SimpleFilesystemView:
"""
Returns a view object for the *underlying* view directory. This means that the
self.root symlink is followed, and that the view has to exist on the filesystem
(unless ``new``). This function is useful when writing to the view.
Raise if new is None and there is no current view
Arguments:
new: If a string, create a FilesystemView rooted at that path. Default None. This
should only be used to regenerate the view, and cannot be used to access specs.
"""
path = new if new else self._current_root
if not path:
# This can only be hit if we write a future bug
raise SpackEnvironmentViewError(
f"Attempting to get nonexistent view from environment. View root is at {self.root}"
)
return self._view(path)
def _view(self, root: str) -> fsv.SimpleFilesystemView:
"""Returns a view object for a given root dir."""
return fsv.SimpleFilesystemView(
root,
spack.store.STORE.layout,
ignore_conflicts=True,
projections=self.projections,
link_type=self.link_type,
)
def __contains__(self, spec):
"""Is the spec described by the view descriptor
Note: This does not claim the spec is already linked in the view.
It merely checks that the spec is selected if a select operation is
specified and is not excluded if an exclude operator is specified.
"""
if self.select:
if not self.select_fn(spec):
return False
if self.exclude:
if not self.exclude_fn(spec):
return False
return True
def specs_for_view(self, concrete_roots: List[Spec]) -> List[Spec]:
"""Flatten the DAGs of the concrete roots, keep only unique, selected, and installed specs
in topological order from root to leaf."""
if self.link == "all":
deptype = dt.LINK | dt.RUN
elif self.link == "run":
deptype = dt.RUN
else:
deptype = dt.NONE
specs = traverse.traverse_nodes(
concrete_roots, order="topo", deptype=deptype, key=traverse.by_dag_hash
)
# Filter selected, installed specs
with spack.store.STORE.db.read_transaction():
result = [s for s in specs if s in self and s.installed]
return self._exclude_duplicate_runtimes(result)
def regenerate(self, concrete_roots: List[Spec]) -> None:
specs = self.specs_for_view(concrete_roots)
# To ensure there are no conflicts with packages being installed
# that cannot be resolved or have repos that have been removed
# we always regenerate the view from scratch.
# We will do this by hashing the view contents and putting the view
# in a directory by hash, and then having a symlink to the real
# view in the root. The real root for a view at /dirname/basename
# will be /dirname/._basename_<hash>.
# This allows for atomic swaps when we update the view
# cache the roots because the way we determine which is which does
# not work while we are updating
new_root = self._next_root(specs)
old_root = self._current_root
if new_root == old_root:
tty.debug(f"View at {self.root} does not need regeneration.")
return
_error_on_nonempty_view_dir(new_root)
# construct view at new_root
if specs:
tty.msg(f"Updating view at {self.root}")
view = self.view(new=new_root)
root_dirname = os.path.dirname(self.root)
tmp_symlink_name = os.path.join(root_dirname, "._view_link")
# Remove self.root if is it an empty dir, since we need a symlink there. Note that rmdir
# fails if self.root is a symlink.
try:
os.rmdir(self.root)
except (FileNotFoundError, NotADirectoryError):
pass
except OSError as e:
if e.errno == errno.ENOTEMPTY:
msg = "it is a non-empty directory"
elif e.errno == errno.EACCES:
msg = "of insufficient permissions"
else:
raise
raise SpackEnvironmentViewError(
f"The environment view in {self.root} cannot not be created because {msg}."
) from e
# Create a new view
try:
fs.mkdirp(new_root)
view.add_specs(*specs)
# create symlink from tmp_symlink_name to new_root
if os.path.exists(tmp_symlink_name):
os.unlink(tmp_symlink_name)
symlink(new_root, tmp_symlink_name)
# mv symlink atomically over root symlink to old_root
fs.rename(tmp_symlink_name, self.root)
except Exception as e:
# Clean up new view and temporary symlink on any failure.
try:
shutil.rmtree(new_root, ignore_errors=True)
os.unlink(tmp_symlink_name)
except OSError:
pass
# Give an informative error message for the typical error case: two specs, same package
# project to same prefix.
if isinstance(e, ConflictingSpecsError):
spec_a = e.args[0].format(color=clr.get_color_when())
spec_b = e.args[1].format(color=clr.get_color_when())
raise SpackEnvironmentViewError(
f"The environment view in {self.root} could not be created, "
"because the following two specs project to the same prefix:\n"
f" {spec_a}, and\n"
f" {spec_b}.\n"
" To resolve this issue:\n"
" a. use `concretization:unify:true` to ensure there is only one "
"package per spec in the environment, or\n"
" b. disable views with `view:false`, or\n"
" c. create custom view projections."
) from e
raise
# Remove the old root when it's in the same folder as the new root. This guards
# against removal of an arbitrary path when the original symlink in self.root
# was not created by the environment, but by the user.
if (
old_root
and os.path.exists(old_root)
and os.path.samefile(os.path.dirname(new_root), os.path.dirname(old_root))
):
try:
shutil.rmtree(old_root)
except OSError as e:
msg = "Failed to remove old view at %s\n" % old_root
msg += str(e)
tty.warn(msg)
def _exclude_duplicate_runtimes(self, nodes):
all_runtimes = spack.repo.PATH.packages_with_tags("runtime")
runtimes_by_name = {}
for s in nodes:
if s.name not in all_runtimes:
continue
current_runtime = runtimes_by_name.get(s.name, s)
runtimes_by_name[s.name] = max(current_runtime, s, key=lambda x: x.version)
return [x for x in nodes if x.name not in all_runtimes or runtimes_by_name[x.name] == x]
def _create_environment(path):
return Environment(path)
def env_subdir_path(manifest_dir: Union[str, pathlib.Path]) -> str:
"""Path to where the environment stores repos, logs, views, configs.
Args:
manifest_dir: directory containing the environment manifest file
Returns: directory the environment uses to manage its files
"""
return os.path.join(str(manifest_dir), env_subdir_name)
| ViewDescriptor |
python | getsentry__sentry | tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py | {
"start": 211,
"end": 9003
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(is_staff=True, is_superuser=True)
self.canary_environment = Environment.objects.create(
organization_id=self.organization.id, name="canary"
)
self.production_environment = Environment.objects.create(
organization_id=self.organization.id, name="production"
)
self.login_as(user=self.user)
self.url = reverse(
"sentry-api-0-project-release-thresholds",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
def test_post_missing_params(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "total_error_count",
"trigger_type": "over",
# value is missing
"window_in_seconds": 1800,
"environment": "canary",
},
)
assert response.status_code == 400
assert response.data == {"value": ["This field is required."]}
def test_post_invalid_threshold_type(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "indiana_jones_and_the_temple_of_doom",
"trigger_type": "over",
"value": 100,
"window_in_seconds": 1800,
"environment": "canary",
},
)
assert response.status_code == 400
assert response.data["threshold_type"][0].code == "invalid_choice"
def test_post_invalid_trigger_type(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "total_error_count",
"trigger_type": "short_round",
"value": 100,
"window_in_seconds": 1800,
"environment": "production",
},
)
assert response.status_code == 400
assert response.data["trigger_type"][0].code == "invalid_choice"
def test_post_invalid_project(self) -> None:
url_with_invalid_project = reverse(
"sentry-api-0-project-release-thresholds",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": "Why did it have to be snakes?",
},
)
response = self.client.post(
url_with_invalid_project,
data={
"threshold_type": "total_error_count",
"trigger_type": "over",
"value": 100,
"window_in_seconds": 1800,
"environment": "production",
},
)
assert response.status_code == 404
def test_post_invalid_environment(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "total_error_count",
"trigger_type": "over",
"value": 100,
"window_in_seconds": 1800,
"environment": "Sentry belongs in a museum.",
},
)
assert response.status_code == 400
assert response.data["environment"][0].code == "invalid"
def test_post_valid_no_environment(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "total_error_count",
"trigger_type": "over",
"value": 100,
"window_in_seconds": 1800,
},
)
assert response.status_code == 201
data = response.data
assert data["threshold_type"] == "total_error_count"
assert data["trigger_type"] == "over"
assert data["value"] == 100
assert data["window_in_seconds"] == 1800
assert data["project"]["id"] == str(self.project.id)
assert data["project"]["slug"] == self.project.slug
assert data["project"]["name"] == self.project.name
assert data["environment"] is None
assert data["date_added"] is not None
def test_post_valid(self) -> None:
response = self.client.post(
self.url,
data={
"threshold_type": "total_error_count",
"trigger_type": "over",
"value": 100,
"window_in_seconds": 1800,
"environment": "canary",
},
)
assert response.status_code == 201
data = response.data
assert data["threshold_type"] == "total_error_count"
assert data["trigger_type"] == "over"
assert data["value"] == 100
assert data["window_in_seconds"] == 1800
assert data["project"]["id"] == str(self.project.id)
assert data["project"]["slug"] == self.project.slug
assert data["project"]["name"] == self.project.name
assert data["environment"]["id"] == str(self.canary_environment.id)
assert data["environment"]["name"] == self.canary_environment.name
assert data["date_added"] is not None
def test_get_invalid_project(self) -> None:
url_with_invalid_project = reverse(
"sentry-api-0-project-release-thresholds",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": "Why did it have to be snakes?",
},
)
response = self.client.get(url_with_invalid_project, data={"environment": "canary"})
assert response.status_code == 404
def test_get_invalid_environment(self) -> None:
response = self.client.get(self.url, data={"environment": "The Hovitos are near"})
assert response.status_code == 200
assert len(response.data) == 0
def test_get_valid_no_environment(self) -> None:
response = self.client.get(self.url)
assert response.status_code == 200
assert len(response.data) == 0
ReleaseThreshold.objects.create(
threshold_type=0,
trigger_type=0,
value=100,
window_in_seconds=1800,
project=self.project,
environment=self.canary_environment,
)
response = self.client.get(self.url)
assert response.status_code == 200
assert len(response.data) == 1
created_threshold = response.data[0]
assert created_threshold["threshold_type"] == "total_error_count"
assert created_threshold["trigger_type"] == "over"
assert created_threshold["value"] == 100
assert created_threshold["window_in_seconds"] == 1800
assert created_threshold["project"]["id"] == str(self.project.id)
assert created_threshold["project"]["slug"] == self.project.slug
assert created_threshold["project"]["name"] == self.project.name
assert created_threshold["environment"]["id"] == str(self.canary_environment.id)
assert created_threshold["environment"]["name"] == self.canary_environment.name
def test_get_valid_with_environment(self) -> None:
response = self.client.get(self.url, data={"environment": "canary"})
assert response.status_code == 200
assert len(response.data) == 0
ReleaseThreshold.objects.create(
threshold_type=0,
trigger_type=0,
value=100,
window_in_seconds=1800,
project=self.project,
environment=self.canary_environment,
)
ReleaseThreshold.objects.create(
threshold_type=0,
trigger_type=1,
value=100,
window_in_seconds=1800,
project=self.project,
environment=self.production_environment,
)
response = self.client.get(self.url, data={"environment": "canary"})
assert response.status_code == 200
assert len(response.data) == 1
created_threshold = response.data[0]
assert created_threshold["threshold_type"] == "total_error_count"
assert created_threshold["trigger_type"] == "over"
assert created_threshold["value"] == 100
assert created_threshold["window_in_seconds"] == 1800
assert created_threshold["project"]["id"] == str(self.project.id)
assert created_threshold["project"]["slug"] == self.project.slug
assert created_threshold["project"]["name"] == self.project.name
assert created_threshold["environment"]["id"] == str(self.canary_environment.id)
assert created_threshold["environment"]["name"] == self.canary_environment.name
| ReleaseThresholdTest |
python | getsentry__sentry | src/sentry/preprod/migrations/0018_add_preprod_artifact_app_icon_id_field.py | {
"start": 155,
"end": 1459
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("preprod", "0017_break_commit_fks"),
]
operations = [
migrations.AddField(
model_name="preprodartifact",
name="app_icon_id",
field=models.CharField(max_length=255, null=True),
),
]
| Migration |
python | tensorflow__tensorflow | tensorflow/python/framework/traceable_stack_test.py | {
"start": 1049,
"end": 3138
} | class ____(test_util.TensorFlowTestCase):
def testSetFilenameAndLineFromCallerUsesCallersStack(self):
t_obj = traceable_stack.TraceableObject(17)
# Do not separate placeholder from the set_filename_and_line_from_caller()
# call one line below it as it is used to calculate the latter's line
# number.
placeholder = lambda x: x
result = t_obj.set_filename_and_line_from_caller()
expected_lineno = inspect.getsourcelines(placeholder)[1] + 1
self.assertEqual(expected_lineno, t_obj.lineno)
self.assertEqual(_THIS_FILENAME, t_obj.filename)
self.assertEqual(t_obj.SUCCESS, result)
def testSetFilenameAndLineFromCallerRespectsOffset(self):
def call_set_filename_and_line_from_caller(t_obj):
# We expect to retrieve the line number from _our_ caller.
return t_obj.set_filename_and_line_from_caller(offset=1)
t_obj = traceable_stack.TraceableObject(None)
# Do not separate placeholder from the
# call_set_filename_and_line_from_caller() call one line below it as it is
# used to calculate the latter's line number.
placeholder = lambda x: x
result = call_set_filename_and_line_from_caller(t_obj)
expected_lineno = inspect.getsourcelines(placeholder)[1] + 1
self.assertEqual(expected_lineno, t_obj.lineno)
self.assertEqual(t_obj.SUCCESS, result)
def testSetFilenameAndLineFromCallerHandlesRidiculousOffset(self):
t_obj = traceable_stack.TraceableObject('The quick brown fox.')
# This line shouldn't die.
result = t_obj.set_filename_and_line_from_caller(offset=300)
# We expect a heuristic to be used because we are not currently 300 frames
# down on the stack. The filename and lineno of the outermost frame are not
# predictable -- in some environments the filename is this test file, but in
# other environments it is not (e.g. due to a test runner calling this
# file). Therefore we only test that the called function knows it applied a
# heuristic for the ridiculous stack offset.
self.assertEqual(t_obj.HEURISTIC_USED, result)
| TraceableObjectTest |
python | python__mypy | mypy/build.py | {
"start": 72512,
"end": 120968
} | class ____:
"""The state for a module.
The source is only used for the -c command line option; in that
case path is None. Otherwise source is None and path isn't.
"""
manager: BuildManager
order_counter: ClassVar[int] = 0
order: int # Order in which modules were encountered
id: str # Fully qualified module name
path: str | None = None # Path to module source
abspath: str | None = None # Absolute path to module source
xpath: str # Path or '<string>'
source: str | None = None # Module source code
source_hash: str | None = None # Hash calculated based on the source code
meta_source_hash: str | None = None # Hash of the source given in the meta, if any
meta: CacheMeta | None = None
data: str | None = None
tree: MypyFile | None = None
# We keep both a list and set of dependencies. A set because it makes it efficient to
# prevent duplicates and the list because I am afraid of changing the order of
# iteration over dependencies.
# They should be managed with add_dependency and suppress_dependency.
dependencies: list[str] # Modules directly imported by the module
dependencies_set: set[str] # The same but as a set for deduplication purposes
suppressed: list[str] # Suppressed/missing dependencies
suppressed_set: set[str] # Suppressed/missing dependencies
priorities: dict[str, int]
# Map each dependency to the line number where it is first imported
dep_line_map: dict[str, int]
# Map from dependency id to its last observed interface hash
dep_hashes: dict[str, bytes] = {}
# List of errors reported for this file last time.
error_lines: list[str] = []
# Parent package, its parent, etc.
ancestors: list[str] | None = None
# List of (path, line number) tuples giving context for import
import_context: list[tuple[str, int]]
# If caller_state is set, the line number in the caller where the import occurred
caller_line = 0
# Contains a hash of the public interface in incremental mode
interface_hash: bytes = b""
# Options, specialized for this file
options: Options
# Whether to ignore all errors
ignore_all = False
# Errors reported before semantic analysis, to allow fine-grained
# mode to keep reporting them.
early_errors: list[ErrorInfo]
# Type checker used for checking this file. Use type_checker() for
# access and to construct this on demand.
_type_checker: TypeChecker | None = None
fine_grained_deps_loaded = False
# Cumulative time spent on this file, in microseconds (for profiling stats)
time_spent_us: int = 0
# Per-line type-checking time (cumulative time spent type-checking expressions
# on a given source code line).
per_line_checking_time_ns: dict[int, int]
def __init__(
self,
id: str | None,
path: str | None,
source: str | None,
manager: BuildManager,
caller_state: State | None = None,
caller_line: int = 0,
ancestor_for: State | None = None,
root_source: bool = False,
# If `temporary` is True, this State is being created to just
# quickly parse/load the tree, without an intention to further
# process it. With this flag, any changes to external state as well
# as error reporting should be avoided.
temporary: bool = False,
) -> None:
if not temporary:
assert id or path or source is not None, "Neither id, path nor source given"
self.manager = manager
State.order_counter += 1
self.order = State.order_counter
self.caller_line = caller_line
if caller_state:
self.import_context = caller_state.import_context.copy()
self.import_context.append((caller_state.xpath, caller_line))
else:
self.import_context = []
self.id = id or "__main__"
self.options = manager.options.clone_for_module(self.id)
self.early_errors = []
self._type_checker = None
if not path and source is None:
assert id is not None
try:
path, follow_imports = find_module_and_diagnose(
manager,
id,
self.options,
caller_state,
caller_line,
ancestor_for,
root_source,
skip_diagnose=temporary,
)
except ModuleNotFound:
if not temporary:
manager.missing_modules.add(id)
raise
if follow_imports == "silent":
self.ignore_all = True
elif path and is_silent_import_module(manager, path) and not root_source:
self.ignore_all = True
self.path = path
if path:
self.abspath = os.path.abspath(path)
self.xpath = path or "<string>"
if path and source is None and self.manager.cache_enabled:
self.meta = find_cache_meta(self.id, path, manager)
# TODO: Get mtime if not cached.
if self.meta is not None:
self.interface_hash = self.meta.interface_hash
self.meta_source_hash = self.meta.hash
if path and source is None and self.manager.fscache.isdir(path):
source = ""
self.source = source
self.add_ancestors()
self.per_line_checking_time_ns = collections.defaultdict(int)
t0 = time.time()
self.meta = validate_meta(self.meta, self.id, self.path, self.ignore_all, manager)
self.manager.add_stats(validate_meta_time=time.time() - t0)
if self.meta:
# Make copies, since we may modify these and want to
# compare them to the originals later.
self.dependencies = list(self.meta.dependencies)
self.dependencies_set = set(self.dependencies)
self.suppressed = list(self.meta.suppressed)
self.suppressed_set = set(self.suppressed)
all_deps = self.dependencies + self.suppressed
assert len(all_deps) == len(self.meta.dep_prios)
self.priorities = {id: pri for id, pri in zip(all_deps, self.meta.dep_prios)}
assert len(all_deps) == len(self.meta.dep_lines)
self.dep_line_map = {id: line for id, line in zip(all_deps, self.meta.dep_lines)}
assert len(self.meta.dep_hashes) == len(self.meta.dependencies)
self.dep_hashes = {
k: v for (k, v) in zip(self.meta.dependencies, self.meta.dep_hashes)
}
self.error_lines = self.meta.error_lines
if temporary:
self.load_tree(temporary=True)
if not manager.use_fine_grained_cache():
# Special case: if there were a previously missing package imported here
# and it is not present, then we need to re-calculate dependencies.
# This is to support patterns like this:
# from missing_package import missing_module # type: ignore
# At first mypy doesn't know that `missing_module` is a module
# (it may be a variable, a class, or a function), so it is not added to
# suppressed dependencies. Therefore, when the package with module is added,
# we need to re-calculate dependencies.
# NOTE: see comment below for why we skip this in fine grained mode.
if exist_added_packages(self.suppressed, manager, self.options):
self.parse_file() # This is safe because the cache is anyway stale.
self.compute_dependencies()
else:
# When doing a fine-grained cache load, pretend we only
# know about modules that have cache information and defer
# handling new modules until the fine-grained update.
if manager.use_fine_grained_cache():
manager.log(f"Deferring module to fine-grained update {path} ({id})")
raise ModuleNotFound
# Parse the file (and then some) to get the dependencies.
self.parse_file(temporary=temporary)
self.compute_dependencies()
def add_ancestors(self) -> None:
if self.path is not None:
_, name = os.path.split(self.path)
base, _ = os.path.splitext(name)
if "." in base:
# This is just a weird filename, don't add anything
self.ancestors = []
return
# All parent packages are new ancestors.
ancestors = []
parent = self.id
while "." in parent:
parent, _ = parent.rsplit(".", 1)
ancestors.append(parent)
self.ancestors = ancestors
def is_fresh(self) -> bool:
"""Return whether the cache data for this file is fresh."""
# NOTE: self.dependencies may differ from
# self.meta.dependencies when a dependency is dropped due to
# suppression by silent mode. However, when a suppressed
# dependency is added back we find out later in the process.
return self.meta is not None and self.dependencies == self.meta.dependencies
def mark_as_rechecked(self) -> None:
"""Marks this module as having been fully re-analyzed by the type-checker."""
self.manager.rechecked_modules.add(self.id)
def mark_interface_stale(self) -> None:
"""Marks this module as having a stale public interface, and discards the cache data."""
self.manager.stale_modules.add(self.id)
def check_blockers(self) -> None:
"""Raise CompileError if a blocking error is detected."""
if self.manager.errors.is_blockers():
self.manager.log("Bailing due to blocking errors")
self.manager.errors.raise_error()
@contextlib.contextmanager
def wrap_context(self, check_blockers: bool = True) -> Iterator[None]:
"""Temporarily change the error import context to match this state.
Also report an internal error if an unexpected exception was raised
and raise an exception on a blocking error, unless
check_blockers is False. Skipping blocking error reporting is used
in the semantic analyzer so that we can report all blocking errors
for a file (across multiple targets) to maintain backward
compatibility.
"""
save_import_context = self.manager.errors.import_context()
self.manager.errors.set_import_context(self.import_context)
try:
yield
except CompileError:
raise
except Exception as err:
report_internal_error(
err,
self.path,
0,
self.manager.errors,
self.options,
self.manager.stdout,
self.manager.stderr,
)
self.manager.errors.set_import_context(save_import_context)
# TODO: Move this away once we've removed the old semantic analyzer?
if check_blockers:
self.check_blockers()
def load_fine_grained_deps(self) -> dict[str, set[str]]:
return self.manager.load_fine_grained_deps(self.id)
def load_tree(self, temporary: bool = False) -> None:
assert (
self.meta is not None
), "Internal error: this method must be called only for cached modules"
data: bytes | dict[str, Any] | None
if self.options.fixed_format_cache:
data = _load_ff_file(self.meta.data_file, self.manager, "Could not load tree: ")
else:
data = _load_json_file(
self.meta.data_file, self.manager, "Load tree ", "Could not load tree: "
)
if data is None:
return
t0 = time.time()
# TODO: Assert data file wasn't changed.
if isinstance(data, bytes):
data_io = ReadBuffer(data)
self.tree = MypyFile.read(data_io)
else:
self.tree = MypyFile.deserialize(data)
t1 = time.time()
self.manager.add_stats(deserialize_time=t1 - t0)
if not temporary:
self.manager.modules[self.id] = self.tree
self.manager.add_stats(fresh_trees=1)
def fix_cross_refs(self) -> None:
assert self.tree is not None, "Internal error: method must be called on parsed file only"
# We need to set allow_missing when doing a fine grained cache
# load because we need to gracefully handle missing modules.
fixup_module(self.tree, self.manager.modules, self.options.use_fine_grained_cache)
# Methods for processing modules from source code.
def parse_file(self, *, temporary: bool = False) -> None:
"""Parse file and run first pass of semantic analysis.
Everything done here is local to the file. Don't depend on imported
modules in any way. Also record module dependencies based on imports.
"""
if self.tree is not None:
# The file was already parsed (in __init__()).
return
manager = self.manager
# Can we reuse a previously parsed AST? This avoids redundant work in daemon.
cached = self.id in manager.ast_cache
modules = manager.modules
if not cached:
manager.log(f"Parsing {self.xpath} ({self.id})")
else:
manager.log(f"Using cached AST for {self.xpath} ({self.id})")
t0 = time_ref()
with self.wrap_context():
source = self.source
self.source = None # We won't need it again.
if self.path and source is None:
try:
path = manager.maybe_swap_for_shadow_path(self.path)
source = decode_python_encoding(manager.fscache.read(path))
self.source_hash = manager.fscache.hash_digest(path)
except OSError as ioerr:
# ioerr.strerror differs for os.stat failures between Windows and
# other systems, but os.strerror(ioerr.errno) does not, so we use that.
# (We want the error messages to be platform-independent so that the
# tests have predictable output.)
assert ioerr.errno is not None
raise CompileError(
[
"mypy: can't read file '{}': {}".format(
self.path.replace(os.getcwd() + os.sep, ""),
os.strerror(ioerr.errno),
)
],
module_with_blocker=self.id,
) from ioerr
except (UnicodeDecodeError, DecodeError) as decodeerr:
if self.path.endswith(".pyd"):
err = f"mypy: stubgen does not support .pyd files: '{self.path}'"
else:
err = f"mypy: can't decode file '{self.path}': {str(decodeerr)}"
raise CompileError([err], module_with_blocker=self.id) from decodeerr
elif self.path and self.manager.fscache.isdir(self.path):
source = ""
self.source_hash = ""
else:
assert source is not None
self.source_hash = compute_hash(source)
self.parse_inline_configuration(source)
if not cached:
self.tree = manager.parse_file(
self.id,
self.xpath,
source,
ignore_errors=self.ignore_all or self.options.ignore_errors,
options=self.options,
)
else:
# Reuse a cached AST
self.tree = manager.ast_cache[self.id][0]
manager.errors.set_file_ignored_lines(
self.xpath,
self.tree.ignored_lines,
self.ignore_all or self.options.ignore_errors,
)
self.time_spent_us += time_spent_us(t0)
if not cached:
# Make a copy of any errors produced during parse time so that
# fine-grained mode can repeat them when the module is
# reprocessed.
self.early_errors = list(manager.errors.error_info_map.get(self.xpath, []))
else:
self.early_errors = manager.ast_cache[self.id][1]
if not temporary:
modules[self.id] = self.tree
if not cached:
self.semantic_analysis_pass1()
if not temporary:
self.check_blockers()
manager.ast_cache[self.id] = (self.tree, self.early_errors)
def parse_inline_configuration(self, source: str) -> None:
"""Check for inline mypy: options directive and parse them."""
flags = get_mypy_comments(source)
if flags:
changes, config_errors = parse_mypy_comments(flags, self.options)
self.options = self.options.apply_changes(changes)
self.manager.errors.set_file(self.xpath, self.id, self.options)
for lineno, error in config_errors:
self.manager.errors.report(lineno, 0, error)
def semantic_analysis_pass1(self) -> None:
"""Perform pass 1 of semantic analysis, which happens immediately after parsing.
This pass can't assume that any other modules have been processed yet.
"""
options = self.options
assert self.tree is not None
t0 = time_ref()
# Do the first pass of semantic analysis: analyze the reachability
# of blocks and import statements. We must do this before
# processing imports, since this may mark some import statements as
# unreachable.
#
# TODO: This should not be considered as a semantic analysis
# pass -- it's an independent pass.
analyzer = SemanticAnalyzerPreAnalysis()
with self.wrap_context():
analyzer.visit_file(self.tree, self.xpath, self.id, options)
self.manager.errors.set_skipped_lines(self.xpath, self.tree.skipped_lines)
# TODO: Do this while constructing the AST?
self.tree.names = SymbolTable()
if not self.tree.is_stub:
if not self.options.allow_redefinition_new:
# Perform some low-key variable renaming when assignments can't
# widen inferred types
self.tree.accept(LimitedVariableRenameVisitor())
if options.allow_redefinition:
# Perform more renaming across the AST to allow variable redefinitions
self.tree.accept(VariableRenameVisitor())
self.time_spent_us += time_spent_us(t0)
def add_dependency(self, dep: str) -> None:
if dep not in self.dependencies_set:
self.dependencies.append(dep)
self.dependencies_set.add(dep)
if dep in self.suppressed_set:
self.suppressed.remove(dep)
self.suppressed_set.remove(dep)
def suppress_dependency(self, dep: str) -> None:
if dep in self.dependencies_set:
self.dependencies.remove(dep)
self.dependencies_set.remove(dep)
if dep not in self.suppressed_set:
self.suppressed.append(dep)
self.suppressed_set.add(dep)
def compute_dependencies(self) -> None:
"""Compute a module's dependencies after parsing it.
This is used when we parse a file that we didn't have
up-to-date cache information for. When we have an up-to-date
cache, we just use the cached info.
"""
manager = self.manager
assert self.tree is not None
# Compute (direct) dependencies.
# Add all direct imports (this is why we needed the first pass).
# Also keep track of each dependency's source line.
# Missing dependencies will be moved from dependencies to
# suppressed when they fail to be loaded in load_graph.
self.dependencies = []
self.dependencies_set = set()
self.suppressed = []
self.suppressed_set = set()
self.priorities = {} # id -> priority
self.dep_line_map = {} # id -> line
self.dep_hashes = {}
dep_entries = manager.all_imported_modules_in_file(
self.tree
) + self.manager.plugin.get_additional_deps(self.tree)
for pri, id, line in dep_entries:
self.priorities[id] = min(pri, self.priorities.get(id, PRI_ALL))
if id == self.id:
continue
self.add_dependency(id)
if id not in self.dep_line_map:
self.dep_line_map[id] = line
# Every module implicitly depends on builtins.
if self.id != "builtins":
self.add_dependency("builtins")
self.check_blockers() # Can fail due to bogus relative imports
def type_check_first_pass(self) -> None:
if self.options.semantic_analysis_only:
return
t0 = time_ref()
with self.wrap_context():
self.type_checker().check_first_pass()
self.time_spent_us += time_spent_us(t0)
def type_checker(self) -> TypeChecker:
if not self._type_checker:
assert self.tree is not None, "Internal error: must be called on parsed file only"
manager = self.manager
self._type_checker = TypeChecker(
manager.errors,
manager.modules,
self.options,
self.tree,
self.xpath,
manager.plugin,
self.per_line_checking_time_ns,
)
return self._type_checker
def type_map(self) -> dict[Expression, Type]:
# We can extract the master type map directly since at this
# point no temporary type maps can be active.
assert len(self.type_checker()._type_maps) == 1
return self.type_checker()._type_maps[0]
def type_check_second_pass(self) -> bool:
if self.options.semantic_analysis_only:
return False
t0 = time_ref()
with self.wrap_context():
result = self.type_checker().check_second_pass()
self.time_spent_us += time_spent_us(t0)
return result
def detect_possibly_undefined_vars(self) -> None:
assert self.tree is not None, "Internal error: method must be called on parsed file only"
if self.tree.is_stub:
# We skip stub files because they aren't actually executed.
return
manager = self.manager
manager.errors.set_file(self.xpath, self.tree.fullname, options=self.options)
if manager.errors.is_error_code_enabled(
codes.POSSIBLY_UNDEFINED
) or manager.errors.is_error_code_enabled(codes.USED_BEFORE_DEF):
self.tree.accept(
PossiblyUndefinedVariableVisitor(
MessageBuilder(manager.errors, manager.modules),
self.type_map(),
self.options,
self.tree.names,
)
)
def finish_passes(self) -> None:
assert self.tree is not None, "Internal error: method must be called on parsed file only"
manager = self.manager
if self.options.semantic_analysis_only:
return
t0 = time_ref()
with self.wrap_context():
# Some tests (and tools) want to look at the set of all types.
options = manager.options
if options.export_types:
manager.all_types.update(self.type_map())
# We should always patch indirect dependencies, even in full (non-incremental) builds,
# because the cache still may be written, and it must be correct.
self.patch_indirect_dependencies(
# Two possible sources of indirect dependencies:
# * Symbols not directly imported in this module but accessed via an attribute
# or via a re-export (vast majority of these recorded in semantic analysis).
# * For each expression type we need to record definitions of type components
# since "meaning" of the type may be updated when definitions are updated.
self.tree.module_refs | self.type_checker().module_refs,
set(self.type_map().values()),
)
if self.options.dump_inference_stats:
dump_type_stats(
self.tree,
self.xpath,
modules=self.manager.modules,
inferred=True,
typemap=self.type_map(),
)
manager.report_file(self.tree, self.type_map(), self.options)
self.update_fine_grained_deps(self.manager.fg_deps)
if manager.options.export_ref_info:
write_undocumented_ref_info(
self, manager.metastore, manager.options, self.type_map()
)
self.free_state()
if not manager.options.fine_grained_incremental and not manager.options.preserve_asts:
free_tree(self.tree)
self.time_spent_us += time_spent_us(t0)
def free_state(self) -> None:
if self._type_checker:
self._type_checker.reset()
self._type_checker = None
def patch_indirect_dependencies(self, module_refs: set[str], types: set[Type]) -> None:
assert self.ancestors is not None
existing_deps = set(self.dependencies + self.suppressed + self.ancestors)
existing_deps.add(self.id)
encountered = self.manager.indirection_detector.find_modules(types) | module_refs
for dep in sorted(encountered - existing_deps):
if dep not in self.manager.modules:
continue
self.add_dependency(dep)
self.priorities[dep] = PRI_INDIRECT
def compute_fine_grained_deps(self) -> dict[str, set[str]]:
assert self.tree is not None
if self.id in ("builtins", "typing", "types", "sys", "_typeshed"):
# We don't track changes to core parts of typeshed -- the
# assumption is that they are only changed as part of mypy
# updates, which will invalidate everything anyway. These
# will always be processed in the initial non-fine-grained
# build. Other modules may be brought in as a result of an
# fine-grained increment, and we may need these
# dependencies then to handle cyclic imports.
return {}
from mypy.server.deps import get_dependencies # Lazy import to speed up startup
return get_dependencies(
target=self.tree,
type_map=self.type_map(),
python_version=self.options.python_version,
options=self.manager.options,
)
def update_fine_grained_deps(self, deps: dict[str, set[str]]) -> None:
options = self.manager.options
if options.cache_fine_grained or options.fine_grained_incremental:
from mypy.server.deps import merge_dependencies # Lazy import to speed up startup
merge_dependencies(self.compute_fine_grained_deps(), deps)
type_state.update_protocol_deps(deps)
def write_cache(self) -> tuple[CacheMeta, str] | None:
assert self.tree is not None, "Internal error: method must be called on parsed file only"
# We don't support writing cache files in fine-grained incremental mode.
if (
not self.path
or self.options.cache_dir == os.devnull
or self.options.fine_grained_incremental
):
if self.options.debug_serialize:
try:
if self.manager.options.fixed_format_cache:
data = WriteBuffer()
self.tree.write(data)
else:
self.tree.serialize()
except Exception:
print(f"Error serializing {self.id}", file=self.manager.stdout)
raise # Propagate to display traceback
return None
dep_prios = self.dependency_priorities()
dep_lines = self.dependency_lines()
assert self.source_hash is not None
assert len(set(self.dependencies)) == len(
self.dependencies
), f"Duplicates in dependencies list for {self.id} ({self.dependencies})"
new_interface_hash, meta_tuple = write_cache(
self.id,
self.path,
self.tree,
list(self.dependencies),
list(self.suppressed),
dep_prios,
dep_lines,
self.interface_hash,
self.source_hash,
self.ignore_all,
self.manager,
)
if new_interface_hash == self.interface_hash:
self.manager.log(f"Cached module {self.id} has same interface")
else:
self.manager.log(f"Cached module {self.id} has changed interface")
self.mark_interface_stale()
self.interface_hash = new_interface_hash
return meta_tuple
def verify_dependencies(self, suppressed_only: bool = False) -> None:
"""Report errors for import targets in modules that don't exist.
If suppressed_only is set, only check suppressed dependencies.
"""
manager = self.manager
assert self.ancestors is not None
# Strip out indirect dependencies. See comment in build.load_graph().
if suppressed_only:
all_deps = [dep for dep in self.suppressed if self.priorities.get(dep) != PRI_INDIRECT]
else:
dependencies = [
dep
for dep in self.dependencies + self.suppressed
if self.priorities.get(dep) != PRI_INDIRECT
]
all_deps = dependencies + self.ancestors
for dep in all_deps:
if dep in manager.modules:
continue
options = manager.options.clone_for_module(dep)
if options.ignore_missing_imports:
continue
line = self.dep_line_map.get(dep, 1)
try:
if dep in self.ancestors:
state: State | None = None
ancestor: State | None = self
else:
state, ancestor = self, None
# Called just for its side effects of producing diagnostics.
find_module_and_diagnose(
manager,
dep,
options,
caller_state=state,
caller_line=line,
ancestor_for=ancestor,
)
except (ModuleNotFound, CompileError):
# Swallow up any ModuleNotFounds or CompilerErrors while generating
# a diagnostic. CompileErrors may get generated in
# fine-grained mode when an __init__.py is deleted, if a module
# that was in that package has targets reprocessed before
# it is renamed.
pass
def dependency_priorities(self) -> list[int]:
return [self.priorities.get(dep, PRI_HIGH) for dep in self.dependencies + self.suppressed]
def dependency_lines(self) -> list[int]:
return [self.dep_line_map.get(dep, 1) for dep in self.dependencies + self.suppressed]
def generate_unused_ignore_notes(self) -> None:
if (
self.options.warn_unused_ignores
or codes.UNUSED_IGNORE in self.options.enabled_error_codes
) and codes.UNUSED_IGNORE not in self.options.disabled_error_codes:
# If this file was initially loaded from the cache, it may have suppressed
# dependencies due to imports with ignores on them. We need to generate
# those errors to avoid spuriously flagging them as unused ignores.
if self.meta:
self.verify_dependencies(suppressed_only=True)
self.manager.errors.generate_unused_ignore_errors(self.xpath)
def generate_ignore_without_code_notes(self) -> None:
if self.manager.errors.is_error_code_enabled(codes.IGNORE_WITHOUT_CODE):
self.manager.errors.generate_ignore_without_code_errors(
self.xpath, self.options.warn_unused_ignores
)
# Module import and diagnostic glue
def find_module_and_diagnose(
manager: BuildManager,
id: str,
options: Options,
caller_state: State | None = None,
caller_line: int = 0,
ancestor_for: State | None = None,
root_source: bool = False,
skip_diagnose: bool = False,
) -> tuple[str, str]:
"""Find a module by name, respecting follow_imports and producing diagnostics.
If the module is not found, then the ModuleNotFound exception is raised.
Args:
id: module to find
options: the options for the module being loaded
caller_state: the state of the importing module, if applicable
caller_line: the line number of the import
ancestor_for: the child module this is an ancestor of, if applicable
root_source: whether this source was specified on the command line
skip_diagnose: skip any error diagnosis and reporting (but ModuleNotFound is
still raised if the module is missing)
The specified value of follow_imports for a module can be overridden
if the module is specified on the command line or if it is a stub,
so we compute and return the "effective" follow_imports of the module.
Returns a tuple containing (file path, target's effective follow_imports setting)
"""
result = find_module_with_reason(id, manager)
if isinstance(result, str):
# For non-stubs, look at options.follow_imports:
# - normal (default) -> fully analyze
# - silent -> analyze but silence errors
# - skip -> don't analyze, make the type Any
follow_imports = options.follow_imports
if (
root_source # Honor top-level modules
or (
result.endswith(".pyi") # Stubs are always normal
and not options.follow_imports_for_stubs # except when they aren't
)
or id in CORE_BUILTIN_MODULES # core is always normal
):
follow_imports = "normal"
if skip_diagnose:
pass
elif follow_imports == "silent":
# Still import it, but silence non-blocker errors.
manager.log(f"Silencing {result} ({id})")
elif follow_imports == "skip" or follow_imports == "error":
# In 'error' mode, produce special error messages.
if id not in manager.missing_modules:
manager.log(f"Skipping {result} ({id})")
if follow_imports == "error":
if ancestor_for:
skipping_ancestor(manager, id, result, ancestor_for)
else:
skipping_module(manager, caller_line, caller_state, id, result)
raise ModuleNotFound
if is_silent_import_module(manager, result) and not root_source:
follow_imports = "silent"
return (result, follow_imports)
else:
# Could not find a module. Typically the reason is a
# misspelled module name, missing stub, module not in
# search path or the module has not been installed.
ignore_missing_imports = options.ignore_missing_imports
# Don't honor a global (not per-module) ignore_missing_imports
# setting for modules that used to have bundled stubs, as
# otherwise updating mypy can silently result in new false
# negatives. (Unless there are stubs but they are incomplete.)
global_ignore_missing_imports = manager.options.ignore_missing_imports
if (
is_module_from_legacy_bundled_package(id)
and global_ignore_missing_imports
and not options.ignore_missing_imports_per_module
and result is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED
):
ignore_missing_imports = False
if skip_diagnose:
raise ModuleNotFound
if caller_state:
if not (ignore_missing_imports or in_partial_package(id, manager)):
module_not_found(manager, caller_line, caller_state, id, result)
raise ModuleNotFound
elif root_source:
# If we can't find a root source it's always fatal.
# TODO: This might hide non-fatal errors from
# root sources processed earlier.
raise CompileError([f"mypy: can't find module '{id}'"])
else:
raise ModuleNotFound
def exist_added_packages(suppressed: list[str], manager: BuildManager, options: Options) -> bool:
"""Find if there are any newly added packages that were previously suppressed.
Exclude everything not in build for follow-imports=skip.
"""
for dep in suppressed:
if dep in manager.source_set.source_modules:
# We don't need to add any special logic for this. If a module
# is added to build, importers will be invalidated by normal mechanism.
continue
path = find_module_simple(dep, manager)
if not path:
continue
if options.follow_imports == "skip" and (
not path.endswith(".pyi") or options.follow_imports_for_stubs
):
continue
if "__init__.py" in path:
# It is better to have a bit lenient test, this will only slightly reduce
# performance, while having a too strict test may affect correctness.
return True
return False
def find_module_simple(id: str, manager: BuildManager) -> str | None:
"""Find a filesystem path for module `id` or `None` if not found."""
t0 = time.time()
x = manager.find_module_cache.find_module(id, fast_path=True)
manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1)
if isinstance(x, ModuleNotFoundReason):
return None
return x
def find_module_with_reason(id: str, manager: BuildManager) -> ModuleSearchResult:
"""Find a filesystem path for module `id` or the reason it can't be found."""
t0 = time.time()
x = manager.find_module_cache.find_module(id, fast_path=False)
manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1)
return x
def in_partial_package(id: str, manager: BuildManager) -> bool:
"""Check if a missing module can potentially be a part of a package.
This checks if there is any existing parent __init__.pyi stub that
defines a module-level __getattr__ (a.k.a. partial stub package).
"""
while "." in id:
parent, _ = id.rsplit(".", 1)
if parent in manager.modules:
parent_mod: MypyFile | None = manager.modules[parent]
else:
# Parent is not in build, try quickly if we can find it.
try:
parent_st = State(
id=parent, path=None, source=None, manager=manager, temporary=True
)
except (ModuleNotFound, CompileError):
parent_mod = None
else:
parent_mod = parent_st.tree
if parent_mod is not None:
# Bail out soon, complete subpackage found
return parent_mod.is_partial_stub_package
id = parent
return False
def module_not_found(
manager: BuildManager,
line: int,
caller_state: State,
target: str,
reason: ModuleNotFoundReason,
) -> None:
errors = manager.errors
save_import_context = errors.import_context()
errors.set_import_context(caller_state.import_context)
errors.set_file(caller_state.xpath, caller_state.id, caller_state.options)
if target == "builtins":
errors.report(
line, 0, "Cannot find 'builtins' module. Typeshed appears broken!", blocker=True
)
errors.raise_error()
else:
daemon = manager.options.fine_grained_incremental
msg, notes = reason.error_message_templates(daemon)
if reason == ModuleNotFoundReason.NOT_FOUND:
code = codes.IMPORT_NOT_FOUND
elif (
reason == ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS
or reason == ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED
):
code = codes.IMPORT_UNTYPED
else:
code = codes.IMPORT
errors.report(line, 0, msg.format(module=target), code=code)
dist = stub_distribution_name(target)
for note in notes:
if "{stub_dist}" in note:
assert dist is not None
note = note.format(stub_dist=dist)
errors.report(line, 0, note, severity="note", only_once=True, code=code)
if reason is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:
assert dist is not None
manager.missing_stub_packages.add(dist)
errors.set_import_context(save_import_context)
def skipping_module(
manager: BuildManager, line: int, caller_state: State | None, id: str, path: str
) -> None:
"""Produce an error for an import ignored due to --follow_imports=error"""
assert caller_state, (id, path)
save_import_context = manager.errors.import_context()
manager.errors.set_import_context(caller_state.import_context)
manager.errors.set_file(caller_state.xpath, caller_state.id, manager.options)
manager.errors.report(line, 0, f'Import of "{id}" ignored', severity="error")
manager.errors.report(
line,
0,
"(Using --follow-imports=error, module not passed on command line)",
severity="note",
only_once=True,
)
manager.errors.set_import_context(save_import_context)
def skipping_ancestor(manager: BuildManager, id: str, path: str, ancestor_for: State) -> None:
"""Produce an error for an ancestor ignored due to --follow_imports=error"""
# TODO: Read the path (the __init__.py file) and return
# immediately if it's empty or only contains comments.
# But beware, some package may be the ancestor of many modules,
# so we'd need to cache the decision.
manager.errors.set_import_context([])
manager.errors.set_file(ancestor_for.xpath, ancestor_for.id, manager.options)
manager.errors.report(
-1, -1, f'Ancestor package "{id}" ignored', severity="error", only_once=True
)
manager.errors.report(
-1,
-1,
"(Using --follow-imports=error, submodule passed on command line)",
severity="note",
only_once=True,
)
def log_configuration(manager: BuildManager, sources: list[BuildSource]) -> None:
"""Output useful configuration information to LOG and TRACE"""
config_file = manager.options.config_file
if config_file:
config_file = os.path.abspath(config_file)
manager.log()
configuration_vars = [
("Mypy Version", __version__),
("Config File", (config_file or "Default")),
("Configured Executable", manager.options.python_executable or "None"),
("Current Executable", sys.executable),
("Cache Dir", manager.options.cache_dir),
("Compiled", str(not __file__.endswith(".py"))),
("Exclude", manager.options.exclude),
]
for conf_name, conf_value in configuration_vars:
manager.log(f"{conf_name + ':':24}{conf_value}")
for source in sources:
manager.log(f"{'Found source:':24}{source}")
# Complete list of searched paths can get very long, put them under TRACE
for path_type, paths in manager.search_paths.asdict().items():
if not paths:
manager.trace(f"No {path_type}")
continue
manager.trace(f"{path_type}:")
for pth in paths:
manager.trace(f" {pth}")
# The driver
def dispatch(sources: list[BuildSource], manager: BuildManager, stdout: TextIO) -> Graph:
log_configuration(manager, sources)
t0 = time.time()
graph = load_graph(sources, manager)
# This is a kind of unfortunate hack to work around some of fine-grained's
# fragility: if we have loaded less than 50% of the specified files from
# cache in fine-grained cache mode, load the graph again honestly.
# In this case, we just turn the cache off entirely, so we don't need
# to worry about some files being loaded and some from cache and so
# that fine-grained mode never *writes* to the cache.
if manager.use_fine_grained_cache() and len(graph) < 0.50 * len(sources):
manager.log("Redoing load_graph without cache because too much was missing")
manager.cache_enabled = False
graph = load_graph(sources, manager)
for id in graph:
manager.import_map[id] = set(graph[id].dependencies + graph[id].suppressed)
t1 = time.time()
manager.add_stats(
graph_size=len(graph),
stubs_found=sum(g.path is not None and g.path.endswith(".pyi") for g in graph.values()),
graph_load_time=(t1 - t0),
fm_cache_size=len(manager.find_module_cache.results),
)
if not graph:
print("Nothing to do?!", file=stdout)
return graph
manager.log(f"Loaded graph with {len(graph)} nodes ({t1 - t0:.3f} sec)")
if manager.options.dump_graph:
dump_graph(graph, stdout)
return graph
# Fine grained dependencies that didn't have an associated module in the build
# are serialized separately, so we read them after we load the graph.
# We need to read them both for running in daemon mode and if we are generating
# a fine-grained cache (so that we can properly update them incrementally).
# The `read_deps_cache` will also validate
# the deps cache against the loaded individual cache files.
if manager.options.cache_fine_grained or manager.use_fine_grained_cache():
t2 = time.time()
fg_deps_meta = read_deps_cache(manager, graph)
manager.add_stats(load_fg_deps_time=time.time() - t2)
if fg_deps_meta is not None:
manager.fg_deps_meta = fg_deps_meta
elif manager.stats.get("fresh_metas", 0) > 0:
# Clear the stats so we don't infinite loop because of positive fresh_metas
manager.stats.clear()
# There were some cache files read, but no fine-grained dependencies loaded.
manager.log("Error reading fine-grained dependencies cache -- aborting cache load")
manager.cache_enabled = False
manager.log("Falling back to full run -- reloading graph...")
return dispatch(sources, manager, stdout)
# If we are loading a fine-grained incremental mode cache, we
# don't want to do a real incremental reprocess of the
# graph---we'll handle it all later.
if not manager.use_fine_grained_cache():
process_graph(graph, manager)
# Update plugins snapshot.
write_plugins_snapshot(manager)
manager.old_plugins_snapshot = manager.plugins_snapshot
if manager.options.cache_fine_grained or manager.options.fine_grained_incremental:
# If we are running a daemon or are going to write cache for further fine grained use,
# then we need to collect fine grained protocol dependencies.
# Since these are a global property of the program, they are calculated after we
# processed the whole graph.
type_state.add_all_protocol_deps(manager.fg_deps)
if not manager.options.fine_grained_incremental:
rdeps = generate_deps_for_cache(manager, graph)
write_deps_cache(rdeps, manager, graph)
if manager.options.dump_deps:
# This speeds up startup a little when not using the daemon mode.
from mypy.server.deps import dump_all_dependencies
dump_all_dependencies(
manager.modules, manager.all_types, manager.options.python_version, manager.options
)
return graph
| State |
python | Netflix__metaflow | metaflow/plugins/argo/argo_client.py | {
"start": 459,
"end": 17404
} | class ____(object):
def __init__(self, namespace=None):
self._client = KubernetesClient()
self._namespace = namespace or "default"
self._group = "argoproj.io"
self._version = "v1alpha1"
def get_workflow(self, name):
client = self._client.get()
try:
workflow = client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflows",
name=name,
)
except client.rest.ApiException as e:
if e.status == 404:
return None
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
return workflow
def get_workflow_template(self, name):
client = self._client.get()
try:
return client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
name=name,
)
except client.rest.ApiException as e:
if e.status == 404:
return None
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def get_workflow_templates(self, page_size=100):
client = self._client.get()
continue_token = None
while True:
try:
params = {"limit": page_size}
if continue_token:
params["_continue"] = continue_token
response = client.CustomObjectsApi().list_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
**params,
)
for item in response.get("items", []):
yield item
metadata = response.get("metadata", {})
continue_token = metadata.get("continue")
if not continue_token:
break
except client.rest.ApiException as e:
if e.status == 404:
return None
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def register_workflow_template(self, name, workflow_template):
# Unfortunately, Kubernetes client does not handle optimistic
# concurrency control by itself unlike kubectl
client = self._client.get()
try:
workflow_template["metadata"][
"resourceVersion"
] = client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
name=name,
)[
"metadata"
][
"resourceVersion"
]
except client.rest.ApiException as e:
if e.status == 404:
try:
return client.CustomObjectsApi().create_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
body=workflow_template,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"]
if e.body is not None
else e.reason
)
else:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
try:
return client.CustomObjectsApi().replace_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
body=workflow_template,
name=name,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def delete_cronworkflow(self, name):
"""
Issues an API call for deleting a cronworkflow
Returns either the successful API response, or None in case the resource was not found.
"""
client = self._client.get()
try:
return client.CustomObjectsApi().delete_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="cronworkflows",
name=name,
)
except client.rest.ApiException as e:
if e.status == 404:
return None
else:
raise wrap_api_error(e)
def delete_workflow_template(self, name):
"""
Issues an API call for deleting a cronworkflow
Returns either the successful API response, or None in case the resource was not found.
"""
client = self._client.get()
try:
return client.CustomObjectsApi().delete_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflowtemplates",
name=name,
)
except client.rest.ApiException as e:
if e.status == 404:
return None
else:
raise wrap_api_error(e)
def terminate_workflow(self, name):
client = self._client.get()
try:
workflow = client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflows",
name=name,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
if workflow["status"]["finishedAt"] is not None:
raise ArgoClientException(
"Cannot terminate an execution that has already finished."
)
if workflow["spec"].get("shutdown") == "Terminate":
raise ArgoClientException("Execution has already been terminated.")
try:
body = {"spec": workflow["spec"]}
body["spec"]["shutdown"] = "Terminate"
return client.CustomObjectsApi().patch_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflows",
name=name,
body=body,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def suspend_workflow(self, name):
workflow = self.get_workflow(name)
if workflow is None:
raise ArgoClientException("Execution argo-%s was not found" % name)
if workflow["status"]["finishedAt"] is not None:
raise ArgoClientException(
"Cannot suspend an execution that has already finished."
)
if workflow["spec"].get("suspend") is True:
raise ArgoClientException("Execution has already been suspended.")
body = {"spec": workflow["spec"]}
body["spec"]["suspend"] = True
return self._patch_workflow(name, body)
def unsuspend_workflow(self, name):
workflow = self.get_workflow(name)
if workflow is None:
raise ArgoClientException("Execution argo-%s was not found" % name)
if workflow["status"]["finishedAt"] is not None:
raise ArgoClientException(
"Cannot unsuspend an execution that has already finished."
)
if not workflow["spec"].get("suspend", False):
raise ArgoClientException("Execution is already proceeding.")
body = {"spec": workflow["spec"]}
body["spec"]["suspend"] = False
return self._patch_workflow(name, body)
def _patch_workflow(self, name, body):
client = self._client.get()
try:
return client.CustomObjectsApi().patch_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflows",
name=name,
body=body,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def trigger_workflow_template(self, name, usertype, username, parameters={}):
client = self._client.get()
body = {
"apiVersion": "argoproj.io/v1alpha1",
"kind": "Workflow",
"metadata": {
"generateName": name + "-",
"annotations": {
"metaflow/triggered_by_user": json.dumps(
{"type": usertype, "name": username}
)
},
},
"spec": {
"workflowTemplateRef": {"name": name},
"arguments": {
"parameters": [
{"name": k, "value": json.dumps(v)}
for k, v in parameters.items()
]
},
},
}
try:
return client.CustomObjectsApi().create_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="workflows",
body=body,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def schedule_workflow_template(self, name, schedule=None, timezone=None):
# Unfortunately, Kubernetes client does not handle optimistic
# concurrency control by itself unlike kubectl
client = self._client.get()
body = {
"apiVersion": "argoproj.io/v1alpha1",
"kind": "CronWorkflow",
"metadata": {"name": name},
"spec": {
"suspend": schedule is None,
"schedule": schedule,
"timezone": timezone,
"failedJobsHistoryLimit": 10000, # default is unfortunately 1
"successfulJobsHistoryLimit": 10000, # default is unfortunately 3
"workflowSpec": {"workflowTemplateRef": {"name": name}},
"startingDeadlineSeconds": 3540, # configuring this to 59 minutes so a failed trigger of cron workflow can succeed at most 59 mins after scheduled execution
},
}
try:
body["metadata"][
"resourceVersion"
] = client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="cronworkflows",
name=name,
)[
"metadata"
][
"resourceVersion"
]
except client.rest.ApiException as e:
# Scheduled workflow does not exist and we want to schedule a workflow
if e.status == 404:
if schedule is None:
return
try:
return client.CustomObjectsApi().create_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="cronworkflows",
body=body,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"]
if e.body is not None
else e.reason
)
else:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
try:
return client.CustomObjectsApi().replace_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=self._namespace,
plural="cronworkflows",
body=body,
name=name,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def register_sensor(
self, name, sensor=None, sensor_namespace=ARGO_EVENTS_SENSOR_NAMESPACE
):
if sensor is None:
sensor = {}
# Unfortunately, Kubernetes client does not handle optimistic
# concurrency control by itself unlike kubectl
client = self._client.get()
if not sensor:
sensor["metadata"] = {}
try:
sensor["metadata"][
"resourceVersion"
] = client.CustomObjectsApi().get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=sensor_namespace,
plural="sensors",
name=name,
)[
"metadata"
][
"resourceVersion"
]
except client.rest.ApiException as e:
# Sensor does not exist and we want to add one
if e.status == 404:
try:
return client.CustomObjectsApi().create_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=sensor_namespace,
plural="sensors",
body=sensor,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"]
if e.body is not None
else e.reason
)
else:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
try:
return client.CustomObjectsApi().replace_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=sensor_namespace,
plural="sensors",
body=sensor,
name=name,
)
except client.rest.ApiException as e:
raise ArgoClientException(
json.loads(e.body)["message"] if e.body is not None else e.reason
)
def delete_sensor(self, name, sensor_namespace):
"""
Issues an API call for deleting a sensor
Returns either the successful API response, or None in case the resource was not found.
"""
client = self._client.get()
try:
return client.CustomObjectsApi().delete_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=sensor_namespace,
plural="sensors",
name=name,
)
except client.rest.ApiException as e:
if e.status == 404:
return None
raise wrap_api_error(e)
def wrap_api_error(error):
message = (
json.loads(error.body)["message"] if error.body is not None else error.reason
)
# catch all
ex = ArgoClientException(message)
if error.status == 404:
# usually handled outside this function as most cases want to return None instead.
ex = ArgoResourceNotFound(message)
if error.status == 403:
ex = ArgoNotPermitted(message)
return ex
| ArgoClient |
python | redis__redis-py | redis/auth/token.py | {
"start": 1737,
"end": 3317
} | class ____(TokenInterface):
REQUIRED_FIELDS = {"exp"}
def __init__(self, token: str):
try:
import jwt
except ImportError as ie:
raise ImportError(
f"The PyJWT library is required for {self.__class__.__name__}.",
) from ie
self._value = token
self._decoded = jwt.decode(
self._value,
options={"verify_signature": False},
algorithms=[jwt.get_unverified_header(self._value).get("alg")],
)
self._validate_token()
def is_expired(self) -> bool:
exp = self._decoded["exp"]
if exp == -1:
return False
return (
self._decoded["exp"] * 1000 <= datetime.now(timezone.utc).timestamp() * 1000
)
def ttl(self) -> float:
exp = self._decoded["exp"]
if exp == -1:
return -1
return (
self._decoded["exp"] * 1000 - datetime.now(timezone.utc).timestamp() * 1000
)
def try_get(self, key: str) -> str:
return self._decoded.get(key)
def get_value(self) -> str:
return self._value
def get_expires_at_ms(self) -> float:
return float(self._decoded["exp"] * 1000)
def get_received_at_ms(self) -> float:
return datetime.now(timezone.utc).timestamp() * 1000
def _validate_token(self):
actual_fields = {x for x in self._decoded.keys()}
if len(self.REQUIRED_FIELDS - actual_fields) != 0:
raise InvalidTokenSchemaErr(self.REQUIRED_FIELDS - actual_fields)
| JWToken |
python | doocs__leetcode | solution/0000-0099/0008.String to Integer (atoi)/Solution.py | {
"start": 0,
"end": 746
} | class ____:
def myAtoi(self, s: str) -> int:
if not s:
return 0
n = len(s)
if n == 0:
return 0
i = 0
while s[i] == ' ':
i += 1
# 仅包含空格
if i == n:
return 0
sign = -1 if s[i] == '-' else 1
if s[i] in ['-', '+']:
i += 1
res, flag = 0, (2**31 - 1) // 10
while i < n:
# 非数字,跳出循环体
if not s[i].isdigit():
break
c = int(s[i])
# 溢出判断
if res > flag or (res == flag and c > 7):
return 2**31 - 1 if sign > 0 else -(2**31)
res = res * 10 + c
i += 1
return sign * res
| Solution |
python | getsentry__sentry-python | sentry_sdk/consts.py | {
"start": 839,
"end": 3021
} | class ____(Enum):
GZIP = "gzip"
BROTLI = "br"
if TYPE_CHECKING:
import sentry_sdk
from typing import Optional
from typing import Callable
from typing import Union
from typing import List
from typing import Type
from typing import Dict
from typing import Any
from typing import Sequence
from typing import Tuple
from typing import AbstractSet
from typing_extensions import Literal
from typing_extensions import TypedDict
from sentry_sdk._types import (
BreadcrumbProcessor,
ContinuousProfilerMode,
Event,
EventProcessor,
Hint,
Log,
MeasurementUnit,
Metric,
ProfilerMode,
TracesSampler,
TransactionProcessor,
)
# Experiments are feature flags to enable and disable certain unstable SDK
# functionality. Changing them from the defaults (`None`) in production
# code is highly discouraged. They are not subject to any stability
# guarantees such as the ones from semantic versioning.
Experiments = TypedDict(
"Experiments",
{
"max_spans": Optional[int],
"max_flags": Optional[int],
"record_sql_params": Optional[bool],
"continuous_profiling_auto_start": Optional[bool],
"continuous_profiling_mode": Optional[ContinuousProfilerMode],
"otel_powered_performance": Optional[bool],
"transport_zlib_compression_level": Optional[int],
"transport_compression_level": Optional[int],
"transport_compression_algo": Optional[CompressionAlgo],
"transport_num_pools": Optional[int],
"transport_http2": Optional[bool],
"enable_logs": Optional[bool],
"before_send_log": Optional[Callable[[Log, Hint], Optional[Log]]],
"enable_metrics": Optional[bool],
"before_send_metric": Optional[Callable[[Metric, Hint], Optional[Metric]]],
},
total=False,
)
DEFAULT_QUEUE_SIZE = 100
DEFAULT_MAX_BREADCRUMBS = 100
MATCH_ALL = r".*"
FALSE_VALUES = [
"false",
"no",
"off",
"n",
"0",
]
| CompressionAlgo |
python | django__django | django/db/models/functions/math.py | {
"start": 2045,
"end": 2139
} | class ____(NumericOutputFieldMixin, Transform):
function = "COS"
lookup_name = "cos"
| Cos |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-lmstudio/llama_index/llms/lmstudio/base.py | {
"start": 1099,
"end": 8354
} | class ____(CustomLLM):
base_url: str = Field(
default="http://localhost:1234/v1",
description="Base url the model is hosted under.",
)
context_window: int = Field(
default=DEFAULT_CONTEXT_WINDOW,
description="The maximum number of context tokens for the model.",
gt=0,
)
model_name: str = Field(description="The model to use.")
request_timeout: float = Field(
default=DEFAULT_REQUEST_TIMEOUT,
description="The timeout for making http request in seconds to LM Studio API server.",
)
num_output: int = Field(
default=DEFAULT_NUM_OUTPUTS,
description=LLMMetadata.model_fields["num_output"].description,
)
is_chat_model: bool = Field(
default=True,
description=(
"LM Studio API supports chat."
+ LLMMetadata.model_fields["is_chat_model"].description
),
)
temperature: float = Field(
default=DEFAULT_TEMPERATURE,
description=("The temperature to use for sampling."),
ge=0.0,
le=1.0,
)
timeout: float = Field(
default=120, description=("The timeout to use in seconds."), ge=0
)
additional_kwargs: Dict[str, Any] = Field(
default_factory=dict, description=("Additional kwargs to pass to the model.")
)
def _create_payload_from_messages(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> Dict[str, Any]:
return {
"model": self.model_name,
"messages": [
{
"role": message.role.value,
"content": message.content,
**(
message.additional_kwargs
if message.additional_kwargs is not None
else {}
),
}
for message in messages
],
"options": self._model_kwargs,
"stream": False,
**kwargs,
}
def _create_chat_response_from_http_response(
self, response: httpx.Response
) -> ChatResponse:
raw = response.json()
message = raw["choices"][0]["message"]
return ChatResponse(
message=ChatMessage(
content=message.get("content"),
role=MessageRole(message.get("role")),
additional_kwargs=get_additional_kwargs(message, ("content", "role")),
),
raw=raw,
additional_kwargs=get_additional_kwargs(raw, ("choices",)),
)
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
payload = self._create_payload_from_messages(messages, **kwargs)
with httpx.Client(timeout=Timeout(self.request_timeout)) as client:
response = client.post(
url=f"{self.base_url}/chat/completions",
json=payload,
)
response.raise_for_status()
return self._create_chat_response_from_http_response(response)
@llm_chat_callback()
async def achat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponse:
payload = self._create_payload_from_messages(messages, **kwargs)
async with httpx.AsyncClient(timeout=Timeout(self.request_timeout)) as client:
response = await client.post(
url=f"{self.base_url}/chat/completions",
json=payload,
)
response.raise_for_status()
return self._create_chat_response_from_http_response(response)
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
complete_fn = chat_to_completion_decorator(self.chat)
return complete_fn(prompt, **kwargs)
@llm_completion_callback()
async def acomplete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
acomplete_fn = achat_to_completion_decorator(self.achat)
return await acomplete_fn(prompt, **kwargs)
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
payload = self._create_payload_from_messages(messages, stream=True, **kwargs)
with httpx.Client(timeout=Timeout(self.request_timeout)) as client:
with client.stream(
method="POST",
url=f"{self.base_url}/chat/completions",
json=payload,
) as response:
response.raise_for_status()
text = ""
for line in response.iter_lines():
if line:
line = line.strip()
if isinstance(line, bytes):
line = line.decode("utf-8")
if line.startswith("data: [DONE]"):
break
# Slice the line to remove the "data: " prefix
chunk = json.loads(line[5:])
delta = chunk["choices"][0].get("delta")
role = delta.get("role") or MessageRole.ASSISTANT
content_delta = delta.get("content") or ""
text += content_delta
yield ChatResponse(
message=ChatMessage(
content=text,
role=MessageRole(role),
additional_kwargs=get_additional_kwargs(
chunk, ("choices",)
),
),
delta=content_delta,
raw=chunk,
additional_kwargs=get_additional_kwargs(
chunk, ("choices",)
),
)
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
stream_complete_fn = stream_chat_to_completion_decorator(self.stream_chat)
return stream_complete_fn(prompt, **kwargs)
@llm_completion_callback()
async def astream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseAsyncGen:
astream_complete_fn = astream_chat_to_completion_decorator(self.astream_chat)
return await astream_complete_fn(prompt, **kwargs)
@property
def metadata(self) -> LLMMetadata:
"""LLM metadata."""
return LLMMetadata(
context_window=self.context_window,
num_output=self.num_output,
model_name=self.model_name,
is_chat_model=self.is_chat_model,
)
@property
def _model_kwargs(self) -> Dict[str, Any]:
base_kwargs = {
"temperature": self.temperature,
"num_ctx": self.context_window,
}
return {
**base_kwargs,
**self.additional_kwargs,
}
| LMStudio |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 32111,
"end": 35880
} | class ____(nn.Module):
def __init__(self, config: Owlv2TextConfig):
super().__init__()
self.config = config
embed_dim = config.hidden_size
self.embeddings = Owlv2TextEmbeddings(config)
self.encoder = Owlv2Encoder(config)
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
@auto_docstring
def forward(
self,
input_ids: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutputWithPooling]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
IDs?](../glossary#input-ids)
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
# num_samples, seq_len = input_shape where num_samples = batch_size * num_max_text_queries
# OWLV2's text model uses causal mask, prepare it here.
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
causal_attention_mask = _create_4d_causal_attention_mask(
input_shape, hidden_states.dtype, device=hidden_states.device
)
# expand attention_mask
if attention_mask is not None:
# [num_samples, seq_len] -> [num_samples, 1, tgt_seq_len, src_seq_len]
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
encoder_outputs = self.encoder(
inputs_embeds=hidden_states,
attention_mask=attention_mask,
causal_attention_mask=causal_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = encoder_outputs[0]
last_hidden_state = self.final_layer_norm(last_hidden_state)
# take features from the end of tokens embedding (end of token is the highest number in each sequence)
# casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
pooled_output = last_hidden_state[
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
input_ids.to(torch.int).argmax(dim=-1).to(last_hidden_state.device),
]
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
# Copied from transformers.models.owlvit.modeling_owlvit.OwlViTTextModel with google/owlvit-base-patch32->google/owlv2-base-patch16, OWLVIT->OWLV2,OwlViT->Owlv2
| Owlv2TextTransformer |
python | facebook__pyre-check | tools/upgrade/errors.py | {
"start": 7498,
"end": 7790
} | class ____(Exception):
def __init__(self, message: str, unsuppressed_paths: List[str]) -> None:
super().__init__(message)
self.unsuppressed_paths: List[str] = unsuppressed_paths
def error_path(error: Dict[str, Any]) -> str:
return error["path"]
| PartialErrorSuppression |
python | spyder-ide__spyder | external-deps/spyder-remote-services/tests/client_api.py | {
"start": 77,
"end": 2101
} | class ____(requests.Session):
"""Class to handle authentication with Jupyter Server.
This class represents a session to communicate with a Jupyter Server.
It automatically handles the authentication with the current running
server and sets the headers, main URL, port and host.
"""
def __init__(self, host=None, port=None, token=None):
running_servers = list_running_servers()
base_url = None
if token:
for server in running_servers:
if server["token"] == token:
base_url = server["url"]
break
elif host and port:
for server in running_servers:
if server["host"] == host and server["port"] == port:
token = server["token"]
base_url = server["url"]
break
elif host:
for server in running_servers:
if server["host"] == host:
token = server["token"]
base_url = server["url"]
break
elif port:
for server in running_servers:
if server["port"] == port:
token = server["token"]
base_url = server["url"]
break
elif token is None and host is None and port is None:
*_, server = running_servers
token = server["token"]
base_url = server["url"]
self.base_url = base_url or f"http://{host}:{port}/"
super().__init__()
self.headers.update({"Authorization": f"token {token}"})
def get(self, url, **kwargs):
return super().get(self.base_url + url, **kwargs)
def post(self, url, **kwargs):
return super().post(self.base_url + url, **kwargs)
def put(self, url, **kwargs):
return super().put(self.base_url + url, **kwargs)
def delete(self, url, **kwargs):
return super().delete(self.base_url + url, **kwargs)
| Session |
python | PyCQA__pylint | tests/functional/u/unsupported/unsupported_binary_operation.py | {
"start": 996,
"end": 1066
} | class ____:
def __add__(self, other):
return NotImplemented
| A2 |
python | getsentry__sentry | src/sentry/rules/history/endpoints/project_rule_stats.py | {
"start": 901,
"end": 979
} | class ____(TypedDict):
date: datetime
count: int
| TimeSeriesValueResponse |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 194916,
"end": 196009
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, user_auth_key: str, start_date: str, outcome_names: str):
"""Airbyte Source for Onesignal.
Documentation can be found at https://docs.airbyte.com/integrations/sources/onesignal
Args:
name (str): The name of the destination.
user_auth_key (str): OneSignal User Auth Key, see the docs for more information on how to obtain this key.
start_date (str): The date from which you'd like to replicate data for OneSignal API, in the format YYYY-MM-DDT00:00:00Z. All data generated after this date will be replicated.
outcome_names (str): Comma-separated list of names and the value (sum/count) for the returned outcome data. See the docs for more details
"""
self.user_auth_key = check.str_param(user_auth_key, "user_auth_key")
self.start_date = check.str_param(start_date, "start_date")
self.outcome_names = check.str_param(outcome_names, "outcome_names")
super().__init__("Onesignal", name)
| OnesignalSource |
python | django__django | tests/forms_tests/field_tests/test_choicefield.py | {
"start": 204,
"end": 5533
} | class ____(FormFieldAssertionsMixin, SimpleTestCase):
def test_choicefield_1(self):
f = ChoiceField(choices=[("1", "One"), ("2", "Two")])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual("1", f.clean(1))
self.assertEqual("1", f.clean("1"))
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("3")
def test_choicefield_2(self):
f = ChoiceField(choices=[("1", "One"), ("2", "Two")], required=False)
self.assertEqual("", f.clean(""))
self.assertEqual("", f.clean(None))
self.assertEqual("1", f.clean(1))
self.assertEqual("1", f.clean("1"))
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("3")
def test_choicefield_3(self):
f = ChoiceField(choices=[("J", "John"), ("P", "Paul")])
self.assertEqual("J", f.clean("J"))
msg = "'Select a valid choice. John is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("John")
def test_choicefield_4(self):
f = ChoiceField(
choices=[
("Numbers", (("1", "One"), ("2", "Two"))),
("Letters", (("3", "A"), ("4", "B"))),
("5", "Other"),
]
)
self.assertEqual("1", f.clean(1))
self.assertEqual("1", f.clean("1"))
self.assertEqual("3", f.clean(3))
self.assertEqual("3", f.clean("3"))
self.assertEqual("5", f.clean(5))
self.assertEqual("5", f.clean("5"))
msg = "'Select a valid choice. 6 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("6")
def test_choicefield_choices_default(self):
f = ChoiceField()
self.assertEqual(f.choices, [])
def test_choicefield_callable(self):
def choices():
return [("J", "John"), ("P", "Paul")]
f = ChoiceField(choices=choices)
self.assertEqual("J", f.clean("J"))
def test_choicefield_callable_mapping(self):
def choices():
return {"J": "John", "P": "Paul"}
f = ChoiceField(choices=choices)
self.assertEqual("J", f.clean("J"))
def test_choicefield_callable_grouped_mapping(self):
def choices():
return {
"Numbers": {"1": "One", "2": "Two"},
"Letters": {"3": "A", "4": "B"},
}
f = ChoiceField(choices=choices)
for i in ("1", "2", "3", "4"):
with self.subTest(i):
self.assertEqual(i, f.clean(i))
def test_choicefield_mapping(self):
f = ChoiceField(choices={"J": "John", "P": "Paul"})
self.assertEqual("J", f.clean("J"))
def test_choicefield_grouped_mapping(self):
f = ChoiceField(
choices={
"Numbers": (("1", "One"), ("2", "Two")),
"Letters": (("3", "A"), ("4", "B")),
}
)
for i in ("1", "2", "3", "4"):
with self.subTest(i):
self.assertEqual(i, f.clean(i))
def test_choicefield_grouped_mapping_inner_dict(self):
f = ChoiceField(
choices={
"Numbers": {"1": "One", "2": "Two"},
"Letters": {"3": "A", "4": "B"},
}
)
for i in ("1", "2", "3", "4"):
with self.subTest(i):
self.assertEqual(i, f.clean(i))
def test_choicefield_callable_may_evaluate_to_different_values(self):
choices = []
def choices_as_callable():
return choices
class ChoiceFieldForm(Form):
choicefield = ChoiceField(choices=choices_as_callable)
choices = [("J", "John")]
form = ChoiceFieldForm()
self.assertEqual(choices, list(form.fields["choicefield"].choices))
self.assertEqual(choices, list(form.fields["choicefield"].widget.choices))
choices = [("P", "Paul")]
form = ChoiceFieldForm()
self.assertEqual(choices, list(form.fields["choicefield"].choices))
self.assertEqual(choices, list(form.fields["choicefield"].widget.choices))
def test_choicefield_disabled(self):
f = ChoiceField(choices=[("J", "John"), ("P", "Paul")], disabled=True)
self.assertWidgetRendersTo(
f,
'<select id="id_f" name="f" disabled><option value="J">John</option>'
'<option value="P">Paul</option></select>',
)
def test_choicefield_enumeration(self):
class FirstNames(models.TextChoices):
JOHN = "J", "John"
PAUL = "P", "Paul"
f = ChoiceField(choices=FirstNames)
self.assertEqual(f.choices, FirstNames.choices)
self.assertEqual(f.clean("J"), "J")
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("3")
| ChoiceFieldTest |
python | plotly__plotly.py | plotly/graph_objs/choroplethmapbox/_unselected.py | {
"start": 233,
"end": 2521
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmapbox"
_path_str = "choroplethmapbox.unselected"
_valid_props = {"marker"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.choroplethmapbox.unselected.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Returns
-------
plotly.graph_objs.choroplethmapbox.unselected.Marker
"""
return self["marker"]
@marker.setter
def marker(self, val):
self["marker"] = val
@property
def _prop_descriptions(self):
return """\
marker
:class:`plotly.graph_objects.choroplethmapbox.unselecte
d.Marker` instance or dict with compatible properties
"""
def __init__(self, arg=None, marker=None, **kwargs):
"""
Construct a new Unselected object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.choroplethmapbox.Unselected`
marker
:class:`plotly.graph_objects.choroplethmapbox.unselecte
d.Marker` instance or dict with compatible properties
Returns
-------
Unselected
"""
super().__init__("unselected")
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.choroplethmapbox.Unselected
constructor must be a dict or
an instance of :class:`plotly.graph_objs.choroplethmapbox.Unselected`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("marker", arg, marker)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Unselected |
python | numpy__numpy | numpy/polynomial/tests/test_hermite_e.py | {
"start": 751,
"end": 1073
} | class ____:
def test_hermedomain(self):
assert_equal(herme.hermedomain, [-1, 1])
def test_hermezero(self):
assert_equal(herme.hermezero, [0])
def test_hermeone(self):
assert_equal(herme.hermeone, [1])
def test_hermex(self):
assert_equal(herme.hermex, [0, 1])
| TestConstants |
python | spack__spack | lib/spack/spack/vendor/jinja2/runtime.py | {
"start": 32517,
"end": 33180
} | class ____(Undefined):
"""An undefined that is chainable, where both ``__getattr__`` and
``__getitem__`` return itself rather than raising an
:exc:`UndefinedError`.
>>> foo = ChainableUndefined(name='foo')
>>> str(foo.bar['baz'])
''
>>> foo.bar['baz'] + 42
Traceback (most recent call last):
...
spack.vendor.jinja2.exceptions.UndefinedError: 'foo' is undefined
.. versionadded:: 2.11.0
"""
__slots__ = ()
def __html__(self) -> str:
return str(self)
def __getattr__(self, _: str) -> "ChainableUndefined":
return self
__getitem__ = __getattr__ # type: ignore
| ChainableUndefined |
python | jina-ai__jina | jina/serve/runtimes/servers/http.py | {
"start": 9945,
"end": 11147
} | class ____(FastAPIBaseServer):
"""
:class:`SagemakerHTTPServer` is a FastAPIBaseServer that uses a custom FastAPI app for sagemaker endpoints
"""
@property
def port(self):
"""Get the port for the sagemaker server
:return: Return the port for the sagemaker server, always 8080"""
return 8080
@property
def ports(self):
"""Get the port for the sagemaker server
:return: Return the port for the sagemaker server, always 8080"""
return [8080]
@property
def app(self):
"""Get the sagemaker fastapi app
:return: Return a FastAPI app for the sagemaker container
"""
return self._request_handler._http_fastapi_csp_app(
title=self.title,
description=self.description,
no_crud_endpoints=self.no_crud_endpoints,
no_debug_endpoints=self.no_debug_endpoints,
expose_endpoints=self.expose_endpoints,
expose_graphql_endpoint=self.expose_graphql_endpoint,
tracing=self.tracing,
tracer_provider=self.tracer_provider,
cors=self.cors,
logger=self.logger,
)
| SagemakerHTTPServer |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/callback.py | {
"start": 4801,
"end": 5639
} | class ____(Callback):
"""
Asynchronous callback that runs in the triggerer.
The `callback_callable` can be a Python callable type or a string containing the path to the callable that
can be used to import the callable. It must be a top-level awaitable callable in a module present on the
triggerer.
It will be called with Airflow context and specified kwargs when a deadline is missed.
"""
def __init__(self, callback_callable: Callable | str, kwargs: dict | None = None):
super().__init__(callback_callable=callback_callable, kwargs=kwargs)
@classmethod
def verify_callable(cls, callback: Callable):
if not (inspect.iscoroutinefunction(callback) or hasattr(callback, "__await__")):
raise AttributeError(f"Provided callback {callback} is not awaitable.")
| AsyncCallback |
python | sqlalchemy__sqlalchemy | test/orm/test_collection.py | {
"start": 65073,
"end": 77392
} | class ____(fixtures.MappedTest):
"""test the integration of collections with mapped classes."""
@classmethod
def define_tables(cls, metadata):
Table(
"sometable",
metadata,
Column(
"col1",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("data", String(30)),
)
Table(
"someothertable",
metadata,
Column(
"col1",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("scol1", Integer, ForeignKey("sometable.col1")),
Column("data", String(20)),
)
def test_basic(self):
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class MyList(list):
pass
class Foo:
pass
class Bar:
pass
self.mapper_registry.map_imperatively(
Foo,
sometable,
properties={"bars": relationship(Bar, collection_class=MyList)},
)
self.mapper_registry.map_imperatively(Bar, someothertable)
f = Foo()
assert isinstance(f.bars, MyList)
def test_lazyload(self):
"""test that a 'set' can be used as a collection and can lazyload."""
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class Foo:
pass
class Bar:
pass
self.mapper_registry.map_imperatively(
Foo,
sometable,
properties={"bars": relationship(Bar, collection_class=set)},
)
self.mapper_registry.map_imperatively(Bar, someothertable)
f = Foo()
f.bars.add(Bar())
f.bars.add(Bar())
sess = fixture_session()
sess.add(f)
sess.flush()
sess.expunge_all()
f = sess.get(Foo, f.col1)
assert len(list(f.bars)) == 2
f.bars.clear()
def test_dict(self):
"""test that a 'dict' can be used as a collection and can lazyload."""
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class Foo:
pass
class Bar:
pass
class AppenderDict(dict):
@collection.appender
def set(self, item):
self[id(item)] = item
@collection.remover
def remove(self, item):
if id(item) in self:
del self[id(item)]
self.mapper_registry.map_imperatively(
Foo,
sometable,
properties={
"bars": relationship(Bar, collection_class=AppenderDict)
},
)
self.mapper_registry.map_imperatively(Bar, someothertable)
f = Foo()
f.bars.set(Bar())
f.bars.set(Bar())
sess = fixture_session()
sess.add(f)
sess.flush()
sess.expunge_all()
f = sess.get(Foo, f.col1)
assert len(list(f.bars)) == 2
f.bars.clear()
def test_dict_wrapper(self):
"""test that the supplied 'dict' wrapper can be used as a
collection and can lazyload."""
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class Foo:
pass
class Bar:
def __init__(self, data):
self.data = data
self.mapper_registry.map_imperatively(
Foo,
sometable,
properties={
"bars": relationship(
Bar,
collection_class=collections.column_keyed_dict(
someothertable.c.data
),
)
},
)
self.mapper_registry.map_imperatively(Bar, someothertable)
f = Foo()
col = collections.collection_adapter(f.bars)
col.append_with_event(Bar("a"))
col.append_with_event(Bar("b"))
sess = fixture_session()
sess.add(f)
sess.flush()
sess.expunge_all()
f = sess.get(Foo, f.col1)
assert len(list(f.bars)) == 2
strongref = list(f.bars.values())
existing = {id(b) for b in strongref}
col = collections.collection_adapter(f.bars)
col.append_with_event(Bar("b"))
f.bars["a"] = Bar("a")
sess.flush()
sess.expunge_all()
f = sess.get(Foo, f.col1)
assert len(list(f.bars)) == 2
replaced = {id(b) for b in list(f.bars.values())}
ne_(existing, replaced)
@testing.combinations("direct", "as_callable", argnames="factory_type")
def test_list(self, factory_type):
if factory_type == "as_callable":
# test passing as callable
# this codepath likely was not working for many major
# versions, at least through 1.3
self._test_list(lambda: [])
else:
self._test_list(list)
@testing.combinations("direct", "as_callable", argnames="factory_type")
def test_list_no_setslice(self, factory_type):
class ListLike:
def __init__(self):
self.data = list()
def append(self, item):
self.data.append(item)
def remove(self, item):
self.data.remove(item)
def insert(self, index, item):
self.data.insert(index, item)
def pop(self, index=-1):
return self.data.pop(index)
def extend(self):
assert False
def __len__(self):
return len(self.data)
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
return self.data[key]
def __delitem__(self, key):
del self.data[key]
def __iter__(self):
return iter(self.data)
__hash__ = object.__hash__
def __eq__(self, other):
return self.data == other
def __repr__(self):
return "ListLike(%s)" % repr(self.data)
if factory_type == "as_callable":
# test passing as callable
# this codepath likely was not working for many major
# versions, at least through 1.3
self._test_list(lambda: ListLike())
else:
self._test_list(ListLike)
def _test_list(self, listcls):
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class Parent:
pass
class Child:
pass
self.mapper_registry.map_imperatively(
Parent,
sometable,
properties={
"children": relationship(Child, collection_class=listcls)
},
)
self.mapper_registry.map_imperatively(Child, someothertable)
control = list()
p = Parent()
o = Child()
control.append(o)
p.children.append(o)
assert control == p.children
assert control == list(p.children)
o = [Child(), Child(), Child(), Child()]
control.extend(o)
p.children.extend(o)
assert control == p.children
assert control == list(p.children)
assert control[0] == p.children[0]
assert control[-1] == p.children[-1]
assert control[1:3] == p.children[1:3]
del control[1]
del p.children[1]
assert control == p.children
assert control == list(p.children)
o = [Child()]
control[1:3] = o
p.children[1:3] = o
assert control == p.children
assert control == list(p.children)
o = [Child(), Child(), Child(), Child()]
control[1:3] = o
p.children[1:3] = o
assert control == p.children
assert control == list(p.children)
o = [Child(), Child(), Child(), Child()]
control[-1:-2] = o
p.children[-1:-2] = o
assert control == p.children
assert control == list(p.children)
o = [Child(), Child(), Child(), Child()]
control[4:] = o
p.children[4:] = o
assert control == p.children
assert control == list(p.children)
o = Child()
control.insert(0, o)
p.children.insert(0, o)
assert control == p.children
assert control == list(p.children)
o = Child()
control.insert(3, o)
p.children.insert(3, o)
assert control == p.children
assert control == list(p.children)
o = Child()
control.insert(999, o)
p.children.insert(999, o)
assert control == p.children
assert control == list(p.children)
del control[0:1]
del p.children[0:1]
assert control == p.children
assert control == list(p.children)
del control[1:1]
del p.children[1:1]
assert control == p.children
assert control == list(p.children)
del control[1:3]
del p.children[1:3]
assert control == p.children
assert control == list(p.children)
del control[7:]
del p.children[7:]
assert control == p.children
assert control == list(p.children)
assert control.pop() == p.children.pop()
assert control == p.children
assert control == list(p.children)
assert control.pop(0) == p.children.pop(0)
assert control == p.children
assert control == list(p.children)
assert control.pop(2) == p.children.pop(2)
assert control == p.children
assert control == list(p.children)
o = Child()
control.insert(2, o)
p.children.insert(2, o)
assert control == p.children
assert control == list(p.children)
control.remove(o)
p.children.remove(o)
assert control == p.children
assert control == list(p.children)
# test #7389
if hasattr(p.children, "__iadd__"):
control += control
p.children += p.children
assert control == list(p.children)
control[:] = [o]
p.children[:] = [o]
if hasattr(p.children, "extend"):
control.extend(control)
p.children.extend(p.children)
assert control == list(p.children)
def test_custom(self):
someothertable, sometable = (
self.tables.someothertable,
self.tables.sometable,
)
class Parent:
pass
class Child:
pass
class MyCollection:
def __init__(self):
self.data = []
@collection.appender
def append(self, value):
self.data.append(value)
@collection.remover
def remove(self, value):
self.data.remove(value)
@collection.iterator
def __iter__(self):
return iter(self.data)
self.mapper_registry.map_imperatively(
Parent,
sometable,
properties={
"children": relationship(Child, collection_class=MyCollection)
},
)
self.mapper_registry.map_imperatively(Child, someothertable)
control = list()
p1 = Parent()
o = Child()
control.append(o)
p1.children.append(o)
assert control == list(p1.children)
o = Child()
control.append(o)
p1.children.append(o)
assert control == list(p1.children)
o = Child()
control.append(o)
p1.children.append(o)
assert control == list(p1.children)
sess = fixture_session()
sess.add(p1)
sess.flush()
sess.expunge_all()
p2 = sess.get(Parent, p1.col1)
o = list(p2.children)
assert len(o) == 3
| CustomCollectionsTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.