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 | Netflix__metaflow | metaflow/plugins/storage_executor.py | {
"start": 3871,
"end": 6137
} | class ____(object):
"""Thin wrapper around a ProcessPoolExecutor, or a ThreadPoolExecutor where
the former may be unsafe.
"""
def __init__(self, use_processes=False):
(
processpool_max_workers,
threadpool_max_workers,
) = _compute_executor_max_workers()
if use_processes:
mp_start_method = multiprocessing.get_start_method(allow_none=True)
if mp_start_method == "spawn":
self._executor = ProcessPoolExecutor(
max_workers=processpool_max_workers
)
elif sys.version_info[:2] >= (3, 7):
self._executor = ProcessPoolExecutor(
mp_context=multiprocessing.get_context("spawn"),
max_workers=processpool_max_workers,
)
else:
raise MetaflowException(
msg="Cannot use ProcessPoolExecutor because Python version is older than 3.7 and multiprocess start method has been set to something other than 'spawn'"
)
else:
self._executor = ThreadPoolExecutor(max_workers=threadpool_max_workers)
def warm_up(self):
# warm up at least one process or thread in the pool.
# we don't await future... just let it complete in background
self._executor.submit(_noop_for_executor_warm_up)
def submit(self, *args, **kwargs):
return self._executor.submit(*args, **kwargs)
def handle_executor_exceptions(func):
"""
Decorator for handling errors that come from an Executor. This decorator should
only be used on functions where executor errors are possible. I.e. the function
uses StorageExecutor.
"""
def inner_function(*args, **kwargs):
try:
return func(*args, **kwargs)
except BrokenStorageExecutorError:
# This is fatal. So we bail ASAP.
# We also don't want to log, because KeyboardInterrupt on worker processes
# also take us here, so it's going to be "normal" user operation most of the
# time.
# BrokenExecutor parents both BrokenThreadPool and BrokenProcessPool.
sys.exit(1)
return inner_function
| StorageExecutor |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 107251,
"end": 107443
} | class ____(ExtensionError):
"""Raised when there are problems activating an extension."""
def __init__(self, msg, long_msg=None):
super().__init__(msg, long_msg)
| ActivationError |
python | scikit-learn__scikit-learn | sklearn/ensemble/_weight_boosting.py | {
"start": 10312,
"end": 28532
} | class ____(
_RoutingNotSupportedMixin, ClassifierMixin, BaseWeightBoosting
):
"""An AdaBoost classifier.
An AdaBoost [1]_ classifier is a meta-estimator that begins by fitting a
classifier on the original dataset and then fits additional copies of the
classifier on the same dataset but where the weights of incorrectly
classified instances are adjusted such that subsequent classifiers focus
more on difficult cases.
This class implements the algorithm based on [2]_.
Read more in the :ref:`User Guide <adaboost>`.
.. versionadded:: 0.14
Parameters
----------
estimator : object, default=None
The base estimator from which the boosted ensemble is built.
Support for sample weighting is required, as well as proper
``classes_`` and ``n_classes_`` attributes. If ``None``, then
the base estimator is :class:`~sklearn.tree.DecisionTreeClassifier`
initialized with `max_depth=1`.
.. versionadded:: 1.2
`base_estimator` was renamed to `estimator`.
n_estimators : int, default=50
The maximum number of estimators at which boosting is terminated.
In case of perfect fit, the learning procedure is stopped early.
Values must be in the range `[1, inf)`.
learning_rate : float, default=1.0
Weight applied to each classifier at each boosting iteration. A higher
learning rate increases the contribution of each classifier. There is
a trade-off between the `learning_rate` and `n_estimators` parameters.
Values must be in the range `(0.0, inf)`.
random_state : int, RandomState instance or None, default=None
Controls the random seed given at each `estimator` at each
boosting iteration.
Thus, it is only used when `estimator` exposes a `random_state`.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Attributes
----------
estimator_ : estimator
The base estimator from which the ensemble is grown.
.. versionadded:: 1.2
`base_estimator_` was renamed to `estimator_`.
estimators_ : list of classifiers
The collection of fitted sub-estimators.
classes_ : ndarray of shape (n_classes,)
The classes labels.
n_classes_ : int
The number of classes.
estimator_weights_ : ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ : ndarray of floats
Classification error for each estimator in the boosted
ensemble.
feature_importances_ : ndarray of shape (n_features,)
The impurity-based feature importances if supported by the
``estimator`` (when based on decision trees).
Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values). See
:func:`sklearn.inspection.permutation_importance` as an alternative.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
AdaBoostRegressor : An AdaBoost regressor that begins by fitting a
regressor on the original dataset and then fits additional copies of
the regressor on the same dataset but where the weights of instances
are adjusted according to the error of the current prediction.
GradientBoostingClassifier : GB builds an additive model in a forward
stage-wise fashion. Regression trees are fit on the negative gradient
of the binomial or multinomial deviance loss function. Binary
classification is a special case where only a single regression tree is
induced.
sklearn.tree.DecisionTreeClassifier : A non-parametric supervised learning
method used for classification.
Creates a model that predicts the value of a target variable by
learning simple decision rules inferred from the data features.
References
----------
.. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
on-Line Learning and an Application to Boosting", 1995.
.. [2] :doi:`J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class adaboost."
Statistics and its Interface 2.3 (2009): 349-360.
<10.4310/SII.2009.v2.n3.a8>`
Examples
--------
>>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.96
For a detailed example of using AdaBoost to fit a sequence of DecisionTrees
as weaklearners, please refer to
:ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_multiclass.py`.
For a detailed example of using AdaBoost to fit a non-linearly separable
classification dataset composed of two Gaussian quantiles clusters, please
refer to :ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_twoclass.py`.
"""
def __init__(
self,
estimator=None,
*,
n_estimators=50,
learning_rate=1.0,
random_state=None,
):
super().__init__(
estimator=estimator,
n_estimators=n_estimators,
learning_rate=learning_rate,
random_state=random_state,
)
def _validate_estimator(self):
"""Check the estimator and set the estimator_ attribute."""
super()._validate_estimator(default=DecisionTreeClassifier(max_depth=1))
if not has_fit_parameter(self.estimator_, "sample_weight"):
raise ValueError(
f"{self.estimator.__class__.__name__} doesn't support sample_weight."
)
def _boost(self, iboost, X, y, sample_weight, random_state):
"""Implement a single boost.
Perform a single boost according to the discrete SAMME algorithm and return the
updated sample weights.
Parameters
----------
iboost : int
The index of the current boost iteration.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The target values (class labels).
sample_weight : array-like of shape (n_samples,)
The current sample weights.
random_state : RandomState instance
The RandomState instance used if the base estimator accepts a
`random_state` attribute.
Returns
-------
sample_weight : array-like of shape (n_samples,) or None
The reweighted sample weights.
If None then boosting has terminated early.
estimator_weight : float
The weight for the current boost.
If None then boosting has terminated early.
estimator_error : float
The classification error for the current boost.
If None then boosting has terminated early.
"""
estimator = self._make_estimator(random_state=random_state)
estimator.fit(X, y, sample_weight=sample_weight)
y_predict = estimator.predict(X)
if iboost == 0:
self.classes_ = getattr(estimator, "classes_", None)
self.n_classes_ = len(self.classes_)
# Instances incorrectly classified
incorrect = y_predict != y
# Error fraction
estimator_error = np.mean(np.average(incorrect, weights=sample_weight, axis=0))
# Stop if classification is perfect
if estimator_error <= 0:
return sample_weight, 1.0, 0.0
n_classes = self.n_classes_
# Stop if the error is at least as bad as random guessing
if estimator_error >= 1.0 - (1.0 / n_classes):
self.estimators_.pop(-1)
if len(self.estimators_) == 0:
raise ValueError(
"BaseClassifier in AdaBoostClassifier "
"ensemble is worse than random, ensemble "
"can not be fit."
)
return None, None, None
# Boost weight using multi-class AdaBoost SAMME alg
estimator_weight = self.learning_rate * (
np.log((1.0 - estimator_error) / estimator_error) + np.log(n_classes - 1.0)
)
# Only boost the weights if it will fit again
if not iboost == self.n_estimators - 1:
# Only boost positive weights
sample_weight = np.exp(
np.log(sample_weight)
+ estimator_weight * incorrect * (sample_weight > 0)
)
return sample_weight, estimator_weight, estimator_error
def predict(self, X):
"""Predict classes for X.
The predicted class of an input sample is computed as the weighted mean
prediction of the classifiers in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Returns
-------
y : ndarray of shape (n_samples,)
The predicted classes.
"""
pred = self.decision_function(X)
if self.n_classes_ == 2:
return self.classes_.take(pred > 0, axis=0)
return self.classes_.take(np.argmax(pred, axis=1), axis=0)
def staged_predict(self, X):
"""Return staged predictions for X.
The predicted class of an input sample is computed as the weighted mean
prediction of the classifiers in the ensemble.
This generator method yields the ensemble prediction after each
iteration of boosting and therefore allows monitoring, such as to
determine the prediction on a test set after each boost.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Yields
------
y : generator of ndarray of shape (n_samples,)
The predicted classes.
"""
X = self._check_X(X)
n_classes = self.n_classes_
classes = self.classes_
if n_classes == 2:
for pred in self.staged_decision_function(X):
yield np.array(classes.take(pred > 0, axis=0))
else:
for pred in self.staged_decision_function(X):
yield np.array(classes.take(np.argmax(pred, axis=1), axis=0))
def decision_function(self, X):
"""Compute the decision function of ``X``.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Returns
-------
score : ndarray of shape of (n_samples, k)
The decision function of the input samples. The order of
outputs is the same as that of the :term:`classes_` attribute.
Binary classification is a special cases with ``k == 1``,
otherwise ``k==n_classes``. For binary classification,
values closer to -1 or 1 mean more like the first or second
class in ``classes_``, respectively.
"""
check_is_fitted(self)
X = self._check_X(X)
n_classes = self.n_classes_
classes = self.classes_[:, np.newaxis]
if n_classes == 1:
return np.zeros_like(X, shape=(X.shape[0], 1))
pred = sum(
np.where(
(estimator.predict(X) == classes).T,
w,
-1 / (n_classes - 1) * w,
)
for estimator, w in zip(self.estimators_, self.estimator_weights_)
)
pred /= self.estimator_weights_.sum()
if n_classes == 2:
pred[:, 0] *= -1
return pred.sum(axis=1)
return pred
def staged_decision_function(self, X):
"""Compute decision function of ``X`` for each boosting iteration.
This method allows monitoring (i.e. determine error on testing set)
after each boosting iteration.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Yields
------
score : generator of ndarray of shape (n_samples, k)
The decision function of the input samples. The order of
outputs is the same of that of the :term:`classes_` attribute.
Binary classification is a special cases with ``k == 1``,
otherwise ``k==n_classes``. For binary classification,
values closer to -1 or 1 mean more like the first or second
class in ``classes_``, respectively.
"""
check_is_fitted(self)
X = self._check_X(X)
n_classes = self.n_classes_
classes = self.classes_[:, np.newaxis]
pred = None
norm = 0.0
for weight, estimator in zip(self.estimator_weights_, self.estimators_):
norm += weight
current_pred = np.where(
(estimator.predict(X) == classes).T,
weight,
-1 / (n_classes - 1) * weight,
)
if pred is None:
pred = current_pred
else:
pred += current_pred
if n_classes == 2:
tmp_pred = np.copy(pred)
tmp_pred[:, 0] *= -1
yield (tmp_pred / norm).sum(axis=1)
else:
yield pred / norm
@staticmethod
def _compute_proba_from_decision(decision, n_classes):
"""Compute probabilities from the decision function.
This is based eq. (15) of [1] where:
p(y=c|X) = exp((1 / K-1) f_c(X)) / sum_k(exp((1 / K-1) f_k(X)))
= softmax((1 / K-1) * f(X))
References
----------
.. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost",
2009.
"""
if n_classes == 2:
decision = np.vstack([-decision, decision]).T / 2
else:
decision /= n_classes - 1
return softmax(decision, copy=False)
def predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the weighted mean predicted class probabilities of the classifiers
in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Returns
-------
p : ndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of
outputs is the same of that of the :term:`classes_` attribute.
"""
check_is_fitted(self)
n_classes = self.n_classes_
if n_classes == 1:
return np.ones((_num_samples(X), 1))
decision = self.decision_function(X)
return self._compute_proba_from_decision(decision, n_classes)
def staged_predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the weighted mean predicted class probabilities of the classifiers
in the ensemble.
This generator method yields the ensemble predicted class probabilities
after each iteration of boosting and therefore allows monitoring, such
as to determine the predicted class probabilities on a test set after
each boost.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Yields
------
p : generator of ndarray of shape (n_samples,)
The class probabilities of the input samples. The order of
outputs is the same of that of the :term:`classes_` attribute.
"""
n_classes = self.n_classes_
for decision in self.staged_decision_function(X):
yield self._compute_proba_from_decision(decision, n_classes)
def predict_log_proba(self, X):
"""Predict class log-probabilities for X.
The predicted class log-probabilities of an input sample is computed as
the weighted mean predicted class log-probabilities of the classifiers
in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Returns
-------
p : ndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of
outputs is the same of that of the :term:`classes_` attribute.
"""
return np.log(self.predict_proba(X))
| AdaBoostClassifier |
python | neetcode-gh__leetcode | python/0151-reverse-words-in-a-string.py | {
"start": 0,
"end": 403
} | class ____:
def reverseWords(self, s: str) -> str:
# Remove leading and trailing spaces
s = s.strip()
# Split the string into words
words = s.split()
# Reverse the order of words
words = words[::-1]
# Join the words with a single space
reversed_str = ' '.join(words)
return reversed_str
| Solution |
python | python__mypy | mypy/expandtype.py | {
"start": 4160,
"end": 4869
} | class ____(BoolTypeQuery):
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
def visit_callable_type(self, t: CallableType) -> bool:
return t.is_generic() or super().visit_callable_type(t)
# Share a singleton since this is performance sensitive
has_generic_callable: Final = HasGenericCallable()
T = TypeVar("T", bound=Type)
def freshen_all_functions_type_vars(t: T) -> T:
result: Type
has_generic_callable.reset()
if not t.accept(has_generic_callable):
return t # Fast path to avoid expensive freshening
else:
result = t.accept(FreshenCallableVisitor())
assert isinstance(result, type(t))
return result
| HasGenericCallable |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 1280,
"end": 1312
} | class ____:
x = 3
@final
| Mixin |
python | coleifer__peewee | peewee.py | {
"start": 269118,
"end": 269444
} | class ____(ModelDictCursorWrapper):
constructor = tuple
def process_row(self, row):
columns, converters = self.columns, self.converters
return self.constructor([
(converters[i](row[i]) if converters[i] is not None else row[i])
for i in range(self.ncols)])
| ModelTupleCursorWrapper |
python | getsentry__sentry | tests/sentry/notifications/platform/test_registry.py | {
"start": 474,
"end": 1251
} | class ____(TestCase):
def test_get_all(self) -> None:
providers = provider_registry.get_all()
expected_providers = [
EmailNotificationProvider,
SlackNotificationProvider,
MSTeamsNotificationProvider,
DiscordNotificationProvider,
]
assert len(providers) == len(expected_providers)
for provider in expected_providers:
assert provider in providers
def test_get_available(self) -> None:
providers = provider_registry.get_available()
expected_providers = [EmailNotificationProvider]
assert len(providers) == len(expected_providers)
for provider in expected_providers:
assert provider in providers
| NotificationProviderRegistryTest |
python | numba__numba | numba/stencils/stencil.py | {
"start": 2449,
"end": 39893
} | class ____(object):
"""
A special type to hold stencil information for the IR.
"""
id_counter = 0
def __init__(self, kernel_ir, mode, options):
self.id = type(self).id_counter
type(self).id_counter += 1
self.kernel_ir = kernel_ir
self.mode = mode
self.options = options
self.kws = [] # remember original kws arguments
# stencils only supported for CPU context currently
self._typingctx = registry.cpu_target.typing_context
self._targetctx = registry.cpu_target.target_context
self._install_type(self._typingctx)
self.neighborhood = self.options.get("neighborhood")
self._type_cache = {}
self._lower_me = StencilFuncLowerer(self)
def replace_return_with_setitem(self, blocks, index_vars, out_name):
"""
Find return statements in the IR and replace them with a SetItem
call of the value "returned" by the kernel into the result array.
Returns the block labels that contained return statements.
"""
ret_blocks = []
for label, block in blocks.items():
scope = block.scope
loc = block.loc
new_body = []
for stmt in block.body:
if isinstance(stmt, ir.Return):
ret_blocks.append(label)
# If 1D array then avoid the tuple construction.
if len(index_vars) == 1:
rvar = ir.Var(scope, out_name, loc)
ivar = ir.Var(scope, index_vars[0], loc)
new_body.append(ir.SetItem(rvar, ivar, stmt.value, loc))
else:
# Convert the string names of the index variables into
# ir.Var's.
var_index_vars = []
for one_var in index_vars:
index_var = ir.Var(scope, one_var, loc)
var_index_vars += [index_var]
s_index_var = scope.redefine("stencil_index", loc)
# Build a tuple from the index ir.Var's.
tuple_call = ir.Expr.build_tuple(var_index_vars, loc)
new_body.append(ir.Assign(tuple_call, s_index_var, loc))
rvar = ir.Var(scope, out_name, loc)
# Write the return statements original value into
# the array using the tuple index.
si = ir.SetItem(rvar, s_index_var, stmt.value, loc)
new_body.append(si)
else:
new_body.append(stmt)
block.body = new_body
return ret_blocks
def add_indices_to_kernel(self, kernel, index_names, ndim,
neighborhood, standard_indexed, typemap, calltypes):
"""
Transforms the stencil kernel as specified by the user into one
that includes each dimension's index variable as part of the getitem
calls. So, in effect array[-1] becomes array[index0-1].
"""
const_dict = {}
kernel_consts = []
if config.DEBUG_ARRAY_OPT >= 1:
print("add_indices_to_kernel", ndim, neighborhood)
ir_utils.dump_blocks(kernel.blocks)
if neighborhood is None:
need_to_calc_kernel = True
else:
need_to_calc_kernel = False
if len(neighborhood) != ndim:
raise NumbaValueError("%d dimensional neighborhood specified "
"for %d dimensional input array" %
(len(neighborhood), ndim))
tuple_table = ir_utils.get_tuple_table(kernel.blocks)
relatively_indexed = set()
for block in kernel.blocks.values():
scope = block.scope
loc = block.loc
new_body = []
for stmt in block.body:
if (isinstance(stmt, ir.Assign) and
isinstance(stmt.value, ir.Const)):
if config.DEBUG_ARRAY_OPT >= 1:
print("remembering in const_dict", stmt.target.name,
stmt.value.value)
# Remember consts for use later.
const_dict[stmt.target.name] = stmt.value.value
if ((isinstance(stmt, ir.Assign)
and isinstance(stmt.value, ir.Expr)
and stmt.value.op in ['setitem', 'static_setitem']
and stmt.value.value.name in kernel.arg_names) or
(isinstance(stmt, ir.SetItem)
and stmt.target.name in kernel.arg_names)):
raise NumbaValueError("Assignments to arrays passed to " \
"stencil kernels is not allowed.")
if (isinstance(stmt, ir.Assign)
and isinstance(stmt.value, ir.Expr)
and stmt.value.op in ['getitem', 'static_getitem']
and stmt.value.value.name in kernel.arg_names
and stmt.value.value.name not in standard_indexed):
# We found a getitem from the input array.
if stmt.value.op == 'getitem':
stmt_index_var = stmt.value.index
else:
stmt_index_var = stmt.value.index_var
# allow static_getitem since rewrite passes are applied
#raise ValueError("Unexpected static_getitem in add_indices_to_kernel.")
relatively_indexed.add(stmt.value.value.name)
# Store the index used after looking up the variable in
# the const dictionary.
if need_to_calc_kernel:
assert hasattr(stmt_index_var, 'name')
if stmt_index_var.name in tuple_table:
kernel_consts += [tuple_table[stmt_index_var.name]]
elif stmt_index_var.name in const_dict:
kernel_consts += [const_dict[stmt_index_var.name]]
else:
raise NumbaValueError("stencil kernel index is not "
"constant, 'neighborhood' option required")
if ndim == 1:
# Single dimension always has index variable 'index0'.
# tmpvar will hold the real index and is computed by
# adding the relative offset in stmt.value.index to
# the current absolute location in index0.
index_var = ir.Var(scope, index_names[0], loc)
tmpvar = scope.redefine("stencil_index", loc)
stmt_index_var_typ = typemap[stmt_index_var.name]
# If the array is indexed with a slice then we
# have to add the index value with a call to
# slice_addition.
if isinstance(stmt_index_var_typ, types.misc.SliceType):
sa_var = scope.redefine("slice_addition", loc)
sa_func = numba.njit(slice_addition)
sa_func_typ = types.functions.Dispatcher(sa_func)
typemap[sa_var.name] = sa_func_typ
g_sa = ir.Global("slice_addition", sa_func, loc)
new_body.append(ir.Assign(g_sa, sa_var, loc))
slice_addition_call = ir.Expr.call(sa_var, [stmt_index_var, index_var], (), loc)
calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [stmt_index_var_typ, types.intp], {})
new_body.append(ir.Assign(slice_addition_call, tmpvar, loc))
new_body.append(ir.Assign(
ir.Expr.getitem(stmt.value.value, tmpvar, loc),
stmt.target, loc))
else:
acc_call = ir.Expr.binop(operator.add, stmt_index_var,
index_var, loc)
new_body.append(ir.Assign(acc_call, tmpvar, loc))
new_body.append(ir.Assign(
ir.Expr.getitem(stmt.value.value, tmpvar, loc),
stmt.target, loc))
else:
index_vars = []
sum_results = []
s_index_var = scope.redefine("stencil_index", loc)
const_index_vars = []
ind_stencils = []
stmt_index_var_typ = typemap[stmt_index_var.name]
# Same idea as above but you have to extract
# individual elements out of the tuple indexing
# expression and add the corresponding index variable
# to them and then reconstitute as a tuple that can
# index the array.
for dim in range(ndim):
tmpvar = scope.redefine("const_index", loc)
new_body.append(ir.Assign(ir.Const(dim, loc),
tmpvar, loc))
const_index_vars += [tmpvar]
index_var = ir.Var(scope, index_names[dim], loc)
index_vars += [index_var]
tmpvar = scope.redefine("ind_stencil_index", loc)
ind_stencils += [tmpvar]
getitemvar = scope.redefine("getitem", loc)
getitemcall = ir.Expr.getitem(stmt_index_var,
const_index_vars[dim], loc)
new_body.append(ir.Assign(getitemcall, getitemvar, loc))
# Get the type of this particular part of the index tuple.
if isinstance(stmt_index_var_typ, types.ConstSized):
one_index_typ = stmt_index_var_typ[dim]
else:
one_index_typ = stmt_index_var_typ[:]
# If the array is indexed with a slice then we
# have to add the index value with a call to
# slice_addition.
if isinstance(one_index_typ, types.misc.SliceType):
sa_var = scope.redefine("slice_addition", loc)
sa_func = numba.njit(slice_addition)
sa_func_typ = types.functions.Dispatcher(sa_func)
typemap[sa_var.name] = sa_func_typ
g_sa = ir.Global("slice_addition", sa_func, loc)
new_body.append(ir.Assign(g_sa, sa_var, loc))
slice_addition_call = ir.Expr.call(sa_var, [getitemvar, index_vars[dim]], (), loc)
calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [one_index_typ, types.intp], {})
new_body.append(ir.Assign(slice_addition_call, tmpvar, loc))
else:
acc_call = ir.Expr.binop(operator.add, getitemvar,
index_vars[dim], loc)
new_body.append(ir.Assign(acc_call, tmpvar, loc))
tuple_call = ir.Expr.build_tuple(ind_stencils, loc)
new_body.append(ir.Assign(tuple_call, s_index_var, loc))
new_body.append(ir.Assign(
ir.Expr.getitem(stmt.value.value,s_index_var,loc),
stmt.target,loc))
else:
new_body.append(stmt)
block.body = new_body
if need_to_calc_kernel:
# Find the size of the kernel by finding the maximum absolute value
# index used in the kernel specification.
neighborhood = [[0,0] for _ in range(ndim)]
if len(kernel_consts) == 0:
raise NumbaValueError("Stencil kernel with no accesses to "
"relatively indexed arrays.")
for index in kernel_consts:
if isinstance(index, tuple) or isinstance(index, list):
for i in range(len(index)):
te = index[i]
if isinstance(te, ir.Var) and te.name in const_dict:
te = const_dict[te.name]
if isinstance(te, int):
neighborhood[i][0] = min(neighborhood[i][0], te)
neighborhood[i][1] = max(neighborhood[i][1], te)
else:
raise NumbaValueError(
"stencil kernel index is not constant,"
"'neighborhood' option required")
index_len = len(index)
elif isinstance(index, int):
neighborhood[0][0] = min(neighborhood[0][0], index)
neighborhood[0][1] = max(neighborhood[0][1], index)
index_len = 1
else:
raise NumbaValueError(
"Non-tuple or non-integer used as stencil index.")
if index_len != ndim:
raise NumbaValueError(
"Stencil index does not match array dimensionality.")
return (neighborhood, relatively_indexed)
def get_return_type(self, argtys):
if config.DEBUG_ARRAY_OPT >= 1:
print("get_return_type", argtys)
ir_utils.dump_blocks(self.kernel_ir.blocks)
if not isinstance(argtys[0], types.npytypes.Array):
raise NumbaValueError("The first argument to a stencil kernel must "
"be the primary input array.")
from numba.core import typed_passes
typemap, return_type, calltypes, _ = typed_passes.type_inference_stage(
self._typingctx,
self._targetctx,
self.kernel_ir,
argtys,
None,
{})
if isinstance(return_type, types.npytypes.Array):
raise NumbaValueError(
"Stencil kernel must return a scalar and not a numpy array.")
real_ret = types.npytypes.Array(return_type, argtys[0].ndim,
argtys[0].layout)
return (real_ret, typemap, calltypes)
def _install_type(self, typingctx):
"""Constructs and installs a typing class for a StencilFunc object in
the input typing context.
"""
_ty_cls = type('StencilFuncTyping_' +
str(self.id),
(AbstractTemplate,),
dict(key=self, generic=self._type_me))
typingctx.insert_user_function(self, _ty_cls)
def compile_for_argtys(self, argtys, kwtys, return_type, sigret):
# look in the type cache to find if result array is passed
(_, result, typemap, calltypes) = self._type_cache[argtys]
new_func = self._stencil_wrapper(result, sigret, return_type,
typemap, calltypes, *argtys)
return new_func
def _type_me(self, argtys, kwtys):
"""
Implement AbstractTemplate.generic() for the typing class
built by StencilFunc._install_type().
Return the call-site signature.
"""
if (self.neighborhood is not None and
len(self.neighborhood) != argtys[0].ndim):
raise NumbaValueError("%d dimensional neighborhood specified "
"for %d dimensional input array" %
(len(self.neighborhood), argtys[0].ndim))
argtys_extra = argtys
sig_extra = ""
result = None
if 'out' in kwtys:
argtys_extra += (kwtys['out'],)
sig_extra += ", out=None"
result = kwtys['out']
if 'neighborhood' in kwtys:
argtys_extra += (kwtys['neighborhood'],)
sig_extra += ", neighborhood=None"
# look in the type cache first
if argtys_extra in self._type_cache:
(_sig, _, _, _) = self._type_cache[argtys_extra]
return _sig
(real_ret, typemap, calltypes) = self.get_return_type(argtys)
sig = signature(real_ret, *argtys_extra)
dummy_text = ("def __numba_dummy_stencil({}{}):\n pass\n".format(
",".join(self.kernel_ir.arg_names), sig_extra))
dct = {}
exec(dummy_text, dct)
dummy_func = dct["__numba_dummy_stencil"]
sig = sig.replace(pysig=utils.pysignature(dummy_func))
self._targetctx.insert_func_defn([(self._lower_me, self, argtys_extra)])
self._type_cache[argtys_extra] = (sig, result, typemap, calltypes)
return sig
def copy_ir_with_calltypes(self, ir, calltypes):
"""
Create a copy of a given IR along with its calltype information.
We need a copy of the calltypes because copy propagation applied
to the copied IR will change the calltypes and make subsequent
uses of the original IR invalid.
"""
copy_calltypes = {}
kernel_copy = ir.copy()
kernel_copy.blocks = {}
# For each block...
for (block_label, block) in ir.blocks.items():
new_block = copy.deepcopy(ir.blocks[block_label])
new_block.body = []
# For each statement in each block...
for stmt in ir.blocks[block_label].body:
# Copy the statement to the new copy of the kernel
# and if the original statement is in the original
# calltypes then add the type associated with this
# statement to the calltypes copy.
scopy = copy.deepcopy(stmt)
new_block.body.append(scopy)
if stmt in calltypes:
copy_calltypes[scopy] = calltypes[stmt]
kernel_copy.blocks[block_label] = new_block
return (kernel_copy, copy_calltypes)
def _stencil_wrapper(self, result, sigret, return_type, typemap, calltypes, *args):
# Overall approach:
# 1) Construct a string containing a function definition for the stencil function
# that will execute the stencil kernel. This function definition includes a
# unique stencil function name, the parameters to the stencil kernel, loop
# nests across the dimensions of the input array. Those loop nests use the
# computed stencil kernel size so as not to try to compute elements where
# elements outside the bounds of the input array would be needed.
# 2) The but of the loop nest in this new function is a special sentinel
# assignment.
# 3) Get the IR of this new function.
# 4) Split the block containing the sentinel assignment and remove the sentinel
# assignment. Insert the stencil kernel IR into the stencil function IR
# after label and variable renaming of the stencil kernel IR to prevent
# conflicts with the stencil function IR.
# 5) Compile the combined stencil function IR + stencil kernel IR into existence.
# Copy the kernel so that our changes for this callsite
# won't effect other callsites.
(kernel_copy, copy_calltypes) = self.copy_ir_with_calltypes(
self.kernel_ir, calltypes)
# The stencil kernel body becomes the body of a loop, for which args aren't needed.
ir_utils.remove_args(kernel_copy.blocks)
first_arg = kernel_copy.arg_names[0]
in_cps, out_cps = ir_utils.copy_propagate(kernel_copy.blocks, typemap)
name_var_table = ir_utils.get_name_var_table(kernel_copy.blocks)
ir_utils.apply_copy_propagate(
kernel_copy.blocks,
in_cps,
name_var_table,
typemap,
copy_calltypes)
if "out" in name_var_table:
raise NumbaValueError("Cannot use the reserved word 'out' in stencil kernels.")
sentinel_name = ir_utils.get_unused_var_name("__sentinel__", name_var_table)
if config.DEBUG_ARRAY_OPT >= 1:
print("name_var_table", name_var_table, sentinel_name)
the_array = args[0]
if config.DEBUG_ARRAY_OPT >= 1:
print("_stencil_wrapper", return_type, return_type.dtype,
type(return_type.dtype), args)
ir_utils.dump_blocks(kernel_copy.blocks)
# We generate a Numba function to execute this stencil and here
# create the unique name of this function.
stencil_func_name = "__numba_stencil_%s_%s" % (
hex(id(the_array)).replace("-", "_"),
self.id)
# We will put a loop nest in the generated function for each
# dimension in the input array. Here we create the name for
# the index variable for each dimension. index0, index1, ...
index_vars = []
for i in range(the_array.ndim):
index_var_name = ir_utils.get_unused_var_name("index" + str(i),
name_var_table)
index_vars += [index_var_name]
# Create extra signature for out and neighborhood.
out_name = ir_utils.get_unused_var_name("out", name_var_table)
neighborhood_name = ir_utils.get_unused_var_name("neighborhood",
name_var_table)
sig_extra = ""
if result is not None:
sig_extra += ", {}=None".format(out_name)
if "neighborhood" in dict(self.kws):
sig_extra += ", {}=None".format(neighborhood_name)
# Get a list of the standard indexed array names.
standard_indexed = self.options.get("standard_indexing", [])
if first_arg in standard_indexed:
raise NumbaValueError("The first argument to a stencil kernel must "
"use relative indexing, not standard indexing.")
if len(set(standard_indexed) - set(kernel_copy.arg_names)) != 0:
raise NumbaValueError("Standard indexing requested for an array name "
"not present in the stencil kernel definition.")
# Add index variables to getitems in the IR to transition the accesses
# in the kernel from relative to regular Python indexing. Returns the
# computed size of the stencil kernel and a list of the relatively indexed
# arrays.
kernel_size, relatively_indexed = self.add_indices_to_kernel(
kernel_copy, index_vars, the_array.ndim,
self.neighborhood, standard_indexed, typemap, copy_calltypes)
if self.neighborhood is None:
self.neighborhood = kernel_size
if config.DEBUG_ARRAY_OPT >= 1:
print("After add_indices_to_kernel")
ir_utils.dump_blocks(kernel_copy.blocks)
# The return in the stencil kernel becomes a setitem for that
# particular point in the iteration space.
ret_blocks = self.replace_return_with_setitem(kernel_copy.blocks,
index_vars, out_name)
if config.DEBUG_ARRAY_OPT >= 1:
print("After replace_return_with_setitem", ret_blocks)
ir_utils.dump_blocks(kernel_copy.blocks)
# Start to form the new function to execute the stencil kernel.
func_text = "def {}({}{}):\n".format(stencil_func_name,
",".join(kernel_copy.arg_names), sig_extra)
# Get loop ranges for each dimension, which could be either int
# or variable. In the latter case we'll use the extra neighborhood
# argument to the function.
ranges = []
for i in range(the_array.ndim):
if isinstance(kernel_size[i][0], int):
lo = kernel_size[i][0]
hi = kernel_size[i][1]
else:
lo = "{}[{}][0]".format(neighborhood_name, i)
hi = "{}[{}][1]".format(neighborhood_name, i)
ranges.append((lo, hi))
# If there are more than one relatively indexed arrays, add a call to
# a function that will raise an error if any of the relatively indexed
# arrays are of different size than the first input array.
if len(relatively_indexed) > 1:
func_text += " raise_if_incompatible_array_sizes(" + first_arg
for other_array in relatively_indexed:
if other_array != first_arg:
func_text += "," + other_array
func_text += ")\n"
# Get the shape of the first input array.
shape_name = ir_utils.get_unused_var_name("full_shape", name_var_table)
func_text += " {} = {}.shape\n".format(shape_name, first_arg)
# Converts cval to a string constant
def cval_as_str(cval):
if not np.isfinite(cval):
# See if this is a string-repr numerical const, issue #7286
if np.isnan(cval):
return "np.nan"
elif np.isinf(cval):
if cval < 0:
return "-np.inf"
else:
return "np.inf"
else:
return str(cval)
# If we have to allocate the output array (the out argument was not used)
# then us numpy.full if the user specified a cval stencil decorator option
# or np.zeros if they didn't to allocate the array.
if result is None:
return_type_name = numpy_support.as_dtype(
return_type.dtype).type.__name__
out_init ="{} = np.empty({}, dtype=np.{})\n".format(
out_name, shape_name, return_type_name)
if "cval" in self.options:
cval = self.options["cval"]
cval_ty = typing.typeof.typeof(cval)
if not self._typingctx.can_convert(cval_ty, return_type.dtype):
msg = "cval type does not match stencil return type."
raise NumbaValueError(msg)
else:
cval = 0
func_text += " " + out_init
for dim in range(the_array.ndim):
start_items = [":"] * the_array.ndim
end_items = [":"] * the_array.ndim
start_items[dim] = ":-{}".format(self.neighborhood[dim][0])
end_items[dim] = "-{}:".format(self.neighborhood[dim][1])
func_text += " " + "{}[{}] = {}\n".format(out_name, ",".join(start_items), cval_as_str(cval))
func_text += " " + "{}[{}] = {}\n".format(out_name, ",".join(end_items), cval_as_str(cval))
else: # result is present, if cval is set then use it
if "cval" in self.options:
cval = self.options["cval"]
cval_ty = typing.typeof.typeof(cval)
if not self._typingctx.can_convert(cval_ty, return_type.dtype):
msg = "cval type does not match stencil return type."
raise NumbaValueError(msg)
out_init = "{}[:] = {}\n".format(out_name, cval_as_str(cval))
func_text += " " + out_init
offset = 1
# Add the loop nests to the new function.
for i in range(the_array.ndim):
for j in range(offset):
func_text += " "
# ranges[i][0] is the minimum index used in the i'th dimension
# but minimum's greater than 0 don't preclude any entry in the array.
# So, take the minimum of 0 and the minimum index found in the kernel
# and this will be a negative number (potentially -0). Then, we do
# unary - on that to get the positive offset in this dimension whose
# use is precluded.
# ranges[i][1] is the maximum of 0 and the observed maximum index
# in this dimension because negative maximums would not cause us to
# preclude any entry in the array from being used.
func_text += ("for {} in range(-min(0,{}),"
"{}[{}]-max(0,{})):\n").format(
index_vars[i],
ranges[i][0],
shape_name,
i,
ranges[i][1])
offset += 1
for j in range(offset):
func_text += " "
# Put a sentinel in the code so we can locate it in the IR. We will
# remove this sentinel assignment and replace it with the IR for the
# stencil kernel body.
func_text += "{} = 0\n".format(sentinel_name)
func_text += " return {}\n".format(out_name)
if config.DEBUG_ARRAY_OPT >= 1:
print("new stencil func text")
print(func_text)
# Force the new stencil function into existence.
dct = {}
dct.update(globals())
exec(func_text, dct)
stencil_func = dct[stencil_func_name]
if sigret is not None:
pysig = utils.pysignature(stencil_func)
sigret.pysig = pysig
# Get the IR for the newly created stencil function.
from numba.core import compiler
stencil_ir = compiler.run_frontend(stencil_func)
ir_utils.remove_dels(stencil_ir.blocks)
# rename all variables in stencil_ir afresh
var_table = ir_utils.get_name_var_table(stencil_ir.blocks)
new_var_dict = {}
reserved_names = ([sentinel_name, out_name, neighborhood_name,
shape_name] + kernel_copy.arg_names + index_vars)
for name, var in var_table.items():
if not name in reserved_names:
assert isinstance(var, ir.Var)
new_var = var.scope.redefine(var.name, var.loc)
new_var_dict[name] = new_var.name
ir_utils.replace_var_names(stencil_ir.blocks, new_var_dict)
stencil_stub_last_label = max(stencil_ir.blocks.keys()) + 1
# Shift labels in the kernel copy so they are guaranteed unique
# and don't conflict with any labels in the stencil_ir.
kernel_copy.blocks = ir_utils.add_offset_to_labels(
kernel_copy.blocks, stencil_stub_last_label)
new_label = max(kernel_copy.blocks.keys()) + 1
# Adjust ret_blocks to account for addition of the offset.
ret_blocks = [x + stencil_stub_last_label for x in ret_blocks]
if config.DEBUG_ARRAY_OPT >= 1:
print("ret_blocks w/ offsets", ret_blocks, stencil_stub_last_label)
print("before replace sentinel stencil_ir")
ir_utils.dump_blocks(stencil_ir.blocks)
print("before replace sentinel kernel_copy")
ir_utils.dump_blocks(kernel_copy.blocks)
# Search all the block in the stencil outline for the sentinel.
for label, block in stencil_ir.blocks.items():
for i, inst in enumerate(block.body):
if (isinstance( inst, ir.Assign) and
inst.target.name == sentinel_name):
# We found the sentinel assignment.
loc = inst.loc
scope = block.scope
# split block across __sentinel__
# A new block is allocated for the statements prior to the
# sentinel but the new block maintains the current block
# label.
prev_block = ir.Block(scope, loc)
prev_block.body = block.body[:i]
# The current block is used for statements after sentinel.
block.body = block.body[i + 1:]
# But the current block gets a new label.
body_first_label = min(kernel_copy.blocks.keys())
# The previous block jumps to the minimum labelled block of
# the parfor body.
prev_block.append(ir.Jump(body_first_label, loc))
# Add all the parfor loop body blocks to the gufunc
# function's IR.
for (l, b) in kernel_copy.blocks.items():
stencil_ir.blocks[l] = b
stencil_ir.blocks[new_label] = block
stencil_ir.blocks[label] = prev_block
# Add a jump from all the blocks that previously contained
# a return in the stencil kernel to the block
# containing statements after the sentinel.
for ret_block in ret_blocks:
stencil_ir.blocks[ret_block].append(
ir.Jump(new_label, loc))
break
else:
continue
break
stencil_ir.blocks = ir_utils.rename_labels(stencil_ir.blocks)
ir_utils.remove_dels(stencil_ir.blocks)
assert(isinstance(the_array, types.Type))
array_types = args
new_stencil_param_types = list(array_types)
if config.DEBUG_ARRAY_OPT >= 1:
print("new_stencil_param_types", new_stencil_param_types)
ir_utils.dump_blocks(stencil_ir.blocks)
# Compile the combined stencil function with the replaced loop
# body in it.
ir_utils.fixup_var_define_in_scope(stencil_ir.blocks)
new_func = compiler.compile_ir(
self._typingctx,
self._targetctx,
stencil_ir,
new_stencil_param_types,
None,
compiler.DEFAULT_FLAGS,
{})
return new_func
def __call__(self, *args, **kwargs):
self._typingctx.refresh()
if (self.neighborhood is not None and
len(self.neighborhood) != args[0].ndim):
raise NumbaValueError("{} dimensional neighborhood specified for "
"{} dimensional input array".format(
len(self.neighborhood), args[0].ndim))
if 'out' in kwargs:
result = kwargs['out']
rdtype = result.dtype
rttype = numpy_support.from_dtype(rdtype)
result_type = types.npytypes.Array(rttype, result.ndim,
numpy_support.map_layout(result))
array_types = tuple([typing.typeof.typeof(x) for x in args])
array_types_full = tuple([typing.typeof.typeof(x) for x in args] +
[result_type])
else:
result = None
array_types = tuple([typing.typeof.typeof(x) for x in args])
array_types_full = array_types
if config.DEBUG_ARRAY_OPT >= 1:
print("__call__", array_types, args, kwargs)
(real_ret, typemap, calltypes) = self.get_return_type(array_types)
new_func = self._stencil_wrapper(result, None, real_ret, typemap,
calltypes, *array_types_full)
if result is None:
return new_func.entry_point(*args)
else:
return new_func.entry_point(*(args+(result,)))
def stencil(func_or_mode='constant', **options):
# called on function without specifying mode style
if not isinstance(func_or_mode, str):
mode = 'constant' # default style
func = func_or_mode
else:
mode = func_or_mode
func = None
for option in options:
if option not in ["cval", "standard_indexing", "neighborhood"]:
raise NumbaValueError("Unknown stencil option " + option)
wrapper = _stencil(mode, options)
if func is not None:
return wrapper(func)
return wrapper
def _stencil(mode, options):
if mode != 'constant':
raise NumbaValueError("Unsupported mode style " + mode)
def decorated(func):
from numba.core import compiler
kernel_ir = compiler.run_frontend(func)
return StencilFunc(kernel_ir, mode, options)
return decorated
@lower_builtin(stencil)
def stencil_dummy_lower(context, builder, sig, args):
"lowering for dummy stencil calls"
return lir.Constant(lir.IntType(types.intp.bitwidth), 0)
| StencilFunc |
python | fastai__fastai | fastai/layers.py | {
"start": 24885,
"end": 25302
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _mish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _mish_jit_bwd(x, grad_output)
# %% ../nbs/01_layers.ipynb 163
def mish(x, inplace=False): return F.mish(x, inplace=inplace)
# %% ../nbs/01_layers.ipynb 164
| MishJitAutoFn |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/cafeteria.py | {
"start": 782,
"end": 2137
} | class ____:
def __init__(
self,
dispenser: BeverageDispenser[Juice],
trash_can: TrashCan[Biodegradable],
):
"""Initialize..."""
################################################ exact types
juice_dispenser = BeverageDispenser(Juice())
bio_can: TrashCan[Biodegradable] = TrashCan()
arnold_hall = Cafeteria(juice_dispenser, bio_can)
################################################ covariant dispenser
orange_juice_dispenser = BeverageDispenser(OrangeJuice())
arnold_hall = Cafeteria(orange_juice_dispenser, bio_can)
################################################ non-covariant dispenser
beverage_dispenser = BeverageDispenser(Beverage())
## Argument 1 to "Cafeteria" has
## incompatible type "BeverageDispenser[Beverage]"
## expected "BeverageDispenser[Juice]"
# arnold_hall = Cafeteria(beverage_dispenser, bio_can)
################################################ contravariant trash
trash_can: TrashCan[Garbage] = TrashCan()
arnold_hall = Cafeteria(juice_dispenser, trash_can)
################################################ non-contravariant trash
compost_can: TrashCan[Compostable] = TrashCan()
## Argument 2 to "Cafeteria" has
## incompatible type "TrashCan[Compostable]"
## expected "TrashCan[Biodegradable]"
# arnold_hall = Cafeteria(juice_dispenser, compost_can)
| Cafeteria |
python | tornadoweb__tornado | demos/blog/blog.py | {
"start": 8280,
"end": 9354
} | class ____(BaseHandler):
async def get(self):
# If there are no authors, redirect to the account creation page.
if not await self.any_author_exists():
self.redirect("/auth/create")
else:
self.render("login.html", error=None)
async def post(self):
try:
author = await self.queryone(
"SELECT * FROM authors WHERE email = %s", self.get_argument("email")
)
except NoResultError:
self.render("login.html", error="email not found")
return
password_equal = await tornado.ioloop.IOLoop.current().run_in_executor(
None,
bcrypt.checkpw,
tornado.escape.utf8(self.get_argument("password")),
tornado.escape.utf8(author.hashed_password),
)
if password_equal:
self.set_signed_cookie("blogdemo_user", str(author.id))
self.redirect(self.get_argument("next", "/"))
else:
self.render("login.html", error="incorrect password")
| AuthLoginHandler |
python | scipy__scipy | scipy/optimize/_minimize.py | {
"start": 47866,
"end": 48427
} | class ____:
# Patches a callback that accepts an intermediate_result
def __init__(self, callback, i_fixed, x_fixed):
self.callback = callback
self.i_fixed = i_fixed
self.x_fixed = x_fixed
def __call__(self, intermediate_result):
x_in = intermediate_result.x
x_out = np.zeros_like(self.i_fixed, dtype=x_in.dtype)
x_out[self.i_fixed] = self.x_fixed
x_out[~self.i_fixed] = x_in
intermediate_result.x = x_out
return self.callback(intermediate_result)
| _Patch_Callback_Equal_Variables |
python | numpy__numpy | numpy/_core/tests/test_ufunc.py | {
"start": 6389,
"end": 116310
} | class ____:
def test_pickle(self):
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_(pickle.loads(pickle.dumps(np.sin,
protocol=proto)) is np.sin)
# Check that ufunc not defined in the top level numpy namespace
# such as numpy._core._rational_tests.test_add can also be pickled
res = pickle.loads(pickle.dumps(_rational_tests.test_add,
protocol=proto))
assert_(res is _rational_tests.test_add)
def test_pickle_withstring(self):
astring = (b"cnumpy.core\n_ufunc_reconstruct\np0\n"
b"(S'numpy._core.umath'\np1\nS'cos'\np2\ntp3\nRp4\n.")
assert_(pickle.loads(astring) is np.cos)
@pytest.mark.skipif(IS_PYPY, reason="'is' check does not work on PyPy")
def test_pickle_name_is_qualname(self):
# This tests that a simplification of our ufunc pickle code will
# lead to allowing qualnames as names. Future ufuncs should
# possible add a specific qualname, or a hook into pickling instead
# (dask+numba may benefit).
_pickleable_module_global.ufunc = umt._pickleable_module_global_ufunc
obj = pickle.loads(pickle.dumps(_pickleable_module_global.ufunc))
assert obj is umt._pickleable_module_global_ufunc
def test_reduceat_shifting_sum(self):
L = 6
x = np.arange(L)
idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel()
assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7])
def test_all_ufunc(self):
"""Try to check presence and results of all ufuncs.
The list of ufuncs comes from generate_umath.py and is as follows:
===== ==== ============= =============== ========================
done args function types notes
===== ==== ============= =============== ========================
n 1 conjugate nums + O
n 1 absolute nums + O complex -> real
n 1 negative nums + O
n 1 sign nums + O -> int
n 1 invert bool + ints + O flts raise an error
n 1 degrees real + M cmplx raise an error
n 1 radians real + M cmplx raise an error
n 1 arccos flts + M
n 1 arccosh flts + M
n 1 arcsin flts + M
n 1 arcsinh flts + M
n 1 arctan flts + M
n 1 arctanh flts + M
n 1 cos flts + M
n 1 sin flts + M
n 1 tan flts + M
n 1 cosh flts + M
n 1 sinh flts + M
n 1 tanh flts + M
n 1 exp flts + M
n 1 expm1 flts + M
n 1 log flts + M
n 1 log10 flts + M
n 1 log1p flts + M
n 1 sqrt flts + M real x < 0 raises error
n 1 ceil real + M
n 1 trunc real + M
n 1 floor real + M
n 1 fabs real + M
n 1 rint flts + M
n 1 isnan flts -> bool
n 1 isinf flts -> bool
n 1 isfinite flts -> bool
n 1 signbit real -> bool
n 1 modf real -> (frac, int)
n 1 logical_not bool + nums + M -> bool
n 2 left_shift ints + O flts raise an error
n 2 right_shift ints + O flts raise an error
n 2 add bool + nums + O boolean + is ||
n 2 subtract bool + nums + O boolean - is ^
n 2 multiply bool + nums + O boolean * is &
n 2 divide nums + O
n 2 floor_divide nums + O
n 2 true_divide nums + O bBhH -> f, iIlLqQ -> d
n 2 fmod nums + M
n 2 power nums + O
n 2 greater bool + nums + O -> bool
n 2 greater_equal bool + nums + O -> bool
n 2 less bool + nums + O -> bool
n 2 less_equal bool + nums + O -> bool
n 2 equal bool + nums + O -> bool
n 2 not_equal bool + nums + O -> bool
n 2 logical_and bool + nums + M -> bool
n 2 logical_or bool + nums + M -> bool
n 2 logical_xor bool + nums + M -> bool
n 2 maximum bool + nums + O
n 2 minimum bool + nums + O
n 2 bitwise_and bool + ints + O flts raise an error
n 2 bitwise_or bool + ints + O flts raise an error
n 2 bitwise_xor bool + ints + O flts raise an error
n 2 arctan2 real + M
n 2 remainder ints + real + O
n 2 hypot real + M
===== ==== ============= =============== ========================
Types other than those listed will be accepted, but they are cast to
the smallest compatible type for which the function is defined. The
casting rules are:
bool -> int8 -> float32
ints -> double
"""
pass
# from include/numpy/ufuncobject.h
size_inferred = 2
can_ignore = 4
def test_signature0(self):
# the arguments to test_signature are: nin, nout, core_signature
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(i),(i)->()")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 1, 0))
assert_equal(ixs, (0, 0))
assert_equal(flags, (self.size_inferred,))
assert_equal(sizes, (-1,))
def test_signature1(self):
# empty core signature; treat as plain ufunc (with trivial core)
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(),()->()")
assert_equal(enabled, 0)
assert_equal(num_dims, (0, 0, 0))
assert_equal(ixs, ())
assert_equal(flags, ())
assert_equal(sizes, ())
def test_signature2(self):
# more complicated names for variables
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(i1,i2),(J_1)->(_kAB)")
assert_equal(enabled, 1)
assert_equal(num_dims, (2, 1, 1))
assert_equal(ixs, (0, 1, 2, 3))
assert_equal(flags, (self.size_inferred,) * 4)
assert_equal(sizes, (-1, -1, -1, -1))
def test_signature3(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(i1, i12), (J_1)->(i12, i2)")
assert_equal(enabled, 1)
assert_equal(num_dims, (2, 1, 2))
assert_equal(ixs, (0, 1, 2, 1, 3))
assert_equal(flags, (self.size_inferred,) * 4)
assert_equal(sizes, (-1, -1, -1, -1))
def test_signature4(self):
# matrix_multiply signature from _umath_tests
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(n,k),(k,m)->(n,m)")
assert_equal(enabled, 1)
assert_equal(num_dims, (2, 2, 2))
assert_equal(ixs, (0, 1, 1, 2, 0, 2))
assert_equal(flags, (self.size_inferred,) * 3)
assert_equal(sizes, (-1, -1, -1))
def test_signature5(self):
# matmul signature from _umath_tests
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
2, 1, "(n?,k),(k,m?)->(n?,m?)")
assert_equal(enabled, 1)
assert_equal(num_dims, (2, 2, 2))
assert_equal(ixs, (0, 1, 1, 2, 0, 2))
assert_equal(flags, (self.size_inferred | self.can_ignore,
self.size_inferred,
self.size_inferred | self.can_ignore))
assert_equal(sizes, (-1, -1, -1))
def test_signature6(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
1, 1, "(3)->()")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 0))
assert_equal(ixs, (0,))
assert_equal(flags, (0,))
assert_equal(sizes, (3,))
def test_signature7(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
3, 1, "(3),(03,3),(n)->(9)")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 2, 1, 1))
assert_equal(ixs, (0, 0, 0, 1, 2))
assert_equal(flags, (0, self.size_inferred, 0))
assert_equal(sizes, (3, -1, 9))
def test_signature8(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
3, 1, "(3?),(3?,3?),(n)->(9)")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 2, 1, 1))
assert_equal(ixs, (0, 0, 0, 1, 2))
assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
assert_equal(sizes, (3, -1, 9))
def test_signature9(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
1, 1, "( 3) -> ( )")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 0))
assert_equal(ixs, (0,))
assert_equal(flags, (0,))
assert_equal(sizes, (3,))
def test_signature10(self):
enabled, num_dims, ixs, flags, sizes = umt.test_signature(
3, 1, "( 3? ) , (3? , 3?) ,(n )-> ( 9)")
assert_equal(enabled, 1)
assert_equal(num_dims, (1, 2, 1, 1))
assert_equal(ixs, (0, 0, 0, 1, 2))
assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
assert_equal(sizes, (3, -1, 9))
def test_signature_failure_extra_parenthesis(self):
with assert_raises(ValueError):
umt.test_signature(2, 1, "((i)),(i)->()")
def test_signature_failure_mismatching_parenthesis(self):
with assert_raises(ValueError):
umt.test_signature(2, 1, "(i),)i(->()")
def test_signature_failure_signature_missing_input_arg(self):
with assert_raises(ValueError):
umt.test_signature(2, 1, "(i),->()")
def test_signature_failure_signature_missing_output_arg(self):
with assert_raises(ValueError):
umt.test_signature(2, 2, "(i),(i)->()")
def test_get_signature(self):
assert_equal(np.vecdot.signature, "(n),(n)->()")
def test_forced_sig(self):
a = 0.5 * np.arange(3, dtype='f8')
assert_equal(np.add(a, 0.5), [0.5, 1, 1.5])
with assert_raises(TypeError):
np.add(a, 0.5, sig='i', casting='unsafe')
assert_equal(np.add(a, 0.5, sig='ii->i', casting='unsafe'), [0, 0, 1])
with assert_raises(TypeError):
np.add(a, 0.5, sig=('i4',), casting='unsafe')
assert_equal(np.add(a, 0.5, sig=('i4', 'i4', 'i4'),
casting='unsafe'), [0, 0, 1])
b = np.zeros((3,), dtype='f8')
np.add(a, 0.5, out=b)
assert_equal(b, [0.5, 1, 1.5])
b[:] = 0
with assert_raises(TypeError):
np.add(a, 0.5, sig='i', out=b, casting='unsafe')
assert_equal(b, [0, 0, 0])
np.add(a, 0.5, sig='ii->i', out=b, casting='unsafe')
assert_equal(b, [0, 0, 1])
b[:] = 0
with assert_raises(TypeError):
np.add(a, 0.5, sig=('i4',), out=b, casting='unsafe')
assert_equal(b, [0, 0, 0])
np.add(a, 0.5, sig=('i4', 'i4', 'i4'), out=b, casting='unsafe')
assert_equal(b, [0, 0, 1])
def test_signature_all_None(self):
# signature all None, is an acceptable alternative (since 1.21)
# to not providing a signature.
res1 = np.add([3], [4], sig=(None, None, None))
res2 = np.add([3], [4])
assert_array_equal(res1, res2)
res1 = np.maximum([3], [4], sig=(None, None, None))
res2 = np.maximum([3], [4])
assert_array_equal(res1, res2)
with pytest.raises(TypeError):
# special case, that would be deprecated anyway, so errors:
np.add(3, 4, signature=(None,))
def test_signature_dtype_type(self):
# Since that will be the normal behaviour (past NumPy 1.21)
# we do support the types already:
float_dtype = type(np.dtype(np.float64))
np.add(3, 4, signature=(float_dtype, float_dtype, None))
@pytest.mark.parametrize("get_kwarg", [
param(lambda dt: {"dtype": dt}, id="dtype"),
param(lambda dt: {"signature": (dt, None, None)}, id="signature")])
def test_signature_dtype_instances_allowed(self, get_kwarg):
# We allow certain dtype instances when there is a clear singleton
# and the given one is equivalent; mainly for backcompat.
int64 = np.dtype("int64")
int64_2 = pickle.loads(pickle.dumps(int64))
# Relies on pickling behavior, if assert fails just remove test...
assert int64 is not int64_2
assert np.add(1, 2, **get_kwarg(int64_2)).dtype == int64
td = np.timedelta64(2, "s")
assert np.add(td, td, **get_kwarg("m8")).dtype == "m8[s]"
msg = "The `dtype` and `signature` arguments to ufuncs"
with pytest.raises(TypeError, match=msg):
np.add(3, 5, **get_kwarg(np.dtype("int64").newbyteorder()))
with pytest.raises(TypeError, match=msg):
np.add(3, 5, **get_kwarg(np.dtype("m8[ns]")))
with pytest.raises(TypeError, match=msg):
np.add(3, 5, **get_kwarg("m8[ns]"))
@pytest.mark.parametrize("casting", ["unsafe", "same_kind", "safe"])
def test_partial_signature_mismatch(self, casting):
# If the second argument matches already, no need to specify it:
res = np.ldexp(np.float32(1.), np.int_(2), dtype="d")
assert res.dtype == "d"
res = np.ldexp(np.float32(1.), np.int_(2), signature=(None, None, "d"))
assert res.dtype == "d"
# ldexp only has a loop for long input as second argument, overriding
# the output cannot help with that (no matter the casting)
with pytest.raises(TypeError):
np.ldexp(1., np.uint64(3), dtype="d")
with pytest.raises(TypeError):
np.ldexp(1., np.uint64(3), signature=(None, None, "d"))
def test_partial_signature_mismatch_with_cache(self):
with pytest.raises(TypeError):
np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
# Ensure e,d->None is in the dispatching cache (double loop)
np.add(np.float16(1), np.float64(2))
# The error must still be raised:
with pytest.raises(TypeError):
np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
def test_use_output_signature_for_all_arguments(self):
# Test that providing only `dtype=` or `signature=(None, None, dtype)`
# is sufficient if falling back to a homogeneous signature works.
# In this case, the `intp, intp -> intp` loop is chosen.
res = np.power(1.5, 2.8, dtype=np.intp, casting="unsafe")
assert res == 1 # the cast happens first.
res = np.power(1.5, 2.8, signature=(None, None, np.intp),
casting="unsafe")
assert res == 1
with pytest.raises(TypeError):
# the unsafe casting would normally cause errors though:
np.power(1.5, 2.8, dtype=np.intp)
def test_signature_errors(self):
with pytest.raises(TypeError,
match="the signature object to ufunc must be a string or"):
np.add(3, 4, signature=123.) # neither a string nor a tuple
with pytest.raises(ValueError):
# bad symbols that do not translate to dtypes
np.add(3, 4, signature="%^->#")
with pytest.raises(ValueError):
np.add(3, 4, signature=b"ii-i") # incomplete and byte string
with pytest.raises(ValueError):
np.add(3, 4, signature="ii>i") # incomplete string
with pytest.raises(ValueError):
np.add(3, 4, signature=(None, "f8")) # bad length
with pytest.raises(UnicodeDecodeError):
np.add(3, 4, signature=b"\xff\xff->i")
def test_forced_dtype_times(self):
# Signatures only set the type numbers (not the actual loop dtypes)
# so using `M` in a signature/dtype should generally work:
a = np.array(['2010-01-02', '1999-03-14', '1833-03'], dtype='>M8[D]')
np.maximum(a, a, dtype="M")
np.maximum.reduce(a, dtype="M")
arr = np.arange(10, dtype="m8[s]")
np.add(arr, arr, dtype="m")
np.maximum(arr, arr, dtype="m")
@pytest.mark.parametrize("ufunc", [np.add, np.sqrt])
def test_cast_safety(self, ufunc):
"""Basic test for the safest casts, because ufuncs inner loops can
indicate a cast-safety as well (which is normally always "no").
"""
def call_ufunc(arr, **kwargs):
return ufunc(*(arr,) * ufunc.nin, **kwargs)
arr = np.array([1., 2., 3.], dtype=np.float32)
arr_bs = arr.astype(arr.dtype.newbyteorder())
expected = call_ufunc(arr)
# Normally, a "no" cast:
res = call_ufunc(arr, casting="no")
assert_array_equal(expected, res)
# Byte-swapping is not allowed with "no" though:
with pytest.raises(TypeError):
call_ufunc(arr_bs, casting="no")
# But is allowed with "equiv":
res = call_ufunc(arr_bs, casting="equiv")
assert_array_equal(expected, res)
# Casting to float64 is safe, but not equiv:
with pytest.raises(TypeError):
call_ufunc(arr_bs, dtype=np.float64, casting="equiv")
# but it is safe cast:
res = call_ufunc(arr_bs, dtype=np.float64, casting="safe")
expected = call_ufunc(arr.astype(np.float64)) # upcast
assert_array_equal(expected, res)
@pytest.mark.parametrize("ufunc", [np.add, np.equal])
def test_cast_safety_scalar(self, ufunc):
# We test add and equal, because equal has special scalar handling
# Note that the "equiv" casting behavior should maybe be considered
# a current implementation detail.
with pytest.raises(TypeError):
# this picks an integer loop, which is not safe
ufunc(3., 4., dtype=int, casting="safe")
with pytest.raises(TypeError):
# We accept python float as float64 but not float32 for equiv.
ufunc(3., 4., dtype="float32", casting="equiv")
# Special case for object and equal (note that equiv implies safe)
ufunc(3, 4, dtype=object, casting="equiv")
# Picks a double loop for both, first is equiv, second safe:
ufunc(np.array([3.]), 3., casting="equiv")
ufunc(np.array([3.]), 3, casting="safe")
ufunc(np.array([3]), 3, casting="equiv")
def test_cast_safety_scalar_special(self):
# We allow this (and it succeeds) via object, although the equiv
# part may not be important.
np.equal(np.array([3]), 2**300, casting="equiv")
def test_true_divide(self):
a = np.array(10)
b = np.array(20)
tgt = np.array(0.5)
for tc in 'bhilqBHILQefdgFDG':
dt = np.dtype(tc)
aa = a.astype(dt)
bb = b.astype(dt)
# Check result value and dtype.
for x, y in itertools.product([aa, -aa], [bb, -bb]):
# Check with no output type specified
if tc in 'FDG':
tgt = complex(x) / complex(y)
else:
tgt = float(x) / float(y)
res = np.true_divide(x, y)
rtol = max(np.finfo(res).resolution, 1e-15)
assert_allclose(res, tgt, rtol=rtol)
if tc in 'bhilqBHILQ':
assert_(res.dtype.name == 'float64')
else:
assert_(res.dtype.name == dt.name)
# Check with output type specified. This also checks for the
# incorrect casts in issue gh-3484 because the unary '-' does
# not change types, even for unsigned types, Hence casts in the
# ufunc from signed to unsigned and vice versa will lead to
# errors in the values.
for tcout in 'bhilqBHILQ':
dtout = np.dtype(tcout)
assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
for tcout in 'efdg':
dtout = np.dtype(tcout)
if tc in 'FDG':
# Casting complex to float is not allowed
assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
else:
tgt = float(x) / float(y)
rtol = max(np.finfo(dtout).resolution, 1e-15)
# The value of tiny for double double is NaN
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
if not np.isnan(np.finfo(dtout).tiny):
atol = max(np.finfo(dtout).tiny, 3e-308)
else:
atol = 3e-308
# Some test values result in invalid for float16
# and the cast to it may overflow to inf.
with np.errstate(invalid='ignore', over='ignore'):
res = np.true_divide(x, y, dtype=dtout)
if not np.isfinite(res) and tcout == 'e':
continue
assert_allclose(res, tgt, rtol=rtol, atol=atol)
assert_(res.dtype.name == dtout.name)
for tcout in 'FDG':
dtout = np.dtype(tcout)
tgt = complex(x) / complex(y)
rtol = max(np.finfo(dtout).resolution, 1e-15)
# The value of tiny for double double is NaN
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
if not np.isnan(np.finfo(dtout).tiny):
atol = max(np.finfo(dtout).tiny, 3e-308)
else:
atol = 3e-308
res = np.true_divide(x, y, dtype=dtout)
if not np.isfinite(res):
continue
assert_allclose(res, tgt, rtol=rtol, atol=atol)
assert_(res.dtype.name == dtout.name)
# Check booleans
a = np.ones((), dtype=np.bool)
res = np.true_divide(a, a)
assert_(res == 1.0)
assert_(res.dtype.name == 'float64')
res = np.true_divide(~a, a)
assert_(res == 0.0)
assert_(res.dtype.name == 'float64')
def test_sum_stability(self):
a = np.ones(500, dtype=np.float32)
assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 4)
a = np.ones(500, dtype=np.float64)
assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 13)
@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
def test_sum(self):
for dt in (int, np.float16, np.float32, np.float64, np.longdouble):
for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
128, 1024, 1235):
# warning if sum overflows, which it does in float16
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", RuntimeWarning)
tgt = dt(v * (v + 1) / 2)
overflow = not np.isfinite(tgt)
assert_equal(len(w), 1 * overflow)
d = np.arange(1, v + 1, dtype=dt)
assert_almost_equal(np.sum(d), tgt)
assert_equal(len(w), 2 * overflow)
assert_almost_equal(np.sum(d[::-1]), tgt)
assert_equal(len(w), 3 * overflow)
d = np.ones(500, dtype=dt)
assert_almost_equal(np.sum(d[::2]), 250.)
assert_almost_equal(np.sum(d[1::2]), 250.)
assert_almost_equal(np.sum(d[::3]), 167.)
assert_almost_equal(np.sum(d[1::3]), 167.)
assert_almost_equal(np.sum(d[::-2]), 250.)
assert_almost_equal(np.sum(d[-1::-2]), 250.)
assert_almost_equal(np.sum(d[::-3]), 167.)
assert_almost_equal(np.sum(d[-1::-3]), 167.)
# sum with first reduction entry != 0
d = np.ones((1,), dtype=dt)
d += d
assert_almost_equal(d, 2.)
def test_sum_complex(self):
for dt in (np.complex64, np.complex128, np.clongdouble):
for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
128, 1024, 1235):
tgt = dt(v * (v + 1) / 2) - dt((v * (v + 1) / 2) * 1j)
d = np.empty(v, dtype=dt)
d.real = np.arange(1, v + 1)
d.imag = -np.arange(1, v + 1)
assert_almost_equal(np.sum(d), tgt)
assert_almost_equal(np.sum(d[::-1]), tgt)
d = np.ones(500, dtype=dt) + 1j
assert_almost_equal(np.sum(d[::2]), 250. + 250j)
assert_almost_equal(np.sum(d[1::2]), 250. + 250j)
assert_almost_equal(np.sum(d[::3]), 167. + 167j)
assert_almost_equal(np.sum(d[1::3]), 167. + 167j)
assert_almost_equal(np.sum(d[::-2]), 250. + 250j)
assert_almost_equal(np.sum(d[-1::-2]), 250. + 250j)
assert_almost_equal(np.sum(d[::-3]), 167. + 167j)
assert_almost_equal(np.sum(d[-1::-3]), 167. + 167j)
# sum with first reduction entry != 0
d = np.ones((1,), dtype=dt) + 1j
d += d
assert_almost_equal(d, 2. + 2j)
def test_sum_initial(self):
# Integer, single axis
assert_equal(np.sum([3], initial=2), 5)
# Floating point
assert_almost_equal(np.sum([0.2], initial=0.1), 0.3)
# Multiple non-adjacent axes
assert_equal(np.sum(np.ones((2, 3, 5), dtype=np.int64), axis=(0, 2), initial=2),
[12, 12, 12])
def test_sum_where(self):
# More extensive tests done in test_reduction_with_where.
assert_equal(np.sum([[1., 2.], [3., 4.]], where=[True, False]), 4.)
assert_equal(np.sum([[1., 2.], [3., 4.]], axis=0, initial=5.,
where=[True, False]), [9., 5.])
def test_vecdot(self):
arr1 = np.arange(6).reshape((2, 3))
arr2 = np.arange(3).reshape((1, 3))
actual = np.vecdot(arr1, arr2)
expected = np.array([5, 14])
assert_array_equal(actual, expected)
actual2 = np.vecdot(arr1.T, arr2.T, axis=-2)
assert_array_equal(actual2, expected)
actual3 = np.vecdot(arr1.astype("object"), arr2)
assert_array_equal(actual3, expected.astype("object"))
def test_matvec(self):
arr1 = np.arange(6).reshape((2, 3))
arr2 = np.arange(3).reshape((1, 3))
actual = np.matvec(arr1, arr2)
expected = np.array([[5, 14]])
assert_array_equal(actual, expected)
actual2 = np.matvec(arr1.T, arr2.T, axes=[(-1, -2), -2, -1])
assert_array_equal(actual2, expected)
actual3 = np.matvec(arr1.astype("object"), arr2)
assert_array_equal(actual3, expected.astype("object"))
@pytest.mark.parametrize("vec", [
np.array([[1., 2., 3.], [4., 5., 6.]]),
np.array([[1., 2j, 3.], [4., 5., 6j]]),
np.array([[1., 2., 3.], [4., 5., 6.]], dtype=object),
np.array([[1., 2j, 3.], [4., 5., 6j]], dtype=object)])
@pytest.mark.parametrize("matrix", [
None,
np.array([[1. + 1j, 0.5, -0.5j],
[0.25, 2j, 0.],
[4., 0., -1j]])])
def test_vecmatvec_identity(self, matrix, vec):
"""Check that (x†A)x equals x†(Ax)."""
mat = matrix if matrix is not None else np.eye(3)
matvec = np.matvec(mat, vec) # Ax
vecmat = np.vecmat(vec, mat) # x†A
if matrix is None:
assert_array_equal(matvec, vec)
assert_array_equal(vecmat.conj(), vec)
assert_array_equal(matvec, (mat @ vec[..., np.newaxis]).squeeze(-1))
assert_array_equal(vecmat, (vec[..., np.newaxis].mT.conj()
@ mat).squeeze(-2))
expected = np.einsum('...i,ij,...j', vec.conj(), mat, vec)
vec_matvec = (vec.conj() * matvec).sum(-1)
vecmat_vec = (vecmat * vec).sum(-1)
assert_array_equal(vec_matvec, expected)
assert_array_equal(vecmat_vec, expected)
@pytest.mark.parametrize("ufunc, shape1, shape2, conj", [
(np.vecdot, (3,), (3,), True),
(np.vecmat, (3,), (3, 1), True),
(np.matvec, (1, 3), (3,), False),
(np.matmul, (1, 3), (3, 1), False),
])
def test_vecdot_matvec_vecmat_complex(self, ufunc, shape1, shape2, conj):
arr1 = np.array([1, 2j, 3])
arr2 = np.array([1, 2, 3])
actual1 = ufunc(arr1.reshape(shape1), arr2.reshape(shape2))
expected1 = np.array(((arr1.conj() if conj else arr1) * arr2).sum(),
ndmin=min(len(shape1), len(shape2)))
assert_array_equal(actual1, expected1)
# This would fail for conj=True, since matmul omits the conjugate.
if not conj:
assert_array_equal(arr1.reshape(shape1) @ arr2.reshape(shape2),
expected1)
actual2 = ufunc(arr2.reshape(shape1), arr1.reshape(shape2))
expected2 = np.array(((arr2.conj() if conj else arr2) * arr1).sum(),
ndmin=min(len(shape1), len(shape2)))
assert_array_equal(actual2, expected2)
actual3 = ufunc(arr1.reshape(shape1).astype("object"),
arr2.reshape(shape2).astype("object"))
expected3 = expected1.astype(object)
assert_array_equal(actual3, expected3)
def test_vecdot_subclass(self):
class MySubclass(np.ndarray):
pass
arr1 = np.arange(6).reshape((2, 3)).view(MySubclass)
arr2 = np.arange(3).reshape((1, 3)).view(MySubclass)
result = np.vecdot(arr1, arr2)
assert isinstance(result, MySubclass)
def test_vecdot_object_no_conjugate(self):
arr = np.array(["1", "2"], dtype=object)
with pytest.raises(AttributeError, match="conjugate"):
np.vecdot(arr, arr)
def test_vecdot_object_breaks_outer_loop_on_error(self):
arr1 = np.ones((3, 3)).astype(object)
arr2 = arr1.copy()
arr2[1, 1] = None
out = np.zeros(3).astype(object)
with pytest.raises(TypeError, match=r"\*: 'float' and 'NoneType'"):
np.vecdot(arr1, arr2, out=out)
assert out[0] == 3
assert out[1] == out[2] == 0
def test_broadcast(self):
msg = "broadcast"
a = np.arange(4).reshape((2, 1, 2))
b = np.arange(4).reshape((1, 2, 2))
assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
msg = "extend & broadcast loop dimensions"
b = np.arange(4).reshape((2, 2))
assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
# Broadcast in core dimensions should fail
a = np.arange(8).reshape((4, 2))
b = np.arange(4).reshape((4, 1))
assert_raises(ValueError, np.vecdot, a, b)
# Extend core dimensions should fail
a = np.arange(8).reshape((4, 2))
b = np.array(7)
assert_raises(ValueError, np.vecdot, a, b)
# Broadcast should fail
a = np.arange(2).reshape((2, 1, 1))
b = np.arange(3).reshape((3, 1, 1))
assert_raises(ValueError, np.vecdot, a, b)
# Writing to a broadcasted array with overlap should warn, gh-2705
a = np.arange(2)
b = np.arange(4).reshape((2, 2))
u, v = np.broadcast_arrays(a, b)
assert_equal(u.strides[0], 0)
x = u + v
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
u += v
assert_equal(len(w), 1)
assert_(x[0, 0] != u[0, 0])
# Output reduction should not be allowed.
# See gh-15139
a = np.arange(6).reshape(3, 2)
b = np.ones(2)
out = np.empty(())
assert_raises(ValueError, np.vecdot, a, b, out)
out2 = np.empty(3)
c = np.vecdot(a, b, out2)
assert_(c is out2)
def test_out_broadcasts(self):
# For ufuncs and gufuncs (not for reductions), we currently allow
# the output to cause broadcasting of the input arrays.
# both along dimensions with shape 1 and dimensions which do not
# exist at all in the inputs.
arr = np.arange(3).reshape(1, 3)
out = np.empty((5, 4, 3))
np.add(arr, arr, out=out)
assert (out == np.arange(3) * 2).all()
# The same holds for gufuncs (gh-16484)
np.vecdot(arr, arr, out=out)
# the result would be just a scalar `5`, but is broadcast fully:
assert (out == 5).all()
@pytest.mark.parametrize(["arr", "out"], [
([2], np.empty(())),
([1, 2], np.empty(1)),
(np.ones((4, 3)), np.empty((4, 1)))],
ids=["(1,)->()", "(2,)->(1,)", "(4, 3)->(4, 1)"])
def test_out_broadcast_errors(self, arr, out):
# Output is (currently) allowed to broadcast inputs, but it cannot be
# smaller than the actual result.
with pytest.raises(ValueError, match="non-broadcastable"):
np.positive(arr, out=out)
with pytest.raises(ValueError, match="non-broadcastable"):
np.add(np.ones(()), arr, out=out)
def test_type_cast(self):
msg = "type cast"
a = np.arange(6, dtype='short').reshape((2, 3))
assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
err_msg=msg)
msg = "type cast on one argument"
a = np.arange(6).reshape((2, 3))
b = a + 0.1
assert_array_almost_equal(np.vecdot(a, b), np.sum(a * b, axis=-1),
err_msg=msg)
def test_endian(self):
msg = "big endian"
a = np.arange(6, dtype='>i4').reshape((2, 3))
assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
err_msg=msg)
msg = "little endian"
a = np.arange(6, dtype='<i4').reshape((2, 3))
assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
err_msg=msg)
# Output should always be native-endian
Ba = np.arange(1, dtype='>f8')
La = np.arange(1, dtype='<f8')
assert_equal((Ba + Ba).dtype, np.dtype('f8'))
assert_equal((Ba + La).dtype, np.dtype('f8'))
assert_equal((La + Ba).dtype, np.dtype('f8'))
assert_equal((La + La).dtype, np.dtype('f8'))
assert_equal(np.absolute(La).dtype, np.dtype('f8'))
assert_equal(np.absolute(Ba).dtype, np.dtype('f8'))
assert_equal(np.negative(La).dtype, np.dtype('f8'))
assert_equal(np.negative(Ba).dtype, np.dtype('f8'))
def test_incontiguous_array(self):
msg = "incontiguous memory layout of array"
x = np.arange(64).reshape((2, 2, 2, 2, 2, 2))
a = x[:, 0, :, 0, :, 0]
b = x[:, 1, :, 1, :, 1]
a[0, 0, 0] = -1
msg2 = "make sure it references to the original array"
assert_equal(x[0, 0, 0, 0, 0, 0], -1, err_msg=msg2)
assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
x = np.arange(24).reshape(2, 3, 4)
a = x.T
b = x.T
a[0, 0, 0] = -1
assert_equal(x[0, 0, 0], -1, err_msg=msg2)
assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
def test_output_argument(self):
msg = "output argument"
a = np.arange(12).reshape((2, 3, 2))
b = np.arange(4).reshape((2, 1, 2)) + 1
c = np.zeros((2, 3), dtype='int')
np.vecdot(a, b, c)
assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
c[:] = -1
np.vecdot(a, b, out=c)
assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
msg = "output argument with type cast"
c = np.zeros((2, 3), dtype='int16')
np.vecdot(a, b, c)
assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
c[:] = -1
np.vecdot(a, b, out=c)
assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
msg = "output argument with incontiguous layout"
c = np.zeros((2, 3, 4), dtype='int16')
np.vecdot(a, b, c[..., 0])
assert_array_equal(c[..., 0], np.sum(a * b, axis=-1), err_msg=msg)
c[:] = -1
np.vecdot(a, b, out=c[..., 0])
assert_array_equal(c[..., 0], np.sum(a * b, axis=-1), err_msg=msg)
@pytest.mark.parametrize("arg", ["array", "scalar", "subclass"])
def test_output_ellipsis(self, arg):
class subclass(np.ndarray):
def __array_wrap__(self, obj, context=None, return_value=None):
return super().__array_wrap__(obj, context, return_value)
if arg == "scalar":
one = 1
expected_type = np.ndarray
elif arg == "array":
one = np.array(1)
expected_type = np.ndarray
elif arg == "subclass":
one = np.array(1).view(subclass)
expected_type = subclass
assert type(np.add(one, 2, out=...)) is expected_type
assert type(np.add.reduce(one, out=...)) is expected_type
res1, res2 = np.divmod(one, 2, out=...)
assert type(res1) is type(res2) is expected_type
def test_output_ellipsis_errors(self):
with pytest.raises(TypeError,
match=r"out=\.\.\. is only allowed as a keyword argument."):
np.add(1, 2, ...)
with pytest.raises(TypeError,
match=r"out=\.\.\. is only allowed as a keyword argument."):
np.add.reduce(1, (), None, ...)
type_error = r"must use `\.\.\.` as `out=\.\.\.` and not per-operand/in a tuple"
with pytest.raises(TypeError, match=type_error):
np.negative(1, out=(...,))
with pytest.raises(TypeError, match=type_error):
# We only allow out=... not individual args for now
np.divmod(1, 2, out=(np.empty(()), ...))
with pytest.raises(TypeError, match=type_error):
np.add.reduce(1, out=(...,))
def test_axes_argument(self):
# vecdot signature: '(n),(n)->()'
a = np.arange(27.).reshape((3, 3, 3))
b = np.arange(10., 19.).reshape((3, 1, 3))
# basic tests on inputs (outputs tested below with matrix_multiply).
c = np.vecdot(a, b)
assert_array_equal(c, (a * b).sum(-1))
# default
c = np.vecdot(a, b, axes=[(-1,), (-1,), ()])
assert_array_equal(c, (a * b).sum(-1))
# integers ok for single axis.
c = np.vecdot(a, b, axes=[-1, -1, ()])
assert_array_equal(c, (a * b).sum(-1))
# mix fine
c = np.vecdot(a, b, axes=[(-1,), -1, ()])
assert_array_equal(c, (a * b).sum(-1))
# can omit last axis.
c = np.vecdot(a, b, axes=[-1, -1])
assert_array_equal(c, (a * b).sum(-1))
# can pass in other types of integer (with __index__ protocol)
c = np.vecdot(a, b, axes=[np.int8(-1), np.array(-1, dtype=np.int32)])
assert_array_equal(c, (a * b).sum(-1))
# swap some axes
c = np.vecdot(a, b, axes=[0, 0])
assert_array_equal(c, (a * b).sum(0))
c = np.vecdot(a, b, axes=[0, 2])
assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
# Check errors for improperly constructed axes arguments.
# should have list.
assert_raises(TypeError, np.vecdot, a, b, axes=-1)
# needs enough elements
assert_raises(ValueError, np.vecdot, a, b, axes=[-1])
# should pass in indices.
assert_raises(TypeError, np.vecdot, a, b, axes=[-1.0, -1.0])
assert_raises(TypeError, np.vecdot, a, b, axes=[(-1.0,), -1])
assert_raises(TypeError, np.vecdot, a, b, axes=[None, 1])
# cannot pass an index unless there is only one dimension
# (output is wrong in this case)
assert_raises(AxisError, np.vecdot, a, b, axes=[-1, -1, -1])
# or pass in generally the wrong number of axes
assert_raises(AxisError, np.vecdot, a, b, axes=[-1, -1, (-1,)])
assert_raises(AxisError, np.vecdot, a, b, axes=[-1, (-2, -1), ()])
# axes need to have same length.
assert_raises(ValueError, np.vecdot, a, b, axes=[0, 1])
# matrix_multiply signature: '(m,n),(n,p)->(m,p)'
mm = umt.matrix_multiply
a = np.arange(12).reshape((2, 3, 2))
b = np.arange(8).reshape((2, 2, 2, 1)) + 1
# Sanity check.
c = mm(a, b)
assert_array_equal(c, np.matmul(a, b))
# Default axes.
c = mm(a, b, axes=[(-2, -1), (-2, -1), (-2, -1)])
assert_array_equal(c, np.matmul(a, b))
# Default with explicit axes.
c = mm(a, b, axes=[(1, 2), (2, 3), (2, 3)])
assert_array_equal(c, np.matmul(a, b))
# swap some axes.
c = mm(a, b, axes=[(0, -1), (1, 2), (-2, -1)])
assert_array_equal(c, np.matmul(a.transpose(1, 0, 2),
b.transpose(0, 3, 1, 2)))
# Default with output array.
c = np.empty((2, 2, 3, 1))
d = mm(a, b, out=c, axes=[(1, 2), (2, 3), (2, 3)])
assert_(c is d)
assert_array_equal(c, np.matmul(a, b))
# Transposed output array
c = np.empty((1, 2, 2, 3))
d = mm(a, b, out=c, axes=[(-2, -1), (-2, -1), (3, 0)])
assert_(c is d)
assert_array_equal(c, np.matmul(a, b).transpose(3, 0, 1, 2))
# Check errors for improperly constructed axes arguments.
# wrong argument
assert_raises(TypeError, mm, a, b, axis=1)
# axes should be list
assert_raises(TypeError, mm, a, b, axes=1)
assert_raises(TypeError, mm, a, b, axes=((-2, -1), (-2, -1), (-2, -1)))
# list needs to have right length
assert_raises(ValueError, mm, a, b, axes=[])
assert_raises(ValueError, mm, a, b, axes=[(-2, -1)])
# list should not contain None, or lists
assert_raises(TypeError, mm, a, b, axes=[None, None, None])
assert_raises(TypeError,
mm, a, b, axes=[[-2, -1], [-2, -1], [-2, -1]])
assert_raises(TypeError,
mm, a, b, axes=[(-2, -1), (-2, -1), [-2, -1]])
assert_raises(TypeError, mm, a, b, axes=[(-2, -1), (-2, -1), None])
# single integers are AxisErrors if more are required
assert_raises(AxisError, mm, a, b, axes=[-1, -1, -1])
assert_raises(AxisError, mm, a, b, axes=[(-2, -1), (-2, -1), -1])
# tuples should not have duplicated values
assert_raises(ValueError, mm, a, b, axes=[(-2, -1), (-2, -1), (-2, -2)])
# arrays should have enough axes.
z = np.zeros((2, 2))
assert_raises(ValueError, mm, z, z[0])
assert_raises(ValueError, mm, z, z, out=z[:, 0])
assert_raises(ValueError, mm, z[1], z, axes=[0, 1])
assert_raises(ValueError, mm, z, z, out=z[0], axes=[0, 1])
# Regular ufuncs should not accept axes.
assert_raises(TypeError, np.add, 1., 1., axes=[0])
# should be able to deal with bad unrelated kwargs.
assert_raises(TypeError, mm, z, z, axes=[0, 1], parrot=True)
def test_axis_argument(self):
# vecdot signature: '(n),(n)->()'
a = np.arange(27.).reshape((3, 3, 3))
b = np.arange(10., 19.).reshape((3, 1, 3))
c = np.vecdot(a, b)
assert_array_equal(c, (a * b).sum(-1))
c = np.vecdot(a, b, axis=-1)
assert_array_equal(c, (a * b).sum(-1))
out = np.zeros_like(c)
d = np.vecdot(a, b, axis=-1, out=out)
assert_(d is out)
assert_array_equal(d, c)
c = np.vecdot(a, b, axis=0)
assert_array_equal(c, (a * b).sum(0))
# Sanity checks on innerwt and cumsum.
a = np.arange(6).reshape((2, 3))
b = np.arange(10, 16).reshape((2, 3))
w = np.arange(20, 26).reshape((2, 3))
assert_array_equal(umt.innerwt(a, b, w, axis=0),
np.sum(a * b * w, axis=0))
assert_array_equal(umt.cumsum(a, axis=0), np.cumsum(a, axis=0))
assert_array_equal(umt.cumsum(a, axis=-1), np.cumsum(a, axis=-1))
out = np.empty_like(a)
b = umt.cumsum(a, out=out, axis=0)
assert_(out is b)
assert_array_equal(b, np.cumsum(a, axis=0))
b = umt.cumsum(a, out=out, axis=1)
assert_(out is b)
assert_array_equal(b, np.cumsum(a, axis=-1))
# Check errors.
# Cannot pass in both axis and axes.
assert_raises(TypeError, np.vecdot, a, b, axis=0, axes=[0, 0])
# Not an integer.
assert_raises(TypeError, np.vecdot, a, b, axis=[0])
# more than 1 core dimensions.
mm = umt.matrix_multiply
assert_raises(TypeError, mm, a, b, axis=1)
# Output wrong size in axis.
out = np.empty((1, 2, 3), dtype=a.dtype)
assert_raises(ValueError, umt.cumsum, a, out=out, axis=0)
# Regular ufuncs should not accept axis.
assert_raises(TypeError, np.add, 1., 1., axis=0)
def test_keepdims_argument(self):
# vecdot signature: '(n),(n)->()'
a = np.arange(27.).reshape((3, 3, 3))
b = np.arange(10., 19.).reshape((3, 1, 3))
c = np.vecdot(a, b)
assert_array_equal(c, (a * b).sum(-1))
c = np.vecdot(a, b, keepdims=False)
assert_array_equal(c, (a * b).sum(-1))
c = np.vecdot(a, b, keepdims=True)
assert_array_equal(c, (a * b).sum(-1, keepdims=True))
out = np.zeros_like(c)
d = np.vecdot(a, b, keepdims=True, out=out)
assert_(d is out)
assert_array_equal(d, c)
# Now combined with axis and axes.
c = np.vecdot(a, b, axis=-1, keepdims=False)
assert_array_equal(c, (a * b).sum(-1, keepdims=False))
c = np.vecdot(a, b, axis=-1, keepdims=True)
assert_array_equal(c, (a * b).sum(-1, keepdims=True))
c = np.vecdot(a, b, axis=0, keepdims=False)
assert_array_equal(c, (a * b).sum(0, keepdims=False))
c = np.vecdot(a, b, axis=0, keepdims=True)
assert_array_equal(c, (a * b).sum(0, keepdims=True))
c = np.vecdot(a, b, axes=[(-1,), (-1,), ()], keepdims=False)
assert_array_equal(c, (a * b).sum(-1))
c = np.vecdot(a, b, axes=[(-1,), (-1,), (-1,)], keepdims=True)
assert_array_equal(c, (a * b).sum(-1, keepdims=True))
c = np.vecdot(a, b, axes=[0, 0], keepdims=False)
assert_array_equal(c, (a * b).sum(0))
c = np.vecdot(a, b, axes=[0, 0, 0], keepdims=True)
assert_array_equal(c, (a * b).sum(0, keepdims=True))
c = np.vecdot(a, b, axes=[0, 2], keepdims=False)
assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
c = np.vecdot(a, b, axes=[0, 2], keepdims=True)
assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
keepdims=True))
c = np.vecdot(a, b, axes=[0, 2, 2], keepdims=True)
assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
keepdims=True))
c = np.vecdot(a, b, axes=[0, 2, 0], keepdims=True)
assert_array_equal(c, (a * b.transpose(2, 0, 1)).sum(0, keepdims=True))
# Hardly useful, but should work.
c = np.vecdot(a, b, axes=[0, 2, 1], keepdims=True)
assert_array_equal(c, (a.transpose(1, 0, 2) * b.transpose(0, 2, 1))
.sum(1, keepdims=True))
# Check with two core dimensions.
a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
expected = uml.det(a)
c = uml.det(a, keepdims=False)
assert_array_equal(c, expected)
c = uml.det(a, keepdims=True)
assert_array_equal(c, expected[:, np.newaxis, np.newaxis])
a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
expected_s, expected_l = uml.slogdet(a)
cs, cl = uml.slogdet(a, keepdims=False)
assert_array_equal(cs, expected_s)
assert_array_equal(cl, expected_l)
cs, cl = uml.slogdet(a, keepdims=True)
assert_array_equal(cs, expected_s[:, np.newaxis, np.newaxis])
assert_array_equal(cl, expected_l[:, np.newaxis, np.newaxis])
# Sanity check on innerwt.
a = np.arange(6).reshape((2, 3))
b = np.arange(10, 16).reshape((2, 3))
w = np.arange(20, 26).reshape((2, 3))
assert_array_equal(umt.innerwt(a, b, w, keepdims=True),
np.sum(a * b * w, axis=-1, keepdims=True))
assert_array_equal(umt.innerwt(a, b, w, axis=0, keepdims=True),
np.sum(a * b * w, axis=0, keepdims=True))
# Check errors.
# Not a boolean
assert_raises(TypeError, np.vecdot, a, b, keepdims='true')
# More than 1 core dimension, and core output dimensions.
mm = umt.matrix_multiply
assert_raises(TypeError, mm, a, b, keepdims=True)
assert_raises(TypeError, mm, a, b, keepdims=False)
# Regular ufuncs should not accept keepdims.
assert_raises(TypeError, np.add, 1., 1., keepdims=False)
def test_innerwt(self):
a = np.arange(6).reshape((2, 3))
b = np.arange(10, 16).reshape((2, 3))
w = np.arange(20, 26).reshape((2, 3))
assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
a = np.arange(100, 124).reshape((2, 3, 4))
b = np.arange(200, 224).reshape((2, 3, 4))
w = np.arange(300, 324).reshape((2, 3, 4))
assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
def test_innerwt_empty(self):
"""Test generalized ufunc with zero-sized operands"""
a = np.array([], dtype='f8')
b = np.array([], dtype='f8')
w = np.array([], dtype='f8')
assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
def test_cross1d(self):
"""Test with fixed-sized signature."""
a = np.eye(3)
assert_array_equal(umt.cross1d(a, a), np.zeros((3, 3)))
out = np.zeros((3, 3))
result = umt.cross1d(a[0], a, out)
assert_(result is out)
assert_array_equal(result, np.vstack((np.zeros(3), a[2], -a[1])))
assert_raises(ValueError, umt.cross1d, np.eye(4), np.eye(4))
assert_raises(ValueError, umt.cross1d, a, np.arange(4.))
# Wrong output core dimension.
assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros((3, 4)))
# Wrong output broadcast dimension (see gh-15139).
assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros(3))
def test_can_ignore_signature(self):
# Comparing the effects of ? in signature:
# matrix_multiply: (m,n),(n,p)->(m,p) # all must be there.
# matmul: (m?,n),(n,p?)->(m?,p?) # allow missing m, p.
mat = np.arange(12).reshape((2, 3, 2))
single_vec = np.arange(2)
col_vec = single_vec[:, np.newaxis]
col_vec_array = np.arange(8).reshape((2, 2, 2, 1)) + 1
# matrix @ single column vector with proper dimension
mm_col_vec = umt.matrix_multiply(mat, col_vec)
# matmul does the same thing
matmul_col_vec = umt.matmul(mat, col_vec)
assert_array_equal(matmul_col_vec, mm_col_vec)
# matrix @ vector without dimension making it a column vector.
# matrix multiply fails -> missing core dim.
assert_raises(ValueError, umt.matrix_multiply, mat, single_vec)
# matmul mimicker passes, and returns a vector.
matmul_col = umt.matmul(mat, single_vec)
assert_array_equal(matmul_col, mm_col_vec.squeeze())
# Now with a column array: same as for column vector,
# broadcasting sensibly.
mm_col_vec = umt.matrix_multiply(mat, col_vec_array)
matmul_col_vec = umt.matmul(mat, col_vec_array)
assert_array_equal(matmul_col_vec, mm_col_vec)
# As above, but for row vector
single_vec = np.arange(3)
row_vec = single_vec[np.newaxis, :]
row_vec_array = np.arange(24).reshape((4, 2, 1, 1, 3)) + 1
# row vector @ matrix
mm_row_vec = umt.matrix_multiply(row_vec, mat)
matmul_row_vec = umt.matmul(row_vec, mat)
assert_array_equal(matmul_row_vec, mm_row_vec)
# single row vector @ matrix
assert_raises(ValueError, umt.matrix_multiply, single_vec, mat)
matmul_row = umt.matmul(single_vec, mat)
assert_array_equal(matmul_row, mm_row_vec.squeeze())
# row vector array @ matrix
mm_row_vec = umt.matrix_multiply(row_vec_array, mat)
matmul_row_vec = umt.matmul(row_vec_array, mat)
assert_array_equal(matmul_row_vec, mm_row_vec)
# Now for vector combinations
# row vector @ column vector
col_vec = row_vec.T
col_vec_array = row_vec_array.swapaxes(-2, -1)
mm_row_col_vec = umt.matrix_multiply(row_vec, col_vec)
matmul_row_col_vec = umt.matmul(row_vec, col_vec)
assert_array_equal(matmul_row_col_vec, mm_row_col_vec)
# single row vector @ single col vector
assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec)
matmul_row_col = umt.matmul(single_vec, single_vec)
assert_array_equal(matmul_row_col, mm_row_col_vec.squeeze())
# row vector array @ matrix
mm_row_col_array = umt.matrix_multiply(row_vec_array, col_vec_array)
matmul_row_col_array = umt.matmul(row_vec_array, col_vec_array)
assert_array_equal(matmul_row_col_array, mm_row_col_array)
# Finally, check that things are *not* squeezed if one gives an
# output.
out = np.zeros_like(mm_row_col_array)
out = umt.matrix_multiply(row_vec_array, col_vec_array, out=out)
assert_array_equal(out, mm_row_col_array)
out[:] = 0
out = umt.matmul(row_vec_array, col_vec_array, out=out)
assert_array_equal(out, mm_row_col_array)
# And check one cannot put missing dimensions back.
out = np.zeros_like(mm_row_col_vec)
assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec,
out)
# But fine for matmul, since it is just a broadcast.
out = umt.matmul(single_vec, single_vec, out)
assert_array_equal(out, mm_row_col_vec.squeeze())
def test_matrix_multiply(self):
self.compare_matrix_multiply_results(np.int64)
self.compare_matrix_multiply_results(np.double)
def test_matrix_multiply_umath_empty(self):
res = umt.matrix_multiply(np.ones((0, 10)), np.ones((10, 0)))
assert_array_equal(res, np.zeros((0, 0)))
res = umt.matrix_multiply(np.ones((10, 0)), np.ones((0, 10)))
assert_array_equal(res, np.zeros((10, 10)))
def compare_matrix_multiply_results(self, tp):
d1 = np.array(np.random.rand(2, 3, 4), dtype=tp)
d2 = np.array(np.random.rand(2, 3, 4), dtype=tp)
msg = f"matrix multiply on type {d1.dtype.name}"
def permute_n(n):
if n == 1:
return ([0],)
ret = ()
base = permute_n(n - 1)
for perm in base:
for i in range(n):
new = perm + [n - 1]
new[n - 1] = new[i]
new[i] = n - 1
ret += (new,)
return ret
def slice_n(n):
if n == 0:
return ((),)
ret = ()
base = slice_n(n - 1)
for sl in base:
ret += (sl + (slice(None),),)
ret += (sl + (slice(0, 1),),)
return ret
def broadcastable(s1, s2):
return s1 == s2 or 1 in {s1, s2}
permute_3 = permute_n(3)
slice_3 = slice_n(3) + ((slice(None, None, -1),) * 3,)
ref = True
for p1 in permute_3:
for p2 in permute_3:
for s1 in slice_3:
for s2 in slice_3:
a1 = d1.transpose(p1)[s1]
a2 = d2.transpose(p2)[s2]
ref = ref and a1.base is not None
ref = ref and a2.base is not None
if (a1.shape[-1] == a2.shape[-2] and
broadcastable(a1.shape[0], a2.shape[0])):
assert_array_almost_equal(
umt.matrix_multiply(a1, a2),
np.sum(a2[..., np.newaxis].swapaxes(-3, -1) *
a1[..., np.newaxis, :], axis=-1),
err_msg=msg + f' {str(a1.shape)} {str(a2.shape)}')
assert_equal(ref, True, err_msg="reference check")
def test_euclidean_pdist(self):
a = np.arange(12, dtype=float).reshape(4, 3)
out = np.empty((a.shape[0] * (a.shape[0] - 1) // 2,), dtype=a.dtype)
umt.euclidean_pdist(a, out)
b = np.sqrt(np.sum((a[:, None] - a)**2, axis=-1))
b = b[~np.tri(a.shape[0], dtype=bool)]
assert_almost_equal(out, b)
# An output array is required to determine p with signature (n,d)->(p)
assert_raises(ValueError, umt.euclidean_pdist, a)
def test_cumsum(self):
a = np.arange(10)
result = umt.cumsum(a)
assert_array_equal(result, a.cumsum())
def test_object_logical(self):
a = np.array([3, None, True, False, "test", ""], dtype=object)
assert_equal(np.logical_or(a, None),
np.array([x or None for x in a], dtype=object))
assert_equal(np.logical_or(a, True),
np.array([x or True for x in a], dtype=object))
assert_equal(np.logical_or(a, 12),
np.array([x or 12 for x in a], dtype=object))
assert_equal(np.logical_or(a, "blah"),
np.array([x or "blah" for x in a], dtype=object))
assert_equal(np.logical_and(a, None),
np.array([x and None for x in a], dtype=object))
assert_equal(np.logical_and(a, True),
np.array([x and True for x in a], dtype=object))
assert_equal(np.logical_and(a, 12),
np.array([x and 12 for x in a], dtype=object))
assert_equal(np.logical_and(a, "blah"),
np.array([x and "blah" for x in a], dtype=object))
assert_equal(np.logical_not(a),
np.array([not x for x in a], dtype=object))
assert_equal(np.logical_or.reduce(a), 3)
assert_equal(np.logical_and.reduce(a), None)
def test_object_comparison(self):
class HasComparisons:
def __eq__(self, other):
return '=='
arr0d = np.array(HasComparisons())
assert_equal(arr0d == arr0d, True)
assert_equal(np.equal(arr0d, arr0d), True) # normal behavior is a cast
arr1d = np.array([HasComparisons()])
assert_equal(arr1d == arr1d, np.array([True]))
# normal behavior is a cast
assert_equal(np.equal(arr1d, arr1d), np.array([True]))
assert_equal(np.equal(arr1d, arr1d, dtype=object), np.array(['==']))
def test_object_array_reduction(self):
# Reductions on object arrays
a = np.array(['a', 'b', 'c'], dtype=object)
assert_equal(np.sum(a), 'abc')
assert_equal(np.max(a), 'c')
assert_equal(np.min(a), 'a')
a = np.array([True, False, True], dtype=object)
assert_equal(np.sum(a), 2)
assert_equal(np.prod(a), 0)
assert_equal(np.any(a), True)
assert_equal(np.all(a), False)
assert_equal(np.max(a), True)
assert_equal(np.min(a), False)
assert_equal(np.array([[1]], dtype=object).sum(), 1)
assert_equal(np.array([[[1, 2]]], dtype=object).sum((0, 1)), [1, 2])
assert_equal(np.array([1], dtype=object).sum(initial=1), 2)
assert_equal(np.array([[1], [2, 3]], dtype=object)
.sum(initial=[0], where=[False, True]), [0, 2, 3])
def test_object_array_accumulate_inplace(self):
# Checks that in-place accumulates work, see also gh-7402
arr = np.ones(4, dtype=object)
arr[:] = [[1] for i in range(4)]
# Twice reproduced also for tuples:
np.add.accumulate(arr, out=arr)
np.add.accumulate(arr, out=arr)
assert_array_equal(arr,
np.array([[1] * i for i in [1, 3, 6, 10]], dtype=object),
)
# And the same if the axis argument is used
arr = np.ones((2, 4), dtype=object)
arr[0, :] = [[2] for i in range(4)]
np.add.accumulate(arr, out=arr, axis=-1)
np.add.accumulate(arr, out=arr, axis=-1)
assert_array_equal(arr[0, :],
np.array([[2] * i for i in [1, 3, 6, 10]], dtype=object),
)
def test_object_array_accumulate_failure(self):
# Typical accumulation on object works as expected:
res = np.add.accumulate(np.array([1, 0, 2], dtype=object))
assert_array_equal(res, np.array([1, 1, 3], dtype=object))
# But errors are propagated from the inner-loop if they occur:
with pytest.raises(TypeError):
np.add.accumulate([1, None, 2])
def test_object_array_reduceat_inplace(self):
# Checks that in-place reduceats work, see also gh-7465
arr = np.empty(4, dtype=object)
arr[:] = [[1] for i in range(4)]
out = np.empty(4, dtype=object)
out[:] = [[1] for i in range(4)]
np.add.reduceat(arr, np.arange(4), out=arr)
np.add.reduceat(arr, np.arange(4), out=arr)
assert_array_equal(arr, out)
# And the same if the axis argument is used
arr = np.ones((2, 4), dtype=object)
arr[0, :] = [[2] for i in range(4)]
out = np.ones((2, 4), dtype=object)
out[0, :] = [[2] for i in range(4)]
np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
assert_array_equal(arr, out)
def test_object_array_reduceat_failure(self):
# Reduceat works as expected when no invalid operation occurs (None is
# not involved in an operation here)
res = np.add.reduceat(np.array([1, None, 2], dtype=object), [1, 2])
assert_array_equal(res, np.array([None, 2], dtype=object))
# But errors when None would be involved in an operation:
with pytest.raises(TypeError):
np.add.reduceat([1, None, 2], [0, 2])
def test_zerosize_reduction(self):
# Test with default dtype and object dtype
for a in [[], np.array([], dtype=object)]:
assert_equal(np.sum(a), 0)
assert_equal(np.prod(a), 1)
assert_equal(np.any(a), False)
assert_equal(np.all(a), True)
assert_raises(ValueError, np.max, a)
assert_raises(ValueError, np.min, a)
def test_axis_out_of_bounds(self):
a = np.array([False, False])
assert_raises(AxisError, a.all, axis=1)
a = np.array([False, False])
assert_raises(AxisError, a.all, axis=-2)
a = np.array([False, False])
assert_raises(AxisError, a.any, axis=1)
a = np.array([False, False])
assert_raises(AxisError, a.any, axis=-2)
def test_scalar_reduction(self):
# The functions 'sum', 'prod', etc allow specifying axis=0
# even for scalars
assert_equal(np.sum(3, axis=0), 3)
assert_equal(np.prod(3.5, axis=0), 3.5)
assert_equal(np.any(True, axis=0), True)
assert_equal(np.all(False, axis=0), False)
assert_equal(np.max(3, axis=0), 3)
assert_equal(np.min(2.5, axis=0), 2.5)
# Check scalar behaviour for ufuncs without an identity
assert_equal(np.power.reduce(3), 3)
# Make sure that scalars are coming out from this operation
assert_(type(np.prod(np.float32(2.5), axis=0)) is np.float32)
assert_(type(np.sum(np.float32(2.5), axis=0)) is np.float32)
assert_(type(np.max(np.float32(2.5), axis=0)) is np.float32)
assert_(type(np.min(np.float32(2.5), axis=0)) is np.float32)
# check if scalars/0-d arrays get cast
assert_(type(np.any(0, axis=0)) is np.bool)
# assert that 0-d arrays get wrapped
class MyArray(np.ndarray):
pass
a = np.array(1).view(MyArray)
assert_(type(np.any(a)) is MyArray)
def test_casting_out_param(self):
# Test that it's possible to do casts on output
a = np.ones((200, 100), np.int64)
b = np.ones((200, 100), np.int64)
c = np.ones((200, 100), np.float64)
np.add(a, b, out=c)
assert_equal(c, 2)
a = np.zeros(65536)
b = np.zeros(65536, dtype=np.float32)
np.subtract(a, 0, out=b)
assert_equal(b, 0)
def test_where_param(self):
# Test that the where= ufunc parameter works with regular arrays
a = np.arange(7)
b = np.ones(7)
c = np.zeros(7)
np.add(a, b, out=c, where=(a % 2 == 1))
assert_equal(c, [0, 2, 0, 4, 0, 6, 0])
a = np.arange(4).reshape(2, 2) + 2
np.power(a, [2, 3], out=a, where=[[0, 1], [1, 0]])
assert_equal(a, [[2, 27], [16, 5]])
# Broadcasting the where= parameter
np.subtract(a, 2, out=a, where=[True, False])
assert_equal(a, [[0, 27], [14, 5]])
def test_where_param_buffer_output(self):
# With casting on output
a = np.ones(10, np.int64)
b = np.ones(10, np.int64)
c = 1.5 * np.ones(10, np.float64)
np.add(a, b, out=c, where=[1, 0, 0, 1, 0, 0, 1, 1, 1, 0])
assert_equal(c, [2, 1.5, 1.5, 2, 1.5, 1.5, 2, 2, 2, 1.5])
def test_where_param_alloc(self):
# With casting and allocated output
a = np.array([1], dtype=np.int64)
m = np.array([True], dtype=bool)
assert_equal(np.sqrt(a, where=m, out=None), [1])
# No casting and allocated output
a = np.array([1], dtype=np.float64)
m = np.array([True], dtype=bool)
assert_equal(np.sqrt(a, where=m, out=None), [1])
def test_where_with_broadcasting(self):
# See gh-17198
a = np.random.random((5000, 4))
b = np.random.random((5000, 1))
where = a > 0.3
out = np.full_like(a, 0)
np.less(a, b, where=where, out=out)
b_where = np.broadcast_to(b, a.shape)[where]
assert_array_equal((a[where] < b_where), out[where].astype(bool))
assert not out[~where].any() # outside mask, out remains all 0
def test_where_warns(self):
a = np.arange(7)
mask = a % 2 == 0
with pytest.warns(UserWarning, match="'where' used without 'out'"):
result1 = np.add(a, a, where=mask)
# Does not warn
result2 = np.add(a, a, where=mask, out=None)
# Sanity check
assert np.all(result1[::2] == [0, 4, 8, 12])
assert np.all(result2[::2] == [0, 4, 8, 12])
@staticmethod
def identityless_reduce_arrs():
yield np.empty((2, 3, 4), order='C')
yield np.empty((2, 3, 4), order='F')
# Mixed order (reduce order differs outer)
yield np.empty((2, 4, 3), order='C').swapaxes(1, 2)
# Reversed order
yield np.empty((2, 3, 4), order='C')[::-1, ::-1, ::-1]
# Not contiguous
yield np.empty((3, 5, 4), order='C').swapaxes(1, 2)[1:, 1:, 1:]
# Not contiguous and not aligned
a = np.empty((3 * 4 * 5 * 8 + 1,), dtype='i1')
a = a[1:].view(dtype='f8')
a.shape = (3, 4, 5)
a = a[1:, 1:, 1:]
yield a
@pytest.mark.parametrize("arrs", identityless_reduce_arrs())
@pytest.mark.parametrize("pos", [(1, 0, 0), (0, 1, 0), (0, 0, 1)])
def test_identityless_reduction(self, arrs, pos):
# np.minimum.reduce is an identityless reduction
a = arrs.copy()
a[...] = 1
a[pos] = 0
for axis in [None, (0, 1), (0, 2), (1, 2), 0, 1, 2, ()]:
if axis is None:
axes = np.array([], dtype=np.intp)
else:
axes = np.delete(np.arange(a.ndim), axis)
expected_pos = tuple(np.array(pos)[axes])
expected = np.ones(np.array(a.shape)[axes])
expected[expected_pos] = 0
res = np.minimum.reduce(a, axis=axis)
assert_equal(res, expected, strict=True)
res = np.full_like(res, np.nan)
np.minimum.reduce(a, axis=axis, out=res)
assert_equal(res, expected, strict=True)
@requires_memory(6 * 1024**3)
@pytest.mark.skipif(sys.maxsize < 2**32,
reason="test array too large for 32bit platform")
@pytest.mark.thread_unsafe(reason="crashes with low memory")
def test_identityless_reduction_huge_array(self):
# Regression test for gh-20921 (copying identity incorrectly failed)
arr = np.zeros((2, 2**31), 'uint8')
arr[:, 0] = [1, 3]
arr[:, -1] = [4, 1]
res = np.maximum.reduce(arr, axis=0)
del arr
assert res[0] == 3
assert res[-1] == 4
def test_reduce_identity_depends_on_loop(self):
"""
The type of the result should always depend on the selected loop, not
necessarily the output (only relevant for object arrays).
"""
# For an object loop, the default value 0 with type int is used:
assert type(np.add.reduce([], dtype=object)) is int
out = np.array(None, dtype=object)
# When the loop is float64 but `out` is object this does not happen,
# the result is float64 cast to object (which gives Python `float`).
np.add.reduce([], out=out, dtype=np.float64)
assert type(out[()]) is float
def test_initial_reduction(self):
# np.minimum.reduce is an identityless reduction
# For cases like np.maximum(np.abs(...), initial=0)
# More generally, a supremum over non-negative numbers.
assert_equal(np.maximum.reduce([], initial=0), 0)
# For cases like reduction of an empty array over the reals.
assert_equal(np.minimum.reduce([], initial=np.inf), np.inf)
assert_equal(np.maximum.reduce([], initial=-np.inf), -np.inf)
# Random tests
assert_equal(np.minimum.reduce([5], initial=4), 4)
assert_equal(np.maximum.reduce([4], initial=5), 5)
assert_equal(np.maximum.reduce([5], initial=4), 5)
assert_equal(np.minimum.reduce([4], initial=5), 4)
# Check initial=None raises ValueError for both types of ufunc reductions
assert_raises(ValueError, np.minimum.reduce, [], initial=None)
assert_raises(ValueError, np.add.reduce, [], initial=None)
# Also in the somewhat special object case:
with pytest.raises(ValueError):
np.add.reduce([], initial=None, dtype=object)
# Check that np._NoValue gives default behavior.
assert_equal(np.add.reduce([], initial=np._NoValue), 0)
# Check that initial kwarg behaves as intended for dtype=object
a = np.array([10], dtype=object)
res = np.add.reduce(a, initial=5)
assert_equal(res, 15)
def test_empty_reduction_and_identity(self):
arr = np.zeros((0, 5))
# OK, since the reduction itself is *not* empty, the result is
assert np.true_divide.reduce(arr, axis=1).shape == (0,)
# Not OK, the reduction itself is empty and we have no identity
with pytest.raises(ValueError):
np.true_divide.reduce(arr, axis=0)
# Test that an empty reduction fails also if the result is empty
arr = np.zeros((0, 0, 5))
with pytest.raises(ValueError):
np.true_divide.reduce(arr, axis=1)
# Division reduction makes sense with `initial=1` (empty or not):
res = np.true_divide.reduce(arr, axis=1, initial=1)
assert_array_equal(res, np.ones((0, 5)))
@pytest.mark.parametrize('axis', (0, 1, None))
@pytest.mark.parametrize('where', (np.array([False, True, True]),
np.array([[True], [False], [True]]),
np.array([[True, False, False],
[False, True, False],
[False, True, True]])))
def test_reduction_with_where(self, axis, where):
a = np.arange(9.).reshape(3, 3)
a_copy = a.copy()
a_check = np.zeros_like(a)
np.positive(a, out=a_check, where=where)
res = np.add.reduce(a, axis=axis, where=where)
check = a_check.sum(axis)
assert_equal(res, check)
# Check we do not overwrite elements of a internally.
assert_array_equal(a, a_copy)
@pytest.mark.parametrize(('axis', 'where'),
((0, np.array([True, False, True])),
(1, [True, True, False]),
(None, True)))
@pytest.mark.parametrize('initial', (-np.inf, 5.))
def test_reduction_with_where_and_initial(self, axis, where, initial):
a = np.arange(9.).reshape(3, 3)
a_copy = a.copy()
a_check = np.full(a.shape, -np.inf)
np.positive(a, out=a_check, where=where)
res = np.maximum.reduce(a, axis=axis, where=where, initial=initial)
check = a_check.max(axis, initial=initial)
assert_equal(res, check)
def test_reduction_where_initial_needed(self):
a = np.arange(9.).reshape(3, 3)
m = [False, True, False]
assert_raises(ValueError, np.maximum.reduce, a, where=m)
def test_identityless_reduction_nonreorderable(self):
a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]])
res = np.divide.reduce(a, axis=0)
assert_equal(res, [8.0, 4.0, 8.0])
res = np.divide.reduce(a, axis=1)
assert_equal(res, [2.0, 8.0])
res = np.divide.reduce(a, axis=())
assert_equal(res, a)
assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1))
def test_reduce_zero_axis(self):
# If we have an n x m array and do a reduction with axis=1, then we are
# doing n reductions, and each reduction takes an m-element array. For
# a reduction operation without an identity, then:
# n > 0, m > 0: fine
# n = 0, m > 0: fine, doing 0 reductions of m-element arrays
# n > 0, m = 0: can't reduce a 0-element array, ValueError
# n = 0, m = 0: can't reduce a 0-element array, ValueError (for
# consistency with the above case)
# This test doesn't actually look at return values, it just checks to
# make sure that error we get an error in exactly those cases where we
# expect one, and assumes the calculations themselves are done
# correctly.
def ok(f, *args, **kwargs):
f(*args, **kwargs)
def err(f, *args, **kwargs):
assert_raises(ValueError, f, *args, **kwargs)
def t(expect, func, n, m):
expect(func, np.zeros((n, m)), axis=1)
expect(func, np.zeros((m, n)), axis=0)
expect(func, np.zeros((n // 2, n // 2, m)), axis=2)
expect(func, np.zeros((n // 2, m, n // 2)), axis=1)
expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2))
expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2))
expect(func, np.zeros((m // 3, m // 3, m // 3,
n // 2, n // 2)),
axis=(0, 1, 2))
# Check what happens if the inner (resp. outer) dimensions are a
# mix of zero and non-zero:
expect(func, np.zeros((10, m, n)), axis=(0, 1))
expect(func, np.zeros((10, n, m)), axis=(0, 2))
expect(func, np.zeros((m, 10, n)), axis=0)
expect(func, np.zeros((10, m, n)), axis=1)
expect(func, np.zeros((10, n, m)), axis=2)
# np.maximum is just an arbitrary ufunc with no reduction identity
assert_equal(np.maximum.identity, None)
t(ok, np.maximum.reduce, 30, 30)
t(ok, np.maximum.reduce, 0, 30)
t(err, np.maximum.reduce, 30, 0)
t(err, np.maximum.reduce, 0, 0)
err(np.maximum.reduce, [])
np.maximum.reduce(np.zeros((0, 0)), axis=())
# all of the combinations are fine for a reduction that has an
# identity
t(ok, np.add.reduce, 30, 30)
t(ok, np.add.reduce, 0, 30)
t(ok, np.add.reduce, 30, 0)
t(ok, np.add.reduce, 0, 0)
np.add.reduce([])
np.add.reduce(np.zeros((0, 0)), axis=())
# OTOH, accumulate always makes sense for any combination of n and m,
# because it maps an m-element array to an m-element array. These
# tests are simpler because accumulate doesn't accept multiple axes.
for uf in (np.maximum, np.add):
uf.accumulate(np.zeros((30, 0)), axis=0)
uf.accumulate(np.zeros((0, 30)), axis=0)
uf.accumulate(np.zeros((30, 30)), axis=0)
uf.accumulate(np.zeros((0, 0)), axis=0)
def test_safe_casting(self):
# In old versions of numpy, in-place operations used the 'unsafe'
# casting rules. In versions >= 1.10, 'same_kind' is the
# default and an exception is raised instead of a warning.
# when 'same_kind' is not satisfied.
a = np.array([1, 2, 3], dtype=int)
# Non-in-place addition is fine
assert_array_equal(assert_no_warnings(np.add, a, 1.1),
[2.1, 3.1, 4.1])
assert_raises(TypeError, np.add, a, 1.1, out=a)
def add_inplace(a, b):
a += b
assert_raises(TypeError, add_inplace, a, 1.1)
# Make sure that explicitly overriding the exception is allowed:
assert_no_warnings(np.add, a, 1.1, out=a, casting="unsafe")
assert_array_equal(a, [2, 3, 4])
def test_ufunc_custom_out(self):
# Test ufunc with built in input types and custom output type
a = np.array([0, 1, 2], dtype='i8')
b = np.array([0, 1, 2], dtype='i8')
c = np.empty(3, dtype=_rational_tests.rational)
# Output must be specified so numpy knows what
# ufunc signature to look for
result = _rational_tests.test_add(a, b, c)
target = np.array([0, 2, 4], dtype=_rational_tests.rational)
assert_equal(result, target)
# The new resolution means that we can (usually) find custom loops
# as long as they match exactly:
result = _rational_tests.test_add(a, b)
assert_equal(result, target)
# This works even more generally, so long the default common-dtype
# promoter works out:
result = _rational_tests.test_add(a, b.astype(np.uint16), out=c)
assert_equal(result, target)
# This scalar path used to go into legacy promotion, but doesn't now:
result = _rational_tests.test_add(a, np.uint16(2))
target = np.array([2, 3, 4], dtype=_rational_tests.rational)
assert_equal(result, target)
def test_operand_flags(self):
a = np.arange(16, dtype=int).reshape(4, 4)
b = np.arange(9, dtype=int).reshape(3, 3)
opflag_tests.inplace_add(a[:-1, :-1], b)
assert_equal(a, np.array([[0, 2, 4, 3], [7, 9, 11, 7],
[14, 16, 18, 11], [12, 13, 14, 15]]))
a = np.array(0)
opflag_tests.inplace_add(a, 3)
assert_equal(a, 3)
opflag_tests.inplace_add(a, [3, 4])
assert_equal(a, 10)
def test_struct_ufunc(self):
import numpy._core._struct_ufunc_tests as struct_ufunc
a = np.array([(1, 2, 3)], dtype='u8,u8,u8')
b = np.array([(1, 2, 3)], dtype='u8,u8,u8')
result = struct_ufunc.add_triplet(a, b)
assert_equal(result, np.array([(2, 4, 6)], dtype='u8,u8,u8'))
assert_raises(RuntimeError, struct_ufunc.register_fail)
def test_custom_ufunc(self):
a = np.array(
[_rational_tests.rational(1, 2),
_rational_tests.rational(1, 3),
_rational_tests.rational(1, 4)],
dtype=_rational_tests.rational)
b = np.array(
[_rational_tests.rational(1, 2),
_rational_tests.rational(1, 3),
_rational_tests.rational(1, 4)],
dtype=_rational_tests.rational)
result = _rational_tests.test_add_rationals(a, b)
expected = np.array(
[_rational_tests.rational(1),
_rational_tests.rational(2, 3),
_rational_tests.rational(1, 2)],
dtype=_rational_tests.rational)
assert_equal(result, expected)
def test_custom_ufunc_forced_sig(self):
# gh-9351 - looking for a non-first userloop would previously hang
with assert_raises(TypeError):
np.multiply(_rational_tests.rational(1), 1,
signature=(_rational_tests.rational, int, None))
def test_custom_array_like(self):
class MyThing:
__array_priority__ = 1000
rmul_count = 0
getitem_count = 0
def __init__(self, shape):
self.shape = shape
def __len__(self):
return self.shape[0]
def __getitem__(self, i):
MyThing.getitem_count += 1
if not isinstance(i, tuple):
i = (i,)
if len(i) > self.ndim:
raise IndexError("boo")
return MyThing(self.shape[len(i):])
def __rmul__(self, other):
MyThing.rmul_count += 1
return self
np.float64(5) * MyThing((3, 3))
assert_(MyThing.rmul_count == 1, MyThing.rmul_count)
assert_(MyThing.getitem_count <= 2, MyThing.getitem_count)
def test_array_wrap_array_priority(self):
class ArrayPriorityBase(np.ndarray):
@classmethod
def __array_wrap__(cls, array, context=None, return_scalar=False):
return cls
class ArrayPriorityMinus0(ArrayPriorityBase):
__array_priority__ = 0
class ArrayPriorityMinus1000(ArrayPriorityBase):
__array_priority__ = -1000
class ArrayPriorityMinus1000b(ArrayPriorityBase):
__array_priority__ = -1000
class ArrayPriorityMinus2000(ArrayPriorityBase):
__array_priority__ = -2000
x = np.ones(2).view(ArrayPriorityMinus1000)
xb = np.ones(2).view(ArrayPriorityMinus1000b)
y = np.ones(2).view(ArrayPriorityMinus2000)
assert np.add(x, y) is ArrayPriorityMinus1000
assert np.add(y, x) is ArrayPriorityMinus1000
assert np.add(x, xb) is ArrayPriorityMinus1000
assert np.add(xb, x) is ArrayPriorityMinus1000b
y_minus0 = np.zeros(2).view(ArrayPriorityMinus0)
assert np.add(np.zeros(2), y_minus0) is ArrayPriorityMinus0
assert type(np.add(xb, x, np.zeros(2))) is np.ndarray
@pytest.mark.parametrize("a", (
np.arange(10, dtype=int),
np.arange(10, dtype=_rational_tests.rational),
))
def test_ufunc_at_basic(self, a):
aa = a.copy()
np.add.at(aa, [2, 5, 2], 1)
assert_equal(aa, [0, 1, 4, 3, 4, 6, 6, 7, 8, 9])
with pytest.raises(ValueError):
# missing second operand
np.add.at(aa, [2, 5, 3])
aa = a.copy()
np.negative.at(aa, [2, 5, 3])
assert_equal(aa, [0, 1, -2, -3, 4, -5, 6, 7, 8, 9])
aa = a.copy()
b = np.array([100, 100, 100])
np.add.at(aa, [2, 5, 2], b)
assert_equal(aa, [0, 1, 202, 3, 4, 105, 6, 7, 8, 9])
with pytest.raises(ValueError):
# extraneous second operand
np.negative.at(a, [2, 5, 3], [1, 2, 3])
with pytest.raises(ValueError):
# second operand cannot be converted to an array
np.add.at(a, [2, 5, 3], [[1, 2], 1])
# ufuncs with indexed loops for performance in ufunc.at
indexed_ufuncs = [np.add, np.subtract, np.multiply, np.floor_divide,
np.maximum, np.minimum, np.fmax, np.fmin]
@pytest.mark.parametrize(
"typecode", np.typecodes['AllInteger'] + np.typecodes['Float'])
@pytest.mark.parametrize("ufunc", indexed_ufuncs)
def test_ufunc_at_inner_loops(self, typecode, ufunc):
if ufunc is np.divide and typecode in np.typecodes['AllInteger']:
# Avoid divide-by-zero and inf for integer divide
a = np.ones(100, dtype=typecode)
indx = np.random.randint(100, size=30, dtype=np.intp)
vals = np.arange(1, 31, dtype=typecode)
else:
a = np.ones(1000, dtype=typecode)
indx = np.random.randint(1000, size=3000, dtype=np.intp)
vals = np.arange(3000, dtype=typecode)
atag = a.copy()
# Do the calculation twice and compare the answers
with warnings.catch_warnings(record=True) as w_at:
warnings.simplefilter('always')
ufunc.at(a, indx, vals)
with warnings.catch_warnings(record=True) as w_loop:
warnings.simplefilter('always')
for i, v in zip(indx, vals):
# Make sure all the work happens inside the ufunc
# in order to duplicate error/warning handling
ufunc(atag[i], v, out=atag[i:i + 1], casting="unsafe")
assert_equal(atag, a)
# If w_loop warned, make sure w_at warned as well
if len(w_loop) > 0:
#
assert len(w_at) > 0
assert w_at[0].category == w_loop[0].category
assert str(w_at[0].message)[:10] == str(w_loop[0].message)[:10]
@pytest.mark.parametrize("typecode", np.typecodes['Complex'])
@pytest.mark.parametrize("ufunc", [np.add, np.subtract, np.multiply])
def test_ufunc_at_inner_loops_complex(self, typecode, ufunc):
a = np.ones(10, dtype=typecode)
indx = np.concatenate([np.ones(6, dtype=np.intp),
np.full(18, 4, dtype=np.intp)])
value = a.dtype.type(1j)
ufunc.at(a, indx, value)
expected = np.ones_like(a)
if ufunc is np.multiply:
expected[1] = expected[4] = -1
else:
expected[1] += 6 * (value if ufunc is np.add else -value)
expected[4] += 18 * (value if ufunc is np.add else -value)
assert_array_equal(a, expected)
def test_ufunc_at_ellipsis(self):
# Make sure the indexed loop check does not choke on iters
# with subspaces
arr = np.zeros(5)
np.add.at(arr, slice(None), np.ones(5))
assert_array_equal(arr, np.ones(5))
def test_ufunc_at_negative(self):
arr = np.ones(5, dtype=np.int32)
indx = np.arange(5)
umt.indexed_negative.at(arr, indx)
# If it is [-1, -1, -1, -100, 0] then the regular strided loop was used
assert np.all(arr == [-1, -1, -1, -200, -1])
def test_ufunc_at_large(self):
# issue gh-23457
indices = np.zeros(8195, dtype=np.int16)
b = np.zeros(8195, dtype=float)
b[0] = 10
b[1] = 5
b[8192:] = 100
a = np.zeros(1, dtype=float)
np.add.at(a, indices, b)
assert a[0] == b.sum()
def test_cast_index_fastpath(self):
arr = np.zeros(10)
values = np.ones(100000)
# index must be cast, which may be buffered in chunks:
index = np.zeros(len(values), dtype=np.uint8)
np.add.at(arr, index, values)
assert arr[0] == len(values)
@pytest.mark.parametrize("value", [
np.ones(1), np.ones(()), np.float64(1.), 1.])
def test_ufunc_at_scalar_value_fastpath(self, value):
arr = np.zeros(1000)
# index must be cast, which may be buffered in chunks:
index = np.repeat(np.arange(1000), 2)
np.add.at(arr, index, value)
assert_array_equal(arr, np.full_like(arr, 2 * value))
def test_ufunc_at_multiD(self):
a = np.arange(9).reshape(3, 3)
b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
np.add.at(a, (slice(None), [1, 2, 1]), b)
assert_equal(a, [[0, 201, 102], [3, 404, 205], [6, 607, 308]])
a = np.arange(27).reshape(3, 3, 3)
b = np.array([100, 200, 300])
np.add.at(a, (slice(None), slice(None), [1, 2, 1]), b)
assert_equal(a,
[[[0, 401, 202],
[3, 404, 205],
[6, 407, 208]],
[[9, 410, 211],
[12, 413, 214],
[15, 416, 217]],
[[18, 419, 220],
[21, 422, 223],
[24, 425, 226]]])
a = np.arange(9).reshape(3, 3)
b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
np.add.at(a, ([1, 2, 1], slice(None)), b)
assert_equal(a, [[0, 1, 2], [403, 404, 405], [206, 207, 208]])
a = np.arange(27).reshape(3, 3, 3)
b = np.array([100, 200, 300])
np.add.at(a, (slice(None), [1, 2, 1], slice(None)), b)
assert_equal(a,
[[[0, 1, 2],
[203, 404, 605],
[106, 207, 308]],
[[9, 10, 11],
[212, 413, 614],
[115, 216, 317]],
[[18, 19, 20],
[221, 422, 623],
[124, 225, 326]]])
a = np.arange(9).reshape(3, 3)
b = np.array([100, 200, 300])
np.add.at(a, (0, [1, 2, 1]), b)
assert_equal(a, [[0, 401, 202], [3, 4, 5], [6, 7, 8]])
a = np.arange(27).reshape(3, 3, 3)
b = np.array([100, 200, 300])
np.add.at(a, ([1, 2, 1], 0, slice(None)), b)
assert_equal(a,
[[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],
[[209, 410, 611],
[12, 13, 14],
[15, 16, 17]],
[[118, 219, 320],
[21, 22, 23],
[24, 25, 26]]])
a = np.arange(27).reshape(3, 3, 3)
b = np.array([100, 200, 300])
np.add.at(a, (slice(None), slice(None), slice(None)), b)
assert_equal(a,
[[[100, 201, 302],
[103, 204, 305],
[106, 207, 308]],
[[109, 210, 311],
[112, 213, 314],
[115, 216, 317]],
[[118, 219, 320],
[121, 222, 323],
[124, 225, 326]]])
def test_ufunc_at_0D(self):
a = np.array(0)
np.add.at(a, (), 1)
assert_equal(a, 1)
assert_raises(IndexError, np.add.at, a, 0, 1)
assert_raises(IndexError, np.add.at, a, [], 1)
def test_ufunc_at_dtypes(self):
# Test mixed dtypes
a = np.arange(10)
np.power.at(a, [1, 2, 3, 2], 3.5)
assert_equal(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9]))
def test_ufunc_at_boolean(self):
# Test boolean indexing and boolean ufuncs
a = np.arange(10)
index = a % 2 == 0
np.equal.at(a, index, [0, 2, 4, 6, 8])
assert_equal(a, [1, 1, 1, 3, 1, 5, 1, 7, 1, 9])
# Test unary operator
a = np.arange(10, dtype='u4')
np.invert.at(a, [2, 5, 2])
assert_equal(a, [0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, 7, 8, 9])
def test_ufunc_at_advanced(self):
# Test empty subspace
orig = np.arange(4)
a = orig[:, None][:, 0:0]
np.add.at(a, [0, 1], 3)
assert_array_equal(orig, np.arange(4))
# Test with swapped byte order
index = np.array([1, 2, 1], np.dtype('i').newbyteorder())
values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder())
np.add.at(values, index, 3)
assert_array_equal(values, [1, 8, 6, 4])
# Test exception thrown
values = np.array(['a', 1], dtype=object)
assert_raises(TypeError, np.add.at, values, [0, 1], 1)
assert_array_equal(values, np.array(['a', 1], dtype=object))
# Test multiple output ufuncs raise error, gh-5665
assert_raises(ValueError, np.modf.at, np.arange(10), [1])
# Test maximum
a = np.array([1, 2, 3])
np.maximum.at(a, [0], 0)
assert_equal(a, np.array([1, 2, 3]))
@pytest.mark.parametrize("dtype",
np.typecodes['AllInteger'] + np.typecodes['Float'])
@pytest.mark.parametrize("ufunc",
[np.add, np.subtract, np.divide, np.minimum, np.maximum])
def test_at_negative_indexes(self, dtype, ufunc):
a = np.arange(0, 10).astype(dtype)
indxs = np.array([-1, 1, -1, 2]).astype(np.intp)
vals = np.array([1, 5, 2, 10], dtype=a.dtype)
expected = a.copy()
for i, v in zip(indxs, vals):
expected[i] = ufunc(expected[i], v)
ufunc.at(a, indxs, vals)
assert_array_equal(a, expected)
assert np.all(indxs == [-1, 1, -1, 2])
def test_at_not_none_signature(self):
# Test ufuncs with non-trivial signature raise a TypeError
a = np.ones((2, 2, 2))
b = np.ones((1, 2, 2))
assert_raises(TypeError, np.matmul.at, a, [0], b)
a = np.array([[[1, 2], [3, 4]]])
assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0])
def test_at_no_loop_for_op(self):
# str dtype does not have a ufunc loop for np.add
arr = np.ones(10, dtype=str)
with pytest.raises(np._core._exceptions._UFuncNoLoopError):
np.add.at(arr, [0, 1], [0, 1])
def test_at_output_casting(self):
arr = np.array([-1])
np.equal.at(arr, [0], [0])
assert arr[0] == 0
def test_at_broadcast_failure(self):
arr = np.arange(5)
with pytest.raises(ValueError):
np.add.at(arr, [0, 1], [1, 2, 3])
def test_reduce_arguments(self):
f = np.add.reduce
d = np.ones((5, 2), dtype=int)
o = np.ones((2,), dtype=d.dtype)
r = o * 5
assert_equal(f(d), r)
# a, axis=0, dtype=None, out=None, keepdims=False
assert_equal(f(d, axis=0), r)
assert_equal(f(d, 0), r)
assert_equal(f(d, 0, dtype=None), r)
assert_equal(f(d, 0, dtype='i'), r)
assert_equal(f(d, 0, 'i'), r)
assert_equal(f(d, 0, None), r)
assert_equal(f(d, 0, None, out=None), r)
assert_equal(f(d, 0, None, out=o), r)
assert_equal(f(d, 0, None, o), r)
assert_equal(f(d, 0, None, None), r)
assert_equal(f(d, 0, None, None, keepdims=False), r)
assert_equal(f(d, 0, None, None, True), r.reshape((1,) + r.shape))
assert_equal(f(d, 0, None, None, False, 0), r)
assert_equal(f(d, 0, None, None, False, initial=0), r)
assert_equal(f(d, 0, None, None, False, 0, True), r)
assert_equal(f(d, 0, None, None, False, 0, where=True), r)
# multiple keywords
assert_equal(f(d, axis=0, dtype=None, out=None, keepdims=False), r)
assert_equal(f(d, 0, dtype=None, out=None, keepdims=False), r)
assert_equal(f(d, 0, None, out=None, keepdims=False), r)
assert_equal(f(d, 0, None, out=None, keepdims=False, initial=0,
where=True), r)
# too little
assert_raises(TypeError, f)
# too much
assert_raises(TypeError, f, d, 0, None, None, False, 0, True, 1)
# invalid axis
assert_raises(TypeError, f, d, "invalid")
assert_raises(TypeError, f, d, axis="invalid")
assert_raises(TypeError, f, d, axis="invalid", dtype=None,
keepdims=True)
# invalid dtype
assert_raises(TypeError, f, d, 0, "invalid")
assert_raises(TypeError, f, d, dtype="invalid")
assert_raises(TypeError, f, d, dtype="invalid", out=None)
# invalid out
assert_raises(TypeError, f, d, 0, None, "invalid")
assert_raises(TypeError, f, d, out="invalid")
assert_raises(TypeError, f, d, out="invalid", dtype=None)
# keepdims boolean, no invalid value
# assert_raises(TypeError, f, d, 0, None, None, "invalid")
# assert_raises(TypeError, f, d, keepdims="invalid", axis=0, dtype=None)
# invalid mix
assert_raises(TypeError, f, d, 0, keepdims="invalid", dtype="invalid",
out=None)
# invalid keyword
assert_raises(TypeError, f, d, axis=0, dtype=None, invalid=0)
assert_raises(TypeError, f, d, invalid=0)
assert_raises(TypeError, f, d, 0, keepdims=True, invalid="invalid",
out=None)
assert_raises(TypeError, f, d, axis=0, dtype=None, keepdims=True,
out=None, invalid=0)
assert_raises(TypeError, f, d, axis=0, dtype=None,
out=None, invalid=0)
def test_structured_equal(self):
# https://github.com/numpy/numpy/issues/4855
class MyA(np.ndarray):
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
return getattr(ufunc, method)(*(input.view(np.ndarray)
for input in inputs), **kwargs)
a = np.arange(12.).reshape(4, 3)
ra = a.view(dtype=('f8,f8,f8')).squeeze()
mra = ra.view(MyA)
target = np.array([True, False, False, False], dtype=bool)
assert_equal(np.all(target == (mra == ra[0])), True)
def test_scalar_equal(self):
# Scalar comparisons should always work, without deprecation warnings.
# even when the ufunc fails.
a = np.array(0.)
b = np.array('a')
assert_(a != b)
assert_(b != a)
assert_(not (a == b))
assert_(not (b == a))
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.maximum, np.minimum, np.mod,
np.greater, np.greater_equal, np.less, np.less_equal,
np.equal, np.not_equal]
a = np.array('1')
b = 1
c = np.array([1., 2.])
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
assert_raises(TypeError, f, c, a)
@pytest.mark.parametrize("ufunc",
[np.logical_and, np.logical_or]) # logical_xor object loop is bad
@pytest.mark.parametrize("signature",
[(None, None, object), (object, None, None),
(None, object, None)])
def test_logical_ufuncs_object_signatures(self, ufunc, signature):
a = np.array([True, None, False], dtype=object)
res = ufunc(a, a, signature=signature)
assert res.dtype == object
@pytest.mark.parametrize("ufunc",
[np.logical_and, np.logical_or, np.logical_xor])
@pytest.mark.parametrize("signature",
[(bool, None, object), (object, None, bool),
(None, object, bool)])
def test_logical_ufuncs_mixed_object_signatures(self, ufunc, signature):
# Most mixed signatures fail (except those with bool out, e.g. `OO->?`)
a = np.array([True, None, False])
with pytest.raises(TypeError):
ufunc(a, a, signature=signature)
@pytest.mark.parametrize("ufunc",
[np.logical_and, np.logical_or, np.logical_xor])
def test_logical_ufuncs_support_anything(self, ufunc):
# The logical ufuncs support even input that can't be promoted:
a = np.array(b'1', dtype="V3")
c = np.array([1., 2.])
assert_array_equal(ufunc(a, c), ufunc([True, True], True))
assert ufunc.reduce(a) == True
# check that the output has no effect:
out = np.zeros(2, dtype=np.int32)
expected = ufunc([True, True], True).astype(out.dtype)
assert_array_equal(ufunc(a, c, out=out), expected)
out = np.zeros((), dtype=np.int32)
assert ufunc.reduce(a, out=out) == True
# Last check, test reduction when out and a match (the complexity here
# is that the "i,i->?" may seem right, but should not match.
a = np.array([3], dtype="i")
out = np.zeros((), dtype=a.dtype)
assert ufunc.reduce(a, out=out) == 1
@pytest.mark.parametrize("ufunc",
[np.logical_and, np.logical_or, np.logical_xor])
@pytest.mark.parametrize("dtype", ["S", "U"])
@pytest.mark.parametrize("values", [["1", "hi", "0"], ["", ""]])
def test_logical_ufuncs_supports_string(self, ufunc, dtype, values):
# note that values are either all true or all false
arr = np.array(values, dtype=dtype)
obj_arr = np.array(values, dtype=object)
res = ufunc(arr, arr)
expected = ufunc(obj_arr, obj_arr, dtype=bool)
assert_array_equal(res, expected)
res = ufunc.reduce(arr)
expected = ufunc.reduce(obj_arr, dtype=bool)
assert_array_equal(res, expected)
@pytest.mark.parametrize("ufunc",
[np.logical_and, np.logical_or, np.logical_xor])
def test_logical_ufuncs_out_cast_check(self, ufunc):
a = np.array('1')
c = np.array([1., 2.])
out = a.copy()
with pytest.raises(TypeError):
# It would be safe, but not equiv casting:
ufunc(a, c, out=out, casting="equiv")
def test_reducelike_byteorder_resolution(self):
# See gh-20699, byte-order changes need some extra care in the type
# resolution to make the following succeed:
arr_be = np.arange(10, dtype=">i8")
arr_le = np.arange(10, dtype="<i8")
assert np.add.reduce(arr_be) == np.add.reduce(arr_le)
assert_array_equal(np.add.accumulate(arr_be), np.add.accumulate(arr_le))
assert_array_equal(
np.add.reduceat(arr_be, [1]), np.add.reduceat(arr_le, [1]))
def test_reducelike_out_promotes(self):
# Check that the out argument to reductions is considered for
# promotion. See also gh-20455.
# Note that these paths could prefer `initial=` in the future and
# do not up-cast to the default integer for add and prod
arr = np.ones(1000, dtype=np.uint8)
out = np.zeros((), dtype=np.uint16)
assert np.add.reduce(arr, out=out) == 1000
arr[:10] = 2
assert np.multiply.reduce(arr, out=out) == 2**10
# For legacy dtypes, the signature currently has to be forced if `out=`
# is passed. The two paths below should differ, without `dtype=` the
# expected result should be: `np.prod(arr.astype("f8")).astype("f4")`!
arr = np.full(5, 2**25 - 1, dtype=np.int64)
# float32 and int64 promote to float64:
res = np.zeros((), dtype=np.float32)
# If `dtype=` is passed, the calculation is forced to float32:
single_res = np.zeros((), dtype=np.float32)
np.multiply.reduce(arr, out=single_res, dtype=np.float32)
assert single_res != res
def test_reducelike_output_needs_identical_cast(self):
# Checks the case where a simple byte-swap works, mainly tests that
# this is not rejected directly.
# (interesting because we require descriptor identity in reducelikes).
arr = np.ones(20, dtype="f8")
out = np.empty((), dtype=arr.dtype.newbyteorder())
expected = np.add.reduce(arr)
np.add.reduce(arr, out=out)
assert_array_equal(expected, out)
# Check reduceat:
out = np.empty(2, dtype=arr.dtype.newbyteorder())
expected = np.add.reduceat(arr, [0, 1])
np.add.reduceat(arr, [0, 1], out=out)
assert_array_equal(expected, out)
# And accumulate:
out = np.empty(arr.shape, dtype=arr.dtype.newbyteorder())
expected = np.add.accumulate(arr)
np.add.accumulate(arr, out=out)
assert_array_equal(expected, out)
def test_reduce_noncontig_output(self):
# Check that reduction deals with non-contiguous output arrays
# appropriately.
#
# gh-8036
x = np.arange(7 * 13 * 8, dtype=np.int16).reshape(7, 13, 8)
x = x[4:6, 1:11:6, 1:5].transpose(1, 2, 0)
y_base = np.arange(4 * 4, dtype=np.int16).reshape(4, 4)
y = y_base[::2, :]
y_base_copy = y_base.copy()
r0 = np.add.reduce(x, out=y.copy(), axis=2)
r1 = np.add.reduce(x, out=y, axis=2)
# The results should match, and y_base shouldn't get clobbered
assert_equal(r0, r1)
assert_equal(y_base[1, :], y_base_copy[1, :])
assert_equal(y_base[3, :], y_base_copy[3, :])
@pytest.mark.parametrize("with_cast", [True, False])
def test_reduceat_and_accumulate_out_shape_mismatch(self, with_cast):
# Should raise an error mentioning "shape" or "size"
arr = np.arange(5)
out = np.arange(3) # definitely wrong shape
if with_cast:
# If a cast is necessary on the output, we can be sure to use
# the generic NpyIter (non-fast) path.
out = out.astype(np.float64)
with pytest.raises(ValueError, match="(shape|size)"):
np.add.reduceat(arr, [0, 3], out=out)
with pytest.raises(ValueError, match="(shape|size)"):
np.add.accumulate(arr, out=out)
@pytest.mark.parametrize('out_shape',
[(), (1,), (3,), (1, 1), (1, 3), (4, 3)])
@pytest.mark.parametrize('keepdims', [True, False])
@pytest.mark.parametrize('f_reduce', [np.add.reduce, np.minimum.reduce])
def test_reduce_wrong_dimension_output(self, f_reduce, keepdims, out_shape):
# Test that we're not incorrectly broadcasting dimensions.
# See gh-15144 (failed for np.add.reduce previously).
a = np.arange(12.).reshape(4, 3)
out = np.empty(out_shape, a.dtype)
correct_out = f_reduce(a, axis=0, keepdims=keepdims)
if out_shape != correct_out.shape:
with assert_raises(ValueError):
f_reduce(a, axis=0, out=out, keepdims=keepdims)
else:
check = f_reduce(a, axis=0, out=out, keepdims=keepdims)
assert_(check is out)
assert_array_equal(check, correct_out)
def test_reduce_output_does_not_broadcast_input(self):
# Test that the output shape cannot broadcast an input dimension
# (it never can add dimensions, but it might expand an existing one)
a = np.ones((1, 10))
out_correct = (np.empty((1, 1)))
out_incorrect = np.empty((3, 1))
np.add.reduce(a, axis=-1, out=out_correct, keepdims=True)
np.add.reduce(a, axis=-1, out=out_correct[:, 0], keepdims=False)
with assert_raises(ValueError):
np.add.reduce(a, axis=-1, out=out_incorrect, keepdims=True)
with assert_raises(ValueError):
np.add.reduce(a, axis=-1, out=out_incorrect[:, 0], keepdims=False)
def test_reduce_output_subclass_ok(self):
class MyArr(np.ndarray):
pass
out = np.empty(())
np.add.reduce(np.ones(5), out=out) # no subclass, all fine
out = out.view(MyArr)
assert np.add.reduce(np.ones(5), out=out) is out
assert type(np.add.reduce(out)) is MyArr
def test_no_doc_string(self):
# gh-9337
assert_('\n' not in umt.inner1d_no_doc.__doc__)
def test_invalid_args(self):
# gh-7961
exc = pytest.raises(TypeError, np.sqrt, None)
# minimally check the exception text
assert exc.match('loop of ufunc does not support')
@pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
def test_nat_is_not_finite(self, nat):
try:
assert not np.isfinite(nat)
except TypeError:
pass # ok, just not implemented
@pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
def test_nat_is_nan(self, nat):
try:
assert np.isnan(nat)
except TypeError:
pass # ok, just not implemented
@pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
def test_nat_is_not_inf(self, nat):
try:
assert not np.isinf(nat)
except TypeError:
pass # ok, just not implemented
| TestUfunc |
python | django__django | tests/logging_tests/tests.py | {
"start": 1732,
"end": 1961
} | class ____:
@classmethod
def setUpClass(cls):
super().setUpClass()
logging.config.dictConfig(DEFAULT_LOGGING)
cls.addClassCleanup(logging.config.dictConfig, settings.LOGGING)
| SetupDefaultLoggingMixin |
python | django__django | tests/admin_changelist/admin.py | {
"start": 1690,
"end": 1765
} | class ____(ChildAdmin):
paginator = CustomPaginator
| CustomPaginationAdmin |
python | ray-project__ray | python/ray/cluster_utils.py | {
"start": 4392,
"end": 15512
} | class ____:
def __init__(
self,
initialize_head: bool = False,
connect: bool = False,
head_node_args: dict = None,
shutdown_at_exit: bool = True,
):
"""Initializes all services of a Ray cluster.
Args:
initialize_head: Automatically start a Ray cluster
by initializing the head node. Defaults to False.
connect: If `initialize_head=True` and `connect=True`,
ray.init will be called with the address of this cluster
passed in.
head_node_args: Arguments to be passed into
`start_ray_head` via `self.add_node`.
shutdown_at_exit: If True, registers an exit hook
for shutting down all started processes.
"""
if cluster_not_supported:
logger.warning(
"Ray cluster mode is currently experimental and untested on "
"Windows. If you are using it and running into issues please "
"file a report at https://github.com/ray-project/ray/issues."
)
self.head_node = None
self.worker_nodes = set()
self.redis_address = None
self.connected = False
# Create a new global state accessor for fetching GCS table.
self.global_state = ray._private.state.GlobalState()
self._shutdown_at_exit = shutdown_at_exit
if not initialize_head and connect:
raise RuntimeError("Cannot connect to uninitialized cluster.")
if initialize_head:
head_node_args = head_node_args or {}
self.add_node(**head_node_args)
if connect:
self.connect()
@property
def gcs_address(self):
if self.head_node is None:
return None
return self.head_node.gcs_address
@property
def address(self):
return self.gcs_address
def connect(self, namespace=None):
"""Connect the driver to the cluster."""
assert self.address is not None
assert not self.connected
output_info = ray.init(
namespace=namespace,
ignore_reinit_error=True,
address=self.address,
_redis_username=self.redis_username,
_redis_password=self.redis_password,
)
logger.info(output_info)
self.connected = True
def add_node(self, wait: bool = True, **node_args):
"""Adds a node to the local Ray Cluster.
All nodes are by default started with the following settings:
cleanup=True,
num_cpus=1,
object_store_memory=150 * 1024 * 1024 # 150 MiB
Args:
wait: Whether to wait until the node is alive.
node_args: Keyword arguments used in `start_ray_head` and
`start_ray_node`. Overrides defaults.
Returns:
Node object of the added Ray node.
"""
default_kwargs = {
"num_cpus": 1,
"num_gpus": 0,
"object_store_memory": 150 * 1024 * 1024, # 150 MiB
"min_worker_port": 0,
"max_worker_port": 0,
}
ray_params = ray._private.parameter.RayParams(**node_args)
ray_params.update_if_absent(**default_kwargs)
with disable_client_hook():
if self.head_node is None:
node = ray._private.node.Node(
ray_params,
head=True,
shutdown_at_exit=self._shutdown_at_exit,
spawn_reaper=self._shutdown_at_exit,
)
self.head_node = node
self.redis_address = self.head_node.redis_address
self.redis_username = node_args.get(
"redis_username", ray_constants.REDIS_DEFAULT_USERNAME
)
self.redis_password = node_args.get(
"redis_password", ray_constants.REDIS_DEFAULT_PASSWORD
)
self.webui_url = self.head_node.webui_url
# Init global state accessor when creating head node.
gcs_options = GcsClientOptions.create(
node.gcs_address,
None,
allow_cluster_id_nil=True,
fetch_cluster_id_if_nil=False,
)
self.global_state._initialize_global_state(gcs_options)
# Write the Ray cluster address for convenience in unit
# testing. ray.init() and ray.init(address="auto") will connect
# to the local cluster.
ray._private.utils.write_ray_address(self.head_node.gcs_address)
else:
ray_params.update_if_absent(redis_address=self.redis_address)
ray_params.update_if_absent(gcs_address=self.gcs_address)
# We only need one log monitor per physical node.
ray_params.update_if_absent(include_log_monitor=False)
# Let grpc pick a port.
ray_params.update_if_absent(node_manager_port=0)
if "dashboard_agent_listen_port" not in node_args:
# Pick a random one to not conflict
# with the head node dashboard agent
ray_params.dashboard_agent_listen_port = None
node = ray._private.node.Node(
ray_params,
head=False,
shutdown_at_exit=self._shutdown_at_exit,
spawn_reaper=self._shutdown_at_exit,
)
self.worker_nodes.add(node)
if wait:
# Wait for the node to appear in the client table. We do this
# so that the nodes appears in the client table in the order
# that the corresponding calls to add_node were made. We do
# this because in the tests we assume that the driver is
# connected to the first node that is added.
self._wait_for_node(node)
return node
def remove_node(self, node, allow_graceful=True):
"""Kills all processes associated with worker node.
Args:
node: Worker node of which all associated processes
will be removed.
"""
global_node = ray._private.worker.global_worker.node
if global_node is not None:
if node._raylet_socket_name == global_node._raylet_socket_name:
ray.shutdown()
raise ValueError(
"Removing a node that is connected to this Ray client "
"is not allowed because it will break the driver. "
"You can use the get_other_node utility to avoid removing "
"a node that the Ray client is connected."
)
node.destroy_external_storage()
if self.head_node == node:
# We have to wait to prevent the raylet becomes a zombie which will prevent
# worker from exiting
self.head_node.kill_all_processes(
check_alive=False, allow_graceful=allow_graceful, wait=True
)
self.head_node = None
# TODO(rliaw): Do we need to kill all worker processes?
else:
# We have to wait to prevent the raylet becomes a zombie which will prevent
# worker from exiting
node.kill_all_processes(
check_alive=False, allow_graceful=allow_graceful, wait=True
)
self.worker_nodes.remove(node)
assert (
not node.any_processes_alive()
), "There are zombie processes left over after killing."
def _wait_for_node(self, node, timeout: float = 30):
"""Wait until this node has appeared in the client table.
Args:
node (ray._private.node.Node): The node to wait for.
timeout: The amount of time in seconds to wait before raising an
exception.
Raises:
TimeoutError: An exception is raised if the timeout expires before
the node appears in the client table.
"""
ray._private.services.wait_for_node(
node.gcs_address,
node.plasma_store_socket_name,
timeout,
)
def wait_for_nodes(self, timeout: float = 30):
"""Waits for correct number of nodes to be registered.
This will wait until the number of live nodes in the client table
exactly matches the number of "add_node" calls minus the number of
"remove_node" calls that have been made on this cluster. This means
that if a node dies without "remove_node" having been called, this will
raise an exception.
Args:
timeout: The number of seconds to wait for nodes to join
before failing.
Raises:
TimeoutError: An exception is raised if we time out while waiting
for nodes to join.
"""
start_time = time.time()
while time.time() - start_time < timeout:
live_clients = self.global_state._live_node_ids()
expected = len(self.list_all_nodes())
if len(live_clients) == expected:
logger.debug("All nodes registered as expected.")
return
else:
logger.debug(
f"{len(live_clients)} nodes are currently registered, "
f"but we are expecting {expected}"
)
time.sleep(0.1)
raise TimeoutError("Timed out while waiting for nodes to join.")
def list_all_nodes(self):
"""Lists all nodes.
TODO(rliaw): What is the desired behavior if a head node
dies before worker nodes die?
Returns:
List of all nodes, including the head node.
"""
nodes = list(self.worker_nodes)
if self.head_node:
nodes = [self.head_node] + nodes
return nodes
def remaining_processes_alive(self):
"""Returns a bool indicating whether all processes are alive or not.
Note that this ignores processes that have been explicitly killed,
e.g., via a command like node.kill_raylet().
Returns:
True if all processes are alive and false otherwise.
"""
return all(node.remaining_processes_alive() for node in self.list_all_nodes())
def shutdown(self):
"""Removes all nodes."""
# We create a list here as a copy because `remove_node`
# modifies `self.worker_nodes`.
all_nodes = list(self.worker_nodes)
for node in all_nodes:
self.remove_node(node)
if self.head_node is not None:
self.remove_node(self.head_node)
# need to reset internal kv since gcs is down
ray.experimental.internal_kv._internal_kv_reset()
# Delete the cluster address.
ray._common.utils.reset_ray_address()
| Cluster |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 542347,
"end": 547733
} | class ____(ExprNode):
"""
Short-circuiting boolean operation.
Note that this node provides the same code generation method as
BoolBinopResultNode to simplify expression nesting.
operator string "and"/"or"
operand1 BoolBinopNode/BoolBinopResultNode left operand
operand2 BoolBinopNode/BoolBinopResultNode right operand
"""
subexprs = ['operand1', 'operand2']
is_temp = True
operator = None
operand1 = None
operand2 = None
def infer_type(self, env):
type1 = self.operand1.infer_type(env)
type2 = self.operand2.infer_type(env)
return PyrexTypes.independent_spanning_type(type1, type2)
def may_be_none(self):
if self.operator == 'or':
return self.operand2.may_be_none()
else:
return self.operand1.may_be_none() or self.operand2.may_be_none()
def calculate_constant_result(self):
operand1 = self.operand1.constant_result
operand2 = self.operand2.constant_result
if self.operator == 'and':
self.constant_result = operand1 and operand2
else:
self.constant_result = operand1 or operand2
def compile_time_value(self, denv):
operand1 = self.operand1.compile_time_value(denv)
operand2 = self.operand2.compile_time_value(denv)
if self.operator == 'and':
return operand1 and operand2
else:
return operand1 or operand2
def is_ephemeral(self):
return self.operand1.is_ephemeral() or self.operand2.is_ephemeral()
def analyse_types(self, env):
# Note: we do not do any coercion here as we most likely do not know the final type anyway.
# We even accept to set self.type to ErrorType if both operands do not have a spanning type.
# The coercion to the final type and to a "simple" value is left to coerce_to().
operand1 = self.operand1.analyse_types(env)
operand2 = self.operand2.analyse_types(env)
self.type = PyrexTypes.independent_spanning_type(
operand1.type, operand2.type)
self.operand1 = self._wrap_operand(operand1, env)
self.operand2 = self._wrap_operand(operand2, env)
return self
def _wrap_operand(self, operand, env):
if not isinstance(operand, (BoolBinopNode, BoolBinopResultNode)):
operand = BoolBinopResultNode(operand, self.type, env)
return operand
def wrap_operands(self, env):
"""
Must get called by transforms that want to create a correct BoolBinopNode
after the type analysis phase.
"""
self.operand1 = self._wrap_operand(self.operand1, env)
self.operand2 = self._wrap_operand(self.operand2, env)
def coerce_to_boolean(self, env):
return self.coerce_to(PyrexTypes.c_bint_type, env)
def coerce_to(self, dst_type, env):
operand1 = self.operand1.coerce_to(dst_type, env)
operand2 = self.operand2.coerce_to(dst_type, env)
return BoolBinopNode.from_node(
self, type=dst_type,
operator=self.operator,
operand1=operand1, operand2=operand2)
def generate_bool_evaluation_code(self, code, final_result_temp, final_result_type, and_label, or_label, end_label, fall_through):
code.mark_pos(self.pos)
outer_labels = (and_label, or_label)
if self.operator == 'and':
my_label = and_label = code.new_label('next_and')
else:
my_label = or_label = code.new_label('next_or')
self.operand1.generate_bool_evaluation_code(
code, final_result_temp, final_result_type, and_label, or_label, end_label, my_label)
and_label, or_label = outer_labels
code.put_label(my_label)
self.operand2.generate_bool_evaluation_code(
code, final_result_temp, final_result_type, and_label, or_label, end_label, fall_through)
def generate_evaluation_code(self, code):
self.allocate_temp_result(code)
result_type = PyrexTypes.py_object_type if self.type.is_pyobject else self.type
or_label = and_label = None
end_label = code.new_label('bool_binop_done')
self.generate_bool_evaluation_code(code, self.result(), result_type, and_label, or_label, end_label, end_label)
code.put_label(end_label)
gil_message = "Truth-testing Python object"
def check_const(self):
return self.operand1.check_const() and self.operand2.check_const()
def generate_subexpr_disposal_code(self, code):
pass # nothing to do here, all done in generate_evaluation_code()
def free_subexpr_temps(self, code):
pass # nothing to do here, all done in generate_evaluation_code()
def generate_operand1_test(self, code):
# Generate code to test the truth of the first operand.
if self.type.is_pyobject:
test_result = code.funcstate.allocate_temp(
PyrexTypes.c_bint_type, manage_ref=False)
code.putln(
"%s = __Pyx_PyObject_IsTrue(%s); %s" % (
test_result,
self.operand1.py_result(),
code.error_goto_if_neg(test_result, self.pos)))
else:
test_result = self.operand1.result()
return (test_result, self.type.is_pyobject)
| BoolBinopNode |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 22603,
"end": 23468
} | class ____:
@pytest.mark.parametrize("unique", [True, False])
@pytest.mark.parametrize("val", [3, 3.0, "3"], ids=type)
def test_setitem_non_bool_into_bool(self, val, indexer_sli, unique):
# dont cast these 3-like values to bool
ser = Series([True, False])
if not unique:
ser.index = [1, 1]
with pytest.raises(TypeError, match="Invalid value"):
indexer_sli(ser)[1] = val
def test_setitem_boolean_array_into_npbool(self):
# GH#45462
ser = Series([True, False, True])
values = ser._values
arr = array([True, False, None])
ser[:2] = arr[:2] # no NAs -> can set inplace
assert ser._values is values
with pytest.raises(TypeError, match="Invalid value"):
ser[1:] = arr[1:] # has an NA -> cast to boolean dtype
| TestSetitemCasting |
python | getsentry__sentry | tests/sentry/preprod/api/endpoints/test_organization_preprod_artifact_assemble.py | {
"start": 1040,
"end": 9565
} | class ____(TestCase):
"""Unit tests for schema validation function - no database required."""
def test_valid_minimal_schema(self) -> None:
"""Test valid minimal schema passes validation."""
data = {"checksum": "a" * 40, "chunks": []}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert result == data
def test_valid_full_schema(self) -> None:
"""Test valid schema with all optional fields passes validation."""
data = {
"checksum": "a" * 40,
"chunks": ["b" * 40, "c" * 40],
"build_configuration": "release",
"head_sha": "e" * 40,
"base_sha": "f" * 40,
"provider": "github",
"head_repo_name": "owner/repo",
"base_repo_name": "owner/repo",
"head_ref": "feature/xyz",
"base_ref": "main",
"pr_number": 123,
}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert result == data
def test_valid_schema_with_commit_comparison(self) -> None:
"""Test valid schema with CommitComparison fields passes validation."""
data = {
"checksum": "a" * 40,
"chunks": ["b" * 40, "c" * 40],
"build_configuration": "release",
"head_sha": "e" * 40,
"base_sha": "f" * 40,
"provider": "github",
"head_repo_name": "owner/repo",
"base_repo_name": "owner/repo",
"head_ref": "feature/xyz",
"base_ref": "main",
"pr_number": 123,
}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert result == data
def test_invalid_json(self) -> None:
"""Test invalid JSON returns error."""
body = b'{"invalid": json}'
result, error = validate_preprod_artifact_schema(body)
assert error == "Invalid json body"
assert result == {}
def test_missing_checksum(self) -> None:
"""Test missing checksum field returns error."""
body = orjson.dumps({"chunks": []})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert "checksum" in error
assert result == {}
def test_invalid_checksum_format(self) -> None:
"""Test invalid checksum format returns error."""
body = orjson.dumps({"checksum": "invalid", "chunks": []})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert "checksum" in error
assert result == {}
def test_checksum_wrong_type(self) -> None:
"""Test non-string checksum returns error."""
body = orjson.dumps({"checksum": 123, "chunks": []})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_missing_chunks(self) -> None:
"""Test missing chunks field returns error."""
body = orjson.dumps({"checksum": "a" * 40})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert "chunks" in error
assert result == {}
def test_chunks_wrong_type(self) -> None:
"""Test non-array chunks returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": "not_array"})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_chunks_invalid_item_format(self) -> None:
"""Test invalid chunk format returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": ["invalid"]})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_chunks_invalid_item_type(self) -> None:
"""Test non-string chunk returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [123]})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_build_configuration_wrong_type(self) -> None:
"""Test non-string build_configuration returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [], "build_configuration": 123})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_head_sha_invalid_format(self) -> None:
"""Test invalid head_sha format returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [], "head_sha": "invalid"})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert "head_sha" in error
assert result == {}
def test_base_sha_invalid_format(self) -> None:
"""Test invalid base_sha format returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [], "base_sha": "invalid"})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert "base_sha" in error
assert result == {}
def test_pr_number_invalid(self) -> None:
"""Test invalid pr_number returns error."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [], "pr_number": 0})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_additional_properties_rejected(self) -> None:
"""Test additional properties are rejected."""
body = orjson.dumps({"checksum": "a" * 40, "chunks": [], "extra_field": "value"})
result, error = validate_preprod_artifact_schema(body)
assert error is not None
assert result == {}
def test_empty_string_head_sha_filtered_out(self) -> None:
"""Test empty string for head_sha is accepted and filtered out."""
data = {"checksum": "a" * 40, "chunks": [], "head_sha": ""}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert "head_sha" not in result
assert result == {"checksum": "a" * 40, "chunks": []}
def test_empty_string_base_sha_filtered_out(self) -> None:
"""Test empty string for base_sha is accepted and filtered out."""
data = {"checksum": "a" * 40, "chunks": [], "base_sha": ""}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert "base_sha" not in result
assert result == {"checksum": "a" * 40, "chunks": []}
def test_empty_string_provider_filtered_out(self) -> None:
"""Test empty string for provider is accepted and filtered out."""
data = {"checksum": "a" * 40, "chunks": [], "provider": ""}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert "provider" not in result
assert result == {"checksum": "a" * 40, "chunks": []}
def test_empty_string_head_ref_filtered_out(self) -> None:
"""Test empty string for head_ref is accepted and filtered out."""
data = {"checksum": "a" * 40, "chunks": [], "head_ref": ""}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert "head_ref" not in result
assert result == {"checksum": "a" * 40, "chunks": []}
def test_empty_strings_with_valid_data_filtered_out(self) -> None:
"""Test empty strings are filtered out while keeping valid data."""
data = {
"checksum": "a" * 40,
"chunks": ["b" * 40],
"head_sha": "",
"provider": "",
"head_ref": "feature/xyz",
"build_configuration": "debug",
}
body = orjson.dumps(data)
result, error = validate_preprod_artifact_schema(body)
assert error is None
assert "head_sha" not in result
assert "provider" not in result
assert result == {
"checksum": "a" * 40,
"chunks": ["b" * 40],
"head_ref": "feature/xyz",
"build_configuration": "debug",
}
| ValidatePreprodArtifactSchemaTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/clever/provider.py | {
"start": 514,
"end": 1753
} | class ____(OAuth2Provider):
id = "clever"
name = "Clever"
account_class = CleverAccount
oauth2_adapter_class = CleverOAuth2Adapter
def extract_uid(self, data):
return data["data"]["id"]
def get_user_type(self, data):
return list(data.get("data", {}).get("roles", {}).keys())[0]
def extract_common_fields(self, data):
return dict(
first_name=data.get("data", {}).get("name", {}).get("first", None),
last_name=data.get("data", {}).get("name", {}).get("last", None),
username=data.get("data", {})
.get("roles", {})
.get(self.get_user_type(data), {})
.get("credentials", {})
.get("district_username", None),
email=data.get("data", {}).get("email", None),
)
def get_default_scope(self):
return [
"read:district_admins",
"read:districts",
"read:resources",
"read:school_admins",
"read:schools",
"read:sections",
"read:student_contacts",
"read:students",
"read:teachers",
"read:user_id",
]
providers.registry.register(CleverProvider)
| CleverProvider |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 10110,
"end": 10214
} | class ____(ShowFieldTypeAndContent, PolymorphicModel):
b = models.CharField(max_length=1)
| CustomPkBase |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail.py | {
"start": 3502,
"end": 3666
} | class ____(BaseModel):
x: int = 1
y = 2
z = 2 # type: ignore[pydantic-field]
AliasGeneratorModel2(x=1)
AliasGeneratorModel2(y=1, z=1)
| UntypedFieldModel |
python | PrefectHQ__prefect | tests/custom_types/test_self_validating_types.py | {
"start": 1053,
"end": 2503
} | class ____:
@pytest.mark.parametrize(
"value,delim,expected",
[
(None, None, set()),
("", None, set()),
("429", None, {429}),
("404,429,503", None, {404, 429, 503}),
("401|403|409", "|", {401, 403, 409}),
(419, None, {419}),
({307, 404, 429, 503}, None, {307, 404, 429, 503}),
],
ids=[
"None",
"empty string",
"single int as string",
"comma separated ints as string",
"pipe separated ints as string",
"single int",
"multiple ints in set",
],
)
def test_valid_set_of_ints(self, value, delim, expected):
"""e.g. scooping PREFECT_CLIENT_RETRY_EXTRA_CODES"""
scoop_set_int_from_string = BeforeValidator(
partial(validate_set_T_from_delim_string, type_=int, delim=delim)
)
_type = Annotated[Set[int], scoop_set_int_from_string]
assert TypeAdapter(_type).validate_python(value) == expected
def test_invalid_list_of_ints(self):
scoop_set_int_from_string = BeforeValidator(
partial(validate_set_T_from_delim_string, type_=int)
)
_type = Annotated[Set[int], scoop_set_int_from_string]
with pytest.raises(ValidationError, match="should be a valid int"):
TypeAdapter(_type).validate_python("just,trust,me")
| TestCustomValidationLogic |
python | google__pytype | pytype/pytd/optimize.py | {
"start": 13881,
"end": 14855
} | class ____(visitors.Visitor):
"""Shortens long unions to object (or "?").
Poor man's version of FindCommonSuperClasses. Shorten types like
"str or unicode or int or float or list" to just "object" or "?".
Additionally, if the union already contains at least one "object", we also
potentially replace the entire union with just "object".
Attributes:
max_length: The maximum number of types to allow in a union. If there are
more types than this, it is shortened.
"""
def __init__(self, max_length: int = 7):
super().__init__()
self.generic_type = pytd.AnythingType()
self.max_length = max_length
def VisitUnionType(self, union):
if len(union.type_list) > self.max_length and not any(
isinstance(t, pytd.Literal) for t in union.type_list
):
return self.generic_type
elif self.generic_type in union.type_list:
return pytd_utils.JoinTypes(union.type_list)
else:
return union
| CollapseLongUnions |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_optimize06.py | {
"start": 315,
"end": 1210
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("optimize06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(
self.got_filename, {"constant_memory": True, "in_memory": False}
)
worksheet = workbook.add_worksheet()
# Test that control characters and any other single byte characters are
# handled correctly by the SharedStrings module. We skip chr 34 = " in
# this test since it isn't encoded by Excel as ".
ordinals = list(range(0, 34))
ordinals.extend(range(35, 128))
for i in ordinals:
worksheet.write_string(i, 0, chr(i))
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | lazyprogrammer__machine_learning_examples | supervised_class2/util.py | {
"start": 1052,
"end": 1763
} | class ____:
def __init__(self, n_estimators, max_depth=None):
self.B = n_estimators
self.max_depth = max_depth
def fit(self, X, Y):
N = len(X)
self.models = []
for b in range(self.B):
idx = np.random.choice(N, size=N, replace=True)
Xb = X[idx]
Yb = Y[idx]
model = DecisionTreeRegressor(max_depth=self.max_depth)
model.fit(Xb, Yb)
self.models.append(model)
def predict(self, X):
predictions = np.zeros(len(X))
for model in self.models:
predictions += model.predict(X)
return predictions / self.B
def score(self, X, Y):
d1 = Y - self.predict(X)
d2 = Y - Y.mean()
return 1 - d1.dot(d1) / d2.dot(d2)
| BaggedTreeRegressor |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 2425,
"end": 14717
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.httpexceptions import HTTPException
return HTTPException
def _getTargetSubclass(
self,
code='200',
title='OK',
explanation='explanation',
empty_body=False,
):
cls = self._getTargetClass()
class Subclass(cls):
pass
Subclass.empty_body = empty_body
Subclass.code = code
Subclass.title = title
Subclass.explanation = explanation
return Subclass
def _makeOne(self, *arg, **kw):
cls = self._getTargetClass()
return cls(*arg, **kw)
def test_implements_IResponse(self):
from pyramid.interfaces import IResponse
cls = self._getTargetClass()
self.assertTrue(IResponse.implementedBy(cls))
def test_provides_IResponse(self):
from pyramid.interfaces import IResponse
inst = self._getTargetClass()()
self.assertTrue(IResponse.providedBy(inst))
def test_implements_IExceptionResponse(self):
from pyramid.interfaces import IExceptionResponse
cls = self._getTargetClass()
self.assertTrue(IExceptionResponse.implementedBy(cls))
def test_provides_IExceptionResponse(self):
from pyramid.interfaces import IExceptionResponse
inst = self._getTargetClass()()
self.assertTrue(IExceptionResponse.providedBy(inst))
def test_ctor_sets_detail(self):
exc = self._makeOne('message')
self.assertEqual(exc.detail, 'message')
def test_ctor_sets_comment(self):
exc = self._makeOne(comment='comment')
self.assertEqual(exc.comment, 'comment')
def test_ctor_calls_Exception_ctor(self):
exc = self._makeOne('message')
self.assertEqual(exc.message, 'message')
def test_ctor_calls_Response_ctor(self):
exc = self._makeOne('message')
self.assertEqual(exc.status, '520 Unknown Error')
def test_ctor_extends_headers(self):
exc = self._makeOne(headers=[('X-Foo', 'foo')])
self.assertEqual(exc.headers.get('X-Foo'), 'foo')
def test_ctor_sets_body_template_obj(self):
exc = self._makeOne(body_template='${foo}')
self.assertEqual(
exc.body_template_obj.substitute({'foo': 'foo'}), 'foo'
)
def test_ctor_with_empty_body(self):
cls = self._getTargetSubclass(empty_body=True)
exc = cls()
self.assertEqual(exc.content_type, None)
self.assertEqual(exc.content_length, None)
def test_ctor_with_body_doesnt_set_default_app_iter(self):
exc = self._makeOne(body=b'123')
self.assertEqual(exc.app_iter, [b'123'])
def test_ctor_with_unicode_body_doesnt_set_default_app_iter(self):
exc = self._makeOne(unicode_body=text_('123'))
self.assertEqual(exc.app_iter, [b'123'])
def test_ctor_with_app_iter_doesnt_set_default_app_iter(self):
exc = self._makeOne(app_iter=[b'123'])
self.assertEqual(exc.app_iter, [b'123'])
def test_ctor_with_body_sets_default_app_iter_html(self):
cls = self._getTargetSubclass()
exc = cls('detail')
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'text/html'
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertTrue(body.startswith(b'<html'))
self.assertTrue(b'200 OK' in body)
self.assertTrue(b'explanation' in body)
self.assertTrue(b'detail' in body)
def test_ctor_with_body_sets_default_app_iter_text(self):
cls = self._getTargetSubclass()
exc = cls('detail')
environ = _makeEnviron()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertEqual(body, b'200 OK\n\nexplanation\n\n\ndetail\n\n')
def test__str__detail(self):
exc = self._makeOne()
exc.detail = 'abc'
self.assertEqual(str(exc), 'abc')
def test__str__explanation(self):
exc = self._makeOne()
exc.explanation = 'def'
self.assertEqual(str(exc), 'def')
def test_wsgi_response(self):
exc = self._makeOne()
self.assertTrue(exc is exc.wsgi_response)
def test_exception(self):
exc = self._makeOne()
self.assertTrue(exc is exc.exception)
def test__calls_start_response(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
start_response = DummyStartResponse()
exc(environ, start_response)
self.assertTrue(start_response.headerlist)
self.assertEqual(start_response.status, '200 OK')
def test_call_returns_same_body_called_twice(self):
# optimization
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = '*/*'
start_response = DummyStartResponse()
app_iter = exc(environ, start_response)
self.assertEqual(app_iter[0], exc.body)
def test__default_app_iter_no_comment_plain(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/plain; charset=UTF-8')
self.assertEqual(body, b'200 OK\n\nexplanation\n\n\n\n\n')
def test__default_app_iter_with_comment_plain(self):
cls = self._getTargetSubclass()
exc = cls(comment='comment')
environ = _makeEnviron()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/plain; charset=UTF-8')
self.assertEqual(body, b'200 OK\n\nexplanation\n\n\n\ncomment\n')
def test__default_app_iter_no_comment_html(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/plain; charset=UTF-8')
self.assertFalse(b'<!-- ' in body)
def test__content_type(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
start_response = DummyStartResponse()
exc(environ, start_response)
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/plain; charset=UTF-8')
def test__content_type_default_is_html(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = '*/*'
start_response = DummyStartResponse()
exc(environ, start_response)
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/html; charset=UTF-8')
def test__content_type_text_html(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'text/html'
start_response = DummyStartResponse()
exc(environ, start_response)
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/html; charset=UTF-8')
def test__content_type_application_json(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'application/json'
start_response = DummyStartResponse()
exc(environ, start_response)
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'application/json')
def test__content_type_invalid(self):
cls = self._getTargetSubclass()
exc = cls()
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'invalid'
start_response = DummyStartResponse()
exc(environ, start_response)
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/html; charset=UTF-8')
def test__default_app_iter_with_comment_ampersand(self):
cls = self._getTargetSubclass()
exc = cls(comment='comment & comment')
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'text/html'
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
for header in start_response.headerlist:
if header[0] == 'Content-Type':
self.assertEqual(header[1], 'text/html; charset=UTF-8')
self.assertTrue(b'<!-- comment & comment -->' in body)
def test__default_app_iter_with_comment_html(self):
cls = self._getTargetSubclass()
exc = cls(comment='comment & comment')
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'text/html'
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertTrue(b'<!-- comment & comment -->' in body)
def test__default_app_iter_with_comment_json(self):
cls = self._getTargetSubclass()
exc = cls(comment='comment & comment')
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'application/json'
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
import json
retval = json.loads(body.decode('UTF-8'))
self.assertEqual(retval['code'], '200 OK')
self.assertEqual(retval['title'], 'OK')
def test__default_app_iter_with_custom_json(self):
def json_formatter(status, body, title, environ):
return {
'message': body,
'code': status,
'title': title,
'custom': environ['CUSTOM_VARIABLE'],
}
cls = self._getTargetSubclass()
exc = cls(comment='comment', json_formatter=json_formatter)
environ = _makeEnviron()
environ['HTTP_ACCEPT'] = 'application/json'
environ['CUSTOM_VARIABLE'] = 'custom!'
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
import json
retval = json.loads(body.decode('UTF-8'))
self.assertEqual(retval['code'], '200 OK')
self.assertEqual(retval['title'], 'OK')
self.assertEqual(retval['custom'], 'custom!')
def test_custom_body_template(self):
cls = self._getTargetSubclass()
exc = cls(body_template='${REQUEST_METHOD}')
environ = _makeEnviron()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertEqual(body, b'200 OK\n\nGET')
def test_custom_body_template_with_custom_variable_doesnt_choke(self):
cls = self._getTargetSubclass()
exc = cls(body_template='${REQUEST_METHOD}')
environ = _makeEnviron()
class Choke:
def __str__(self): # pragma no cover
raise ValueError
environ['gardentheory.user'] = Choke()
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertEqual(body, b'200 OK\n\nGET')
def test_body_template_unicode(self):
cls = self._getTargetSubclass()
la = text_(b'/La Pe\xc3\xb1a', 'utf-8')
environ = _makeEnviron(unicodeval=la)
exc = cls(body_template='${unicodeval}')
start_response = DummyStartResponse()
body = list(exc(environ, start_response))[0]
self.assertEqual(body, b'200 OK\n\n/La Pe\xc3\xb1a')
def test_allow_detail_non_str(self):
exc = self._makeOne(detail={'error': 'This is a test'})
self.assertIsInstance(exc.__str__(), str)
| TestHTTPException |
python | kamyu104__LeetCode-Solutions | Python/closest-node-to-path-in-tree.py | {
"start": 225,
"end": 1159
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.ancestor = range(n) # added
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
self.set[stk.pop()] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return False
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
self.set[x] = self.set[y]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
return True
def find_ancestor_of_set(self, x): # added
return self.ancestor[self.find_set(x)]
def update_ancestor_of_set(self, x): # added
self.ancestor[self.find_set(x)] = x
| UnionFind |
python | plotly__plotly.py | _plotly_utils/exceptions.py | {
"start": 1054,
"end": 1572
} | class ____(PlotlyGraphObjectError):
def __init__(self, obj, path, notes=()):
"""See PlotlyGraphObjectError.__init__ for param docs."""
format_dict = {"attribute": path[-1], "object_name": obj._name}
message = "'{attribute}' is not allowed in '{object_name}'".format(
**format_dict
)
notes = [obj.help(return_help=True)] + list(notes)
super(PlotlyDictKeyError, self).__init__(
message=message, path=path, notes=notes
)
| PlotlyDictKeyError |
python | PyCQA__pylint | doc/data/messages/i/invalid-str-returned/good.py | {
"start": 0,
"end": 105
} | class ____:
"""__str__ returns <type 'str'>"""
def __str__(self):
return "oranges"
| CustomStr |
python | django__django | django/views/generic/edit.py | {
"start": 6479,
"end": 6939
} | class ____(ModelFormMixin, ProcessFormView):
"""
Base view for updating an existing object.
This requires subclassing to provide a response mixin.
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
| BaseUpdateView |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_taskgroup.py | {
"start": 1265,
"end": 31761
} | class ____:
@pytest.mark.parametrize(
("group_id", "exc_type", "exc_value"),
[
pytest.param(
123,
TypeError,
"The key has to be a string and is <class 'int'>:123",
id="type",
),
pytest.param(
"a" * 1000,
ValueError,
"The key has to be less than 200 characters, not 1000",
id="long",
),
pytest.param(
"something*invalid",
ValueError,
"The key 'something*invalid' has to be made of alphanumeric characters, dashes, "
"and underscores exclusively",
id="illegal",
),
],
)
def test_dag_id_validation(self, group_id, exc_type, exc_value):
with pytest.raises(exc_type) as ctx:
TaskGroup(group_id)
assert str(ctx.value) == exc_value
def test_task_group_dependencies_between_tasks_if_task_group_is_empty_1():
"""
Test that if a task group is empty, the dependencies between tasks are still maintained.
"""
with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.parse("20200101")):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group1") as tg1:
pass
with TaskGroup("group2") as tg2:
task2 = EmptyOperator(task_id="task2")
task3 = EmptyOperator(task_id="task3")
task2 >> task3
task1 >> tg1 >> tg2
assert task1.downstream_task_ids == {"group2.task2"}
def test_task_group_dependencies_between_tasks_if_task_group_is_empty_2():
"""
Test that if a task group is empty, the dependencies between tasks are still maintained.
"""
with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.parse("20200101")):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group1") as tg1:
pass
with TaskGroup("group2") as tg2:
pass
with TaskGroup("group3") as tg3:
pass
with TaskGroup("group4") as tg4:
pass
with TaskGroup("group5") as tg5:
task2 = EmptyOperator(task_id="task2")
task3 = EmptyOperator(task_id="task3")
task2 >> task3
task1 >> tg1 >> tg2 >> tg3 >> tg4 >> tg5
assert task1.downstream_task_ids == {"group5.task2"}
def test_task_group_dependencies_between_tasks_if_task_group_is_empty_3():
"""
Test that if a task group is empty, the dependencies between tasks are still maintained.
"""
with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.parse("20200101")):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group1") as tg1:
pass
with TaskGroup("group2") as tg2:
pass
task2 = EmptyOperator(task_id="task2")
with TaskGroup("group3") as tg3:
pass
with TaskGroup("group4") as tg4:
pass
with TaskGroup("group5") as tg5:
task3 = EmptyOperator(task_id="task3")
task4 = EmptyOperator(task_id="task4")
task3 >> task4
task1 >> tg1 >> tg2 >> task2 >> tg3 >> tg4 >> tg5
assert task1.downstream_task_ids == {"task2"}
assert task2.downstream_task_ids == {"group5.task3"}
def test_build_task_group_context_manager():
"""Test basic TaskGroup functionality using context manager."""
logical_date = pendulum.parse("20200101")
with DAG("test_build_task_group_context_manager", schedule=None, start_date=logical_date) as dag:
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group234") as group234:
_ = EmptyOperator(task_id="task2")
with TaskGroup("group34") as group34:
_ = EmptyOperator(task_id="task3")
_ = EmptyOperator(task_id="task4")
task5 = EmptyOperator(task_id="task5")
task1 >> group234
group34 >> task5
assert task1.get_direct_relative_ids(upstream=False) == {
"group234.group34.task4",
"group234.group34.task3",
"group234.task2",
}
assert task5.get_direct_relative_ids(upstream=True) == {
"group234.group34.task4",
"group234.group34.task3",
}
assert dag.task_group.group_id is None
assert dag.task_group.is_root
assert set(dag.task_group.children.keys()) == {"task1", "group234", "task5"}
assert group34.group_id == "group234.group34"
def test_build_task_group():
"""
Test alternative syntax to use TaskGroup. It should result in the same TaskGroup
as using context manager.
"""
logical_date = pendulum.parse("20200101")
dag = DAG("test_build_task_group", schedule=None, start_date=logical_date)
task1 = EmptyOperator(task_id="task1", dag=dag)
group234 = TaskGroup("group234", dag=dag)
_ = EmptyOperator(task_id="task2", dag=dag, task_group=group234)
group34 = TaskGroup("group34", dag=dag, parent_group=group234)
_ = EmptyOperator(task_id="task3", dag=dag, task_group=group34)
_ = EmptyOperator(task_id="task4", dag=dag, task_group=group34)
task5 = EmptyOperator(task_id="task5", dag=dag)
task1 >> group234
group34 >> task5
# Test basic TaskGroup structure
assert dag.task_group.group_id is None
assert dag.task_group.is_root
assert set(dag.task_group.children.keys()) == {"task1", "group234", "task5"}
assert group34.group_id == "group234.group34"
def test_build_task_group_with_prefix():
"""
Tests that prefix_group_id turns on/off prefixing of task_id with group_id.
"""
logical_date = pendulum.parse("20200101")
with DAG("test_build_task_group_with_prefix", start_date=logical_date):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group234", prefix_group_id=False) as group234:
task2 = EmptyOperator(task_id="task2")
with TaskGroup("group34") as group34:
task3 = EmptyOperator(task_id="task3")
with TaskGroup("group4", prefix_group_id=False) as group4:
task4 = EmptyOperator(task_id="task4")
task5 = EmptyOperator(task_id="task5")
task1 >> group234
group34 >> task5
assert task2.task_id == "task2"
assert group34.group_id == "group34"
assert task3.task_id == "group34.task3"
assert group4.group_id == "group34.group4"
assert task4.task_id == "task4"
assert task5.task_id == "task5"
assert group234.get_child_by_label("task2") == task2
assert group234.get_child_by_label("group34") == group34
assert group4.get_child_by_label("task4") == task4
def test_build_task_group_with_prefix_functionality():
"""
Tests TaskGroup prefix_group_id functionality - additional test for comprehensive coverage.
"""
logical_date = pendulum.parse("20200101")
with DAG("test_prefix_functionality", start_date=logical_date):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group234", prefix_group_id=False) as group234:
task2 = EmptyOperator(task_id="task2")
with TaskGroup("group34") as group34:
task3 = EmptyOperator(task_id="task3")
with TaskGroup("group4", prefix_group_id=False) as group4:
task4 = EmptyOperator(task_id="task4")
task5 = EmptyOperator(task_id="task5")
task1 >> group234
group34 >> task5
# Test prefix_group_id behavior
assert task2.task_id == "task2" # prefix_group_id=False, so no prefix
assert group34.group_id == "group34" # nested group gets prefixed
assert task3.task_id == "group34.task3" # task in nested group gets full prefix
assert group4.group_id == "group34.group4" # nested group gets parent prefix
assert task4.task_id == "task4" # prefix_group_id=False, so no prefix
assert task5.task_id == "task5" # root level task, no prefix
# Test group hierarchy and child access
assert group234.get_child_by_label("task2") == task2
assert group234.get_child_by_label("group34") == group34
assert group4.get_child_by_label("task4") == task4
def test_build_task_group_with_task_decorator():
"""
Test that TaskGroup can be used with the @task decorator.
"""
from airflow.sdk import task
@task
def task_1():
print("task_1")
@task
def task_2():
return "task_2"
@task
def task_3():
return "task_3"
@task
def task_4(task_2_output, task_3_output):
print(task_2_output, task_3_output)
@task
def task_5():
print("task_5")
logical_date = pendulum.parse("20200101")
with DAG("test_build_task_group_with_task_decorator", start_date=logical_date):
tsk_1 = task_1()
with TaskGroup("group234") as group234:
tsk_2 = task_2()
tsk_3 = task_3()
tsk_4 = task_4(tsk_2, tsk_3)
tsk_5 = task_5()
tsk_1 >> group234 >> tsk_5
# Test TaskGroup functionality with @task decorator
assert tsk_1.operator in tsk_2.operator.upstream_list
assert tsk_1.operator in tsk_3.operator.upstream_list
assert tsk_5.operator in tsk_4.operator.downstream_list
# Test TaskGroup structure
assert group234.group_id == "group234"
assert len(group234.children) == 3 # task_2, task_3, task_4
assert "group234.task_2" in group234.children
assert "group234.task_3" in group234.children
assert "group234.task_4" in group234.children
def test_sub_dag_task_group():
"""
Tests dag.partial_subset() updates task_group correctly.
"""
logical_date = pendulum.parse("20200101")
with DAG("test_test_task_group_sub_dag", schedule=None, start_date=logical_date) as dag:
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group234") as group234:
_ = EmptyOperator(task_id="task2")
with TaskGroup("group34") as group34:
_ = EmptyOperator(task_id="task3")
_ = EmptyOperator(task_id="task4")
with TaskGroup("group6") as group6:
_ = EmptyOperator(task_id="task6")
task7 = EmptyOperator(task_id="task7")
task5 = EmptyOperator(task_id="task5")
task1 >> group234
group34 >> task5
group234 >> group6
group234 >> task7
subset = dag.partial_subset(task_ids="task5", include_upstream=True, include_downstream=False)
# Test that partial_subset correctly updates task_group structure
groups = subset.task_group.get_task_group_dict()
assert groups.keys() == {None, "group234", "group234.group34"}
included_group_ids = {"group234", "group234.group34"}
included_task_ids = {"group234.group34.task3", "group234.group34.task4", "task1", "task5"}
# Test that subset maintains correct group relationships
for task_group in groups.values():
assert task_group.upstream_group_ids.issubset(included_group_ids)
assert task_group.downstream_group_ids.issubset(included_group_ids)
assert task_group.upstream_task_ids.issubset(included_task_ids)
assert task_group.downstream_task_ids.issubset(included_task_ids)
# Test that subset maintains correct task relationships
for task in subset.task_group:
assert task.upstream_task_ids.issubset(included_task_ids)
assert task.downstream_task_ids.issubset(included_task_ids)
# Test basic subset properties
assert len(subset.tasks) == 4 # task1, task3, task4, task5
assert subset.task_dict["task1"].task_id == "task1"
assert subset.task_dict["group234.group34.task3"].task_id == "group234.group34.task3"
assert subset.task_dict["group234.group34.task4"].task_id == "group234.group34.task4"
assert subset.task_dict["task5"].task_id == "task5"
def test_dag_edges_task_group_structure():
logical_date = pendulum.parse("20200101")
with DAG("test_dag_edges", schedule=None, start_date=logical_date):
task1 = EmptyOperator(task_id="task1")
with TaskGroup("group_a") as group_a:
with TaskGroup("group_b") as group_b:
task2 = EmptyOperator(task_id="task2")
task3 = EmptyOperator(task_id="task3")
task4 = EmptyOperator(task_id="task4")
task2 >> [task3, task4]
task5 = EmptyOperator(task_id="task5")
task5 << group_b
task1 >> group_a
with TaskGroup("group_c") as group_c:
task6 = EmptyOperator(task_id="task6")
task7 = EmptyOperator(task_id="task7")
task8 = EmptyOperator(task_id="task8")
[task6, task7] >> task8
group_a >> group_c
task5 >> task8
task9 = EmptyOperator(task_id="task9")
task10 = EmptyOperator(task_id="task10")
group_c >> [task9, task10]
with TaskGroup("group_d") as group_d:
task11 = EmptyOperator(task_id="task11")
task12 = EmptyOperator(task_id="task12")
task11 >> task12
group_d << group_c
# Test TaskGroup structure and relationships
assert group_a.group_id == "group_a"
assert group_b.group_id == "group_a.group_b"
assert group_c.group_id == "group_c"
assert group_d.group_id == "group_d"
# Test task relationships within groups
assert task2.downstream_task_ids == {"group_a.group_b.task3", "group_a.group_b.task4"}
assert task3.upstream_task_ids == {"group_a.group_b.task2"}
assert task4.upstream_task_ids == {"group_a.group_b.task2"}
assert task5.upstream_task_ids == {"group_a.group_b.task3", "group_a.group_b.task4"}
# Test cross-group relationships
assert task1.downstream_task_ids == {"group_a.group_b.task2"}
assert task6.upstream_task_ids == {"group_a.task5"}
assert task7.upstream_task_ids == {"group_a.task5"}
assert task8.upstream_task_ids == {"group_c.task6", "group_c.task7", "group_a.task5"}
# Test group-to-task relationships
assert task9.upstream_task_ids == {"group_c.task8"}
assert task10.upstream_task_ids == {"group_c.task8"}
assert task11.upstream_task_ids == {"group_c.task8"}
def test_duplicate_group_id():
from airflow.exceptions import DuplicateTaskIdFound
logical_date = pendulum.parse("20200101")
with DAG("test_duplicate_group_id", schedule=None, start_date=logical_date):
_ = EmptyOperator(task_id="task1")
with pytest.raises(DuplicateTaskIdFound, match=r".* 'task1' .*"), TaskGroup("task1"):
pass
with DAG("test_duplicate_group_id", schedule=None, start_date=logical_date):
_ = EmptyOperator(task_id="task1")
with TaskGroup("group1", prefix_group_id=False):
with pytest.raises(DuplicateTaskIdFound, match=r".* 'group1' .*"), TaskGroup("group1"):
pass
with DAG("test_duplicate_group_id", schedule=None, start_date=logical_date):
with TaskGroup("group1", prefix_group_id=False):
with pytest.raises(DuplicateTaskIdFound, match=r".* 'group1' .*"):
_ = EmptyOperator(task_id="group1")
with DAG("test_duplicate_group_id", schedule=None, start_date=logical_date):
_ = EmptyOperator(task_id="task1")
with TaskGroup("group1"):
with pytest.raises(DuplicateTaskIdFound, match=r".* 'group1.downstream_join_id' .*"):
_ = EmptyOperator(task_id="downstream_join_id")
with DAG("test_duplicate_group_id", schedule=None, start_date=logical_date):
_ = EmptyOperator(task_id="task1")
with TaskGroup("group1"):
with pytest.raises(DuplicateTaskIdFound, match=r".* 'group1.upstream_join_id' .*"):
_ = EmptyOperator(task_id="upstream_join_id")
def test_task_without_dag():
"""
Test that if a task doesn't have a DAG when it's being set as the relative of another task which
has a DAG, the task should be added to the root TaskGroup of the other task's DAG.
"""
dag = DAG(dag_id="test_task_without_dag", schedule=None, start_date=pendulum.parse("20200101"))
op1 = EmptyOperator(task_id="op1", dag=dag)
op2 = EmptyOperator(task_id="op2")
op3 = EmptyOperator(task_id="op3")
op1 >> op2
op3 >> op2
assert op1.dag == op2.dag == op3.dag
assert dag.task_group.children.keys() == {"op1", "op2", "op3"}
assert dag.task_group.children.keys() == dag.task_dict.keys()
def test_default_args():
"""Testing TaskGroup with default_args"""
logical_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_default_args",
schedule=None,
start_date=logical_date,
default_args={"owner": "dag"},
):
with TaskGroup("group1", default_args={"owner": "group"}):
task_1 = EmptyOperator(task_id="task_1")
task_2 = EmptyOperator(task_id="task_2", owner="task")
task_3 = EmptyOperator(task_id="task_3", default_args={"owner": "task"})
assert task_1.owner == "group"
assert task_2.owner == "task"
assert task_3.owner == "task"
def test_iter_tasks():
with DAG("test_dag", schedule=None, start_date=pendulum.parse("20200101")) as dag:
with TaskGroup("section_1") as tg1:
EmptyOperator(task_id="task1")
with TaskGroup("section_2") as tg2:
task2 = EmptyOperator(task_id="task2")
task3 = EmptyOperator(task_id="task3")
mapped_bash_operator = BashOperator.partial(task_id="bash_task").expand(
bash_command=[
"echo hello 1",
"echo hello 2",
"echo hello 3",
]
)
task2 >> task3 >> mapped_bash_operator
tg1 >> tg2
root_group = dag.task_group
assert [t.task_id for t in root_group.iter_tasks()] == [
"section_1.task1",
"section_2.task2",
"section_2.task3",
"section_2.bash_task",
]
assert [t.task_id for t in tg1.iter_tasks()] == [
"section_1.task1",
]
assert [t.task_id for t in tg2.iter_tasks()] == [
"section_2.task2",
"section_2.task3",
"section_2.bash_task",
]
def test_override_dag_default_args():
logical_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_default_args",
schedule=None,
start_date=logical_date,
default_args={"owner": "dag"},
):
with TaskGroup("group1", default_args={"owner": "group"}):
task_1 = EmptyOperator(task_id="task_1")
task_2 = EmptyOperator(task_id="task_2", owner="task")
task_3 = EmptyOperator(task_id="task_3", default_args={"owner": "task"})
assert task_1.owner == "group"
assert task_2.owner == "task"
assert task_3.owner == "task"
def test_override_dag_default_args_in_nested_tg():
logical_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_default_args",
schedule=None,
start_date=logical_date,
default_args={"owner": "dag"},
):
with TaskGroup("group1", default_args={"owner": "group1"}):
task_1 = EmptyOperator(task_id="task_1")
with TaskGroup("group2", default_args={"owner": "group2"}):
task_2 = EmptyOperator(task_id="task_2")
task_3 = EmptyOperator(task_id="task_3", owner="task")
assert task_1.owner == "group1"
assert task_2.owner == "group2"
assert task_3.owner == "task"
def test_override_dag_default_args_in_multi_level_nested_tg():
logical_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_default_args",
schedule=None,
start_date=logical_date,
default_args={"owner": "dag"},
):
with TaskGroup("group1", default_args={"owner": "group1"}):
task_1 = EmptyOperator(task_id="task_1")
with TaskGroup("group2"):
task_2 = EmptyOperator(task_id="task_2")
with TaskGroup("group3", default_args={"owner": "group3"}):
task_3 = EmptyOperator(task_id="task_3")
task_4 = EmptyOperator(task_id="task_4", owner="task")
assert task_1.owner == "group1"
assert task_2.owner == "group1" # inherits from group1
assert task_3.owner == "group3"
assert task_4.owner == "task"
def test_task_group_arrow_with_setups_teardowns():
with DAG(dag_id="hi", schedule=None, start_date=pendulum.datetime(2022, 1, 1)):
with TaskGroup(group_id="tg1") as tg1:
s1 = EmptyOperator(task_id="s1")
w1 = EmptyOperator(task_id="w1")
t1 = EmptyOperator(task_id="t1")
s1 >> w1 >> t1.as_teardown(setups=s1)
w2 = EmptyOperator(task_id="w2")
tg1 >> w2
assert t1.downstream_task_ids == set()
assert w1.downstream_task_ids == {"tg1.t1", "w2"}
assert s1.downstream_task_ids == {"tg1.t1", "tg1.w1"}
assert t1.upstream_task_ids == {"tg1.s1", "tg1.w1"}
def test_task_group_arrow_basic():
with DAG(dag_id="basic_group_test"):
with TaskGroup("group_1") as g1:
task_1 = EmptyOperator(task_id="task_1")
with TaskGroup("group_2") as g2:
task_2 = EmptyOperator(task_id="task_2")
g1 >> g2
# Test basic TaskGroup relationships
assert task_1.downstream_task_ids == {"group_2.task_2"}
assert task_2.upstream_task_ids == {"group_1.task_1"}
def test_task_group_nested_structure():
with DAG(dag_id="nested_group_test"):
with TaskGroup("group_1") as g1:
with TaskGroup("group_1_1") as g1_1:
task_1_1 = EmptyOperator(task_id="task_1_1")
with TaskGroup("group_2") as g2:
task_2 = EmptyOperator(task_id="task_2")
g1 >> g2
# Test nested TaskGroup structure
assert g1_1.group_id == "group_1.group_1_1"
assert task_1_1.task_id == "group_1.group_1_1.task_1_1"
assert task_1_1.downstream_task_ids == {"group_2.task_2"}
assert task_2.upstream_task_ids == {"group_1.group_1_1.task_1_1"}
def test_task_group_with_invalid_arg_type_raises_error():
error_msg = r"'ui_color' must be <class 'str'> \(got 123 that is a <class 'int'>\)\."
with DAG(dag_id="dag_with_tg_invalid_arg_type", schedule=None):
with pytest.raises(TypeError, match=error_msg):
_ = TaskGroup("group_1", ui_color=123)
def test_task_group_arrow_with_setup_group_deeper_setup():
"""
When recursing upstream for a non-teardown leaf, we should ignore setups that
are direct upstream of a teardown.
"""
with DAG(dag_id="setup_group_teardown_group_2", schedule=None, start_date=pendulum.now()):
with TaskGroup("group_1") as g1:
@setup
def setup_1(): ...
@setup
def setup_2(): ...
@teardown
def teardown_0(): ...
s1 = setup_1()
s2 = setup_2()
t0 = teardown_0()
s2 >> t0
with TaskGroup("group_2") as g2:
@teardown
def teardown_1(): ...
@teardown
def teardown_2(): ...
t1 = teardown_1()
t2 = teardown_2()
@task_decorator
def work(): ...
w1 = work()
g1 >> w1 >> g2
t1.as_teardown(setups=s1)
t2.as_teardown(setups=s2)
assert set(s1.operator.downstream_task_ids) == {"work", "group_2.teardown_1"}
assert set(s2.operator.downstream_task_ids) == {"group_1.teardown_0", "group_2.teardown_2"}
assert set(w1.operator.downstream_task_ids) == {"group_2.teardown_1", "group_2.teardown_2"}
assert set(t1.operator.downstream_task_ids) == set()
assert set(t2.operator.downstream_task_ids) == set()
def test_add_to_sub_group():
with DAG("test_dag", schedule=None, start_date=pendulum.parse("20200101")):
tg = TaskGroup("section")
task = EmptyOperator(task_id="task")
with pytest.raises(TaskAlreadyInTaskGroup) as ctx:
tg.add(task)
assert str(ctx.value) == "cannot add 'task' to 'section' (already in the DAG's root group)"
def test_add_to_another_group():
with DAG("test_dag", schedule=None, start_date=pendulum.parse("20200101")):
tg = TaskGroup("section_1")
with TaskGroup("section_2"):
task = EmptyOperator(task_id="task")
with pytest.raises(TaskAlreadyInTaskGroup) as ctx:
tg.add(task)
assert str(ctx.value) == "cannot add 'section_2.task' to 'section_1' (already in group 'section_2')"
def test_task_group_edge_modifier_chain():
from airflow.sdk import Label, chain
with DAG(dag_id="test", schedule=None, start_date=pendulum.DateTime(2022, 5, 20)) as dag:
start = EmptyOperator(task_id="sleep_3_seconds")
with TaskGroup(group_id="group1") as tg:
t1 = EmptyOperator(task_id="dummy1")
t2 = EmptyOperator(task_id="dummy2")
t3 = EmptyOperator(task_id="echo_done")
# The case we are testing for is when a Label is inside a list -- meaning that we do tg.set_upstream
# instead of label.set_downstream
chain(start, [Label("branch three")], tg, t3)
assert start.downstream_task_ids == {t1.node_id, t2.node_id}
assert t3.upstream_task_ids == {t1.node_id, t2.node_id}
assert tg.upstream_task_ids == set()
assert tg.downstream_task_ids == {t3.node_id}
# Check that we can perform a topological_sort
dag.topological_sort()
def test_mapped_task_group_id_prefix_task_id():
from tests_common.test_utils.mock_operators import MockOperator
with DAG(dag_id="d", schedule=None, start_date=DEFAULT_DATE) as dag:
t1 = MockOperator.partial(task_id="t1").expand(arg1=[])
with TaskGroup("g"):
t2 = MockOperator.partial(task_id="t2").expand(arg1=[])
assert t1.task_id == "t1"
assert t2.task_id == "g.t2"
dag.get_task("t1") == t1
dag.get_task("g.t2") == t2
def test_pass_taskgroup_output_to_task():
"""Test that the output of a task group can be passed to a task."""
from airflow.sdk import task
@task
def one():
return 1
@task_group_decorator
def addition_task_group(num):
@task
def add_one(i):
return i + 1
return add_one(num)
@task
def increment(num):
return num + 1
@dag(schedule=None, start_date=pendulum.DateTime(2022, 1, 1), default_args={"owner": "airflow"})
def wrap():
total_1 = one()
assert isinstance(total_1, XComArg)
total_2 = addition_task_group(total_1)
assert isinstance(total_2, XComArg)
total_3 = increment(total_2)
assert isinstance(total_3, XComArg)
wrap()
def test_decorator_unknown_args():
"""Test that unknown args passed to the decorator cause an error at parse time"""
with pytest.raises(TypeError):
@task_group_decorator(b=2)
def tg(): ...
def test_decorator_multiple_use_task():
from airflow.sdk import task
@dag("test-dag", schedule=None, start_date=DEFAULT_DATE)
def _test_dag():
@task
def t():
pass
@task_group_decorator
def tg():
for _ in range(3):
t()
t() >> tg() >> t()
test_dag = _test_dag()
assert test_dag.task_ids == [
"t", # Start end.
"tg.t",
"tg.t__1",
"tg.t__2",
"t__1", # End node.
]
def test_build_task_group_depended_by_task():
"""A decorator-based task group should be able to be used as a relative to operators."""
from airflow.sdk import dag as dag_decorator, task
@dag_decorator(schedule=None, start_date=pendulum.now())
def build_task_group_depended_by_task():
@task
def task_start():
return "[Task_start]"
@task
def task_end():
return "[Task_end]"
@task
def task_thing(value):
return f"[Task_thing {value}]"
@task_group_decorator
def section_1():
task_thing(1)
task_thing(2)
task_start() >> section_1() >> task_end()
dag = build_task_group_depended_by_task()
task_thing_1 = dag.task_dict["section_1.task_thing"]
task_thing_2 = dag.task_dict["section_1.task_thing__1"]
# Tasks in the task group don't depend on each other; they both become
# downstreams to task_start, and upstreams to task_end.
assert task_thing_1.upstream_task_ids == task_thing_2.upstream_task_ids == {"task_start"}
assert task_thing_1.downstream_task_ids == task_thing_2.downstream_task_ids == {"task_end"}
def test_build_task_group_with_operators():
"""Tests Dag with Tasks created with *Operators and TaskGroup created with taskgroup decorator"""
from airflow.sdk import task
def task_start():
return "[Task_start]"
def task_end():
print("[ Task_End ]")
# Creating Tasks
@task
def task_1(value):
return f"[ Task1 {value} ]"
@task
def task_2(value):
return f"[ Task2 {value} ]"
@task
def task_3(value):
print(f"[ Task3 {value} ]")
# Creating TaskGroups
@task_group_decorator(group_id="section_1")
def section_a(value):
"""TaskGroup for grouping related Tasks"""
return task_3(task_2(task_1(value)))
logical_date = pendulum.parse("20201109")
with DAG(
dag_id="example_task_group_decorator_mix",
schedule=None,
start_date=logical_date,
tags=["example"],
) as dag:
t_start = PythonOperator(task_id="task_start", python_callable=task_start, dag=dag)
sec_1 = section_a(t_start.output)
t_end = PythonOperator(task_id="task_end", python_callable=task_end, dag=dag)
sec_1.set_downstream(t_end)
# Testing Tasks in Dag
assert set(dag.task_group.children.keys()) == {"section_1", "task_start", "task_end"}
assert set(dag.task_group.children["section_1"].children.keys()) == {
"section_1.task_2",
"section_1.task_3",
"section_1.task_1",
}
# Testing Tasks downstream
assert dag.task_dict["task_start"].downstream_task_ids == {"section_1.task_1"}
assert dag.task_dict["section_1.task_3"].downstream_task_ids == {"task_end"}
| TestTaskGroup |
python | pennersr__django-allauth | allauth/mfa/webauthn/views.py | {
"start": 2444,
"end": 2892
} | class ____(ListView):
template_name = (
"mfa/webauthn/authenticator_list." + account_settings.TEMPLATE_EXTENSION
)
context_object_name = "authenticators"
def get_queryset(self):
return Authenticator.objects.filter(
user=self.request.user, type=Authenticator.Type.WEBAUTHN
)
list_webauthn = ListWebAuthnView.as_view()
@method_decorator(reauthentication_required, name="dispatch")
| ListWebAuthnView |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 30356,
"end": 30751
} | class ____(TestBasicOps, TestCase):
def setUp(self):
super().setUp()
self.case = "empty OrderedSet"
self.values = []
self.OrderedSet = OrderedSet(self.values)
self.dup = OrderedSet(self.values)
self.length = 0
self.repr = "OrderedSet()"
# ------------------------------------------------------------------------------
| TestBasicOpsEmpty |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 6521,
"end": 6931
} | class ____(BaseModel):
commands: List[str]
"""Ordered shell commands for the execution environment to run."""
max_output_length: Optional[int] = None
"""
Maximum number of UTF-8 characters to capture from combined stdout and stderr
output.
"""
timeout_ms: Optional[int] = None
"""Maximum wall-clock time in milliseconds to allow the shell commands to run."""
| ShellCallAction |
python | neetcode-gh__leetcode | python/0110-balanced-binary-tree.py | {
"start": 192,
"end": 572
} | class ____:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def dfs(root):
if not root:
return [True, 0]
left, right = dfs(root.left), dfs(root.right)
balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1
return [balanced, 1 + max(left[1], right[1])]
return dfs(root)[0]
| Solution |
python | econchick__interrogate | src/interrogate/coverage.py | {
"start": 2938,
"end": 20374
} | class ____:
"""The doc coverage interrogator!
:param list(str) paths: list of paths to interrogate.
:param config.InterrogateConfig conf: interrogation configuration.
:param tuple(str) excluded: tuple of files and directories to exclude
in assessing coverage.
:param list[str] extensions: additional file extensions to interrogate.
"""
COMMON_EXCLUDE: Final[list[str]] = [".tox", ".venv", "venv", ".git", ".hg"]
VALID_EXT: Final[list[str]] = [
".py",
".pyi",
] # someday in the future: .ipynb
def __init__(
self,
paths: list[str],
conf: config.InterrogateConfig | None = None,
excluded: tuple[str] | None = None,
extensions: tuple[str] | None = None,
):
self.paths = paths
self.extensions = set(extensions or set())
self.extensions.add(".py")
self.config = conf or config.InterrogateConfig()
self.excluded = excluded or ()
self.common_base = ""
self._add_common_exclude()
self.skipped_file_count = 0
self.output_formatter: utils.OutputFormatter
def _add_common_exclude(self) -> None:
"""Ignore common directories by default"""
for path in self.paths:
self.excluded = self.excluded + tuple( # type: ignore
os.path.join(path, i) for i in self.COMMON_EXCLUDE
)
def _filter_files(self, files: list[str]) -> Iterator[str]:
"""Filter files that are explicitly excluded."""
for f in files:
has_valid_ext = any([f.endswith(ext) for ext in self.extensions])
if not has_valid_ext:
continue
if self.config.ignore_init_module:
basename = os.path.basename(f)
if basename == "__init__.py":
continue
if any(fnmatch.fnmatch(f, exc + "*") for exc in self.excluded):
continue
yield f
def get_filenames_from_paths(self) -> list[str]:
"""Find all files to measure for docstring coverage."""
filenames = []
for path in self.paths:
if os.path.isfile(path):
has_valid_ext = any(
[path.endswith(ext) for ext in self.VALID_EXT]
)
if not has_valid_ext:
msg = (
f"E: Invalid file '{path}'. Unable to interrogate "
"non-Python or Python-like files. "
f"Valid file extensions: {', '.join(self.VALID_EXT)}"
)
click.echo(msg, err=True)
return sys.exit(1)
filenames.append(path)
continue
for root, dirs, fs in os.walk(path):
full_paths = [os.path.join(root, f) for f in fs]
filenames.extend(self._filter_files(full_paths))
if not filenames:
p = ", ".join(self.paths)
msg = (
f"E: No Python or Python-like files found to interrogate in "
f"'{p}'."
)
click.echo(msg, err=True)
return sys.exit(1)
self.common_base = utils.get_common_base(filenames)
return filenames
def _filter_nodes(self, nodes: list[visit.CovNode]) -> list[visit.CovNode]:
"""Remove empty modules when ignoring modules."""
is_empty = 1 == len(nodes)
if is_empty and self.config.ignore_module:
return []
if not self.config.include_regex:
return nodes
# FIXME: any methods, closures, inner functions/classes, etc
# will print out with extra indentation if the parent
# does not meet the whitelist
filtered = []
module_node = None
for node in nodes:
if node.node_type == "Module":
module_node = node
continue
for regexp in self.config.include_regex:
match = regexp.match(node.name)
if match:
filtered.append(node)
if module_node and filtered:
filtered.insert(0, module_node)
return filtered
def _filter_inner_nested(
self, nodes: list[visit.CovNode]
) -> list[visit.CovNode]:
"""Filter out children of ignored nested funcs/classes."""
nested_cls = [n for n in nodes if n.is_nested_cls]
inner_nested_nodes = [n for n in nodes if n.parent in nested_cls]
filtered_nodes = [n for n in nodes if n not in inner_nested_nodes]
filtered_nodes = [n for n in filtered_nodes if n not in nested_cls]
return filtered_nodes
def _set_google_style(self, nodes: list[visit.CovNode]) -> None:
"""Apply Google-style docstrings for class coverage.
Update coverage of a class node if its `__init__` method has a
docstring, or an `__init__` method if its class has a docstring.
A class and its `__init__` method are considered covered if either one
contains a docstring. See <https://sphinxcontrib-napoleon.readthedocs.
io/en/latest/example_google.html>`_ for more info and an example.
"""
for node in nodes:
if node.node_type == "FunctionDef" and node.name == "__init__":
if not node.covered and node.parent.covered: # type: ignore
setattr(node, "covered", True)
elif node.covered and not node.parent.covered: # type: ignore
setattr(node.parent, "covered", True)
def _get_file_coverage(
self, filename: str
) -> InterrogateFileResult | None:
"""Get coverage results for a particular file."""
with open(filename, encoding="utf-8") as f:
source_tree = f.read()
parsed_tree = ast.parse(source_tree)
visitor = visit.CoverageVisitor(filename=filename, config=self.config)
visitor.visit(parsed_tree)
filtered_nodes = self._filter_nodes(visitor.nodes)
if len(filtered_nodes) == 0:
return None
if self.config.ignore_nested_functions:
filtered_nodes = [
n for n in filtered_nodes if not n.is_nested_func
]
if self.config.ignore_nested_classes:
filtered_nodes = self._filter_inner_nested(filtered_nodes)
if self.config.docstring_style == "google":
self._set_google_style(filtered_nodes)
results = InterrogateFileResult(
filename=filename,
ignore_module=self.config.ignore_module,
nodes=filtered_nodes,
)
results.combine()
return results
def _get_coverage(self, filenames: list[str]) -> InterrogateResults:
"""Get coverage results."""
results = InterrogateResults()
file_results = []
for f in filenames:
result = self._get_file_coverage(f)
if result:
file_results.append(result)
results.file_results = file_results
results.combine()
fail_under_str = str(self.config.fail_under)
fail_under_dec = decimal.Decimal(fail_under_str)
round_to = -fail_under_dec.as_tuple().exponent # type: ignore
if self.config.fail_under > round(results.perc_covered, round_to):
results.ret_code = 1
return results
def get_coverage(self) -> InterrogateResults:
"""Get coverage results from files."""
filenames = self.get_filenames_from_paths()
return self._get_coverage(filenames)
def _get_filename(self, filename: str) -> str:
"""Get filename for output information.
If only one file is being interrogated, then ``self.common_base``
and ``filename`` will be the same. Therefore, take the file
``os.path.basename`` as the return ``filename``.
"""
if filename == self.common_base:
return os.path.basename(filename)
return filename[len(self.common_base) + 1 :]
def _get_detailed_row(
self, node: visit.CovNode, filename: str
) -> list[str]:
"""Generate a row of data for the detailed view."""
filename = self._get_filename(filename)
if node.node_type == "Module":
if self.config.ignore_module:
return [filename, ""]
name = f"{filename} (module)"
else:
name = node.path.split(":")[-1]
name = f"{name} (L{node.lineno})"
padding = " " * node.level
name = f"{padding}{name}"
status = "MISSED" if not node.covered else "COVERED"
return [name, status]
def _create_detailed_table(
self, combined_results: InterrogateResults
) -> list[list[str]]:
"""Generate table for the detailed view.
The detailed view shows coverage of each module, class, and
function/method.
"""
def _sort_nodes(x: visit.CovNode) -> int:
"""Sort nodes by line number."""
lineno = getattr(x, "lineno", 0)
# lineno is "None" if module is empty
if lineno is None:
lineno = 0
return lineno
verbose_tbl = []
header = ["Name", "Status"]
verbose_tbl.append(header)
verbose_tbl.append(self.output_formatter.TABLE_SEPARATOR)
for file_result in combined_results.file_results:
if (
self.config.omit_covered_files
and file_result.perc_covered == 100
):
continue
nodes = file_result.nodes
nodes = sorted(nodes, key=_sort_nodes)
for n in nodes:
verbose_tbl.append(
self._get_detailed_row(n, file_result.filename)
)
verbose_tbl.append(self.output_formatter.TABLE_SEPARATOR)
return verbose_tbl
def _print_detailed_table(self, results: InterrogateResults) -> None:
"""Print detailed table to the given output stream."""
detailed_table = self._create_detailed_table(results)
# don't print an empty table if --omit-covered & all files have 100%
if len(detailed_table) < 3:
return
to_print = tabulate.tabulate(
detailed_table,
tablefmt=self.output_formatter.get_table_formatter(
table_type="detailed"
),
colalign=["left", "right"],
)
self.output_formatter.tw.sep(
"-",
"Detailed Coverage",
fullwidth=self.output_formatter.TERMINAL_WIDTH,
)
self.output_formatter.tw.line(to_print)
self.output_formatter.tw.line()
def _create_summary_table(
self, combined_results: InterrogateResults
) -> list[list[str]]:
"""Generate table for the summary view.
The summary view shows coverage for an overall file.
"""
table = []
header = ["Name", "Total", "Miss", "Cover", "Cover%"]
table.append(header)
table.append(self.output_formatter.TABLE_SEPARATOR)
for file_result in combined_results.file_results:
filename = self._get_filename(file_result.filename)
if (
self.config.omit_covered_files
and file_result.perc_covered == 100
):
continue
perc_covered = f"{file_result.perc_covered:.0f}%"
row = [
filename,
str(file_result.total),
str(file_result.missing),
str(file_result.covered),
perc_covered,
]
table.append(row)
# avoid printing an unneeded second separator if there are
# no summary results from --omit-covered
if len(table) > 2:
table.append(self.output_formatter.TABLE_SEPARATOR)
total_perc_covered = f"{combined_results.perc_covered:.1f}%"
total_row = [
"TOTAL",
str(combined_results.total),
str(combined_results.missing),
str(combined_results.covered),
total_perc_covered,
]
table.append(total_row)
return table
def _print_summary_table(self, results: InterrogateResults) -> None:
"""Print summary table to the given output stream."""
summary_table = self._create_summary_table(results)
self.output_formatter.tw.sep(
"-",
title="Summary",
fullwidth=self.output_formatter.TERMINAL_WIDTH,
)
to_print = tabulate.tabulate(
summary_table,
tablefmt=self.output_formatter.get_table_formatter(
table_type="summary"
),
colalign=("left", "right", "right", "right", "right"),
)
self.output_formatter.tw.line(to_print)
@staticmethod
def _sort_results(results: InterrogateResults) -> InterrogateResults:
"""Sort results by filename, directories first"""
all_filenames_map = {r.filename: r for r in results.file_results}
all_dirs = sorted(
{
os.path.dirname(r.filename)
for r in results.file_results
if os.path.dirname(r.filename) != ""
}
)
sorted_results = []
while all_dirs:
current_dir = all_dirs.pop(0)
files = []
for p in os.listdir(current_dir):
path = os.path.join(current_dir, p)
if path in all_filenames_map.keys():
files.append(path)
files = sorted(files)
sorted_results.extend(files)
sorted_res = []
for filename in sorted_results:
sorted_res.append(all_filenames_map[filename])
results.file_results = sorted_res
return results
def _get_header_base(self) -> str:
"""Get common base directory for header of verbose output."""
base = self.common_base
if os.path.isfile(base):
base = os.path.dirname(base)
if sys.platform in ("cygwin", "win32"): # pragma: no cover
return base + "\\"
return base + "/"
def _print_omitted_file_count(self, results: InterrogateResults) -> None:
"""Print # of files omitted due to 100% coverage and --omit-covered.
:param InterrogateResults results: results of docstring coverage
interrogation.
"""
if not self.config.omit_covered_files:
return
omitted_files = [
r for r in results.file_results if r.perc_covered == 100
]
omitted_file_count = len(omitted_files)
if omitted_file_count == 0:
return
total_files_scanned = len(results.file_results)
files_humanized = "files" if total_files_scanned > 1 else "file"
files_skipped = (
f"({omitted_file_count} of {total_files_scanned} {files_humanized} "
"omitted due to complete coverage)"
)
to_print = tabulate.tabulate(
[self.output_formatter.TABLE_SEPARATOR, [files_skipped]],
tablefmt=self.output_formatter.get_table_formatter(
table_type="summary"
),
colalign=("center",),
)
self.output_formatter.tw.line(to_print)
def print_results(
self, results: InterrogateResults, output: str | None, verbosity: int
) -> None:
"""Print results to a given output stream.
:param InterrogateResults results: results of docstring coverage
interrogation.
:param output: filename to output results. If ``None``, uses
``sys.stdout``.
:type output: ``str`` or ``None``
:param int verbosity: level of detail to print out (``0``-``2``).
"""
with utils.smart_open(output, "w") as f:
self.output_formatter = utils.OutputFormatter(
file=f, config=self.config
)
results = self._sort_results(results)
if verbosity > 0:
base = self._get_header_base()
self.output_formatter.tw.sep(
"=",
f"Coverage for {base}",
fullwidth=self.output_formatter.TERMINAL_WIDTH,
)
if verbosity > 1:
self._print_detailed_table(results)
if verbosity > 0:
self._print_summary_table(results)
status, color = "PASSED", {"green": True}
if results.ret_code > 0:
status, color = "FAILED", {"red": True}
if self.output_formatter.should_markup() is False:
color = {}
status_line = "RESULT: {} (minimum: {}%, actual: {:.1f}%)".format(
status, self.config.fail_under, results.perc_covered
)
if verbosity > 0:
self._print_omitted_file_count(results)
self.output_formatter.tw.sep(
"-",
title=status_line,
fullwidth=self.output_formatter.TERMINAL_WIDTH,
**color,
)
else:
self.output_formatter.tw.line(status_line)
| InterrogateCoverage |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 130218,
"end": 137637
} | class ____(fixtures.MappedTest, testing.AssertsCompiledSQL):
"""test #2188"""
__dialect__ = "default"
run_create_tables = None
@classmethod
def define_tables(cls, metadata):
Table("a", metadata, Column("id", Integer, primary_key=True))
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("a_id", Integer, ForeignKey("a.id")),
Column("value", Integer),
)
@classmethod
def setup_classes(cls):
class A(cls.Comparable):
pass
class B(cls.Comparable):
pass
def _fixture(self, props):
A, B = self.classes.A, self.classes.B
b_table, a_table = self.tables.b, self.tables.a
self.mapper_registry.map_imperatively(A, a_table, properties=props)
self.mapper_registry.map_imperatively(
B, b_table, properties={"a": relationship(A, backref="bs")}
)
def test_column_property(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
cp = select(func.sum(b_table.c.value)).where(
b_table.c.a_id == a_table.c.id
)
self._fixture({"summation": column_property(cp.scalar_subquery())})
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(A.summation)
.limit(50),
"SELECT anon_1.anon_2 AS anon_1_anon_2, anon_1.a_id "
"AS anon_1_a_id, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT "
"(SELECT sum(b.value) AS sum_1 FROM b WHERE b.a_id = a.id) "
"AS anon_2, a.id AS a_id FROM a ORDER BY anon_2 "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 ON "
"anon_1.a_id = b_1.a_id ORDER BY anon_1.anon_2",
)
def test_column_property_desc(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
cp = select(func.sum(b_table.c.value)).where(
b_table.c.a_id == a_table.c.id
)
self._fixture({"summation": column_property(cp.scalar_subquery())})
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(A.summation.desc())
.limit(50),
"SELECT anon_1.anon_2 AS anon_1_anon_2, anon_1.a_id "
"AS anon_1_a_id, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT "
"(SELECT sum(b.value) AS sum_1 FROM b WHERE b.a_id = a.id) "
"AS anon_2, a.id AS a_id FROM a ORDER BY anon_2 DESC "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 ON "
"anon_1.a_id = b_1.a_id ORDER BY anon_1.anon_2 DESC",
)
def test_column_property_correlated(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
cp = (
select(func.sum(b_table.c.value))
.where(b_table.c.a_id == a_table.c.id)
.correlate(a_table)
)
self._fixture({"summation": column_property(cp.scalar_subquery())})
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(A.summation)
.limit(50),
"SELECT anon_1.anon_2 AS anon_1_anon_2, anon_1.a_id "
"AS anon_1_a_id, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT "
"(SELECT sum(b.value) AS sum_1 FROM b WHERE b.a_id = a.id) "
"AS anon_2, a.id AS a_id FROM a ORDER BY anon_2 "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 ON "
"anon_1.a_id = b_1.a_id ORDER BY anon_1.anon_2",
)
def test_standalone_subquery_unlabeled(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
self._fixture({})
cp = (
select(func.sum(b_table.c.value))
.where(b_table.c.a_id == a_table.c.id)
.correlate(a_table)
.scalar_subquery()
)
# up until 0.8, this was ordering by a new subquery.
# the removal of a separate _make_proxy() from ScalarSelect
# fixed that.
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(cp)
.limit(50),
"SELECT anon_1.a_id AS anon_1_a_id, anon_1.anon_2 "
"AS anon_1_anon_2, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT a.id "
"AS a_id, (SELECT sum(b.value) AS sum_1 FROM b WHERE "
"b.a_id = a.id) AS anon_2 FROM a ORDER BY (SELECT "
"sum(b.value) AS sum_1 FROM b WHERE b.a_id = a.id) "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 "
"ON anon_1.a_id = b_1.a_id ORDER BY anon_1.anon_2",
)
def test_standalone_subquery_labeled(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
self._fixture({})
cp = (
select(func.sum(b_table.c.value))
.where(b_table.c.a_id == a_table.c.id)
.correlate(a_table)
.scalar_subquery()
.label("foo")
)
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(cp)
.limit(50),
"SELECT anon_1.a_id AS anon_1_a_id, anon_1.foo "
"AS anon_1_foo, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT a.id "
"AS a_id, (SELECT sum(b.value) AS sum_1 FROM b WHERE "
"b.a_id = a.id) AS foo FROM a ORDER BY foo "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 "
"ON anon_1.a_id = b_1.a_id ORDER BY "
"anon_1.foo",
)
def test_standalone_negated(self):
A = self.classes.A
b_table, a_table = self.tables.b, self.tables.a
self._fixture({})
cp = (
select(func.sum(b_table.c.value))
.where(b_table.c.a_id == a_table.c.id)
.correlate(a_table)
.scalar_subquery()
)
# test a different unary operator
# TODO: there is no test in Core that asserts what is happening
# here as far as the label generation for the ORDER BY
# NOTE: this very old test was in fact producing invalid SQL
# until #6008 was fixed
self.assert_compile(
fixture_session()
.query(A)
.options(joinedload(A.bs))
.order_by(~cp)
.limit(50),
"SELECT anon_1.a_id AS anon_1_a_id, anon_1.anon_2 "
"AS anon_1_anon_2, b_1.id AS b_1_id, b_1.a_id AS "
"b_1_a_id, b_1.value AS b_1_value FROM (SELECT a.id "
"AS a_id, NOT (SELECT sum(b.value) AS sum_1 FROM b "
"WHERE b.a_id = a.id) AS anon_2 FROM a ORDER BY NOT (SELECT "
"sum(b.value) AS sum_1 FROM b WHERE b.a_id = a.id) "
"LIMIT :param_1) AS anon_1 LEFT OUTER JOIN b AS b_1 "
"ON anon_1.a_id = b_1.a_id ORDER BY anon_1.anon_2",
)
| SubqueryAliasingTest |
python | getsentry__sentry | src/sentry/web/api.py | {
"start": 2711,
"end": 4259
} | class ____(BaseView):
def get(self, request: Request) -> HttpResponse:
return HttpResponse(json.dumps(get_client_config(request)), content_type="application/json")
@all_silo_view
@cache_control(max_age=3600, public=True)
def robots_txt(request):
if settings.SENTRY_MODE == SentryMode.SAAS and not request.subdomain:
return HttpResponse(ROBOTS_SENTRY_IO, content_type="text/plain")
return HttpResponse(ROBOTS_DISALLOW_ALL, content_type="text/plain")
@all_silo_view
@cache_control(max_age=3600, public=True)
def security_txt(request):
if settings.SENTRY_MODE == SentryMode.SELF_HOSTED:
return HttpResponse(status=404)
return HttpResponse(SECURITY, content_type="text/plain")
@all_silo_view
@cache_control(max_age=3600, public=True)
def mcp_json(request):
if settings.SENTRY_MODE == SentryMode.SELF_HOSTED:
return HttpResponse(status=404)
return HttpResponse(json.dumps(MCP_CONFIG), content_type="application/json")
@region_silo_view
@cache_control(max_age=60)
def crossdomain_xml(request, project_id):
try:
project = Project.objects.get_from_cache(id=project_id)
except Project.DoesNotExist:
return HttpResponse(status=404)
origin_list = get_origins(project)
response = render_to_response("sentry/crossdomain.xml", {"origin_list": origin_list})
response["Content-Type"] = "application/xml"
return response
@all_silo_view
@cache_control(max_age=3600, public=True)
def not_found(request):
return HttpResponse(status=404)
| ClientConfigView |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar15.py | {
"start": 315,
"end": 1829
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar15.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
chartsheet1 = workbook.add_chartsheet()
worksheet2 = workbook.add_worksheet()
chartsheet2 = workbook.add_chartsheet()
chart1 = workbook.add_chart({"type": "bar"})
chart2 = workbook.add_chart({"type": "column"})
chart1.axis_ids = [62576896, 62582784]
chart2.axis_ids = [65979904, 65981440]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet1.write_column("A1", data[0])
worksheet1.write_column("B1", data[1])
worksheet1.write_column("C1", data[2])
worksheet2.write_column("A1", data[0])
worksheet2.write_column("B1", data[1])
worksheet2.write_column("C1", data[2])
chart1.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart1.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart1.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart2.add_series({"values": "=Sheet2!$A$1:$A$5"})
chartsheet1.set_chart(chart1)
chartsheet2.set_chart(chart2)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/olostep_web/base.py | {
"start": 259,
"end": 5215
} | class ____(BasePydanticReader):
"""
A web reader that uses Olostep API to scrape web pages.
Args:
api_key (str): The Olostep API key.
mode (str): The mode to run the loader in. One of "scrape" or "search".
Default is "scrape".
params (Optional[dict]): Additional parameters for the API call.
"""
api_key: str
mode: str
params: Optional[dict]
_metadata_fn: Optional[Callable[[str], Dict]] = PrivateAttr()
def __init__(
self,
api_key: str,
mode: str = "scrape",
params: Optional[dict] = None,
) -> None:
"""Initialize with parameters."""
super().__init__(
api_key=api_key,
mode=mode,
params=params or {},
)
@classmethod
def class_name(cls) -> str:
return "OlostepWebReader"
def load_data(
self,
url: Optional[str] = None,
query: Optional[str] = None,
params: Optional[dict] = None,
) -> List[Document]:
"""
Load data from the input URL or query.
Args:
url (Optional[str]): URL to scrape or for sitemap.
query (Optional[str]): Query for search.
params (Optional[dict]): Additional parameters for the API call.
Returns:
List[Document]: List of documents.
"""
if self.mode == "scrape":
if not url:
raise ValueError("URL must be provided for scrape mode.")
return self._scrape(url, params=params)
elif self.mode == "search":
if not query:
raise ValueError("Query must be provided for search mode.")
return self._search(query, params=params)
else:
raise ValueError("Invalid mode. Choose from 'scrape' or 'search'.")
def _search(self, query: str, params: Optional[dict] = None) -> List[Document]:
"""
Perform a search using Olostep's Google Search parser.
Args:
query (str): The search query.
params (Optional[dict]): Additional parameters for the API call.
Returns:
List[Document]: A list containing a single document with the search results.
"""
import json
combined_params = {**(self.params or {}), **(params or {})}
search_url = f"https://www.google.com/search?q={query}"
api_url = "https://api.olostep.com/v1/scrapes"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
data = {
"url_to_scrape": search_url,
"formats": ["json"],
"parser": {"id": "@olostep/google-search"},
"wait_before_scraping": 0,
}
data.update(combined_params)
response = requests.post(api_url, headers=headers, json=data)
response.raise_for_status()
result = response.json().get("result", {})
json_content = result.get("json_content")
metadata = {
"source": search_url,
"query": query,
"page_metadata": result.get("page_metadata", {}),
}
return [Document(text=json.dumps(json_content, indent=4), metadata=metadata)]
def _scrape(self, url: str, params: Optional[dict] = None) -> List[Document]:
"""
Scrape a single URL.
Args:
url (str): The URL to scrape.
params (Optional[dict]): Additional parameters for the API call.
Returns:
List[Document]: A list containing a single document with the scraped content.
"""
api_url = "https://api.olostep.com/v1/scrapes"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
data = {"url_to_scrape": url, "formats": ["markdown"]}
# Combine and add parameters
combined_params = {**(self.params or {}), **(params or {})}
data.update(combined_params)
response = requests.post(api_url, headers=headers, json=data)
response.raise_for_status()
result = response.json().get("result", {})
import json
content_parts = []
requested_formats = data.get("formats", [])
for format in requested_formats:
content_key = f"{format}_content"
if content_key in result:
content_value = result[content_key]
if format == "json" and isinstance(content_value, (dict, list)):
content_parts.append(json.dumps(content_value, indent=4))
else:
content_parts.append(str(content_value))
content = "\n\n".join(content_parts)
metadata = {"source": url, "page_metadata": result.get("page_metadata", {})}
return [Document(text=content, metadata=metadata)]
| OlostepWebReader |
python | nryoung__algorithms | tests/test_math.py | {
"start": 1517,
"end": 1777
} | class ____(unittest.TestCase):
def test_lcm(self):
# Find lcm of (16, 20) and (20, 16)
r, r2 = lcm(16, 20), lcm(20, 16)
self.assertEqual(r, 80)
# Checks that lcm function is commutative
self.assertEqual(r, r2)
| TestLCM |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 146967,
"end": 147278
} | class ____(IterDataPipe):
def __init__(self) -> None:
self.n = 10
self.source = list(range(self.n))
# This class's `__iter__` is not a generator function
def __iter__(self):
return iter(self.source)
def __len__(self):
return self.n
| _CustomNonGeneratorTestDataPipe |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/configurable.py | {
"start": 2753,
"end": 4718
} | class ____(ConfigurableDefinition):
"""An interface that makes the `configured` method not accept a name argument."""
def configured(
self,
config_or_config_fn: Any,
config_schema: CoercableToConfigSchema = None,
description: Optional[str] = None,
) -> Self:
"""Wraps this object in an object of the same type that provides configuration to the inner
object.
Using ``configured`` may result in config values being displayed in
the Dagster UI, so it is not recommended to use this API with sensitive values,
such as secrets.
Args:
config_or_config_fn (Union[Any, Callable[[Any], Any]]): Either (1) Run configuration
that fully satisfies this object's config schema or (2) A function that accepts run
configuration and returns run configuration that fully satisfies this object's
config schema. In the latter case, config_schema must be specified. When
passing a function, it's easiest to use :py:func:`configured`.
config_schema (ConfigSchema): If config_or_config_fn is a function, the config schema
that its input must satisfy.
description (Optional[str]): Description of the new definition. If not specified,
inherits the description of the definition being configured.
Returns (ConfigurableDefinition): A configured version of this object.
"""
new_config_schema = ConfiguredDefinitionConfigSchema(
self, convert_user_facing_definition_config_schema(config_schema), config_or_config_fn
)
return self.copy_for_configured(description, new_config_schema)
@abstractmethod
def copy_for_configured(
self,
description: Optional[str],
config_schema: IDefinitionConfigSchema,
) -> Self:
raise NotImplementedError()
| AnonymousConfigurableDefinition |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 18720,
"end": 19006
} | class ____(count_neighbors_consistency):
def setup_method(self):
n = 50
m = 2
np.random.seed(1234)
self.T1 = self.kdtree_type(np.random.randn(n, m), leafsize=2)
self.T2 = self.kdtree_type(np.random.randn(n, m), leafsize=2)
| _Test_count_neighbors |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 23981,
"end": 25064
} | class ____(AsyncHTTPTestCase):
def respond_100(self, request):
self.http1 = request.version.startswith("HTTP/1.")
if not self.http1:
request.connection.write_headers(
ResponseStartLine("", 200, "OK"), HTTPHeaders()
)
request.connection.finish()
return
self.request = request
fut = self.request.connection.stream.write(b"HTTP/1.1 100 CONTINUE\r\n\r\n")
fut.add_done_callback(self.respond_200)
def respond_200(self, fut):
fut.result()
fut = self.request.connection.stream.write(
b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nA"
)
fut.add_done_callback(lambda f: self.request.connection.stream.close())
def get_app(self):
# Not a full Application, but works as an HTTPServer callback
return self.respond_100
def test_100_continue(self):
res = self.fetch("/")
if not self.http1:
self.skipTest("requires HTTP/1.x")
self.assertEqual(res.body, b"A")
| HTTP100ContinueTestCase |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 50049,
"end": 51836
} | class ____(Request):
"""
Gets queue information
:param queue: Queue ID
:type queue: str
:param max_task_entries: Max number of queue task entries to return
:type max_task_entries: int
"""
_service = "queues"
_action = "get_by_id"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"max_task_entries": {
"description": "Max number of queue task entries to return",
"type": "integer",
},
"queue": {"description": "Queue ID", "type": "string"},
},
"required": ["queue"],
"type": "object",
}
def __init__(self, queue: str, max_task_entries: Optional[int] = None, **kwargs: Any) -> None:
super(GetByIdRequest, self).__init__(**kwargs)
self.queue = queue
self.max_task_entries = max_task_entries
@schema_property("queue")
def queue(self) -> str:
return self._property_queue
@queue.setter
def queue(self, value: str) -> None:
if value is None:
self._property_queue = None
return
self.assert_isinstance(value, "queue", six.string_types)
self._property_queue = value
@schema_property("max_task_entries")
def max_task_entries(self) -> Optional[int]:
return self._property_max_task_entries
@max_task_entries.setter
def max_task_entries(self, value: Optional[int]) -> None:
if value is None:
self._property_max_task_entries = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "max_task_entries", six.integer_types)
self._property_max_task_entries = value
| GetByIdRequest |
python | has2k1__plotnine | plotnine/stats/stat_boxplot.py | {
"start": 139,
"end": 6034
} | class ____(stat):
"""
Compute boxplot statistics
{usage}
Parameters
----------
{common_parameters}
coef : float, default=1.5
Length of the whiskers as a multiple of the Interquartile
Range.
See Also
--------
plotnine.geom_boxplot: The default `geom` for this `stat`.
"""
_aesthetics_doc = """
{aesthetics_table}
**Options for computed aesthetics**
```python
"width" # width of boxplot
"lower" # lower hinge, 25% quantile
"middle" # median, 50% quantile
"upper" # upper hinge, 75% quantile
# lower edge of notch, computed as;
# median - 1.58 * IQR / sqrt(n)
"notchlower"
# upper edge of notch, computed as;
# median + 1.58 * IQR / sqrt(n)
"notchupper"
# lower whisker, computed as; smallest observation
# greater than or equal to lower hinge - 1.5 * IQR
"ymin"
# upper whisker, computed as; largest observation
# less than or equal to upper hinge + 1.5 * IQR
"ymax"
```
'n' # Number of observations at a position
Calculated aesthetics are accessed using the `after_stat` function.
e.g. `after_stat('width')`{.py}.
"""
REQUIRED_AES = {"x", "y"}
NON_MISSING_AES = {"weight"}
DEFAULT_PARAMS = {
"geom": "boxplot",
"position": "dodge",
"na_rm": False,
"coef": 1.5,
"width": None,
}
CREATES = {
"lower",
"upper",
"middle",
"ymin",
"ymax",
"outliers",
"notchupper",
"notchlower",
"width",
"relvarwidth",
"n",
}
def setup_data(self, data):
if "x" not in data:
data["x"] = 0
return data
def setup_params(self, data):
if self.params["width"] is None:
x = data.get("x", 0)
self.params["width"] = resolution(x, False) * 0.75
def compute_group(self, data, scales):
n = len(data)
y = data["y"].to_numpy()
if "weight" in data:
weights = data["weight"]
total_weight = np.sum(weights)
else:
weights = None
total_weight = len(y)
res = weighted_boxplot_stats(
y, weights=weights, whis=self.params["coef"]
)
if len(np.unique(data["x"])) > 1:
width = np.ptp(data["x"]) * 0.9
else:
width = self.params["width"]
if isinstance(data["x"].dtype, pd.CategoricalDtype):
x = data["x"].iloc[0]
else:
x = np.mean([data["x"].min(), data["x"].max()])
d = {
"ymin": res["whislo"],
"lower": res["q1"],
"middle": [res["med"]],
"upper": res["q3"],
"ymax": res["whishi"],
"outliers": [res["fliers"]],
"notchupper": res["cihi"],
"notchlower": res["cilo"],
"x": x,
"width": width,
"relvarwidth": np.sqrt(total_weight),
"n": n,
}
return pd.DataFrame(d)
def weighted_percentile(a, q, weights=None):
"""
Compute the weighted q-th percentile of data
Parameters
----------
a : array_like
Input that can be converted into an array.
q : array_like[float]
Percentile or sequence of percentiles to compute. Must be int
the range [0, 100]
weights : array_like
Weights associated with the input values.
"""
# Calculate and interpolate weighted percentiles
# method derived from https://en.wikipedia.org/wiki/Percentile
# using numpy's standard C = 1
if weights is None:
weights = np.ones(len(a))
weights = np.asarray(weights)
q = np.asarray(q)
C = 1
idx_s = np.argsort(a)
a_s = a[idx_s]
w_n = weights[idx_s]
S_N = np.sum(weights)
S_n = np.cumsum(w_n)
p_n = (S_n - C * w_n) / (S_N + (1 - 2 * C) * w_n)
pcts = np.interp(q / 100.0, p_n, a_s)
return pcts
def weighted_boxplot_stats(x, weights=None, whis=1.5):
"""
Calculate weighted boxplot plot statistics
Parameters
----------
x : array_like
Data
weights : array_like
Weights associated with the data.
whis : float
Position of the whiskers beyond the interquartile range.
The data beyond the whisker are considered outliers.
If a float, the lower whisker is at the lowest datum above
`Q1 - whis*(Q3-Q1)`, and the upper whisker at the highest
datum below `Q3 + whis*(Q3-Q1)`, where Q1 and Q3 are the
first and third quartiles. The default value of
`whis = 1.5` corresponds to Tukey's original definition of
boxplots.
Notes
-----
This method adapted from Matplotlibs boxplot_stats. The key difference
is the use of a weighted percentile calculation and then using linear
interpolation to map weight percentiles back to data.
"""
if weights is None:
q1, med, q3 = np.percentile(x, (25, 50, 75))
n = len(x)
else:
q1, med, q3 = weighted_percentile(x, (25, 50, 75), weights)
n = np.sum(weights)
iqr = q3 - q1
mean = np.average(x, weights=weights)
cilo = med - 1.58 * iqr / np.sqrt(n)
cihi = med + 1.58 * iqr / np.sqrt(n)
# low extreme
loval = q1 - whis * iqr
lox = x[x >= loval]
whislo = q1 if (len(lox) == 0 or np.min(lox) > q1) else np.min(lox)
# high extreme
hival = q3 + whis * iqr
hix = x[x <= hival]
whishi = q3 if (len(hix) == 0 or np.max(hix) < q3) else np.max(hix)
bpstats = {
"fliers": x[(x < whislo) | (x > whishi)],
"mean": mean,
"med": med,
"q1": q1,
"q3": q3,
"iqr": iqr,
"whislo": whislo,
"whishi": whishi,
"cilo": cilo,
"cihi": cihi,
}
return bpstats
| stat_boxplot |
python | django__django | tests/admin_registration/tests.py | {
"start": 500,
"end": 4347
} | class ____(SimpleTestCase):
def setUp(self):
self.site = admin.AdminSite()
def test_bare_registration(self):
self.site.register(Person)
self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin)
self.site.unregister(Person)
self.assertEqual(self.site._registry, {})
def test_registration_with_model_admin(self):
self.site.register(Person, NameAdmin)
self.assertIsInstance(self.site.get_model_admin(Person), NameAdmin)
self.site.unregister(Person)
self.assertEqual(self.site._registry, {})
def test_prevent_double_registration(self):
self.site.register(Person)
msg = "The model Person is already registered in app 'admin_registration'."
with self.assertRaisesMessage(AlreadyRegistered, msg):
self.site.register(Person)
def test_prevent_double_registration_for_custom_admin(self):
class PersonAdmin(admin.ModelAdmin):
pass
self.site.register(Person, PersonAdmin)
msg = (
"The model Person is already registered with "
"'admin_registration.PersonAdmin'."
)
with self.assertRaisesMessage(AlreadyRegistered, msg):
self.site.register(Person, PersonAdmin)
def test_unregister_unregistered_model(self):
msg = "The model Person is not registered"
with self.assertRaisesMessage(NotRegistered, msg):
self.site.unregister(Person)
def test_registration_with_star_star_options(self):
self.site.register(Person, search_fields=["name"])
self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"])
def test_get_model_admin_unregister_model(self):
msg = "The model Person is not registered."
with self.assertRaisesMessage(NotRegistered, msg):
self.site.get_model_admin(Person)
def test_star_star_overrides(self):
self.site.register(
Person, NameAdmin, search_fields=["name"], list_display=["__str__"]
)
person_admin = self.site.get_model_admin(Person)
self.assertEqual(person_admin.search_fields, ["name"])
self.assertEqual(person_admin.list_display, ["__str__"])
self.assertIs(person_admin.save_on_top, True)
def test_iterable_registration(self):
self.site.register([Person, Place], search_fields=["name"])
self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin)
self.assertEqual(self.site.get_model_admin(Person).search_fields, ["name"])
self.assertIsInstance(self.site.get_model_admin(Place), admin.ModelAdmin)
self.assertEqual(self.site.get_model_admin(Place).search_fields, ["name"])
self.site.unregister([Person, Place])
self.assertEqual(self.site._registry, {})
def test_abstract_model(self):
"""
Exception is raised when trying to register an abstract model.
Refs #12004.
"""
msg = "The model Location is abstract, so it cannot be registered with admin."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.site.register(Location)
def test_composite_pk_model(self):
msg = (
"The model Guest has a composite primary key, so it cannot be registered "
"with admin."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.site.register(Guest)
def test_is_registered_model(self):
"Checks for registered models should return true."
self.site.register(Person)
self.assertTrue(self.site.is_registered(Person))
def test_is_registered_not_registered_model(self):
"Checks for unregistered models should return false."
self.assertFalse(self.site.is_registered(Person))
| TestRegistration |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/conftabs/linting.py | {
"start": 600,
"end": 10891
} | class ____(SpyderPreferencesTab):
"""Linting configuration tab."""
TITLE = _('Linting')
def __init__(self, parent):
super().__init__(parent)
newcb = self.create_checkbox
linting_label = QLabel(
_(
"Spyder can highlight syntax errors and possible problems "
"with your code in the editor by using one of the providers "
"below"
)
)
linting_label.setOpenExternalLinks(True)
linting_label.setWordWrap(True)
linting_select_group = QGroupBox(_("Provider"))
linting_bg = QButtonGroup(linting_select_group)
basic_linting_radio = self.create_radiobutton(
_("Pyflakes (Basic)"),
'pyflakes',
button_group=linting_bg
)
flake_linting_radio = self.create_radiobutton(
_("Flake8 (Intermediate)"),
'flake8',
button_group=linting_bg
)
ruff_linting_radio = self.create_radiobutton(
_("Ruff (Advanced)"),
'ruff',
button_group=linting_bg
)
disable_linting_radio = self.create_radiobutton(
_("Disable linting"),
'no_linting',
button_group=linting_bg
)
linting_select_layout = QVBoxLayout()
linting_select_layout.addSpacing(3 * AppStyle.MarginSize)
linting_select_layout.addWidget(basic_linting_radio)
linting_select_layout.addWidget(flake_linting_radio)
linting_select_layout.addWidget(ruff_linting_radio)
linting_select_layout.addWidget(disable_linting_radio)
linting_select_group.setLayout(linting_select_layout)
additional_options_group = QGroupBox(_("Additional options"))
underline_errors_box = newcb(
_("Underline errors and warnings"),
'underline_errors',
section='editor')
additional_options_layout = QVBoxLayout()
additional_options_layout.addWidget(underline_errors_box)
additional_options_group.setLayout(additional_options_layout)
configuration_options_group = QGroupBox(_("Provider options"))
configuration_options_layout = QVBoxLayout()
# ruff options
# This needs to be an attribute of the config page since it is used
# for `test_mainwindow.py::test_preferences_checkboxes_not_checked_regression`
self.docstring_style_check = self.create_checkbox(
_("Enable docstring style linting"), "pydocstyle"
)
docstring_style_convention = self.create_combobox(
_("Convention used to lint docstrings: "),
(
("Numpy", "numpy"),
("PEP 257", "pep257"),
("Google", "google"),
),
"pydocstyle/convention",
)
docstring_style_convention.label.setEnabled(
self.get_option('pydocstyle')
)
docstring_style_convention.combobox.setEnabled(
self.get_option('pydocstyle')
)
self.docstring_style_check.checkbox.toggled.connect(
docstring_style_convention.label.setEnabled
)
self.docstring_style_check.checkbox.toggled.connect(
docstring_style_convention.combobox.setEnabled
)
self.ruff_exclude = self.create_lineedit(
_("Exclude these files or directories:"),
'ruff/exclude',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Exclude test files: (?!test_).*\\.py"),
)
ruff_select = self.create_lineedit(
_("Show these errors or warnings:"),
'ruff/extendSelect',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Example codes: E113, W391"),
)
ruff_ignore = self.create_lineedit(
_("Ignore these errors or warnings:"),
'ruff/extendIgnore',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Default is: E"),
)
ruff_layout = QGridLayout()
ruff_layout.addWidget(self.docstring_style_check)
ruff_layout.addWidget(docstring_style_convention.label, 1, 0)
ruff_layout.addWidget(docstring_style_convention.combobox, 1, 1)
ruff_layout.addWidget(self.ruff_exclude.label, 2, 0)
ruff_layout.addWidget(self.ruff_exclude.textbox, 2, 1)
ruff_layout.addWidget(ruff_select.label, 3, 0)
ruff_layout.addWidget(ruff_select.textbox, 3, 1)
ruff_layout.addWidget(ruff_ignore.label, 4, 0)
ruff_layout.addWidget(ruff_ignore.textbox, 4, 1)
ruff_grid_widget = QWidget()
ruff_grid_widget.setLayout(ruff_layout)
# Flake8 options
self.flake8_filenames_match = self.create_lineedit(
_("Only check these filenames:"),
'flake8/filename',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Check test files: test_.*\\.py"),
)
self.flake8_exclude = self.create_lineedit(
_("Exclude these files or directories:"),
'flake8/exclude',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Exclude test files: (?!test_).*\\.py"),
)
flake8_select = self.create_lineedit(
_("Show these errors or warnings:"),
'flake8/extendSelect',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Example codes: E113, W391"),
)
flake8_ignore = self.create_lineedit(
_("Ignore these errors or warnings:"),
'flake8/extendIgnore',
alignment=Qt.Horizontal,
word_wrap=False,
placeholder=_("Default is: E,W,C90"),
)
flake8_layout = QGridLayout()
flake8_layout.addWidget(self.flake8_filenames_match.label, 1, 0)
flake8_layout.addWidget(self.flake8_filenames_match.textbox, 1, 1)
flake8_layout.addWidget(self.flake8_exclude.label, 2, 0)
flake8_layout.addWidget(self.flake8_exclude.textbox, 2, 1)
flake8_layout.addWidget(flake8_select.label, 3, 0)
flake8_layout.addWidget(flake8_select.textbox, 3, 1)
flake8_layout.addWidget(flake8_ignore.label, 4, 0)
flake8_layout.addWidget(flake8_ignore.textbox, 4, 1)
flake8_grid_widget = QWidget()
flake8_grid_widget.setLayout(flake8_layout)
# pyflakes options
pyflakes_conf_options = QLabel(
_("There are no configuration options for Pyflakes")
)
# Disabled linting options
not_select_conf_options = QLabel(_("Linting is disabled"))
configuration_options_layout.addWidget(ruff_grid_widget)
configuration_options_layout.addWidget(flake8_grid_widget)
configuration_options_layout.addWidget(pyflakes_conf_options)
configuration_options_layout.addWidget(not_select_conf_options)
ruff_linting_radio.radiobutton.toggled.connect(
lambda checked: (
ruff_grid_widget.setVisible(checked),
flake8_grid_widget.setVisible(False),
pyflakes_conf_options.setVisible(False),
not_select_conf_options.setVisible(False)
) if checked else None
)
flake_linting_radio.radiobutton.toggled.connect(
lambda checked: (
ruff_grid_widget.setVisible(False),
flake8_grid_widget.setVisible(checked),
pyflakes_conf_options.setVisible(False),
not_select_conf_options.setVisible(False)
) if checked else None
)
basic_linting_radio.radiobutton.toggled.connect(
lambda checked: (
ruff_grid_widget.setVisible(False),
flake8_grid_widget.setVisible(False),
pyflakes_conf_options.setVisible(checked),
not_select_conf_options.setVisible(False)
) if checked else None
)
disable_linting_radio.radiobutton.toggled.connect(
lambda checked: (
ruff_grid_widget.setVisible(False),
flake8_grid_widget.setVisible(False),
pyflakes_conf_options.setVisible(False),
not_select_conf_options.setVisible(checked)
) if checked else None
)
configuration_options_group.setLayout(configuration_options_layout)
# Linting layout
linting_layout = QVBoxLayout()
linting_layout.addWidget(linting_label)
linting_layout.addWidget(linting_select_group)
linting_layout.addWidget(configuration_options_group)
linting_layout.addWidget(additional_options_group)
self.setLayout(linting_layout)
def report_invalid_regex(self, files=True):
"""
Report that excluded files/directories should be valid regular
expressions.
"""
msg = _(
"Directory patterns listed for exclusion should be valid regular "
"expressions"
)
if files:
msg = _(
"File patterns listed for inclusion should be valid regular "
"expressions"
)
QMessageBox.critical(self, _("Error"), msg)
def is_valid(self):
# Check regexs
try:
flake8_filenames_matches = (
self.flake8_filenames_match.textbox.text().split(",")
)
for match in flake8_filenames_matches:
re.compile(match.strip())
except re.error:
self.report_invalid_regex()
return False
try:
# flake8 check
flake8_excludes = self.flake8_exclude.textbox.text().split(",")
for match in flake8_excludes:
re.compile(match.strip())
# ruff check
ruff_excludes = self.ruff_exclude.textbox.text().split(",")
for match in ruff_excludes:
re.compile(match.strip())
except re.error:
self.report_invalid_regex(files=False)
return False
return True
| LintingConfigTab |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 34834,
"end": 46924
} | class ____(Request):
"""
Get all the company's projects and all public projects
:param id: List of IDs to filter by
:type id: Sequence[str]
:param name: Get only projects whose name matches this pattern (python regular
expression syntax)
:type name: str
:param description: Get only projects whose description matches this pattern
(python regular expression syntax)
:type description: str
:param tags: User-defined tags list used to filter results. Prepend '-' to tag
name to indicate exclusion
:type tags: Sequence[str]
:param system_tags: System tags list used to filter results. Prepend '-' to
system tag name to indicate exclusion
:type system_tags: Sequence[str]
:param order_by: List of field names to order by. When search_text is used,
'@text_score' can be used as a field representing the text score of returned
documents. Use '-' prefix to specify descending order. Optional, recommended
when using page
:type order_by: Sequence[str]
:param page: Page number, returns a specific page out of the resulting list of
dataviews
:type page: int
:param page_size: Page size, specifies the number of results returned in each
page (last page may contain fewer results)
:type page_size: int
:param search_text: Free text search query
:type search_text: str
:param only_fields: List of document's field names (nesting is supported using
'.', e.g. execution.model_labels). If provided, this list defines the query's
projection (only these fields will be returned for each result entry)
:type only_fields: Sequence[str]
:param _all_: Multi-field pattern condition (all fields match pattern)
:type _all_: MultiFieldPatternData
:param _any_: Multi-field pattern condition (any field matches pattern)
:type _any_: MultiFieldPatternData
"""
_service = "projects"
_action = "get_all"
_version = "2.9"
_schema = {
"definitions": {
"multi_field_pattern_data": {
"properties": {
"fields": {
"description": "List of field names",
"items": {"type": "string"},
"type": ["array", "null"],
},
"pattern": {
"description": "Pattern string (regex)",
"type": ["string", "null"],
},
},
"type": "object",
}
},
"properties": {
"_all_": {
"description": "Multi-field pattern condition (all fields match pattern)",
"oneOf": [
{"$ref": "#/definitions/multi_field_pattern_data"},
{"type": "null"},
],
},
"_any_": {
"description": "Multi-field pattern condition (any field matches pattern)",
"oneOf": [
{"$ref": "#/definitions/multi_field_pattern_data"},
{"type": "null"},
],
},
"description": {
"description": "Get only projects whose description matches this pattern (python regular expression syntax)",
"type": ["string", "null"],
},
"id": {
"description": "List of IDs to filter by",
"items": {"type": "string"},
"type": ["array", "null"],
},
"name": {
"description": "Get only projects whose name matches this pattern (python regular expression syntax)",
"type": ["string", "null"],
},
"only_fields": {
"description": "List of document's field names (nesting is supported using '.', e.g. execution.model_labels). If provided, this list defines the query's projection (only these fields will be returned for each result entry)",
"items": {"type": "string"},
"type": ["array", "null"],
},
"order_by": {
"description": "List of field names to order by. When search_text is used, '@text_score' can be used as a field representing the text score of returned documents. Use '-' prefix to specify descending order. Optional, recommended when using page",
"items": {"type": "string"},
"type": ["array", "null"],
},
"page": {
"description": "Page number, returns a specific page out of the resulting list of dataviews",
"minimum": 0,
"type": ["integer", "null"],
},
"page_size": {
"description": "Page size, specifies the number of results returned in each page (last page may contain fewer results)",
"minimum": 1,
"type": ["integer", "null"],
},
"search_text": {
"description": "Free text search query",
"type": ["string", "null"],
},
"system_tags": {
"description": "System tags list used to filter results. Prepend '-' to system tag name to indicate exclusion",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags list used to filter results. Prepend '-' to tag name to indicate exclusion",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self,
id: Optional[List[str]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
order_by: Optional[List[str]] = None,
page: Optional[int] = None,
page_size: Optional[int] = None,
search_text: Optional[str] = None,
only_fields: Optional[List[str]] = None,
_all_: Any = None,
_any_: Any = None,
**kwargs: Any
) -> None:
super(GetAllRequest, self).__init__(**kwargs)
self.id = id
self.name = name
self.description = description
self.tags = tags
self.system_tags = system_tags
self.order_by = order_by
self.page = page
self.page_size = page_size
self.search_text = search_text
self.only_fields = only_fields
self._all_ = _all_
self._any_ = _any_
@schema_property("id")
def id(self) -> Optional[List[str]]:
return self._property_id
@id.setter
def id(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", (list, tuple))
self.assert_isinstance(value, "id", six.string_types, is_array=True)
self._property_id = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("order_by")
def order_by(self) -> Optional[List[str]]:
return self._property_order_by
@order_by.setter
def order_by(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_order_by = None
return
self.assert_isinstance(value, "order_by", (list, tuple))
self.assert_isinstance(value, "order_by", six.string_types, is_array=True)
self._property_order_by = value
@schema_property("page")
def page(self) -> Optional[int]:
return self._property_page
@page.setter
def page(self, value: Optional[int]) -> None:
if value is None:
self._property_page = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "page", six.integer_types)
self._property_page = value
@schema_property("page_size")
def page_size(self) -> Optional[int]:
return self._property_page_size
@page_size.setter
def page_size(self, value: Optional[int]) -> None:
if value is None:
self._property_page_size = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "page_size", six.integer_types)
self._property_page_size = value
@schema_property("search_text")
def search_text(self) -> Optional[str]:
return self._property_search_text
@search_text.setter
def search_text(self, value: Optional[str]) -> None:
if value is None:
self._property_search_text = None
return
self.assert_isinstance(value, "search_text", six.string_types)
self._property_search_text = value
@schema_property("only_fields")
def only_fields(self) -> Optional[List[str]]:
return self._property_only_fields
@only_fields.setter
def only_fields(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_only_fields = None
return
self.assert_isinstance(value, "only_fields", (list, tuple))
self.assert_isinstance(value, "only_fields", six.string_types, is_array=True)
self._property_only_fields = value
@schema_property("_all_")
def _all_(self) -> Any:
return self._property__all_
@_all_.setter
def _all_(self, value: Any) -> None:
if value is None:
self._property__all_ = None
return
if isinstance(value, dict):
value = MultiFieldPatternData.from_dict(value)
else:
self.assert_isinstance(value, "_all_", MultiFieldPatternData)
self._property__all_ = value
@schema_property("_any_")
def _any_(self) -> Any:
return self._property__any_
@_any_.setter
def _any_(self, value: Any) -> None:
if value is None:
self._property__any_ = None
return
if isinstance(value, dict):
value = MultiFieldPatternData.from_dict(value)
else:
self.assert_isinstance(value, "_any_", MultiFieldPatternData)
self._property__any_ = value
| GetAllRequest |
python | django__django | tests/postgres_tests/test_functions.py | {
"start": 874,
"end": 1246
} | class ____(PostgreSQLTestCase):
def test_random_uuid(self):
m1 = UUIDTestModel.objects.create()
m2 = UUIDTestModel.objects.create()
UUIDTestModel.objects.update(uuid=RandomUUID())
m1.refresh_from_db()
m2.refresh_from_db()
self.assertIsInstance(m1.uuid, uuid.UUID)
self.assertNotEqual(m1.uuid, m2.uuid)
| TestRandomUUID |
python | numba__numba | numba/cpython/setobj.py | {
"start": 12301,
"end": 41796
} | class ____(object):
def __init__(self, context, builder, set_type, set_val):
self._context = context
self._builder = builder
self._ty = set_type
self._entrysize = get_entry_size(context, set_type)
self._set = context.make_helper(builder, set_type, set_val)
@property
def dtype(self):
return self._ty.dtype
@property
def payload(self):
"""
The _SetPayload for this set.
"""
# This cannot be cached as the pointer can move around!
context = self._context
builder = self._builder
ptr = self._context.nrt.meminfo_data(builder, self.meminfo)
return _SetPayload(context, builder, self._ty, ptr)
@property
def value(self):
return self._set._getvalue()
@property
def meminfo(self):
return self._set.meminfo
@property
def parent(self):
return self._set.parent
@parent.setter
def parent(self, value):
self._set.parent = value
def get_size(self):
"""
Return the number of elements in the size.
"""
return self.payload.used
def set_dirty(self, val):
if self._ty.reflected:
self.payload.dirty = cgutils.true_bit if val else cgutils.false_bit
def _add_entry(self, payload, entry, item, h, do_resize=True):
context = self._context
builder = self._builder
old_hash = entry.hash
entry.hash = h
self.incref_value(item)
entry.key = item
# used++
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = builder.add(used, one)
# fill++ if entry wasn't a deleted one
with builder.if_then(is_hash_empty(context, builder, old_hash),
likely=True):
payload.fill = builder.add(payload.fill, one)
# Grow table if necessary
if do_resize:
self.upsize(used)
self.set_dirty(True)
def _add_key(self, payload, item, h, do_resize=True, do_incref=True):
context = self._context
builder = self._builder
found, i = payload._lookup(item, h, for_insert=True)
not_found = builder.not_(found)
with builder.if_then(not_found):
# Not found => add it
entry = payload.get_entry(i)
old_hash = entry.hash
entry.hash = h
if do_incref:
self.incref_value(item)
entry.key = item
# used++
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = builder.add(used, one)
# fill++ if entry wasn't a deleted one
with builder.if_then(is_hash_empty(context, builder, old_hash),
likely=True):
payload.fill = builder.add(payload.fill, one)
# Grow table if necessary
if do_resize:
self.upsize(used)
self.set_dirty(True)
def _remove_entry(self, payload, entry, do_resize=True, do_decref=True):
# Mark entry deleted
entry.hash = ir.Constant(entry.hash.type, DELETED)
if do_decref:
self.decref_value(entry.key)
# used--
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = self._builder.sub(used, one)
# Shrink table if necessary
if do_resize:
self.downsize(used)
self.set_dirty(True)
def _remove_key(self, payload, item, h, do_resize=True):
context = self._context
builder = self._builder
found, i = payload._lookup(item, h)
with builder.if_then(found):
entry = payload.get_entry(i)
self._remove_entry(payload, entry, do_resize)
return found
def add(self, item, do_resize=True):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
self._add_key(payload, item, h, do_resize)
def add_pyapi(self, pyapi, item, do_resize=True):
"""A version of .add for use inside functions following Python calling
convention.
"""
context = self._context
builder = self._builder
payload = self.payload
h = self._pyapi_get_hash_value(pyapi, context, builder, item)
self._add_key(payload, item, h, do_resize)
def _pyapi_get_hash_value(self, pyapi, context, builder, item):
"""Python API compatible version of `get_hash_value()`.
"""
argtypes = [self._ty.dtype]
resty = types.intp
def wrapper(val):
return _get_hash_value_intrinsic(val)
args = [item]
sig = typing.signature(resty, *argtypes)
is_error, retval = pyapi.call_jit_code(wrapper, sig, args)
# Handle return status
with builder.if_then(is_error, likely=False):
# Raise nopython exception as a Python exception
builder.ret(pyapi.get_null_object())
return retval
def contains(self, item):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
found, i = payload._lookup(item, h)
return found
def discard(self, item):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
found = self._remove_key(payload, item, h)
return found
def pop(self):
context = self._context
builder = self._builder
lty = context.get_value_type(self._ty.dtype)
key = cgutils.alloca_once(builder, lty)
payload = self.payload
with payload._next_entry() as entry:
builder.store(entry.key, key)
# since the value is returned don't decref in _remove_entry()
self._remove_entry(payload, entry, do_decref=False)
return builder.load(key)
def clear(self):
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
minsize = ir.Constant(intp_t, MINSIZE)
self._replace_payload(minsize)
self.set_dirty(True)
def copy(self):
"""
Return a copy of this set.
"""
context = self._context
builder = self._builder
payload = self.payload
used = payload.used
fill = payload.fill
other = type(self)(context, builder, self._ty, None)
no_deleted_entries = builder.icmp_unsigned('==', used, fill)
with builder.if_else(no_deleted_entries, likely=True) \
as (if_no_deleted, if_deleted):
with if_no_deleted:
# No deleted entries => raw copy the payload
ok = other._copy_payload(payload)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot copy set",))
with if_deleted:
# Deleted entries => re-insert entries one by one
nentries = self.choose_alloc_size(context, builder, used)
ok = other._allocate_payload(nentries)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot copy set",))
other_payload = other.payload
with payload._iterate() as loop:
entry = loop.entry
other._add_key(other_payload, entry.key, entry.hash,
do_resize=False)
return other
def intersect(self, other):
"""
In-place intersection with *other* set.
"""
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
self._remove_entry(payload, entry, do_resize=False)
# Final downsize
self.downsize(payload.used)
def difference(self, other):
"""
In-place difference with *other* set.
"""
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
with other_payload._iterate() as loop:
entry = loop.entry
self._remove_key(payload, entry.key, entry.hash, do_resize=False)
# Final downsize
self.downsize(payload.used)
def symmetric_difference(self, other):
"""
In-place symmetric difference with *other* set.
"""
context = self._context
builder = self._builder
other_payload = other.payload
with other_payload._iterate() as loop:
key = loop.entry.key
h = loop.entry.hash
# We must reload our payload as it may be resized during the loop
payload = self.payload
found, i = payload._lookup(key, h, for_insert=True)
entry = payload.get_entry(i)
with builder.if_else(found) as (if_common, if_not_common):
with if_common:
self._remove_entry(payload, entry, do_resize=False)
with if_not_common:
self._add_entry(payload, entry, key, h)
# Final downsize
self.downsize(self.payload.used)
def issubset(self, other, strict=False):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
cmp_op = '<' if strict else '<='
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
with builder.if_else(
builder.icmp_unsigned(cmp_op, payload.used, other_payload.used)
) as (if_smaller, if_larger):
with if_larger:
# self larger than other => self cannot possibly a subset
builder.store(cgutils.false_bit, res)
with if_smaller:
# check whether each key of self is in other
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
builder.store(cgutils.false_bit, res)
loop.do_break()
return builder.load(res)
def isdisjoint(self, other):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
def check(smaller, larger):
# Loop over the smaller of the two, and search in the larger
with smaller._iterate() as loop:
entry = loop.entry
found, _ = larger._lookup(entry.key, entry.hash)
with builder.if_then(found):
builder.store(cgutils.false_bit, res)
loop.do_break()
with builder.if_else(
builder.icmp_unsigned('>', payload.used, other_payload.used)
) as (if_larger, otherwise):
with if_larger:
# len(self) > len(other)
check(other_payload, payload)
with otherwise:
# len(self) <= len(other)
check(payload, other_payload)
return builder.load(res)
def equals(self, other):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
with builder.if_else(
builder.icmp_unsigned('==', payload.used, other_payload.used)
) as (if_same_size, otherwise):
with if_same_size:
# same sizes => check whether each key of self is in other
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
builder.store(cgutils.false_bit, res)
loop.do_break()
with otherwise:
# different sizes => cannot possibly be equal
builder.store(cgutils.false_bit, res)
return builder.load(res)
@classmethod
def allocate_ex(cls, context, builder, set_type, nitems=None):
"""
Allocate a SetInstance with its storage.
Return a (ok, instance) tuple where *ok* is a LLVM boolean and
*instance* is a SetInstance object (the object's contents are
only valid when *ok* is true).
"""
intp_t = context.get_value_type(types.intp)
if nitems is None:
nentries = ir.Constant(intp_t, MINSIZE)
else:
if isinstance(nitems, int):
nitems = ir.Constant(intp_t, nitems)
nentries = cls.choose_alloc_size(context, builder, nitems)
self = cls(context, builder, set_type, None)
ok = self._allocate_payload(nentries)
return ok, self
@classmethod
def allocate(cls, context, builder, set_type, nitems=None):
"""
Allocate a SetInstance with its storage. Same as allocate_ex(),
but return an initialized *instance*. If allocation failed,
control is transferred to the caller using the target's current
call convention.
"""
ok, self = cls.allocate_ex(context, builder, set_type, nitems)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot allocate set",))
return self
@classmethod
def from_meminfo(cls, context, builder, set_type, meminfo):
"""
Allocate a new set instance pointing to an existing payload
(a meminfo pointer).
Note the parent field has to be filled by the caller.
"""
self = cls(context, builder, set_type, None)
self._set.meminfo = meminfo
self._set.parent = context.get_constant_null(types.pyobject)
context.nrt.incref(builder, set_type, self.value)
# Payload is part of the meminfo, no need to touch it
return self
@classmethod
def choose_alloc_size(cls, context, builder, nitems):
"""
Choose a suitable number of entries for the given number of items.
"""
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
minsize = ir.Constant(intp_t, MINSIZE)
# Ensure number of entries >= 2 * used
min_entries = builder.shl(nitems, one)
# Find out first suitable power of 2, starting from MINSIZE
size_p = cgutils.alloca_once_value(builder, minsize)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
size = builder.load(size_p)
is_large_enough = builder.icmp_unsigned('>=', size, min_entries)
with builder.if_then(is_large_enough, likely=False):
builder.branch(bb_end)
next_size = builder.shl(size, one)
builder.store(next_size, size_p)
builder.branch(bb_body)
builder.position_at_end(bb_end)
return builder.load(size_p)
def upsize(self, nitems):
"""
When adding to the set, ensure it is properly sized for the given
number of used entries.
"""
context = self._context
builder = self._builder
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
two = ir.Constant(intp_t, 2)
payload = self.payload
# Ensure number of entries >= 2 * used
min_entries = builder.shl(nitems, one)
size = builder.add(payload.mask, one)
need_resize = builder.icmp_unsigned('>=', min_entries, size)
with builder.if_then(need_resize, likely=False):
# Find out next suitable size
new_size_p = cgutils.alloca_once_value(builder, size)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
# Multiply by 4 (ensuring size remains a power of two)
new_size = builder.load(new_size_p)
new_size = builder.shl(new_size, two)
builder.store(new_size, new_size_p)
is_too_small = builder.icmp_unsigned('>=', min_entries, new_size)
builder.cbranch(is_too_small, bb_body, bb_end)
builder.position_at_end(bb_end)
new_size = builder.load(new_size_p)
if DEBUG_ALLOCS:
context.printf(builder,
"upsize to %zd items: current size = %zd, "
"min entries = %zd, new size = %zd\n",
nitems, size, min_entries, new_size)
self._resize(payload, new_size, "cannot grow set")
def downsize(self, nitems):
"""
When removing from the set, ensure it is properly sized for the given
number of used entries.
"""
context = self._context
builder = self._builder
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
two = ir.Constant(intp_t, 2)
minsize = ir.Constant(intp_t, MINSIZE)
payload = self.payload
# Ensure entries >= max(2 * used, MINSIZE)
min_entries = builder.shl(nitems, one)
min_entries = builder.select(builder.icmp_unsigned('>=', min_entries, minsize),
min_entries, minsize)
# Shrink only if size >= 4 * min_entries && size > MINSIZE
max_size = builder.shl(min_entries, two)
size = builder.add(payload.mask, one)
need_resize = builder.and_(
builder.icmp_unsigned('<=', max_size, size),
builder.icmp_unsigned('<', minsize, size))
with builder.if_then(need_resize, likely=False):
# Find out next suitable size
new_size_p = cgutils.alloca_once_value(builder, size)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
# Divide by 2 (ensuring size remains a power of two)
new_size = builder.load(new_size_p)
new_size = builder.lshr(new_size, one)
# Keep current size if new size would be < min_entries
is_too_small = builder.icmp_unsigned('>', min_entries, new_size)
with builder.if_then(is_too_small):
builder.branch(bb_end)
builder.store(new_size, new_size_p)
builder.branch(bb_body)
builder.position_at_end(bb_end)
# Ensure new_size >= MINSIZE
new_size = builder.load(new_size_p)
# At this point, new_size should be < size if the factors
# above were chosen carefully!
if DEBUG_ALLOCS:
context.printf(builder,
"downsize to %zd items: current size = %zd, "
"min entries = %zd, new size = %zd\n",
nitems, size, min_entries, new_size)
self._resize(payload, new_size, "cannot shrink set")
def _resize(self, payload, nentries, errmsg):
"""
Resize the payload to the given number of entries.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder
# Allocate new entries
old_payload = payload
ok = self._allocate_payload(nentries, realloc=True)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
(errmsg,))
# Re-insert old entries
# No incref since they already were the first time they were inserted
payload = self.payload
with old_payload._iterate() as loop:
entry = loop.entry
self._add_key(payload, entry.key, entry.hash,
do_resize=False, do_incref=False)
self._free_payload(old_payload.ptr)
def _replace_payload(self, nentries):
"""
Replace the payload with a new empty payload with the given number
of entries.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder
# decref all of the previous entries
with self.payload._iterate() as loop:
entry = loop.entry
self.decref_value(entry.key)
# Free old payload
self._free_payload(self.payload.ptr)
ok = self._allocate_payload(nentries, realloc=True)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot reallocate set",))
def _allocate_payload(self, nentries, realloc=False):
"""
Allocate and initialize payload for the given number of entries.
If *realloc* is True, the existing meminfo is reused.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder
ok = cgutils.alloca_once_value(builder, cgutils.true_bit)
intp_t = context.get_value_type(types.intp)
zero = ir.Constant(intp_t, 0)
one = ir.Constant(intp_t, 1)
payload_type = context.get_data_type(types.SetPayload(self._ty))
payload_size = context.get_abi_sizeof(payload_type)
entry_size = self._entrysize
# Account for the fact that the payload struct already contains an entry
payload_size -= entry_size
# Total allocation size = <payload header size> + nentries * entry_size
allocsize, ovf = cgutils.muladd_with_overflow(builder, nentries,
ir.Constant(intp_t, entry_size),
ir.Constant(intp_t, payload_size))
with builder.if_then(ovf, likely=False):
builder.store(cgutils.false_bit, ok)
with builder.if_then(builder.load(ok), likely=True):
if realloc:
meminfo = self._set.meminfo
ptr = context.nrt.meminfo_varsize_alloc_unchecked(builder,
meminfo,
size=allocsize)
alloc_ok = cgutils.is_null(builder, ptr)
else:
# create destructor to be called upon set destruction
dtor = self._imp_dtor(context, builder.module)
meminfo = context.nrt.meminfo_new_varsize_dtor_unchecked(
builder, allocsize, builder.bitcast(dtor, cgutils.voidptr_t))
alloc_ok = cgutils.is_null(builder, meminfo)
with builder.if_else(alloc_ok,
likely=False) as (if_error, if_ok):
with if_error:
builder.store(cgutils.false_bit, ok)
with if_ok:
if not realloc:
self._set.meminfo = meminfo
self._set.parent = context.get_constant_null(types.pyobject)
payload = self.payload
# Initialize entries to 0xff (EMPTY)
cgutils.memset(builder, payload.ptr, allocsize, 0xFF)
payload.used = zero
payload.fill = zero
payload.finger = zero
new_mask = builder.sub(nentries, one)
payload.mask = new_mask
if DEBUG_ALLOCS:
context.printf(builder,
"allocated %zd bytes for set at %p: mask = %zd\n",
allocsize, payload.ptr, new_mask)
return builder.load(ok)
def _free_payload(self, ptr):
"""
Free an allocated old payload at *ptr*.
"""
self._context.nrt.meminfo_varsize_free(self._builder, self.meminfo, ptr)
def _copy_payload(self, src_payload):
"""
Raw-copy the given payload into self.
"""
context = self._context
builder = self._builder
ok = cgutils.alloca_once_value(builder, cgutils.true_bit)
intp_t = context.get_value_type(types.intp)
zero = ir.Constant(intp_t, 0)
one = ir.Constant(intp_t, 1)
payload_type = context.get_data_type(types.SetPayload(self._ty))
payload_size = context.get_abi_sizeof(payload_type)
entry_size = self._entrysize
# Account for the fact that the payload struct already contains an entry
payload_size -= entry_size
mask = src_payload.mask
nentries = builder.add(one, mask)
# Total allocation size = <payload header size> + nentries * entry_size
# (note there can't be any overflow since we're reusing an existing
# payload's parameters)
allocsize = builder.add(ir.Constant(intp_t, payload_size),
builder.mul(ir.Constant(intp_t, entry_size),
nentries))
with builder.if_then(builder.load(ok), likely=True):
# create destructor for new meminfo
dtor = self._imp_dtor(context, builder.module)
meminfo = context.nrt.meminfo_new_varsize_dtor_unchecked(
builder, allocsize, builder.bitcast(dtor, cgutils.voidptr_t))
alloc_ok = cgutils.is_null(builder, meminfo)
with builder.if_else(alloc_ok, likely=False) as (if_error, if_ok):
with if_error:
builder.store(cgutils.false_bit, ok)
with if_ok:
self._set.meminfo = meminfo
payload = self.payload
payload.used = src_payload.used
payload.fill = src_payload.fill
payload.finger = zero
payload.mask = mask
# instead of using `_add_key` for every entry, since the
# size of the new set is the same, we can just copy the
# data directly without having to re-compute the hash
cgutils.raw_memcpy(builder, payload.entries,
src_payload.entries, nentries,
entry_size)
# increment the refcounts to simulate `_add_key` for each
# element
with src_payload._iterate() as loop:
self.incref_value(loop.entry.key)
if DEBUG_ALLOCS:
context.printf(builder,
"allocated %zd bytes for set at %p: mask = %zd\n",
allocsize, payload.ptr, mask)
return builder.load(ok)
def _imp_dtor(self, context, module):
"""Define the dtor for set
"""
llvoidptr = cgutils.voidptr_t
llsize_t= context.get_value_type(types.size_t)
# create a dtor function that takes (void* set, size_t size, void* dtor_info)
fnty = ir.FunctionType(
ir.VoidType(),
[llvoidptr, llsize_t, llvoidptr],
)
# create type-specific name
fname = f".dtor.set.{self._ty.dtype}"
fn = cgutils.get_or_insert_function(module, fnty, name=fname)
if fn.is_declaration:
# Set linkage
fn.linkage = 'linkonce_odr'
# Define
builder = ir.IRBuilder(fn.append_basic_block())
payload = _SetPayload(context, builder, self._ty, fn.args[0])
with payload._iterate() as loop:
entry = loop.entry
context.nrt.decref(builder, self._ty.dtype, entry.key)
builder.ret_void()
return fn
def incref_value(self, val):
"""Incref an element value
"""
self._context.nrt.incref(self._builder, self._ty.dtype, val)
def decref_value(self, val):
"""Decref an element value
"""
self._context.nrt.decref(self._builder, self._ty.dtype, val)
| SetInstance |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_unicode_polish_utf8.py | {
"start": 315,
"end": 1548
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("unicode_polish_utf8.xlsx")
self.set_text_file("unicode_polish_utf8.txt")
def test_create_file(self):
"""Test example file converting Unicode text."""
# Open the input file with the correct encoding.
textfile = open(self.txt_filename, mode="r", encoding="utf-8")
# Create an new Excel file and convert the text data.
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column("A:A", 50)
# Start from the first cell.
row = 0
col = 0
# Read the text file and write it to the worksheet.
for line in textfile:
# Ignore the comments in the sample file.
if line.startswith("#"):
continue
# Write any other lines to the worksheet.
worksheet.write(row, col, line.rstrip("\n"))
row += 1
workbook.close()
textfile.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_update_old_row.py | {
"start": 4688,
"end": 8253
} | class ____(VersionedStartEnd, Base):
__tablename__ = "child"
id = Column(Integer, primary_key=True)
start = Column(DateTime, primary_key=True)
end = Column(DateTime, primary_key=True)
data = Column(String)
def new_version(self, session):
# expire parent's reference to us
session.expire(self.parent, ["child"])
# create new version
VersionedStartEnd.new_version(self, session)
# re-add ourselves to the parent
self.parent.child = self
times = []
def time_passes(s):
"""keep track of timestamps in terms of the database and allow time to
pass between steps."""
# close the transaction, if any, since PG time doesn't increment in the
# transaction
s.commit()
# get "now" in terms of the DB so we can keep the ranges low and
# still have our assertions pass
if times:
time.sleep(1)
times.append(datetime.datetime.now())
if len(times) > 1:
assert times[-1] > times[-2]
return times[-1]
e = create_engine("sqlite://", echo="debug")
Base.metadata.create_all(e)
s = Session(e)
now = time_passes(s)
c1 = Child(id=1, data="child 1")
p1 = Parent(id=1, data="c1", child=c1)
s.add(p1)
s.commit()
# assert raw DB data
assert s.query(Parent.__table__).all() == [
(
1,
times[0] - datetime.timedelta(days=3),
times[0] + datetime.timedelta(days=3),
"c1",
1,
)
]
assert s.query(Child.__table__).all() == [
(
1,
times[0] - datetime.timedelta(days=3),
times[0] + datetime.timedelta(days=3),
"child 1",
)
]
now = time_passes(s)
p1_check = s.query(Parent).first()
assert p1_check is p1
assert p1_check.child is c1
p1.child.data = "elvis presley"
s.commit()
p2_check = s.query(Parent).first()
assert p2_check is p1_check
c2_check = p2_check.child
# same object
assert p2_check.child is c1
# new data
assert c1.data == "elvis presley"
# new end time
assert c1.end == now + datetime.timedelta(days=2)
# assert raw DB data
assert s.query(Parent.__table__).all() == [
(
1,
times[0] - datetime.timedelta(days=3),
times[0] + datetime.timedelta(days=3),
"c1",
1,
)
]
assert s.query(Child.__table__).order_by(Child.end).all() == [
(1, times[0] - datetime.timedelta(days=3), times[1], "child 1"),
(1, times[1], times[1] + datetime.timedelta(days=2), "elvis presley"),
]
now = time_passes(s)
p1.data = "c2 elvis presley"
s.commit()
# assert raw DB data. now there are two parent rows.
assert s.query(Parent.__table__).order_by(Parent.end).all() == [
(1, times[0] - datetime.timedelta(days=3), times[2], "c1", 1),
(
1,
times[2],
times[2] + datetime.timedelta(days=2),
"c2 elvis presley",
1,
),
]
assert s.query(Child.__table__).order_by(Child.end).all() == [
(1, times[0] - datetime.timedelta(days=3), times[1], "child 1"),
(1, times[1], times[1] + datetime.timedelta(days=2), "elvis presley"),
]
# add some more rows to test that these aren't coming back for
# queries
s.add(Parent(id=2, data="unrelated", child=Child(id=2, data="unrelated")))
s.commit()
# Query only knows about one parent for id=1
p3_check = s.query(Parent).filter_by(id=1).one()
assert p3_check is p1
assert p3_check.child is c1
# and one child.
c3_check = s.query(Child).filter(Child.parent == p3_check).one()
assert c3_check is c1
# one child one parent....
c3_check = (
s.query(Child).join(Parent.child).filter(Parent.id == p3_check.id).one()
)
| Child |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 20065,
"end": 21911
} | class ____(TestCase):
def setUp(self):
BasicModel(text='foo').save()
User.objects.create_user('username', 'username@example.com', 'password')
credentials = basic_auth_header('username', 'password')
self.request = factory.get('/1', format='json', HTTP_AUTHORIZATION=credentials)
self.custom_message = 'Custom: You cannot access this resource'
self.custom_code = 'permission_denied_custom'
def test_permission_denied(self):
response = denied_view(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(detail, self.custom_message)
self.assertNotEqual(detail.code, self.custom_code)
def test_permission_denied_with_custom_detail(self):
response = denied_view_with_detail(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(detail, self.custom_message)
self.assertEqual(detail.code, self.custom_code)
def test_permission_denied_for_object(self):
response = denied_object_view(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(detail, self.custom_message)
self.assertNotEqual(detail.code, self.custom_code)
def test_permission_denied_for_object_with_custom_detail(self):
response = denied_object_view_with_detail(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(detail, self.custom_message)
self.assertEqual(detail.code, self.custom_code)
| CustomPermissionsTests |
python | ray-project__ray | cpp/src/ray/test/cluster/test_cross_language_invocation.py | {
"start": 125,
"end": 307
} | class ____(object):
def __init__(self, value):
self.value = int(value)
def increase(self, delta):
self.value += int(delta)
return str(self.value)
| Counter |
python | huggingface__transformers | tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py | {
"start": 15613,
"end": 24523
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
# Ignore copy
all_model_classes = (
(
Wav2Vec2BertForCTC,
Wav2Vec2BertModel,
Wav2Vec2BertForSequenceClassification,
Wav2Vec2BertForAudioFrameClassification,
Wav2Vec2BertForXVector,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"audio-classification": Wav2Vec2BertForSequenceClassification,
"automatic-speech-recognition": Wav2Vec2BertForCTC,
"feature-extraction": Wav2Vec2BertModel,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = Wav2Vec2BertModelTester(self)
self.config_tester = ConfigTester(self, config_class=Wav2Vec2BertConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@is_flaky(description="Get lager difference with A10 and even with the new `5e-4` still flaky")
def test_batching_equivalence(self, atol=5e-4, rtol=5e-4):
super().test_batching_equivalence(atol=atol, rtol=rtol)
def test_model_with_relative(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative")
self.model_tester.create_and_check_model(*config_and_inputs)
# Ignore copy
def test_model_with_relative_key(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative_key")
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_rotary(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary")
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_no_rel_pos(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type=None)
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_adapter(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter(*config_and_inputs)
def test_model_with_adapter_for_ctc(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter_for_ctc(*config_and_inputs)
# Ignore copy
def test_model_with_intermediate_ffn_before_adapter(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_intermediate_ffn_before_adapter(*config_and_inputs)
def test_model_with_adapter_proj_dim(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter_proj_dim(*config_and_inputs)
@require_torch_accelerator
@require_torch_fp16
def test_model_float16_with_relative(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative")
self.model_tester.create_and_check_model_float16(*config_and_inputs)
# Ignore copy
@require_torch_accelerator
@require_torch_fp16
def test_model_float16_with_relative_key(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative_key")
self.model_tester.create_and_check_model_float16(*config_and_inputs)
@require_torch_accelerator
@require_torch_fp16
def test_model_float16_with_rotary(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary")
self.model_tester.create_and_check_model_float16(*config_and_inputs)
def test_ctc_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_loss(*config_and_inputs)
def test_seq_classifier_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_loss(*config_and_inputs)
def test_ctc_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_training(*config_and_inputs)
def test_seq_classifier_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_training(*config_and_inputs)
def test_xvector_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_xvector_training(*config_and_inputs)
def test_labels_out_of_vocab(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_labels_out_of_vocab(*config_and_inputs)
# Ignore copy
@unittest.skip(reason="Wav2Vec2Bert has no inputs_embeds")
def test_inputs_embeds(self):
pass
# Ignore copy
@unittest.skip(reason="`input_ids` is renamed to `input_features`")
def test_forward_signature(self):
pass
# Ignore copy
@unittest.skip(reason="Wav2Vec2Bert has no tokens embeddings")
def test_resize_tokens_embeddings(self):
pass
# Ignore copy
@unittest.skip(reason="Wav2Vec2Bert has no inputs_embeds")
def test_model_get_set_embeddings(self):
pass
def test_retain_grad_hidden_states_attentions(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.output_hidden_states = True
config.output_attentions = True
# no need to test all models as different heads yield the same functionality
model_class = self.all_model_classes[0]
model = model_class(config)
model.to(torch_device)
# set layer drop to 0
model.config.layerdrop = 0.0
input_features = inputs_dict["input_features"]
input_lengths = torch.tensor(
[input_features.shape[1] for _ in range(input_features.shape[0])], dtype=torch.long, device=torch_device
)
output_lengths = model._get_feat_extract_output_lengths(input_lengths)
labels = ids_tensor((input_features.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size)
inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"])
inputs_dict["labels"] = labels
outputs = model(**inputs_dict)
output = outputs[0]
# Encoder-/Decoder-only models
hidden_states = outputs.hidden_states[0]
attentions = outputs.attentions[0]
hidden_states.retain_grad()
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=True)
self.assertIsNotNone(hidden_states.grad)
self.assertIsNotNone(attentions.grad)
# overwrite from test_modeling_common
def _mock_init_weights(self, module):
if hasattr(module, "weight") and module.weight is not None:
module.weight.fill_(3)
if hasattr(module, "weight_g") and module.weight_g is not None:
module.weight_g.data.fill_(3)
if hasattr(module, "weight_v") and module.weight_v is not None:
module.weight_v.data.fill_(3)
if hasattr(module, "bias") and module.bias is not None:
module.bias.fill_(3)
if hasattr(module, "pos_bias_u") and module.pos_bias_u is not None:
module.pos_bias_u.data.fill_(3)
if hasattr(module, "pos_bias_v") and module.pos_bias_v is not None:
module.pos_bias_v.data.fill_(3)
if hasattr(module, "codevectors") and module.codevectors is not None:
module.codevectors.data.fill_(3)
if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None:
module.masked_spec_embed.data.fill_(3)
# Ignore copy
@unittest.skip(reason="Kept to make #Copied from working")
def test_mask_feature_prob_ctc(self):
pass
# Ignore copy
@unittest.skip(reason="Kept to make #Copied from working")
def test_mask_time_prob_ctc(self):
pass
@unittest.skip(reason="Feed forward chunking is not implemented")
def test_feed_forward_chunking(self):
pass
@slow
def test_model_from_pretrained(self):
# Ignore copy
model = Wav2Vec2BertModel.from_pretrained("facebook/w2v-bert-2.0")
self.assertIsNotNone(model)
@require_torch
# Copied from tests.models.wav2vec2_conformer.test_modeling_wav2vec2_conformer.Wav2Vec2ConformerUtilsTest with Conformer->Bert, input_values->input_features
| Wav2Vec2BertModelTest |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/arg.py | {
"start": 125,
"end": 1035
} | class ____(Operator):
"""Operator for function arguments/parameters."""
def __init__(self):
super().__init__("arg")
@property
def torch_op_name(self) -> str | None:
"""Arg is not a torch operation, it represents function arguments."""
return None
def can_produce(self, output_spec: Spec) -> bool:
"""Arg can produce any type of output."""
return True
def fuzz_inputs_specs(self, output_spec: Spec) -> list[Spec]:
"""Arg requires no inputs for fuzzing."""
return []
def codegen(
self, output_name: str, input_names: list[str], output_spec: Spec
) -> str:
"""Generate code for arg operation."""
# The actual argument name assignment will be handled separately
# in the codegen.py when processing arg operations
return f"# {output_name} will be assigned an argument value"
| ArgOperator |
python | crytic__slither | slither/core/declarations/structure_contract.py | {
"start": 117,
"end": 372
} | class ____(Structure, ContractLevel):
def is_declared_by(self, contract):
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
| StructureContract |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 36695,
"end": 37550
} | class ____(Reduction):
_parameters = ["frame", "skipna", "numeric_only", "split_every", "axis"]
_defaults = {"skipna": True, "numeric_only": False, "split_every": False, "axis": 0}
@functools.cached_property
def _meta(self):
return make_meta(
meta_nonempty(self.frame._meta).mean(
skipna=self.skipna, numeric_only=self.numeric_only, axis=self.axis
)
)
def _lower(self):
s = self.frame.sum(
skipna=self.skipna,
numeric_only=self.numeric_only,
split_every=self.split_every,
)
c = self.frame.count(
split_every=self.split_every, numeric_only=self.numeric_only
)
if self.axis is None and s.ndim == 1:
return s.sum() / c.sum()
else:
return MeanAggregate(s, c)
| Mean |
python | scikit-image__scikit-image | src/skimage/_shared/utils.py | {
"start": 18239,
"end": 21393
} | class ____:
"""Decorator for automatically making channels axis last for all arrays.
This decorator reorders axes for compatibility with functions that only
support channels along the last axis. After the function call is complete
the channels axis is restored back to its original position.
Parameters
----------
channel_arg_positions : tuple of int, optional
Positional arguments at the positions specified in this tuple are
assumed to be multichannel arrays. The default is to assume only the
first argument to the function is a multichannel array.
channel_kwarg_names : tuple of str, optional
A tuple containing the names of any keyword arguments corresponding to
multichannel arrays.
multichannel_output : bool, optional
A boolean that should be True if the output of the function is not a
multichannel array and False otherwise. This decorator does not
currently support the general case of functions with multiple outputs
where some or all are multichannel.
"""
def __init__(
self,
channel_arg_positions=(0,),
channel_kwarg_names=(),
multichannel_output=True,
):
self.arg_positions = set(channel_arg_positions)
self.kwarg_names = set(channel_kwarg_names)
self.multichannel_output = multichannel_output
def __call__(self, func):
@functools.wraps(func)
def fixed_func(*args, **kwargs):
channel_axis = kwargs.get('channel_axis', None)
if channel_axis is None:
return func(*args, **kwargs)
# TODO: convert scalars to a tuple in anticipation of eventually
# supporting a tuple of channel axes. Right now, only an
# integer or a single-element tuple is supported, though.
if np.isscalar(channel_axis):
channel_axis = (channel_axis,)
if len(channel_axis) > 1:
raise ValueError("only a single channel axis is currently supported")
if channel_axis == (-1,) or channel_axis == -1:
return func(*args, **kwargs)
if self.arg_positions:
new_args = []
for pos, arg in enumerate(args):
if pos in self.arg_positions:
new_args.append(np.moveaxis(arg, channel_axis[0], -1))
else:
new_args.append(arg)
new_args = tuple(new_args)
else:
new_args = args
for name in self.kwarg_names:
kwargs[name] = np.moveaxis(kwargs[name], channel_axis[0], -1)
# now that we have moved the channels axis to the last position,
# change the channel_axis argument to -1
kwargs["channel_axis"] = -1
# Call the function with the fixed arguments
out = func(*new_args, **kwargs)
if self.multichannel_output:
out = np.moveaxis(out, -1, channel_axis[0])
return out
return fixed_func
| channel_as_last_axis |
python | pydata__xarray | xarray/core/groupby.py | {
"start": 62540,
"end": 62675
} | class ____(
DataArrayGroupByBase,
DataArrayGroupByAggregations,
ImplementsArrayReduce,
):
__slots__ = ()
| DataArrayGroupBy |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 164128,
"end": 165993
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[1, 1]"):
l_x_ = L_x_
l__self___l1: "f32[1, 1]" = self.L__self___l1(l_x_); l_x_ = None
l__self___buffer: "f32[1]" = self.L__self___buffer
add: "f32[1, 1]" = l__self___l1 + l__self___buffer; l__self___l1 = l__self___buffer = None
return (add,)
""",
)
@config.patch(inline_inbuilt_nn_modules=False)
def test_functional_call_disable_inline_nn_module(self):
counters.clear()
def wrapper_fn(model, params, inputs, targets):
prediction = torch.func.functional_call(model, params, (inputs,))
return torch.nn.functional.mse_loss(prediction, targets)
model = torch.nn.Linear(3, 3)
params = dict(model.named_parameters())
inputs = torch.randn(64, 3)
targets = torch.randn(64, 3)
actual = wrapper_fn(model, params, inputs, targets)
expected = torch.compile(wrapper_fn, backend="aot_eager", fullgraph=False)(
model, params, inputs, targets
)
self.assertEqual(len(counters["graph_break"]), 1)
self.assertIn(
"torch.func.functional_call capture is disabled",
next(iter(counters["graph_break"].keys())),
)
self.assertEqual(actual, expected)
def test_grad(self):
counters.clear()
def fn(x):
return x.sin().sum()
def wrapper_fn(x):
return torch.func.grad(fn)(x)
x = torch.randn(3, 3, 3)
wrapped_gm = self._compile_check(wrapper_fn, (x,))
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 1828,
"end": 2238
} | class ____(OAuth2Error):
"""The request is missing a required parameter, includes an
unsupported parameter value (other than grant type),
repeats a parameter, includes multiple credentials,
utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.
https://tools.ietf.org/html/rfc6749#section-5.2
"""
error = "invalid_request"
| InvalidRequestError |
python | pytorch__pytorch | test/cpp_extensions/libtorch_agnostic_2_9_extension/setup.py | {
"start": 303,
"end": 2343
} | class ____(distutils.command.clean.clean):
def run(self):
# Run default behavior first
distutils.command.clean.clean.run(self)
# Remove extension
for path in (ROOT_DIR / "libtorch_agnostic_2_9").glob("**/*.so"):
path.unlink()
# Remove build and dist and egg-info directories
dirs = [
ROOT_DIR / "build",
ROOT_DIR / "dist",
ROOT_DIR / "libtorch_agnostic_2_9.egg-info",
]
for path in dirs:
if path.exists():
shutil.rmtree(str(path), ignore_errors=True)
def get_extension():
extra_compile_args = {
"cxx": [
"-fdiagnostics-color=always",
"-DTORCH_STABLE_ONLY",
"-DTORCH_TARGET_VERSION=0x0209000000000000",
],
}
sources = list(CSRC_DIR.glob("**/*.cpp"))
extension = CppExtension
# allow including <cuda_runtime.h>
if torch.cuda.is_available():
extra_compile_args["cxx"].append("-DLAE_USE_CUDA")
extra_compile_args["nvcc"] = [
"-O2",
"-DTORCH_TARGET_VERSION=0x0209000000000000",
]
extension = CUDAExtension
sources.extend(CSRC_DIR.glob("**/*.cu"))
return [
extension(
"libtorch_agnostic_2_9._C",
sources=sorted(str(s) for s in sources),
py_limited_api=True,
extra_compile_args=extra_compile_args,
extra_link_args=[],
)
]
setup(
name="libtorch_agnostic_2_9",
version="0.0",
author="PyTorch Core Team",
description="Example of libtorch agnostic extension for PyTorch 2.9",
packages=find_packages(exclude=("test",)),
package_data={"libtorch_agnostic_2_9": ["*.dll", "*.dylib", "*.so"]},
install_requires=[
"torch",
],
ext_modules=get_extension(),
cmdclass={
"build_ext": BuildExtension.with_options(no_python_abi_suffix=True),
"clean": clean,
},
options={"bdist_wheel": {"py_limited_api": "cp39"}},
)
| clean |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 37001,
"end": 37343
} | class ____(Operator):
""" Increment an upper index. """
def __init__(self, ai):
ai = sympify(ai)
if ai == 0:
raise ValueError('Cannot increment zero upper index.')
self._poly = Poly(_x/ai + 1, _x)
def __str__(self):
return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0])
| ShiftA |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3620,
"end": 3750
} | class ____(APIStatusError):
status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
| ConflictError |
python | getsentry__sentry | tests/sentry/receivers/test_transactions.py | {
"start": 674,
"end": 4511
} | class ____(TestCase):
@cached_property
def min_ago(self) -> str:
return before_now(minutes=1).isoformat()
def test_transaction_processed(self) -> None:
assert not self.project.flags.has_transactions
event = self.store_event(
data={
"type": "transaction",
"timestamp": self.min_ago,
"start_timestamp": self.min_ago,
"contexts": {"trace": {"trace_id": "b" * 32, "span_id": "c" * 16, "op": ""}},
},
project_id=self.project.id,
)
transaction_processed.send(project=self.project, event=event, sender=type(self.project))
project = Project.objects.get(id=self.project.id)
assert project.flags.has_transactions
def test_transaction_processed_no_platform(self) -> None:
self.project.update(platform=None)
assert not self.project.platform
assert not self.project.flags.has_transactions
event = self.store_event(
data={
"type": "transaction",
"timestamp": self.min_ago,
"start_timestamp": self.min_ago,
"contexts": {"trace": {"trace_id": "b" * 32, "span_id": "c" * 16, "op": ""}},
},
project_id=self.project.id,
)
transaction_processed.send(project=self.project, event=event, sender=type(self.project))
project = Project.objects.get(id=self.project.id)
assert project.flags.has_transactions
def test_event_processed(self) -> None:
assert not self.project.flags.has_transactions
event = self.store_event(
data={"type": "default", "timestamp": self.min_ago}, project_id=self.project.id
)
event_processed.send(project=self.project, event=event, sender=type(self.project))
project = Project.objects.get(id=self.project.id)
assert not project.flags.has_transactions
@patch("sentry.analytics.record")
def test_analytics_event(self, mock_record: MagicMock) -> None:
assert not self.project.flags.has_transactions
event = self.store_event(
data={
"type": "transaction",
"timestamp": self.min_ago,
"start_timestamp": self.min_ago,
"contexts": {"trace": {"trace_id": "b" * 32, "span_id": "c" * 16, "op": ""}},
},
project_id=self.project.id,
)
transaction_processed.send(project=self.project, event=event, sender=type(self.project))
project = Project.objects.get(id=self.project.id)
assert project.flags.has_transactions
assert_any_analytics_event(
mock_record,
FirstTransactionSentEvent(
default_user_id=self.user.id,
organization_id=self.organization.id,
project_id=self.project.id,
platform=self.project.platform,
),
)
def test_analytics_event_no_owner(self) -> None:
with unguarded_write(using=router.db_for_write(OrganizationMember)):
OrganizationMember.objects.filter(organization=self.organization, role="owner").delete()
assert not self.project.flags.has_transactions
event = self.store_event(
data={
"type": "transaction",
"timestamp": self.min_ago,
"start_timestamp": self.min_ago,
"contexts": {"trace": {"trace_id": "b" * 32, "span_id": "c" * 16, "op": ""}},
},
project_id=self.project.id,
)
transaction_processed.send(project=self.project, event=event, sender=type(self.project))
project = Project.objects.get(id=self.project.id)
assert project.flags.has_transactions
| RecordFirstTransactionTest |
python | boto__boto3 | boto3/utils.py | {
"start": 2377,
"end": 3141
} | class ____:
"""A lazily loaded waiter model
This does not load the service waiter model until an attempt is made
to retrieve the waiter model for a specific waiter. This is helpful
in docstring generation where we do not need to actually need to grab
the waiter-2.json until it is accessed through a ``get_waiter`` call
when the docstring is generated/accessed.
"""
def __init__(self, bc_session, service_name, api_version):
self._session = bc_session
self._service_name = service_name
self._api_version = api_version
def get_waiter(self, waiter_name):
return self._session.get_waiter_model(
self._service_name, self._api_version
).get_waiter(waiter_name)
| LazyLoadedWaiterModel |
python | ethereum__web3.py | web3/contract/base_contract.py | {
"start": 29454,
"end": 32968
} | class ____(Generic[TContractFn]):
"""Class containing contract function objects"""
_functions: Sequence[ABIFunction] = None
def __init__(
self,
abi: ABI,
w3: Union["Web3", "AsyncWeb3[Any]"],
contract_function_class: type[TContractFn],
address: ChecksumAddress | None = None,
decode_tuples: bool | None = False,
) -> None:
self.abi = abi
self.w3 = w3
self.address = address
_functions: Sequence[ABIFunction] = None
if self.abi:
# Function with least number of inputs is first
# This ensures ambiguity will always be deterministic
# Prefer function without arguments if present, otherwise
# just use the first available
_functions = sorted(
filter_abi_by_type("function", self.abi),
key=lambda fn: (fn["name"], len(fn.get("inputs", []))),
)
for func in _functions:
abi_signature = abi_to_signature(func)
function_factory = contract_function_class.factory(
abi_signature,
w3=self.w3,
contract_abi=self.abi,
address=self.address,
decode_tuples=decode_tuples,
abi=func,
)
# Set function name on instance if it does not already exist
if func["name"] not in self.__dict__:
setattr(self, func["name"], function_factory)
# Set function signature on instance
# Handles ambiguity in overloaded contract functions
setattr(self, f"_{abi_signature}", function_factory)
if _functions:
self._functions = _functions
def __hasattr__(self, function_name: str) -> bool:
try:
return function_name in self.__dict__["_functions"]
except ABIFunctionNotFound:
return False
def __iter__(self) -> Iterable[TContractFn]:
if not hasattr(self, "_functions") or not self._functions:
return
for func in self._functions:
yield self[abi_to_signature(func)]
def __getattr__(self, function_name: str) -> TContractFn:
if super().__getattribute__("abi") is None:
raise NoABIFound(
"There is no ABI found for this contract.",
)
elif "_functions" not in self.__dict__ or len(self._functions) == 0:
raise NoABIFunctionsFound(
"The abi for this contract contains no function definitions. ",
"Are you sure you provided the correct contract abi?",
)
elif get_name_from_abi_element_identifier(function_name) not in [
get_name_from_abi_element_identifier(function["name"])
for function in self._functions
]:
raise ABIFunctionNotFound(
f"The function '{function_name}' was not found in this ",
"contract's abi.",
)
if "(" not in function_name:
function_name = _get_any_abi_signature_with_name(
function_name, self._functions
)
else:
function_name = f"_{function_name}"
return super().__getattribute__(
function_name,
)
def __getitem__(self, function_name: str) -> TContractFn:
return getattr(self, function_name)
| BaseContractFunctions |
python | pandas-dev__pandas | pandas/core/tools/datetimes.py | {
"start": 2665,
"end": 41479
} | class ____(YearMonthDayDict, total=False):
hour: DatetimeDictArg
hours: DatetimeDictArg
minute: DatetimeDictArg
minutes: DatetimeDictArg
second: DatetimeDictArg
seconds: DatetimeDictArg
ms: DatetimeDictArg
us: DatetimeDictArg
ns: DatetimeDictArg
DictConvertible = Union[FulldatetimeDict, "DataFrame"]
start_caching_at = 50
# ---------------------------------------------------------------------
def _guess_datetime_format_for_array(arr, dayfirst: bool | None = False) -> str | None:
# Try to guess the format based on the first non-NaN element, return None if can't
if (first_non_null := tslib.first_non_null(arr)) != -1:
if type(first_non_nan_element := arr[first_non_null]) is str:
# GH#32264 np.str_ object
guessed_format = guess_datetime_format(
first_non_nan_element, dayfirst=dayfirst
)
if guessed_format is not None:
return guessed_format
# If there are multiple non-null elements, warn about
# how parsing might not be consistent
if tslib.first_non_null(arr[first_non_null + 1 :]) != -1:
warnings.warn(
"Could not infer format, so each element will be parsed "
"individually, falling back to `dateutil`. To ensure parsing is "
"consistent and as-expected, please specify a format.",
UserWarning,
stacklevel=find_stack_level(),
)
return None
def should_cache(
arg: ArrayConvertible, unique_share: float = 0.7, check_count: int | None = None
) -> bool:
"""
Decides whether to do caching.
If the percent of unique elements among `check_count` elements less
than `unique_share * 100` then we can do caching.
Parameters
----------
arg: listlike, tuple, 1-d array, Series
unique_share: float, default=0.7, optional
0 < unique_share < 1
check_count: int, optional
0 <= check_count <= len(arg)
Returns
-------
do_caching: bool
Notes
-----
By default for a sequence of less than 50 items in size, we don't do
caching; for the number of elements less than 5000, we take ten percent of
all elements to check for a uniqueness share; if the sequence size is more
than 5000, then we check only the first 500 elements.
All constants were chosen empirically by.
"""
do_caching = True
# default realization
if check_count is None:
# in this case, the gain from caching is negligible
if len(arg) <= start_caching_at:
return False
if len(arg) <= 5000:
check_count = len(arg) // 10
else:
check_count = 500
else:
assert 0 <= check_count <= len(arg), (
"check_count must be in next bounds: [0; len(arg)]"
)
if check_count == 0:
return False
assert 0 < unique_share < 1, "unique_share must be in next bounds: (0; 1)"
try:
# We can't cache if the items are not hashable.
unique_elements = set(islice(arg, check_count))
except TypeError:
return False
if len(unique_elements) > check_count * unique_share:
do_caching = False
return do_caching
def _maybe_cache(
arg: ArrayConvertible,
format: str | None,
cache: bool,
convert_listlike: Callable,
) -> Series:
"""
Create a cache of unique dates from an array of dates
Parameters
----------
arg : listlike, tuple, 1-d array, Series
format : string
Strftime format to parse time
cache : bool
True attempts to create a cache of converted values
convert_listlike : function
Conversion function to apply on dates
Returns
-------
cache_array : Series
Cache of converted, unique dates. Can be empty
"""
from pandas import Series
cache_array = Series(dtype=object)
if cache:
# Perform a quicker unique check
if not should_cache(arg):
return cache_array
if not isinstance(arg, (np.ndarray, ExtensionArray, Index, ABCSeries)):
arg = np.array(arg)
unique_dates = unique(arg)
if len(unique_dates) < len(arg):
cache_dates = convert_listlike(unique_dates, format)
# GH#45319
try:
cache_array = Series(cache_dates, index=unique_dates, copy=False)
except OutOfBoundsDatetime:
return cache_array
# GH#39882 and GH#35888 in case of None and NaT we get duplicates
if not cache_array.index.is_unique:
cache_array = cache_array[~cache_array.index.duplicated()]
return cache_array
def _box_as_indexlike(
dt_array: ArrayLike, utc: bool = False, name: Hashable | None = None
) -> Index:
"""
Properly boxes the ndarray of datetimes to DatetimeIndex
if it is possible or to generic Index instead
Parameters
----------
dt_array: 1-d array
Array of datetimes to be wrapped in an Index.
utc : bool
Whether to convert/localize timestamps to UTC.
name : string, default None
Name for a resulting index
Returns
-------
result : datetime of converted dates
- DatetimeIndex if convertible to sole datetime64 type
- general Index otherwise
"""
if lib.is_np_dtype(dt_array.dtype, "M"):
tz = "utc" if utc else None
return DatetimeIndex(dt_array, tz=tz, name=name)
return Index(dt_array, name=name, dtype=dt_array.dtype)
def _convert_and_box_cache(
arg: DatetimeScalarOrArrayConvertible,
cache_array: Series,
name: Hashable | None = None,
) -> Index:
"""
Convert array of dates with a cache and wrap the result in an Index.
Parameters
----------
arg : integer, float, string, datetime, list, tuple, 1-d array, Series
cache_array : Series
Cache of converted, unique dates
name : string, default None
Name for a DatetimeIndex
Returns
-------
result : Index-like of converted dates
"""
from pandas import Series
result = Series(arg, dtype=cache_array.index.dtype).map(cache_array)
return _box_as_indexlike(result._values, utc=False, name=name)
def _convert_listlike_datetimes(
arg,
format: str | None,
name: Hashable | None = None,
utc: bool = False,
unit: str | None = None,
errors: DateTimeErrorChoices = "raise",
dayfirst: bool | None = None,
yearfirst: bool | None = None,
exact: bool = True,
):
"""
Helper function for to_datetime. Performs the conversions of 1D listlike
of dates
Parameters
----------
arg : list, tuple, ndarray, Series, Index
date to be parsed
name : object
None or string for the Index name
utc : bool
Whether to convert/localize timestamps to UTC.
unit : str
None or string of the frequency of the passed data
errors : str
error handing behaviors from to_datetime, 'raise', 'coerce'
dayfirst : bool
dayfirst parsing behavior from to_datetime
yearfirst : bool
yearfirst parsing behavior from to_datetime
exact : bool, default True
exact format matching behavior from to_datetime
Returns
-------
Index-like of parsed dates
"""
if isinstance(arg, (list, tuple)):
arg = np.array(arg, dtype="O")
elif isinstance(arg, NumpyExtensionArray):
arg = np.array(arg)
arg_dtype = getattr(arg, "dtype", None)
# these are shortcutable
tz = "utc" if utc else None
if isinstance(arg_dtype, DatetimeTZDtype):
if not isinstance(arg, (DatetimeArray, DatetimeIndex)):
return DatetimeIndex(arg, tz=tz, name=name)
if utc:
arg = arg.tz_convert(None).tz_localize("utc")
return arg
elif isinstance(arg_dtype, ArrowDtype) and arg_dtype.type is Timestamp:
# TODO: Combine with above if DTI/DTA supports Arrow timestamps
if utc:
# pyarrow uses UTC, not lowercase utc
if isinstance(arg, Index):
arg_array = cast(ArrowExtensionArray, arg.array)
if arg_dtype.pyarrow_dtype.tz is not None:
arg_array = arg_array._dt_tz_convert("UTC")
else:
arg_array = arg_array._dt_tz_localize("UTC")
arg = Index(arg_array)
else:
# ArrowExtensionArray
if arg_dtype.pyarrow_dtype.tz is not None:
arg = arg._dt_tz_convert("UTC")
else:
arg = arg._dt_tz_localize("UTC")
return arg
elif lib.is_np_dtype(arg_dtype, "M"):
if not is_supported_dtype(arg_dtype):
# We go to closest supported reso, i.e. "s"
arg = astype_overflowsafe(
np.asarray(arg),
np.dtype("M8[s]"),
is_coerce=errors == "coerce",
)
if not isinstance(arg, (DatetimeArray, DatetimeIndex)):
return DatetimeIndex(arg, tz=tz, name=name)
elif utc:
# DatetimeArray, DatetimeIndex
return arg.tz_localize("utc")
return arg
elif unit is not None:
if format is not None:
raise ValueError("cannot specify both format and unit")
return _to_datetime_with_unit(arg, unit, name, utc, errors)
elif getattr(arg, "ndim", 1) > 1:
raise TypeError(
"arg must be a string, datetime, list, tuple, 1-d array, or Series"
)
# warn if passing timedelta64, raise for PeriodDtype
# NB: this must come after unit transformation
try:
arg, _ = maybe_convert_dtype(arg, copy=False, tz=libtimezones.maybe_get_tz(tz))
except TypeError:
if errors == "coerce":
npvalues = np.full(len(arg), np.datetime64("NaT", "ns"))
return DatetimeIndex(npvalues, name=name)
raise
arg = ensure_object(arg)
if format is None:
format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst)
# `format` could be inferred, or user didn't ask for mixed-format parsing.
if format is not None and format != "mixed":
return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)
result, tz_parsed = objects_to_datetime64(
arg,
dayfirst=dayfirst,
yearfirst=yearfirst,
utc=utc,
errors=errors,
allow_object=True,
)
if tz_parsed is not None:
# We can take a shortcut since the datetime64 numpy array
# is in UTC
out_unit = np.datetime_data(result.dtype)[0]
out_unit = cast("TimeUnit", out_unit)
dtype = tz_to_dtype(tz_parsed, out_unit)
dt64_values = result.view(f"M8[{dtype.unit}]")
dta = DatetimeArray._simple_new(dt64_values, dtype=dtype)
return DatetimeIndex._simple_new(dta, name=name)
return _box_as_indexlike(result, utc=utc, name=name)
def _array_strptime_with_fallback(
arg,
name,
utc: bool,
fmt: str,
exact: bool,
errors: str,
) -> Index:
"""
Call array_strptime, with fallback behavior depending on 'errors'.
"""
result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)
if tz_out is not None:
unit = np.datetime_data(result.dtype)[0]
unit = cast("TimeUnit", unit)
dtype = DatetimeTZDtype(tz=tz_out, unit=unit)
dta = DatetimeArray._simple_new(result, dtype=dtype)
if utc:
dta = dta.tz_convert("UTC")
return Index(dta, name=name)
elif result.dtype != object and utc:
unit = np.datetime_data(result.dtype)[0]
unit = cast("TimeUnit", unit)
res = Index(result, dtype=f"M8[{unit}, UTC]", name=name)
return res
return Index(result, dtype=result.dtype, name=name)
def _to_datetime_with_unit(arg, unit, name, utc: bool, errors: str) -> Index:
"""
to_datetime specalized to the case where a 'unit' is passed.
"""
arg = extract_array(arg, extract_numpy=True)
# GH#30050 pass an ndarray to tslib.array_to_datetime
# because it expects an ndarray argument
if isinstance(arg, IntegerArray):
arr = arg.astype(f"datetime64[{unit}]")
tz_parsed = None
else:
arg = np.asarray(arg)
if arg.dtype.kind in "iu":
# Note we can't do "f" here because that could induce unwanted
# rounding GH#14156, GH#20445
arr = arg.astype(f"datetime64[{unit}]", copy=False)
try:
arr = astype_overflowsafe(arr, np.dtype("M8[ns]"), copy=False)
except OutOfBoundsDatetime:
if errors == "raise":
raise
arg = arg.astype(object)
return _to_datetime_with_unit(arg, unit, name, utc, errors)
tz_parsed = None
elif arg.dtype.kind == "f":
with np.errstate(over="raise"):
try:
arr = cast_from_unit_vectorized(arg, unit=unit)
except OutOfBoundsDatetime as err:
if errors != "raise":
return _to_datetime_with_unit(
arg.astype(object), unit, name, utc, errors
)
raise OutOfBoundsDatetime(
f"cannot convert input with unit '{unit}'"
) from err
arr = arr.view("M8[ns]")
tz_parsed = None
else:
arg = arg.astype(object, copy=False)
arr, tz_parsed = tslib.array_to_datetime(
arg,
utc=utc,
errors=errors,
unit_for_numerics=unit,
creso=cast(int, NpyDatetimeUnit.NPY_FR_ns.value),
)
result = DatetimeIndex(arr, name=name)
if not isinstance(result, DatetimeIndex):
return result
# GH#23758: We may still need to localize the result with tz
# GH#25546: Apply tz_parsed first (from arg), then tz (from caller)
# result will be naive but in UTC
result = result.tz_localize("UTC").tz_convert(tz_parsed)
if utc:
if result.tz is None:
result = result.tz_localize("utc")
else:
result = result.tz_convert("utc")
return result
def _adjust_to_origin(arg, origin, unit):
"""
Helper function for to_datetime.
Adjust input argument to the specified origin
Parameters
----------
arg : list, tuple, ndarray, Series, Index
date to be adjusted
origin : 'julian' or Timestamp
origin offset for the arg
unit : str
passed unit from to_datetime, must be 'D'
Returns
-------
ndarray or scalar of adjusted date(s)
"""
if origin == "julian":
original = arg
j0 = Timestamp(0).to_julian_date()
if unit != "D":
raise ValueError("unit must be 'D' for origin='julian'")
try:
arg = arg - j0
except TypeError as err:
raise ValueError(
"incompatible 'arg' type for given 'origin'='julian'"
) from err
# preemptively check this for a nice range
j_max = Timestamp.max.to_julian_date() - j0
j_min = Timestamp.min.to_julian_date() - j0
if np.any(arg > j_max) or np.any(arg < j_min):
raise OutOfBoundsDatetime(
f"{original} is Out of Bounds for origin='julian'"
)
else:
# arg must be numeric
if not (
(is_integer(arg) or is_float(arg)) or is_numeric_dtype(np.asarray(arg))
):
raise ValueError(
f"'{arg}' is not compatible with origin='{origin}'; "
"it must be numeric with a unit specified"
)
# we are going to offset back to unix / epoch time
try:
if lib.is_integer(origin) or lib.is_float(origin):
offset = Timestamp(origin, unit=unit)
else:
offset = Timestamp(origin)
except OutOfBoundsDatetime as err:
raise OutOfBoundsDatetime(f"origin {origin} is Out of Bounds") from err
except ValueError as err:
raise ValueError(
f"origin {origin} cannot be converted to a Timestamp"
) from err
if offset.tz is not None:
raise ValueError(f"origin offset {offset} must be tz-naive")
td_offset = offset - Timestamp(0)
# convert the offset to the unit of the arg
# this should be lossless in terms of precision
ioffset = td_offset // Timedelta(1, unit=unit)
# scalars & ndarray-like can handle the addition
if is_list_like(arg) and not isinstance(arg, (ABCSeries, Index, np.ndarray)):
arg = np.asarray(arg)
arg = arg + ioffset
return arg
@overload
def to_datetime(
arg: DatetimeScalar,
errors: DateTimeErrorChoices = ...,
dayfirst: bool = ...,
yearfirst: bool = ...,
utc: bool = ...,
format: str | None = ...,
exact: bool = ...,
unit: str | None = ...,
origin=...,
cache: bool = ...,
) -> Timestamp: ...
@overload
def to_datetime(
arg: Series | DictConvertible,
errors: DateTimeErrorChoices = ...,
dayfirst: bool = ...,
yearfirst: bool = ...,
utc: bool = ...,
format: str | None = ...,
exact: bool = ...,
unit: str | None = ...,
origin=...,
cache: bool = ...,
) -> Series: ...
@overload
def to_datetime(
arg: list | tuple | Index | ArrayLike,
errors: DateTimeErrorChoices = ...,
dayfirst: bool = ...,
yearfirst: bool = ...,
utc: bool = ...,
format: str | None = ...,
exact: bool = ...,
unit: str | None = ...,
origin=...,
cache: bool = ...,
) -> DatetimeIndex: ...
@set_module("pandas")
def to_datetime(
arg: DatetimeScalarOrArrayConvertible | DictConvertible,
errors: DateTimeErrorChoices = "raise",
dayfirst: bool = False,
yearfirst: bool = False,
utc: bool = False,
format: str | None = None,
exact: bool | lib.NoDefault = lib.no_default,
unit: str | None = None,
origin: str = "unix",
cache: bool = True,
) -> DatetimeIndex | Series | DatetimeScalar | NaTType:
"""
Convert argument to datetime.
This function converts a scalar, array-like, :class:`Series` or
:class:`DataFrame`/dict-like to a pandas datetime object.
Parameters
----------
arg : int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like
The object to convert to a datetime. If a :class:`DataFrame` is provided, the
method expects minimally the following columns: :const:`"year"`,
:const:`"month"`, :const:`"day"`. The column "year"
must be specified in 4-digit format.
errors : {'raise', 'coerce'}, default 'raise'
- If :const:`'raise'`, then invalid parsing will raise an exception.
- If :const:`'coerce'`, then invalid parsing will be set as :const:`NaT`.
dayfirst : bool, default False
Specify a date parse order if `arg` is str or is list-like.
If :const:`True`, parses dates with the day first, e.g. :const:`"10/11/12"`
is parsed as :const:`2012-11-10`.
.. warning::
``dayfirst=True`` is not strict, but will prefer to parse
with day first.
yearfirst : bool, default False
Specify a date parse order if `arg` is str or is list-like.
- If :const:`True` parses dates with the year first, e.g.
:const:`"10/11/12"` is parsed as :const:`2010-11-12`.
- If both `dayfirst` and `yearfirst` are :const:`True`, `yearfirst` is
preceded (same as :mod:`dateutil`).
.. warning::
``yearfirst=True`` is not strict, but will prefer to parse
with year first.
utc : bool, default False
Control timezone-related parsing, localization and conversion.
- If :const:`True`, the function *always* returns a timezone-aware
UTC-localized :class:`Timestamp`, :class:`Series` or
:class:`DatetimeIndex`. To do this, timezone-naive inputs are
*localized* as UTC, while timezone-aware inputs are *converted* to UTC.
- If :const:`False` (default), inputs will not be coerced to UTC.
Timezone-naive inputs will remain naive, while timezone-aware ones
will keep their time offsets. Limitations exist for mixed
offsets (typically, daylight savings), see :ref:`Examples
<to_datetime_tz_examples>` section for details.
See also: pandas general documentation about `timezone conversion and
localization
<https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
#time-zone-handling>`_.
format : str, default None
The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. See
`strftime documentation
<https://docs.python.org/3/library/datetime.html
#strftime-and-strptime-behavior>`_ for more information on choices, though
note that :const:`"%f"` will parse all the way up to nanoseconds.
You can also pass:
- "ISO8601", to parse any `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_
time string (not necessarily in exactly the same format);
- "mixed", to infer the format for each element individually. This is risky,
and you should probably use it along with `dayfirst`.
.. note::
If a :class:`DataFrame` is passed, then `format` has no effect.
exact : bool, default True
Control how `format` is used:
- If :const:`True`, require an exact `format` match.
- If :const:`False`, allow the `format` to match anywhere in the target
string.
Cannot be used alongside ``format='ISO8601'`` or ``format='mixed'``.
unit : str, default 'ns'
The unit of the arg (D,s,ms,us,ns) denote the unit, which is an
integer or float number. This will be based off the origin.
Example, with ``unit='ms'`` and ``origin='unix'``, this would calculate
the number of milliseconds to the unix epoch start.
origin : scalar, default 'unix'
Define the reference date. The numeric values would be parsed as number
of units (defined by `unit`) since this reference date.
- If :const:`'unix'` (or POSIX) time; origin is set to 1970-01-01.
- If :const:`'julian'`, unit must be :const:`'D'`, and origin is set to
beginning of Julian Calendar. Julian day number :const:`0` is assigned
to the day starting at noon on January 1, 4713 BC.
- If Timestamp convertible (Timestamp, dt.datetime, np.datetimt64 or date
string), origin is set to Timestamp identified by origin.
- If a float or integer, origin is the difference
(in units determined by the ``unit`` argument) relative to 1970-01-01.
cache : bool, default True
If :const:`True`, use a cache of unique, converted dates to apply the
datetime conversion. May produce significant speed-up when parsing
duplicate date strings, especially ones with timezone offsets. The cache
is only used when there are at least 50 values. The presence of
out-of-bounds values will render the cache unusable and may slow down
parsing.
Returns
-------
datetime
If parsing succeeded.
Return type depends on input (types in parenthesis correspond to
fallback in case of unsuccessful timezone or out-of-range timestamp
parsing):
- scalar: :class:`Timestamp` (or :class:`datetime.datetime`)
- array-like: :class:`DatetimeIndex` (or :class:`Series` with
:class:`object` dtype containing :class:`datetime.datetime`)
- Series: :class:`Series` of :class:`datetime64` dtype (or
:class:`Series` of :class:`object` dtype containing
:class:`datetime.datetime`)
- DataFrame: :class:`Series` of :class:`datetime64` dtype (or
:class:`Series` of :class:`object` dtype containing
:class:`datetime.datetime`)
Raises
------
ParserError
When parsing a date from string fails.
ValueError
When another datetime conversion error happens. For example when one
of 'year', 'month', day' columns is missing in a :class:`DataFrame`, or
when a Timezone-aware :class:`datetime.datetime` is found in an array-like
of mixed time offsets, and ``utc=False``, or when parsing datetimes
with mixed time zones unless ``utc=True``. If parsing datetimes with mixed
time zones, please specify ``utc=True``.
See Also
--------
DataFrame.astype : Cast argument to a specified dtype.
to_timedelta : Convert argument to timedelta.
convert_dtypes : Convert dtypes.
Notes
-----
Many input types are supported, and lead to different output types:
- **scalars** can be int, float, str, datetime object (from stdlib :mod:`datetime`
module or :mod:`numpy`). They are converted to :class:`Timestamp` when
possible, otherwise they are converted to :class:`datetime.datetime`.
None/NaN/null scalars are converted to :const:`NaT`.
- **array-like** can contain int, float, str, datetime objects. They are
converted to :class:`DatetimeIndex` when possible, otherwise they are
converted to :class:`Index` with :class:`object` dtype, containing
:class:`datetime.datetime`. None/NaN/null entries are converted to
:const:`NaT` in both cases.
- **Series** are converted to :class:`Series` with :class:`datetime64`
dtype when possible, otherwise they are converted to :class:`Series` with
:class:`object` dtype, containing :class:`datetime.datetime`. None/NaN/null
entries are converted to :const:`NaT` in both cases.
- **DataFrame/dict-like** are converted to :class:`Series` with
:class:`datetime64` dtype. For each row a datetime is created from assembling
the various dataframe columns. Column keys can be common abbreviations
like ['year', 'month', 'day', 'minute', 'second', 'ms', 'us', 'ns']) or
plurals of the same.
The following causes are responsible for :class:`datetime.datetime` objects
being returned (possibly inside an :class:`Index` or a :class:`Series` with
:class:`object` dtype) instead of a proper pandas designated type
(:class:`Timestamp`, :class:`DatetimeIndex` or :class:`Series`
with :class:`datetime64` dtype):
- when any input element is before :const:`Timestamp.min` or after
:const:`Timestamp.max`, see `timestamp limitations
<https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
#timeseries-timestamp-limits>`_.
- when ``utc=False`` (default) and the input is an array-like or
:class:`Series` containing mixed naive/aware datetime, or aware with mixed
time offsets. Note that this happens in the (quite frequent) situation when
the timezone has a daylight savings policy. In that case you may wish to
use ``utc=True``.
Examples
--------
**Handling various input formats**
Assembling a datetime from multiple columns of a :class:`DataFrame`. The keys
can be common abbreviations like ['year', 'month', 'day', 'minute', 'second',
'ms', 'us', 'ns']) or plurals of the same
>>> df = pd.DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]})
>>> pd.to_datetime(df)
0 2015-02-04
1 2016-03-05
dtype: datetime64[us]
Using a unix epoch time
>>> pd.to_datetime(1490195805, unit="s")
Timestamp('2017-03-22 15:16:45')
>>> pd.to_datetime(1490195805433502912, unit="ns")
Timestamp('2017-03-22 15:16:45.433502912')
.. warning:: For float arg, precision rounding might happen. To prevent
unexpected behavior use a fixed-width exact type.
Using a non-unix epoch origin
>>> pd.to_datetime([1, 2, 3], unit="D", origin=pd.Timestamp("1960-01-01"))
DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],
dtype='datetime64[ns]', freq=None)
**Differences with strptime behavior**
:const:`"%f"` will parse all the way up to nanoseconds.
>>> pd.to_datetime("2018-10-26 12:00:00.0000000011", format="%Y-%m-%d %H:%M:%S.%f")
Timestamp('2018-10-26 12:00:00.000000001')
**Non-convertible date/times**
Passing ``errors='coerce'`` will force an out-of-bounds date to :const:`NaT`,
in addition to forcing non-dates (or non-parseable dates) to :const:`NaT`.
>>> pd.to_datetime("invalid for Ymd", format="%Y%m%d", errors="coerce")
NaT
.. _to_datetime_tz_examples:
**Timezones and time offsets**
The default behaviour (``utc=False``) is as follows:
- Timezone-naive inputs are converted to timezone-naive :class:`DatetimeIndex`:
>>> pd.to_datetime(["2018-10-26 12:00:00", "2018-10-26 13:00:15"])
DatetimeIndex(['2018-10-26 12:00:00', '2018-10-26 13:00:15'],
dtype='datetime64[us]', freq=None)
- Timezone-aware inputs *with constant time offset* are converted to
timezone-aware :class:`DatetimeIndex`:
>>> pd.to_datetime(["2018-10-26 12:00 -0500", "2018-10-26 13:00 -0500"])
DatetimeIndex(['2018-10-26 12:00:00-05:00', '2018-10-26 13:00:00-05:00'],
dtype='datetime64[us, UTC-05:00]', freq=None)
- However, timezone-aware inputs *with mixed time offsets* (for example
issued from a timezone with daylight savings, such as Europe/Paris)
are **not successfully converted** to a :class:`DatetimeIndex`.
Parsing datetimes with mixed time zones will raise a ValueError unless
``utc=True``:
>>> pd.to_datetime(
... ["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"]
... ) # doctest: +SKIP
ValueError: Mixed timezones detected. Pass utc=True in to_datetime
or tz='UTC' in DatetimeIndex to convert to a common timezone.
- To create a :class:`Series` with mixed offsets and ``object`` dtype, please use
:meth:`Series.apply` and :func:`datetime.datetime.strptime`:
>>> import datetime as dt
>>> ser = pd.Series(["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"])
>>> ser.apply(lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M %z"))
0 2020-10-25 02:00:00+02:00
1 2020-10-25 04:00:00+01:00
dtype: object
- A mix of timezone-aware and timezone-naive inputs will also raise a ValueError
unless ``utc=True``:
>>> from datetime import datetime
>>> pd.to_datetime(
... ["2020-01-01 01:00:00-01:00", datetime(2020, 1, 1, 3, 0)]
... ) # doctest: +SKIP
ValueError: Mixed timezones detected. Pass utc=True in to_datetime
or tz='UTC' in DatetimeIndex to convert to a common timezone.
|
Setting ``utc=True`` solves most of the above issues:
- Timezone-naive inputs are *localized* as UTC
>>> pd.to_datetime(["2018-10-26 12:00", "2018-10-26 13:00"], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2018-10-26 13:00:00+00:00'],
dtype='datetime64[us, UTC]', freq=None)
- Timezone-aware inputs are *converted* to UTC (the output represents the
exact same datetime, but viewed from the UTC time offset `+00:00`).
>>> pd.to_datetime(["2018-10-26 12:00 -0530", "2018-10-26 12:00 -0500"], utc=True)
DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],
dtype='datetime64[us, UTC]', freq=None)
- Inputs can contain both string or datetime, the above
rules still apply
>>> pd.to_datetime(["2018-10-26 12:00", datetime(2020, 1, 1, 18)], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2020-01-01 18:00:00+00:00'],
dtype='datetime64[us, UTC]', freq=None)
"""
if exact is not lib.no_default and format in {"mixed", "ISO8601"}:
raise ValueError("Cannot use 'exact' when 'format' is 'mixed' or 'ISO8601'")
if arg is None:
return NaT
if origin != "unix":
arg = _adjust_to_origin(arg, origin, unit)
convert_listlike = partial(
_convert_listlike_datetimes,
utc=utc,
unit=unit,
dayfirst=dayfirst,
yearfirst=yearfirst,
errors=errors,
exact=exact, # type: ignore[arg-type]
)
result: Timestamp | NaTType | Series | Index
if isinstance(arg, Timestamp):
result = arg
if utc:
if arg.tz is not None:
result = arg.tz_convert("utc")
else:
result = arg.tz_localize("utc")
elif isinstance(arg, ABCSeries):
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
if not cache_array.empty:
result = arg.map(cache_array)
else:
values = convert_listlike(arg._values, format)
result = arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, (ABCDataFrame, abc.MutableMapping)):
result = _assemble_from_unit_mappings(arg, errors, utc)
elif isinstance(arg, Index):
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
if not cache_array.empty:
result = _convert_and_box_cache(arg, cache_array, name=arg.name)
else:
result = convert_listlike(arg, format, name=arg.name)
elif is_list_like(arg):
try:
# error: Argument 1 to "_maybe_cache" has incompatible type
# "Union[float, str, datetime, List[Any], Tuple[Any, ...], ExtensionArray,
# ndarray[Any, Any], Series]"; expected "Union[List[Any], Tuple[Any, ...],
# Union[Union[ExtensionArray, ndarray[Any, Any]], Index, Series], Series]"
argc = cast(
Union[list, tuple, ExtensionArray, np.ndarray, "Series", Index], arg
)
cache_array = _maybe_cache(argc, format, cache, convert_listlike)
except OutOfBoundsDatetime:
# caching attempts to create a DatetimeIndex, which may raise
# an OOB. If that's the desired behavior, then just reraise...
if errors == "raise":
raise
# ... otherwise, continue without the cache.
from pandas import Series
cache_array = Series([], dtype=object) # just an empty array
if not cache_array.empty:
result = _convert_and_box_cache(argc, cache_array)
else:
result = convert_listlike(argc, format)
else:
result = convert_listlike(np.array([arg]), format)[0]
if isinstance(arg, bool) and isinstance(result, np.bool_):
result = bool(result) # TODO: avoid this kludge.
# error: Incompatible return value type (got "Union[Timestamp, NaTType,
# Series, Index]", expected "Union[DatetimeIndex, Series, float, str,
# NaTType, None]")
return result # type: ignore[return-value]
# mappings for assembling units
_unit_map = {
"year": "year",
"years": "year",
"month": "month",
"months": "month",
"day": "day",
"days": "day",
"hour": "h",
"hours": "h",
"minute": "m",
"minutes": "m",
"second": "s",
"seconds": "s",
"ms": "ms",
"millisecond": "ms",
"milliseconds": "ms",
"us": "us",
"microsecond": "us",
"microseconds": "us",
"ns": "ns",
"nanosecond": "ns",
"nanoseconds": "ns",
}
def _assemble_from_unit_mappings(
arg, errors: DateTimeErrorChoices, utc: bool
) -> Series:
"""
assemble the unit specified fields from the arg (DataFrame)
Return a Series for actual parsing
Parameters
----------
arg : DataFrame
errors : {'raise', 'coerce'}, default 'raise'
- If :const:`'raise'`, then invalid parsing will raise an exception
- If :const:`'coerce'`, then invalid parsing will be set as :const:`NaT`
utc : bool
Whether to convert/localize timestamps to UTC.
Returns
-------
Series
"""
from pandas import (
DataFrame,
to_numeric,
to_timedelta,
)
arg = DataFrame(arg)
if not arg.columns.is_unique:
raise ValueError("cannot assemble with duplicate keys")
# replace passed unit with _unit_map
def f(value):
if value in _unit_map:
return _unit_map[value]
# m is case significant
if value.lower() in _unit_map:
return _unit_map[value.lower()]
return value
unit = {k: f(k) for k in arg.keys()}
unit_rev = {v: k for k, v in unit.items()}
# we require at least Ymd
required = ["year", "month", "day"]
req = set(required) - set(unit_rev.keys())
if len(req):
_required = ",".join(sorted(req))
raise ValueError(
"to assemble mappings requires at least that "
f"[year, month, day] be specified: [{_required}] is missing"
)
# keys we don't recognize
excess = set(unit_rev.keys()) - set(_unit_map.values())
if len(excess):
_excess = ",".join(sorted(excess))
raise ValueError(
f"extra keys have been passed to the datetime assemblage: [{_excess}]"
)
def coerce(values):
# we allow coercion to if errors allows
values = to_numeric(values, errors=errors)
# prevent prevision issues in case of float32 # GH#60506
if is_float_dtype(values.dtype):
values = values.astype("float64")
# prevent overflow in case of int8 or int16
if is_integer_dtype(values.dtype):
values = values.astype("int64")
return values
values = (
coerce(arg[unit_rev["year"]]) * 10000
+ coerce(arg[unit_rev["month"]]) * 100
+ coerce(arg[unit_rev["day"]])
)
try:
values = to_datetime(values, format="%Y%m%d", errors=errors, utc=utc)
except (TypeError, ValueError) as err:
raise ValueError(f"cannot assemble the datetimes: {err}") from err
units: list[UnitChoices] = ["h", "m", "s", "ms", "us", "ns"]
for u in units:
value = unit_rev.get(u)
if value is not None and value in arg:
try:
values += to_timedelta(coerce(arg[value]), unit=u, errors=errors)
except (TypeError, ValueError) as err:
raise ValueError(
f"cannot assemble the datetimes [{value}]: {err}"
) from err
return values
__all__ = [
"DateParseError",
"should_cache",
"to_datetime",
]
| FulldatetimeDict |
python | PrefectHQ__prefect | tests/server/schemas/test_actions.py | {
"start": 1000,
"end": 1316
} | class ____:
def test_model_dump_json_mode_succeeds_with_parameters(
self, test_params, expected_dict
):
frc = FlowRunCreate(flow_id=uuid4(), flow_version="0.1", parameters=test_params)
res = frc.model_dump(mode="json")
assert res["parameters"] == expected_dict
| TestFlowRunCreate |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 356349,
"end": 356676
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("IpAllowListEntry", graphql_name="node")
| IpAllowListEntryEdge |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 29771,
"end": 30356
} | class ____(
roles.BinaryElementRole[Any], elements.CompilerColumnElement
):
"""lightweight label object which acts as an expression.Label."""
__visit_name__ = "label"
__slots__ = "element", "name", "_alt_names"
def __init__(self, col, name, alt_names=()):
self.element = col
self.name = name
self._alt_names = (col,) + alt_names
@property
def proxy_set(self):
return self.element.proxy_set
@property
def type(self):
return self.element.type
def self_group(self, **kw):
return self
| _CompileLabel |
python | pydata__xarray | xarray/namedarray/_typing.py | {
"start": 6911,
"end": 7165
} | class ____(
_array[_ShapeType_co, _DType_co], Protocol[_ShapeType_co, _DType_co]
):
"""
Minimal sparse duck array.
Corresponds to np.ndarray.
"""
def todense(self) -> np.ndarray[Any, _DType_co]: ...
@runtime_checkable
| _sparsearray |
python | bokeh__bokeh | tests/unit/bokeh/application/handlers/test_server_lifecycle.py | {
"start": 1832,
"end": 7814
} | class ____:
# Public methods ----------------------------------------------------------
async def test_empty_lifecycle(self) -> None:
doc = Document()
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
handler.modify_document(doc)
result['handler'] = handler
with_file_contents("# This script does nothing", load)
handler = result['handler']
handler.on_server_loaded(None)
handler.on_server_unloaded(None)
await handler.on_session_created(None)
await handler.on_session_destroyed(None)
if handler.failed:
raise RuntimeError(handler.error)
assert not doc.roots
def test_lifecycle_bad_syntax(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("This is a syntax error", load)
handler = result['handler']
assert handler.error is not None
assert 'Invalid syntax' in handler.error
def test_lifecycle_runtime_error(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("raise RuntimeError('nope')", load)
handler = result['handler']
assert handler.error is not None
assert 'nope' in handler.error
def test_lifecycle_bad_server_loaded_signature(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
def on_server_loaded(a,b):
pass
""", load)
handler = result['handler']
assert handler.error is not None
assert handler.error_detail is not None
assert 'on_server_loaded must have signature func(server_context)' in handler.error
assert 'func(a, b)' in handler.error
assert "Traceback" in handler.error_detail
def test_lifecycle_bad_server_unloaded_signature(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
def on_server_unloaded(a,b):
pass
""", load)
handler = result['handler']
assert handler.error is not None
assert handler.error_detail is not None
assert 'on_server_unloaded must have signature func(server_context)' in handler.error
assert 'func(a, b)' in handler.error
assert "Traceback" in handler.error_detail
def test_lifecycle_bad_session_created_signature(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
def on_session_created(a,b):
pass
""", load)
handler = result['handler']
assert handler.error is not None
assert 'on_session_created must have signature func(session_context)' in handler.error
assert 'func(a, b)' in handler.error
def test_lifecycle_bad_session_destroyed_signature(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
def on_session_destroyed(a,b):
pass
""", load)
handler = result['handler']
assert handler.error is not None
assert 'on_session_destroyed must have signature func(session_context)' in handler.error
assert 'func(a, b)' in handler.error
async def test_calling_lifecycle_hooks(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = result['handler'] = bahs.ServerLifecycleHandler(filename=filename)
if handler.failed:
raise RuntimeError(handler.error)
with_file_contents(script_adds_four_handlers, load)
handler = result['handler']
assert "on_server_loaded" == handler.on_server_loaded(None)
assert "on_server_unloaded" == handler.on_server_unloaded(None)
assert "on_session_created" == await handler.on_session_created(None)
assert "on_session_destroyed" == await handler.on_session_destroyed(None)
def test_url_path(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
def on_server_unloaded(server_context):
pass
""", load)
handler = result['handler']
assert handler.error is None
url_path = handler.url_path()
assert url_path is not None and url_path.startswith("/")
def test_url_path_failed(self) -> None:
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
result['handler'] = handler
with_file_contents("""
# bad signature
def on_server_unloaded():
pass
""", load)
handler = result['handler']
assert handler.error is not None
assert handler.url_path() is None
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Test_ServerLifecycleHandler |
python | ray-project__ray | python/ray/data/tests/test_namespace_expressions.py | {
"start": 20181,
"end": 21949
} | class ____:
"""Tests for chaining and combining namespace expressions."""
def test_list_with_arithmetic(self, dataset_format):
"""Test list operations combined with arithmetic."""
data = [{"items": [1, 2, 3]}]
ds = _create_dataset(data, dataset_format)
result = ds.with_column("len_plus_one", col("items").list.len() + 1).to_pandas()
expected = pd.DataFrame({"items": [[1, 2, 3]], "len_plus_one": [4]})
assert rows_same(result, expected)
def test_string_with_comparison(self, dataset_format):
"""Test string operations combined with comparison."""
data = [{"name": "Alice"}, {"name": "Bo"}]
ds = _create_dataset(data, dataset_format)
result = ds.with_column("long_name", col("name").str.len() > 3).to_pandas()
expected = pd.DataFrame({"name": ["Alice", "Bo"], "long_name": [True, False]})
assert rows_same(result, expected)
def test_multiple_operations(self, dataset_format):
"""Test multiple namespace operations in single pipeline."""
data = [{"name": "alice"}]
ds = _create_dataset(data, dataset_format)
result = (
ds.with_column("upper", col("name").str.upper())
.with_column("len", col("name").str.len())
.with_column("starts_a", col("name").str.starts_with("a"))
.to_pandas()
)
expected = pd.DataFrame(
{
"name": ["alice"],
"upper": ["ALICE"],
"len": [5],
"starts_a": [True],
}
)
assert rows_same(result, expected)
# ──────────────────────────────────────
# Error Handling Tests
# ──────────────────────────────────────
| TestNamespaceIntegration |
python | ray-project__ray | python/ray/train/backend.py | {
"start": 724,
"end": 1761
} | class ____(metaclass=Singleton):
"""Singleton for distributed communication backend.
Attributes:
share_cuda_visible_devices: If True, each worker
process will have CUDA_VISIBLE_DEVICES set as the visible device
IDs of all workers on the same node for this training instance.
If False, each worker will have CUDA_VISIBLE_DEVICES set to the
device IDs allocated by Ray for that worker.
"""
share_cuda_visible_devices: bool = False
def on_start(self, worker_group: BaseWorkerGroup, backend_config: BackendConfig):
"""Logic for starting this backend."""
pass
def on_shutdown(self, worker_group: BaseWorkerGroup, backend_config: BackendConfig):
"""Logic for shutting down the backend."""
pass
def on_training_start(
self, worker_group: BaseWorkerGroup, backend_config: BackendConfig
):
"""Logic ran right before training is started.
Session API is available at this point."""
pass
| Backend |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 1342,
"end": 1464
} | class ____:
"""Represents the details of a backfill."""
id: NonNegativeInt | None = None
@dataclass
| BackfillDetails |
python | jazzband__django-model-utils | tests/test_fields/test_field_tracker.py | {
"start": 35893,
"end": 36195
} | class ____(ModelTrackerTests):
tracked_class = InheritedModelTracked
def test_child_fields_not_tracked(self) -> None:
self.name2 = 'test'
self.assertEqual(self.tracker.previous('name2'), None)
self.assertTrue(self.tracker.has_changed('name2'))
| InheritedModelTrackerTests |
python | marshmallow-code__apispec | tests/schemas.py | {
"start": 1655,
"end": 1785
} | class ____(Schema):
id = fields.Int()
name = fields.Str(required=True)
breed = fields.Str(dump_only=True)
| CategorySchema |
python | pypa__installer | tests/test_core.py | {
"start": 3286,
"end": 32859
} | class ____:
def test_calls_destination_correctly(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
print("I'm a fancy package")
""",
"fancy/__main__.py": b"""\
if __name__ == "__main__":
from . import main
main()
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
mock_destination.assert_has_calls(
[
mock.call.write_script(
name="fancy",
module="fancy",
attr="main",
section="console",
),
mock.call.write_script(
name="fancy-gui",
module="fancy",
attr="main",
section="gui",
),
mock.call.write_file(
scheme="purelib",
path="fancy/__init__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy/__main__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/METADATA",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/WHEEL",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/entry_points.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/top_level.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/fun_file.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.finalize_installation(
scheme="purelib",
record_file_path="fancy-1.0.0.dist-info/RECORD",
records=[
("scripts", ("fancy", "fancy", "main", "console")),
("scripts", ("fancy-gui", "fancy", "main", "gui")),
("purelib", ("fancy/__init__.py", "purelib", 0)),
("purelib", ("fancy/__main__.py", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/METADATA", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/WHEEL", "purelib", 0)),
(
"purelib",
("fancy-1.0.0.dist-info/entry_points.txt", "purelib", 0),
),
(
"purelib",
("fancy-1.0.0.dist-info/top_level.txt", "purelib", 0),
),
(
"purelib",
("fancy-1.0.0.dist-info/fun_file.txt", "purelib", 0),
),
(
"purelib",
RecordEntry("fancy-1.0.0.dist-info/RECORD", None, None),
),
],
),
]
)
def test_no_entrypoints_is_ok(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
print("I'm a fancy package")
""",
"fancy/__main__.py": b"""\
if __name__ == "__main__":
from . import main
main()
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
mock_destination.assert_has_calls(
[
mock.call.write_file(
scheme="purelib",
path="fancy/__init__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy/__main__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/METADATA",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/WHEEL",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/top_level.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/fun_file.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.finalize_installation(
scheme="purelib",
record_file_path="fancy-1.0.0.dist-info/RECORD",
records=[
("purelib", ("fancy/__init__.py", "purelib", 0)),
("purelib", ("fancy/__main__.py", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/METADATA", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/WHEEL", "purelib", 0)),
(
"purelib",
("fancy-1.0.0.dist-info/top_level.txt", "purelib", 0),
),
(
"purelib",
("fancy-1.0.0.dist-info/fun_file.txt", "purelib", 0),
),
(
"purelib",
RecordEntry("fancy-1.0.0.dist-info/RECORD", None, None),
),
],
),
]
)
def test_handles_platlib(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
print("I'm a fancy package")
""",
"fancy/__main__.py": b"""\
if __name__ == "__main__":
from . import main
main()
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: false
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
mock_destination.assert_has_calls(
[
mock.call.write_script(
name="fancy",
module="fancy",
attr="main",
section="console",
),
mock.call.write_script(
name="fancy-gui",
module="fancy",
attr="main",
section="gui",
),
mock.call.write_file(
scheme="platlib",
path="fancy/__init__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy/__main__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy-1.0.0.dist-info/METADATA",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy-1.0.0.dist-info/WHEEL",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy-1.0.0.dist-info/entry_points.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy-1.0.0.dist-info/top_level.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy-1.0.0.dist-info/fun_file.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.finalize_installation(
scheme="platlib",
record_file_path="fancy-1.0.0.dist-info/RECORD",
records=[
("scripts", ("fancy", "fancy", "main", "console")),
("scripts", ("fancy-gui", "fancy", "main", "gui")),
("platlib", ("fancy/__init__.py", "platlib", 0)),
("platlib", ("fancy/__main__.py", "platlib", 0)),
("platlib", ("fancy-1.0.0.dist-info/METADATA", "platlib", 0)),
("platlib", ("fancy-1.0.0.dist-info/WHEEL", "platlib", 0)),
(
"platlib",
("fancy-1.0.0.dist-info/entry_points.txt", "platlib", 0),
),
(
"platlib",
("fancy-1.0.0.dist-info/top_level.txt", "platlib", 0),
),
(
"platlib",
("fancy-1.0.0.dist-info/fun_file.txt", "platlib", 0),
),
(
"platlib",
RecordEntry("fancy-1.0.0.dist-info/RECORD", None, None),
),
],
),
]
)
def test_accepts_newer_minor_wheel_versions(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
print("I'm a fancy package")
""",
"fancy/__main__.py": b"""\
if __name__ == "__main__":
from . import main
main()
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 1.1
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
# no assertions necessary, since we want to make sure this test didn't
# raises errors.
assert True
def test_rejects_newer_major_wheel_versions(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
print("I'm a fancy package")
""",
"fancy/__main__.py": b"""\
if __name__ == "__main__":
from . import main
main()
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 2.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
with pytest.raises(InvalidWheelSource) as ctx:
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
assert "Incompatible Wheel-Version" in str(ctx.value)
def test_handles_data_properly(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
# put me in purelib
""",
"fancy-1.0.0.data/purelib/fancy/purelib.py": b"""\
# put me in purelib
""",
"fancy-1.0.0.data/platlib/fancy/platlib.py": b"""\
# put me in platlib
""",
"fancy-1.0.0.data/scripts/fancy/scripts.py": b"""\
# put me in scripts
""",
"fancy-1.0.0.data/headers/fancy/headers.py": b"""\
# put me in headers
""",
"fancy-1.0.0.data/data/fancy/data.py": b"""\
# put me in data
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
install(
source=source,
destination=mock_destination,
additional_metadata={},
)
mock_destination.assert_has_calls(
[
mock.call.write_script(
name="fancy",
module="fancy",
attr="main",
section="console",
),
mock.call.write_script(
name="fancy-gui",
module="fancy",
attr="main",
section="gui",
),
mock.call.write_file(
scheme="data",
path="fancy/data.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="headers",
path="fancy/headers.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="platlib",
path="fancy/platlib.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy/purelib.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="scripts",
path="fancy/scripts.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy/__init__.py",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/METADATA",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/WHEEL",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/entry_points.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/top_level.txt",
stream=mock.ANY,
is_executable=False,
),
mock.call.finalize_installation(
scheme="purelib",
record_file_path="fancy-1.0.0.dist-info/RECORD",
records=[
("scripts", ("fancy", "fancy", "main", "console")),
("scripts", ("fancy-gui", "fancy", "main", "gui")),
("data", ("fancy/data.py", "data", 0)),
("headers", ("fancy/headers.py", "headers", 0)),
("platlib", ("fancy/platlib.py", "platlib", 0)),
("purelib", ("fancy/purelib.py", "purelib", 0)),
("scripts", ("fancy/scripts.py", "scripts", 0)),
("purelib", ("fancy/__init__.py", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/METADATA", "purelib", 0)),
("purelib", ("fancy-1.0.0.dist-info/WHEEL", "purelib", 0)),
(
"purelib",
("fancy-1.0.0.dist-info/entry_points.txt", "purelib", 0),
),
(
"purelib",
("fancy-1.0.0.dist-info/top_level.txt", "purelib", 0),
),
(
"purelib",
RecordEntry("fancy-1.0.0.dist-info/RECORD", None, None),
),
],
),
]
)
def test_errors_out_when_given_invalid_scheme_in_data(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
# put me in purelib
""",
"fancy-1.0.0.data/purelib/fancy/purelib.py": b"""\
# put me in purelib
""",
"fancy-1.0.0.data/invalid/fancy/invalid.py": b"""\
# i am invalid
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"entry_points.txt": b"""\
[console_scripts]
fancy = fancy:main
[gui_scripts]
fancy-gui = fancy:main
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
with pytest.raises(InvalidWheelSource) as ctx:
install(
source=source,
destination=mock_destination,
additional_metadata={},
)
assert "fancy-1.0.0.data/invalid/fancy/invalid.py" in str(ctx.value)
def test_ensure_non_executable_for_additional_metadata(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
# put me in purelib
""",
},
dist_info_files={
"top_level.txt": b"""\
fancy
""",
"WHEEL": b"""\
Wheel-Version: 1.0
Generator: magic (1.0.0)
Root-Is-Purelib: true
Tag: py3-none-any
""",
"METADATA": b"""\
Metadata-Version: 2.1
Name: fancy
Version: 1.0.0
Summary: A fancy package
Author: Agendaless Consulting
Author-email: nobody@example.com
License: MIT
Keywords: fancy amazing
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
""",
},
)
all_contents = list(source.get_contents())
source.get_contents = lambda: (
(*contents, True) for (*contents, _) in all_contents
)
install(
source=source,
destination=mock_destination,
additional_metadata={
"fun_file.txt": b"this should be in dist-info!",
},
)
mock_destination.assert_has_calls(
[
mock.call.write_file(
scheme="purelib",
path="fancy/__init__.py",
stream=mock.ANY,
is_executable=True,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/METADATA",
stream=mock.ANY,
is_executable=True,
),
mock.call.write_file(
scheme="purelib",
path="fancy-1.0.0.dist-info/fun_file.txt",
stream=mock.ANY,
is_executable=False,
),
],
any_order=True,
)
| TestInstall |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/projects.py | {
"start": 10459,
"end": 14357
} | class ____(Repository, Serializable):
"""
A cloned GitHub repository, which includes the hash of the current commit.
"""
commit_hash: str
path: Path
def url_for(
self: Self,
path: str,
line_number: int | None = None,
end_line_number: int | None = None,
) -> str:
"""
Return the remote GitHub URL for the given path in this repository.
"""
url = f"https://github.com/{self.owner}/{self.name}/blob/{self.commit_hash}/{path}"
if line_number:
url += f"#L{line_number}"
if end_line_number:
url += f"-L{end_line_number}"
return url
@property
def url(self: Self) -> str:
return f"https://github.com/{self.owner}/{self.name}@{self.commit_hash}"
@classmethod
async def from_path(cls, path: Path, repo: Repository):
return cls(
name=repo.name,
owner=repo.owner,
ref=repo.ref,
path=path,
commit_hash=await cls._get_head_commit(path),
)
@staticmethod
async def _get_head_commit(checkout_dir: Path) -> str:
"""
Return the commit sha for the repository in the checkout directory.
"""
process = await create_subprocess_exec(
*["git", "rev-parse", "HEAD"],
cwd=checkout_dir,
stdout=PIPE,
)
stdout, _ = await process.communicate()
if await process.wait() != 0:
raise ProjectSetupError(f"Failed to retrieve commit sha at {checkout_dir}")
return stdout.decode().strip()
async def reset(self: Self) -> None:
"""
Reset the cloned repository to the ref it started at.
"""
process = await create_subprocess_exec(
*["git", "reset", "--hard", "origin/" + self.ref] if self.ref else [],
cwd=self.path,
env={"GIT_TERMINAL_PROMPT": "0"},
stdout=PIPE,
stderr=PIPE,
)
_, stderr = await process.communicate()
if await process.wait() != 0:
raise RuntimeError(f"Failed to reset: {stderr.decode()}")
async def pull(self: Self) -> None:
"""
Pull the latest changes.
Typically `reset` should be run first.
"""
process = await create_subprocess_exec(
*["git", "pull"],
cwd=self.path,
env={"GIT_TERMINAL_PROMPT": "0"},
stdout=PIPE,
stderr=PIPE,
)
_, stderr = await process.communicate()
if await process.wait() != 0:
raise RuntimeError(f"Failed to pull: {stderr.decode()}")
async def commit(self: Self, message: str) -> str:
"""
Commit all current changes.
Empty commits are allowed.
"""
process = await create_subprocess_exec(
*["git", "commit", "--allow-empty", "-a", "-m", message],
cwd=self.path,
env={"GIT_TERMINAL_PROMPT": "0"},
stdout=PIPE,
stderr=PIPE,
)
_, stderr = await process.communicate()
if await process.wait() != 0:
raise RuntimeError(f"Failed to commit: {stderr.decode()}")
return await self._get_head_commit(self.path)
async def diff(self: Self, *args: str) -> list[str]:
"""
Get the current diff from git.
Arguments are passed to `git diff ...`
"""
process = await create_subprocess_exec(
*["git", "diff", *args],
cwd=self.path,
env={"GIT_TERMINAL_PROMPT": "0"},
stdout=PIPE,
stderr=PIPE,
)
stdout, stderr = await process.communicate()
if await process.wait() != 0:
raise RuntimeError(f"Failed to commit: {stderr.decode()}")
return stdout.decode().splitlines()
| ClonedRepository |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass1.py | {
"start": 14551,
"end": 14770
} | class ____:
x: int
def func22(subj: Proto1 | int):
match subj:
case Proto1():
reveal_type(subj, expected_text="Proto1")
case _:
reveal_type(subj, expected_text="int")
| Impl1 |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 31140,
"end": 31573
} | class ____(GroupByApply):
_defaults = {
"observed": None,
"dropna": None,
"_slice": None,
"func": None,
"group_keys": True,
}
@functools.cached_property
def grp_func(self):
return functools.partial(groupby_slice_shift, shuffled=False)
def _shuffle_grp_func(self, shuffled=False):
return functools.partial(groupby_slice_shift, shuffled=shuffled)
| GroupByShift |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 54701,
"end": 55030
} | class ____(EnumDDLEventTest):
@testing.fixture
def produce_event_target(self, produce_subject, connection):
return produce_subject
@testing.fixture
def produce_subject(self):
return ENUM(
"x",
"y",
"z",
name="status",
)
| NativeEnumDDLEventTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 6599,
"end": 6696
} | class ____(A16):
def m0(self):
return self.m1()
def m2(self):
return 0
| B16 |
python | catalyst-team__catalyst | catalyst/callbacks/batch_transform.py | {
"start": 486,
"end": 9358
} | class ____(Callback):
"""
Preprocess your batch with specified function.
Args:
transform: Function to apply. If string will get function from registry.
scope: ``"on_batch_end"`` (post-processing model output) or
``"on_batch_start"`` (pre-processing model input).
input_key: Keys in batch dict to apply function. Defaults to ``None``.
output_key: Keys for output.
If None then will apply function inplace to ``keys_to_apply``.
Defaults to ``None``.
transform_kwargs: Kwargs for transform.
Raises:
TypeError: When keys is not str or a list.
When ``scope`` is not in ``["on_batch_end", "on_batch_start"]``.
Examples:
.. code-block:: python
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
# sample data
num_users, num_features, num_items = int(1e4), int(1e1), 10
X = torch.rand(num_users, num_features)
y = (torch.rand(num_users, num_items) > 0.5).to(torch.float32)
# pytorch loaders
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=32, num_workers=1)
loaders = {"train": loader, "valid": loader}
# model, criterion, optimizer, scheduler
model = torch.nn.Linear(num_features, num_items)
criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters())
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [2])
# model training
runner = SupervisedRunner()
runner.train(
model=model,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
loaders=loaders,
num_epochs=3,
verbose=True,
callbacks=[
dl.BatchTransformCallback(
input_key="logits", output_key="scores", transform="F.sigmoid"
),
dl.CriterionCallback(
input_key="logits", target_key="targets", metric_key="loss"
),
dl.OptimizerCallback(metric_key="loss"),
dl.SchedulerCallback(),
dl.CheckpointCallback(
logdir="./logs",
loader_key="valid",
metric_key="map01",
minimize=False
),
]
)
.. code-block:: python
class CustomRunner(dl.Runner):
def handle_batch(self, batch):
logits = self.model(
batch["features"].view(batch["features"].size(0), -1)
)
loss = F.cross_entropy(logits, batch["targets"])
accuracy01, accuracy03 = metrics.accuracy(
logits, batch["targets"], topk=(1, 3)
)
self.batch_metrics.update({
"loss": loss,
"accuracy01":accuracy01,
"accuracy03": accuracy03
})
if self.is_train_loader:
self.engine.backward(loss)
self.optimizer.step()
self.optimizer.zero_grad()
class MnistDataset(torch.utils.data.Dataset):
def __init__(self, dataset):
self.dataset = dataset
def __getitem__(self, item):
return {
"features": self.dataset[item][0],
"targets": self.dataset[item][1]
}
def __len__(self):
return len(self.dataset)
model = torch.nn.Linear(28 * 28, 10)
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
loaders = {
"train": DataLoader(
MnistDataset(
MNIST(os.getcwd(), train=False)
),
batch_size=32,
),
"valid": DataLoader(
MnistDataset(
MNIST(os.getcwd(), train=False)
),
batch_size=32,
),
}
transrorms = [
augmentation.RandomAffine(degrees=(-15, 20), scale=(0.75, 1.25)),
]
runner = CustomRunner()
# model training
runner.train(
model=model,
optimizer=optimizer,
loaders=loaders,
logdir="./logs",
num_epochs=5,
verbose=False,
load_best_on_end=True,
check=True,
callbacks=[
BatchTransformCallback(
transform=transrorms,
scope="on_batch_start",
input_key="features"
)
],
)
.. code-block:: yaml
...
callbacks:
transform:
_target_: BatchTransformCallback
transform: catalyst.ToTensor
scope: on_batch_start
input_key: features
"""
def __init__(
self,
transform: Union[Callable, str],
scope: str,
input_key: Union[List[str], str] = None,
output_key: Union[List[str], str] = None,
transform_kwargs: Dict[str, Any] = None,
):
"""
Preprocess your batch with specified function.
Args:
transform: Function to apply.
If string will get function from registry.
scope: ``"on_batch_end"`` (post-processing model output) or
``"on_batch_start"`` (pre-processing model input).
input_key: Keys in batch dict to apply function. Defaults to ``None``.
output_key: Keys for output.
If None then will apply function inplace to ``keys_to_apply``.
Defaults to ``None``.
transform_kwargs: Kwargs for transform.
Raises:
TypeError: When keys is not str or a list.
When ``scope`` is not in ``["on_batch_end", "on_batch_start"]``.
"""
super().__init__(order=CallbackOrder.Internal)
if isinstance(transform, str):
transform = REGISTRY.get(transform)
if transform_kwargs is not None:
transform = partial(transform, **transform_kwargs)
if input_key is not None:
if not isinstance(input_key, (list, str)):
raise TypeError("input key should be str or a list of str.")
elif isinstance(input_key, str):
input_key = [input_key]
self._handle_batch = self._handle_value
else:
self._handle_batch = self._handle_key_value
output_key = output_key or input_key
if output_key is not None:
if input_key is None:
raise TypeError(
"You should define input_key in " "case if output_key is not None"
)
if not isinstance(output_key, (list, str)):
raise TypeError("output key should be str or a list of str.")
if isinstance(output_key, str):
output_key = [output_key]
transform = _TupleWrapper(transform)
if isinstance(scope, str) and scope in ["on_batch_end", "on_batch_start"]:
self.scope = scope
else:
raise TypeError(
'Expected scope to be on of the ["on_batch_end", "on_batch_start"]'
)
self.input_key = input_key
self.output_key = output_key
self.transform = transform
def _handle_value(self, runner):
batch_in = [runner.batch[key] for key in self.input_key]
batch_out = self.transform(*batch_in)
runner.batch.update(
**{key: value for key, value in zip(self.output_key, batch_out)}
)
def _handle_key_value(self, runner):
runner.batch = self.transform(runner.batch)
def on_batch_start(self, runner: "IRunner") -> None:
"""Event handler."""
if self.scope == "on_batch_start":
self._handle_batch(runner)
def on_batch_end(self, runner: "IRunner") -> None:
"""Event handler."""
if self.scope == "on_batch_end":
self._handle_batch(runner)
__all__ = ["BatchTransformCallback"]
| BatchTransformCallback |
python | paramiko__paramiko | tests/test_gssapi.py | {
"start": 1288,
"end": 8574
} | class ____(KerberosTestCase):
def setUp(self):
super().setUp()
# TODO: these vars should all come from os.environ or whatever the
# approved pytest method is for runtime-configuring test data.
self.krb5_mech = "1.2.840.113554.1.2.2"
self.targ_name = self.realm.hostname
self.server_mode = False
update_env(self, self.realm.env)
def test_pyasn1(self):
"""
Test the used methods of pyasn1.
"""
from pyasn1.type.univ import ObjectIdentifier
from pyasn1.codec.der import encoder, decoder
oid = encoder.encode(ObjectIdentifier(self.krb5_mech))
mech, __ = decoder.decode(oid)
self.assertEquals(self.krb5_mech, mech.__str__())
def _gssapi_sspi_test(self):
"""
Test the used methods of python-gssapi or sspi, sspicon from pywin32.
"""
try:
import gssapi
if (
hasattr(gssapi, "__title__")
and gssapi.__title__ == "python-gssapi"
):
_API = "PYTHON-GSSAPI-OLD"
else:
_API = "PYTHON-GSSAPI-NEW"
except ImportError:
import sspicon
import sspi
_API = "SSPI"
c_token = None
gss_ctxt_status = False
mic_msg = b"G'day Mate!"
if _API == "PYTHON-GSSAPI-OLD":
if self.server_mode:
gss_flags = (
gssapi.C_PROT_READY_FLAG,
gssapi.C_INTEG_FLAG,
gssapi.C_MUTUAL_FLAG,
gssapi.C_DELEG_FLAG,
)
else:
gss_flags = (
gssapi.C_PROT_READY_FLAG,
gssapi.C_INTEG_FLAG,
gssapi.C_DELEG_FLAG,
)
# Initialize a GSS-API context.
ctx = gssapi.Context()
ctx.flags = gss_flags
krb5_oid = gssapi.OID.mech_from_string(self.krb5_mech)
target_name = gssapi.Name(
"host@" + self.targ_name, gssapi.C_NT_HOSTBASED_SERVICE
)
gss_ctxt = gssapi.InitContext(
peer_name=target_name, mech_type=krb5_oid, req_flags=ctx.flags
)
if self.server_mode:
c_token = gss_ctxt.step(c_token)
gss_ctxt_status = gss_ctxt.established
self.assertEquals(False, gss_ctxt_status)
# Accept a GSS-API context.
gss_srv_ctxt = gssapi.AcceptContext()
s_token = gss_srv_ctxt.step(c_token)
gss_ctxt_status = gss_srv_ctxt.established
self.assertNotEquals(None, s_token)
self.assertEquals(True, gss_ctxt_status)
# Establish the client context
c_token = gss_ctxt.step(s_token)
self.assertEquals(None, c_token)
else:
while not gss_ctxt.established:
c_token = gss_ctxt.step(c_token)
self.assertNotEquals(None, c_token)
# Build MIC
mic_token = gss_ctxt.get_mic(mic_msg)
if self.server_mode:
# Check MIC
status = gss_srv_ctxt.verify_mic(mic_msg, mic_token)
self.assertEquals(0, status)
elif _API == "PYTHON-GSSAPI-NEW":
if self.server_mode:
gss_flags = (
gssapi.RequirementFlag.protection_ready,
gssapi.RequirementFlag.integrity,
gssapi.RequirementFlag.mutual_authentication,
gssapi.RequirementFlag.delegate_to_peer,
)
else:
gss_flags = (
gssapi.RequirementFlag.protection_ready,
gssapi.RequirementFlag.integrity,
gssapi.RequirementFlag.delegate_to_peer,
)
# Initialize a GSS-API context.
krb5_oid = gssapi.MechType.kerberos
target_name = gssapi.Name(
"host@" + self.targ_name,
name_type=gssapi.NameType.hostbased_service,
)
gss_ctxt = gssapi.SecurityContext(
name=target_name,
flags=gss_flags,
mech=krb5_oid,
usage="initiate",
)
if self.server_mode:
c_token = gss_ctxt.step(c_token)
gss_ctxt_status = gss_ctxt.complete
self.assertEquals(False, gss_ctxt_status)
# Accept a GSS-API context.
gss_srv_ctxt = gssapi.SecurityContext(usage="accept")
s_token = gss_srv_ctxt.step(c_token)
gss_ctxt_status = gss_srv_ctxt.complete
self.assertNotEquals(None, s_token)
self.assertEquals(True, gss_ctxt_status)
# Establish the client context
c_token = gss_ctxt.step(s_token)
self.assertEquals(None, c_token)
else:
while not gss_ctxt.complete:
c_token = gss_ctxt.step(c_token)
self.assertNotEquals(None, c_token)
# Build MIC
mic_token = gss_ctxt.get_signature(mic_msg)
if self.server_mode:
# Check MIC
status = gss_srv_ctxt.verify_signature(mic_msg, mic_token)
self.assertEquals(0, status)
else:
gss_flags = (
sspicon.ISC_REQ_INTEGRITY
| sspicon.ISC_REQ_MUTUAL_AUTH
| sspicon.ISC_REQ_DELEGATE
)
# Initialize a GSS-API context.
target_name = "host/" + socket.getfqdn(self.targ_name)
gss_ctxt = sspi.ClientAuth(
"Kerberos", scflags=gss_flags, targetspn=target_name
)
if self.server_mode:
error, token = gss_ctxt.authorize(c_token)
c_token = token[0].Buffer
self.assertEquals(0, error)
# Accept a GSS-API context.
gss_srv_ctxt = sspi.ServerAuth("Kerberos", spn=target_name)
error, token = gss_srv_ctxt.authorize(c_token)
s_token = token[0].Buffer
# Establish the context.
error, token = gss_ctxt.authorize(s_token)
c_token = token[0].Buffer
self.assertEquals(None, c_token)
self.assertEquals(0, error)
# Build MIC
mic_token = gss_ctxt.sign(mic_msg)
# Check MIC
gss_srv_ctxt.verify(mic_msg, mic_token)
else:
error, token = gss_ctxt.authorize(c_token)
c_token = token[0].Buffer
self.assertNotEquals(0, error)
def test_gssapi_sspi_client(self):
"""
Test the used methods of python-gssapi or sspi, sspicon from pywin32.
"""
self._gssapi_sspi_test()
def test_gssapi_sspi_server(self):
"""
Test the used methods of python-gssapi or sspi, sspicon from pywin32.
"""
self.server_mode = True
self._gssapi_sspi_test()
| GSSAPITest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/lambda_function.py | {
"start": 6585,
"end": 10696
} | class ____(AwsBaseOperator[LambdaHook]):
"""
Invokes an AWS Lambda function.
You can invoke a function synchronously (and wait for the response), or asynchronously.
To invoke a function asynchronously, set `invocation_type` to `Event`. For more details,
review the boto3 Lambda invoke docs.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:LambdaInvokeFunctionOperator`
:param function_name: The name of the AWS Lambda function, version, or alias.
:param log_type: Set to Tail to include the execution log in the response and task logs.
Otherwise, set to "None". Applies to synchronously invoked functions only,
and returns the last 4 KB of the execution log.
:param keep_empty_log_lines: Whether or not keep empty lines in the execution log.
:param qualifier: Specify a version or alias to invoke a published version of the function.
:param invocation_type: AWS Lambda invocation type (RequestResponse, Event, DryRun)
:param client_context: Data about the invoking client to pass to the function in the context object
:param payload: JSON provided as input to the Lambda function
:param aws_conn_id: The AWS connection ID to use
"""
aws_hook_class = LambdaHook
template_fields: Sequence[str] = aws_template_fields(
"function_name",
"payload",
"qualifier",
"invocation_type",
)
ui_color = "#ff7300"
def __init__(
self,
*,
function_name: str,
log_type: str | None = None,
keep_empty_log_lines: bool = True,
qualifier: str | None = None,
invocation_type: str | None = None,
client_context: str | None = None,
payload: bytes | str | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.function_name = function_name
self.payload = payload
self.log_type = log_type
self.keep_empty_log_lines = keep_empty_log_lines
self.qualifier = qualifier
self.invocation_type = invocation_type
self.client_context = client_context
def execute(self, context: Context):
"""
Invoke the target AWS Lambda function from Airflow.
:return: The response payload from the function, or an error object.
"""
success_status_codes = [200, 202, 204]
self.log.info("Invoking AWS Lambda function: %s with payload: %s", self.function_name, self.payload)
response = self.hook.invoke_lambda(
function_name=self.function_name,
invocation_type=self.invocation_type,
log_type=self.log_type,
client_context=self.client_context,
payload=self.payload,
qualifier=self.qualifier,
)
self.log.info("Lambda response metadata: %r", response.get("ResponseMetadata"))
if log_result := response.get("LogResult"):
log_records = self.hook.encode_log_result(
log_result,
keep_empty_lines=self.keep_empty_log_lines,
)
if log_records:
self.log.info(
"The last 4 KB of the Lambda execution log (keep_empty_log_lines=%s).",
self.keep_empty_log_lines,
)
for log_record in log_records:
self.log.info(log_record)
if response.get("StatusCode") not in success_status_codes:
raise ValueError("Lambda function did not execute", json.dumps(response.get("ResponseMetadata")))
payload_stream = response.get("Payload")
payload = payload_stream.read().decode()
if "FunctionError" in response:
raise ValueError(
"Lambda function execution resulted in error",
{"ResponseMetadata": response.get("ResponseMetadata"), "Payload": payload},
)
self.log.info("Lambda function invocation succeeded: %r", response.get("ResponseMetadata"))
return payload
| LambdaInvokeFunctionOperator |
python | lazyprogrammer__machine_learning_examples | rl2/cartpole/pg_tf.py | {
"start": 1261,
"end": 3465
} | class ____:
def __init__(self, D, K, hidden_layer_sizes):
# create the graph
# K = number of actions
self.layers = []
M1 = D
for M2 in hidden_layer_sizes:
layer = HiddenLayer(M1, M2)
self.layers.append(layer)
M1 = M2
# final layer
# layer = HiddenLayer(M1, K, lambda x: x, use_bias=False)
layer = HiddenLayer(M1, K, tf.nn.softmax, use_bias=False)
self.layers.append(layer)
# inputs and targets
self.X = tf.placeholder(tf.float32, shape=(None, D), name='X')
self.actions = tf.placeholder(tf.int32, shape=(None,), name='actions')
self.advantages = tf.placeholder(tf.float32, shape=(None,), name='advantages')
# calculate output and cost
Z = self.X
for layer in self.layers:
Z = layer.forward(Z)
p_a_given_s = Z
# action_scores = Z
# p_a_given_s = tf.nn.softmax(action_scores)
# self.action_scores = action_scores
self.predict_op = p_a_given_s
# self.one_hot_actions = tf.one_hot(self.actions, K)
selected_probs = tf.log(
tf.reduce_sum(
p_a_given_s * tf.one_hot(self.actions, K),
reduction_indices=[1]
)
)
# self.selected_probs = selected_probs
cost = -tf.reduce_sum(self.advantages * selected_probs)
# self.cost = cost
# self.train_op = tf.train.AdamOptimizer(1e-1).minimize(cost)
self.train_op = tf.train.AdagradOptimizer(1e-1).minimize(cost)
# self.train_op = tf.train.MomentumOptimizer(1e-4, momentum=0.9).minimize(cost)
# self.train_op = tf.train.GradientDescentOptimizer(1e-4).minimize(cost)
def set_session(self, session):
self.session = session
def partial_fit(self, X, actions, advantages):
X = np.atleast_2d(X)
actions = np.atleast_1d(actions)
advantages = np.atleast_1d(advantages)
self.session.run(
self.train_op,
feed_dict={
self.X: X,
self.actions: actions,
self.advantages: advantages,
}
)
def predict(self, X):
X = np.atleast_2d(X)
return self.session.run(self.predict_op, feed_dict={self.X: X})
def sample_action(self, X):
p = self.predict(X)[0]
return np.random.choice(len(p), p=p)
# approximates V(s)
| PolicyModel |
python | django__django | tests/model_fields/models.py | {
"start": 11694,
"end": 11996
} | class ____(json.JSONDecoder):
def __init__(self, object_hook=None, *args, **kwargs):
return super().__init__(object_hook=self.as_uuid, *args, **kwargs)
def as_uuid(self, dct):
if "uuid" in dct:
dct["uuid"] = uuid.UUID(dct["uuid"])
return dct
| CustomJSONDecoder |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 21639,
"end": 25462
} | class ____(unittest.TestCase):
def test_sidebyside(self):
""" provide double-sized vectors to the index, where each vector
is the concatenation of twice the same vector """
ds = SyntheticDataset(32, 1000, 500, 50)
index = faiss.index_factory(ds.d, "IVF32,SQ8")
index.train(ds.get_train())
index.add(ds.get_database())
index.nprobe = 4
Dref, Iref = index.search(ds.get_queries(), 10)
select32first = make_LinearTransform_matrix(
np.eye(64, dtype='float32')[:32])
select32last = make_LinearTransform_matrix(
np.eye(64, dtype='float32')[32:])
quantizer = faiss.IndexPreTransform(
select32first,
index.quantizer
)
index2 = faiss.IndexIVFIndependentQuantizer(
quantizer,
index, select32last
)
xq2 = np.hstack([ds.get_queries()] * 2)
quantizer.search(xq2, 30)
Dnew, Inew = index2.search(xq2, 10)
np.testing.assert_array_equal(Dref, Dnew)
np.testing.assert_array_equal(Iref, Inew)
# test add
index2.reset()
xb2 = np.hstack([ds.get_database()] * 2)
index2.add(xb2)
Dnew, Inew = index2.search(xq2, 10)
np.testing.assert_array_equal(Dref, Dnew)
np.testing.assert_array_equal(Iref, Inew)
def test_half_store(self):
""" the index stores only the first half of each vector
but the coarse quantizer sees them entirely """
ds = SyntheticDataset(32, 1000, 500, 50)
gt = ds.get_groundtruth(10)
select32first = make_LinearTransform_matrix(
np.eye(32, dtype='float32')[:16])
index_ivf = faiss.index_factory(ds.d // 2, "IVF32,Flat")
index_ivf.nprobe = 4
index = faiss.IndexPreTransform(select32first, index_ivf)
index.train(ds.get_train())
index.add(ds.get_database())
Dref, Iref = index.search(ds.get_queries(), 10)
perf_ref = faiss.eval_intersection(Iref, gt)
index_ivf = faiss.index_factory(ds.d // 2, "IVF32,Flat")
index_ivf.nprobe = 4
index = faiss.IndexIVFIndependentQuantizer(
faiss.IndexFlatL2(ds.d),
index_ivf, select32first
)
index.train(ds.get_train())
index.add(ds.get_database())
Dnew, Inew = index.search(ds.get_queries(), 10)
perf_new = faiss.eval_intersection(Inew, gt)
self.assertLess(perf_ref, perf_new)
def test_precomputed_tables(self):
""" see how precomputed tables behave with centroid distance estimates from a mismatching
coarse quantizer """
ds = SyntheticDataset(48, 2000, 500, 250)
gt = ds.get_groundtruth(10)
index = faiss.IndexIVFIndependentQuantizer(
faiss.IndexFlatL2(48),
faiss.index_factory(16, "IVF64,PQ4np"),
faiss.PCAMatrix(48, 16)
)
index.train(ds.get_train())
index.add(ds.get_database())
index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
index_ivf.nprobe = 4
Dref, Iref = index.search(ds.get_queries(), 10)
perf_ref = faiss.eval_intersection(Iref, gt)
index_ivf.use_precomputed_table = 1
index_ivf.precompute_table()
Dnew, Inew = index.search(ds.get_queries(), 10)
perf_new = faiss.eval_intersection(Inew, gt)
# to be honest, it is not clear which one is better...
self.assertNotEqual(perf_ref, perf_new)
# check IO while we are at it
index2 = faiss.deserialize_index(faiss.serialize_index(index))
D2, I2 = index2.search(ds.get_queries(), 10)
np.testing.assert_array_equal(Dnew, D2)
np.testing.assert_array_equal(Inew, I2)
| TestIndependentQuantizer |
python | matplotlib__matplotlib | lib/matplotlib/layout_engine.py | {
"start": 3749,
"end": 4545
} | class ____(LayoutEngine):
"""
This layout engine does not adjust the figure layout at all.
The purpose of this `.LayoutEngine` is to act as a placeholder when the user removes
a layout engine to ensure an incompatible `.LayoutEngine` cannot be set later.
Parameters
----------
adjust_compatible, colorbar_gridspec : bool
Allow the PlaceHolderLayoutEngine to mirror the behavior of whatever
layout engine it is replacing.
"""
def __init__(self, adjust_compatible, colorbar_gridspec, **kwargs):
self._adjust_compatible = adjust_compatible
self._colorbar_gridspec = colorbar_gridspec
super().__init__(**kwargs)
def execute(self, fig):
"""
Do nothing.
"""
return
| PlaceHolderLayoutEngine |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 36108,
"end": 45690
} | class ____(PreTrainedModel):
config: Wav2Vec2ConformerConfig
base_model_prefix = "wav2vec2_conformer"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
# Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
if isinstance(module, Wav2Vec2ConformerForPreTraining):
module.project_hid.reset_parameters()
module.project_q.reset_parameters()
# gumbel softmax requires special init
elif isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):
init.normal_(module.weight_proj.weight, mean=0.0, std=1)
init.zeros_(module.weight_proj.bias)
init.uniform_(module.codevectors)
elif isinstance(module, Wav2Vec2ConformerSelfAttention):
if hasattr(module, "pos_bias_u"):
init.xavier_uniform_(module.pos_bias_u)
if hasattr(module, "pos_bias_v"):
init.xavier_uniform_(module.pos_bias_v)
elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):
init.normal_(
module.conv.weight,
mean=0,
std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
)
init.constant_(module.conv.bias, 0)
elif isinstance(module, Wav2Vec2ConformerFeatureProjection):
k = math.sqrt(1 / module.projection.in_features)
init.uniform_(module.projection.weight, a=-k, b=k)
init.uniform_(module.projection.bias, a=-k, b=k)
elif isinstance(module, nn.Linear):
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
init.zeros_(module.bias)
init.ones_(module.weight)
elif isinstance(module, nn.Conv1d):
init.kaiming_normal_(module.weight)
if module.bias is not None:
k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
init.uniform_(module.bias, a=-k, b=k)
def _get_feat_extract_output_lengths(
self, input_lengths: Union[torch.LongTensor, int], add_adapter: Optional[bool] = None
):
"""
Computes the output length of the convolutional layers
"""
add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
def _conv_out_length(input_length, kernel_size, stride):
# 1D convolutional layer output length formula taken
# from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
if add_adapter:
for _ in range(self.config.num_adapter_layers):
input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
return input_lengths
def _get_feature_vector_attention_mask(
self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
):
# Effectively attention_mask.sum(-1), but not inplace to be able to run
# on inference mode.
non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
output_lengths = output_lengths.to(torch.long)
batch_size = attention_mask.shape[0]
attention_mask = torch.zeros(
(batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
)
# these two operations makes sure that all values before the output lengths idxs are attended to
attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
return attention_mask
def _compute_mask_indices(
shape: tuple[int, int],
mask_prob: float,
mask_length: int,
attention_mask: Optional[torch.LongTensor] = None,
min_masks: int = 0,
) -> np.ndarray:
"""
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
CPU as part of the preprocessing during training.
Args:
shape: The shape for which to compute masks. This should be of a tuple of size 2 where
the first element is the batch size and the second element is the length of the axis to span.
mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
independently generated mask spans of length `mask_length` is computed by
`mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
actual percentage will be smaller.
mask_length: size of the mask
min_masks: minimum number of masked spans
attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
each batch dimension.
"""
batch_size, sequence_length = shape
if mask_length < 1:
raise ValueError("`mask_length` has to be bigger than 0.")
if mask_length > sequence_length:
raise ValueError(
f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
f" and `sequence_length`: {sequence_length}`"
)
# epsilon is used for probabilistic rounding
epsilon = np.random.rand(1).item()
def compute_num_masked_span(input_length):
"""Given input length, compute how many spans should be masked"""
num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
num_masked_span = max(num_masked_span, min_masks)
# make sure num masked span <= sequence_length
if num_masked_span * mask_length > sequence_length:
num_masked_span = sequence_length // mask_length
# make sure num_masked span is also <= input_length - (mask_length - 1)
if input_length - (mask_length - 1) < num_masked_span:
num_masked_span = max(input_length - (mask_length - 1), 0)
return num_masked_span
# compute number of masked spans in batch
input_lengths = (
attention_mask.detach().sum(-1).tolist()
if attention_mask is not None
else [sequence_length for _ in range(batch_size)]
)
# SpecAugment mask to fill
spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
spec_aug_mask_idxs = []
max_num_masked_span = compute_num_masked_span(sequence_length)
if max_num_masked_span == 0:
return spec_aug_mask
for input_length in input_lengths:
# compute num of masked spans for this input
num_masked_span = compute_num_masked_span(input_length)
# get random indices to mask
spec_aug_mask_idx = np.random.choice(
np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
)
# pick first sampled index that will serve as a dummy index to pad vector
# to ensure same dimension for all batches due to probabilistic rounding
# Picking first sample just pads those vectors twice.
if len(spec_aug_mask_idx) == 0:
# this case can only happen if `input_length` is strictly smaller then
# `sequence_length` in which case the last token has to be a padding
# token which we can use as a dummy mask id
dummy_mask_idx = sequence_length - 1
else:
dummy_mask_idx = spec_aug_mask_idx[0]
spec_aug_mask_idx = np.concatenate(
[spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
)
spec_aug_mask_idxs.append(spec_aug_mask_idx)
spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
# expand masked indices to masked spans
spec_aug_mask_idxs = np.broadcast_to(
spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
)
spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
# add offset to the starting indexes so that indexes now create a span
offsets = np.arange(mask_length)[None, None, :]
offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
batch_size, max_num_masked_span * mask_length
)
spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
# ensure that we cannot have indices larger than sequence_length
if spec_aug_mask_idxs.max() > sequence_length - 1:
spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
# scatter indices to mask
np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
return spec_aug_mask
Wav2Vec2ConformerBaseModelOutput = Wav2Vec2BaseModelOutput
@auto_docstring
| Wav2Vec2ConformerPreTrainedModel |
python | plotly__plotly.py | plotly/graph_objs/bar/hoverlabel/_font.py | {
"start": 233,
"end": 17123
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar.hoverlabel"
_path_str = "bar.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.bar.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.bar.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.bar.hoverlabel.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("family", arg, family)
self._set_property("familysrc", arg, familysrc)
self._set_property("lineposition", arg, lineposition)
self._set_property("linepositionsrc", arg, linepositionsrc)
self._set_property("shadow", arg, shadow)
self._set_property("shadowsrc", arg, shadowsrc)
self._set_property("size", arg, size)
self._set_property("sizesrc", arg, sizesrc)
self._set_property("style", arg, style)
self._set_property("stylesrc", arg, stylesrc)
self._set_property("textcase", arg, textcase)
self._set_property("textcasesrc", arg, textcasesrc)
self._set_property("variant", arg, variant)
self._set_property("variantsrc", arg, variantsrc)
self._set_property("weight", arg, weight)
self._set_property("weightsrc", arg, weightsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | huggingface__transformers | src/transformers/models/tapas/tokenization_tapas.py | {
"start": 101984,
"end": 120139
} | class ____:
original_text: str # The original raw question string.
text: str # The question string after normalization.
numeric_spans: Optional[list[NumericValueSpan]] = None
# Below: all functions from number_utils.py as well as 2 functions (namely get_all_spans and normalize_for_match)
# from text_utils.py of the original implementation. URL's:
# - https://github.com/google-research/tapas/blob/master/tapas/utils/number_utils.py
# - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
# Constants for parsing date expressions.
# Masks that specify (by a bool) which of (year, month, day) will be populated.
_DateMask = collections.namedtuple("_DateMask", ["year", "month", "day"])
_YEAR = _DateMask(True, False, False)
_YEAR_MONTH = _DateMask(True, True, False)
_YEAR_MONTH_DAY = _DateMask(True, True, True)
_MONTH = _DateMask(False, True, False)
_MONTH_DAY = _DateMask(False, True, True)
# Pairs of patterns to pass to 'datetime.strptime' and masks specifying which
# fields will be set by the corresponding pattern.
_DATE_PATTERNS = (
("%B", _MONTH),
("%Y", _YEAR),
("%Ys", _YEAR),
("%b %Y", _YEAR_MONTH),
("%B %Y", _YEAR_MONTH),
("%B %d", _MONTH_DAY),
("%b %d", _MONTH_DAY),
("%d %b", _MONTH_DAY),
("%d %B", _MONTH_DAY),
("%B %d, %Y", _YEAR_MONTH_DAY),
("%d %B %Y", _YEAR_MONTH_DAY),
("%m-%d-%Y", _YEAR_MONTH_DAY),
("%Y-%m-%d", _YEAR_MONTH_DAY),
("%Y-%m", _YEAR_MONTH),
("%B %Y", _YEAR_MONTH),
("%d %b %Y", _YEAR_MONTH_DAY),
("%Y-%m-%d", _YEAR_MONTH_DAY),
("%b %d, %Y", _YEAR_MONTH_DAY),
("%d.%m.%Y", _YEAR_MONTH_DAY),
("%A, %b %d", _MONTH_DAY),
("%A, %B %d", _MONTH_DAY),
)
# This mapping is used to convert date patterns to regex patterns.
_FIELD_TO_REGEX = (
("%A", r"\w+"), # Weekday as locale’s full name.
("%B", r"\w+"), # Month as locale’s full name.
("%Y", r"\d{4}"), # Year with century as a decimal number.
("%b", r"\w{3}"), # Month as locale’s abbreviated name.
("%d", r"\d{1,2}"), # Day of the month as a zero-padded decimal number.
("%m", r"\d{1,2}"), # Month as a zero-padded decimal number.
)
def _process_date_pattern(dp):
"""Compute a regex for each date pattern to use as a prefilter."""
pattern, mask = dp
regex = pattern
regex = regex.replace(".", re.escape("."))
regex = regex.replace("-", re.escape("-"))
regex = regex.replace(" ", r"\s+")
for field, field_regex in _FIELD_TO_REGEX:
regex = regex.replace(field, field_regex)
# Make sure we didn't miss any of the fields.
assert "%" not in regex, regex
return pattern, mask, re.compile("^" + regex + "$")
def _process_date_patterns():
return tuple(_process_date_pattern(dp) for dp in _DATE_PATTERNS)
_PROCESSED_DATE_PATTERNS = _process_date_patterns()
_MAX_DATE_NGRAM_SIZE = 5
# Following DynSp:
# https://github.com/Microsoft/DynSP/blob/master/util.py#L414.
_NUMBER_WORDS = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
]
_ORDINAL_WORDS = [
"zeroth",
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth",
]
_ORDINAL_SUFFIXES = ["st", "nd", "rd", "th"]
_NUMBER_PATTERN = re.compile(r"((^|\s)[+-])?((\.\d+)|(\d+(,\d\d\d)*(\.\d*)?))")
# Following DynSp:
# https://github.com/Microsoft/DynSP/blob/master/util.py#L293.
_MIN_YEAR = 1700
_MAX_YEAR = 2016
_INF = float("INF")
def _get_numeric_value_from_date(date, mask):
"""Converts date (datetime Python object) to a NumericValue object with a Date object value."""
if date.year < _MIN_YEAR or date.year > _MAX_YEAR:
raise ValueError(f"Invalid year: {date.year}")
new_date = Date()
if mask.year:
new_date.year = date.year
if mask.month:
new_date.month = date.month
if mask.day:
new_date.day = date.day
return NumericValue(date=new_date)
def _get_span_length_key(span):
"""Sorts span by decreasing length first and increasing first index second."""
return span[1] - span[0], -span[0]
def _get_numeric_value_from_float(value):
"""Converts float (Python) to a NumericValue object with a float value."""
return NumericValue(float_value=value)
# Doesn't parse ordinal expressions such as '18th of february 1655'.
def _parse_date(text):
"""Attempts to format a text as a standard date string (yyyy-mm-dd)."""
text = re.sub(r"Sept\b", "Sep", text)
for in_pattern, mask, regex in _PROCESSED_DATE_PATTERNS:
if not regex.match(text):
continue
try:
date = datetime.datetime.strptime(text, in_pattern).date()
except ValueError:
continue
try:
return _get_numeric_value_from_date(date, mask)
except ValueError:
continue
return None
def _parse_number(text):
"""Parses simple cardinal and ordinals numbers."""
for suffix in _ORDINAL_SUFFIXES:
if text.endswith(suffix):
text = text[: -len(suffix)]
break
text = text.replace(",", "")
try:
value = float(text)
except ValueError:
return None
if math.isnan(value):
return None
if value == _INF:
return None
return value
def get_all_spans(text, max_ngram_length):
"""
Split a text into all possible ngrams up to 'max_ngram_length'. Split points are white space and punctuation.
Args:
text: Text to split.
max_ngram_length: maximal ngram length.
Yields:
Spans, tuples of begin-end index.
"""
start_indexes = []
for index, char in enumerate(text):
if not char.isalnum():
continue
if index == 0 or not text[index - 1].isalnum():
start_indexes.append(index)
if index + 1 == len(text) or not text[index + 1].isalnum():
for start_index in start_indexes[-max_ngram_length:]:
yield start_index, index + 1
def normalize_for_match(text):
return " ".join(text.lower().split())
def format_text(text):
"""Lowercases and strips punctuation."""
text = text.lower().strip()
if text == "n/a" or text == "?" or text == "nan":
text = EMPTY_TEXT
text = re.sub(r"[^\w\d]+", " ", text).replace("_", " ")
text = " ".join(text.split())
text = text.strip()
if text:
return text
return EMPTY_TEXT
def parse_text(text):
"""
Extracts longest number and date spans.
Args:
text: text to annotate
Returns:
List of longest numeric value spans.
"""
span_dict = collections.defaultdict(list)
for match in _NUMBER_PATTERN.finditer(text):
span_text = text[match.start() : match.end()]
number = _parse_number(span_text)
if number is not None:
span_dict[match.span()].append(_get_numeric_value_from_float(number))
for begin_index, end_index in get_all_spans(text, max_ngram_length=1):
if (begin_index, end_index) in span_dict:
continue
span_text = text[begin_index:end_index]
number = _parse_number(span_text)
if number is not None:
span_dict[begin_index, end_index].append(_get_numeric_value_from_float(number))
for number, word in enumerate(_NUMBER_WORDS):
if span_text == word:
span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
break
for number, word in enumerate(_ORDINAL_WORDS):
if span_text == word:
span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
break
for begin_index, end_index in get_all_spans(text, max_ngram_length=_MAX_DATE_NGRAM_SIZE):
span_text = text[begin_index:end_index]
date = _parse_date(span_text)
if date is not None:
span_dict[begin_index, end_index].append(date)
spans = sorted(span_dict.items(), key=lambda span_value: _get_span_length_key(span_value[0]), reverse=True)
selected_spans = []
for span, value in spans:
for selected_span, _ in selected_spans:
if selected_span[0] <= span[0] and span[1] <= selected_span[1]:
break
else:
selected_spans.append((span, value))
selected_spans.sort(key=lambda span_value: span_value[0][0])
numeric_value_spans = []
for span, values in selected_spans:
numeric_value_spans.append(NumericValueSpan(begin_index=span[0], end_index=span[1], values=values))
return numeric_value_spans
# Below: all functions from number_annotation_utils.py and 2 functions (namely filter_invalid_unicode
# and filter_invalid_unicode_from_table) from text_utils.py of the original implementation. URL's:
# - https://github.com/google-research/tapas/blob/master/tapas/utils/number_annotation_utils.py
# - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
_PrimitiveNumericValue = Union[float, tuple[Optional[float], Optional[float], Optional[float]]]
_SortKeyFn = Callable[[NumericValue], tuple[float, Ellipsis]]
_DATE_TUPLE_SIZE = 3
EMPTY_TEXT = "EMPTY"
NUMBER_TYPE = "number"
DATE_TYPE = "date"
def _get_value_type(numeric_value):
if numeric_value.float_value is not None:
return NUMBER_TYPE
elif numeric_value.date is not None:
return DATE_TYPE
raise ValueError(f"Unknown type: {numeric_value}")
def _get_value_as_primitive_value(numeric_value):
"""Maps a NumericValue proto to a float or tuple of float."""
if numeric_value.float_value is not None:
return numeric_value.float_value
if numeric_value.date is not None:
date = numeric_value.date
value_tuple = [None, None, None]
# All dates fields are cased to float to produce a simple primitive value.
if date.year is not None:
value_tuple[0] = float(date.year)
if date.month is not None:
value_tuple[1] = float(date.month)
if date.day is not None:
value_tuple[2] = float(date.day)
return tuple(value_tuple)
raise ValueError(f"Unknown type: {numeric_value}")
def _get_all_types(numeric_values):
return {_get_value_type(value) for value in numeric_values}
def get_numeric_sort_key_fn(numeric_values):
"""
Creates a function that can be used as a sort key or to compare the values. Maps to primitive types and finds the
biggest common subset. Consider the values "05/05/2010" and "August 2007". With the corresponding primitive values
(2010.,5.,5.) and (2007.,8., None). These values can be compared by year and date so we map to the sequence (2010.,
5.), (2007., 8.). If we added a third value "2006" with primitive value (2006., None, None), we could only compare
by the year so we would map to (2010.,), (2007.,) and (2006.,).
Args:
numeric_values: Values to compare
Returns:
A function that can be used as a sort key function (mapping numeric values to a comparable tuple)
Raises:
ValueError if values don't have a common type or are not comparable.
"""
value_types = _get_all_types(numeric_values)
if len(value_types) != 1:
raise ValueError(f"No common value type in {numeric_values}")
value_type = next(iter(value_types))
if value_type == NUMBER_TYPE:
# Primitive values are simple floats, nothing to do here.
return _get_value_as_primitive_value
# The type can only be Date at this point which means the primitive type
# is a float triple.
valid_indexes = set(range(_DATE_TUPLE_SIZE))
for numeric_value in numeric_values:
value = _get_value_as_primitive_value(numeric_value)
assert isinstance(value, tuple)
for tuple_index, inner_value in enumerate(value):
if inner_value is None:
valid_indexes.discard(tuple_index)
if not valid_indexes:
raise ValueError(f"No common value in {numeric_values}")
def _sort_key_fn(numeric_value):
value = _get_value_as_primitive_value(numeric_value)
return tuple(value[index] for index in valid_indexes)
return _sort_key_fn
def _consolidate_numeric_values(row_index_to_values, min_consolidation_fraction, debug_info):
"""
Finds the most common numeric values in a column and returns them
Args:
row_index_to_values:
For each row index all the values in that cell.
min_consolidation_fraction:
Fraction of cells that need to have consolidated value.
debug_info:
Additional information only used for logging
Returns:
For each row index the first value that matches the most common value. Rows that don't have a matching value
are dropped. Empty list if values can't be consolidated.
"""
type_counts = collections.Counter()
for numeric_values in row_index_to_values.values():
type_counts.update(_get_all_types(numeric_values))
if not type_counts:
return {}
max_count = max(type_counts.values())
if max_count < len(row_index_to_values) * min_consolidation_fraction:
# logging.log_every_n(logging.INFO, f'Can\'t consolidate types: {debug_info} {row_index_to_values} {max_count}', 100)
return {}
valid_types = set()
for value_type, count in type_counts.items():
if count == max_count:
valid_types.add(value_type)
if len(valid_types) > 1:
assert DATE_TYPE in valid_types
max_type = DATE_TYPE
else:
max_type = next(iter(valid_types))
new_row_index_to_value = {}
for index, values in row_index_to_values.items():
# Extract the first matching value.
for value in values:
if _get_value_type(value) == max_type:
new_row_index_to_value[index] = value
break
return new_row_index_to_value
def _get_numeric_values(text):
"""Parses text and returns numeric values."""
numeric_spans = parse_text(text)
return itertools.chain(*(span.values for span in numeric_spans))
def _get_column_values(table, col_index):
"""
Parses text in column and returns a dict mapping row_index to values. This is the _get_column_values function from
number_annotation_utils.py of the original implementation
Args:
table: Pandas dataframe
col_index: integer, indicating the index of the column to get the numeric values of
"""
index_to_values = {}
for row_index, row in table.iterrows():
text = normalize_for_match(row[col_index].text)
index_to_values[row_index] = list(_get_numeric_values(text))
return index_to_values
def get_numeric_relation(value, other_value, sort_key_fn):
"""Compares two values and returns their relation or None."""
value = sort_key_fn(value)
other_value = sort_key_fn(other_value)
if value == other_value:
return Relation.EQ
if value < other_value:
return Relation.LT
if value > other_value:
return Relation.GT
return None
def add_numeric_values_to_question(question):
"""Adds numeric value spans to a question."""
original_text = question
question = normalize_for_match(question)
numeric_spans = parse_text(question)
return Question(original_text=original_text, text=question, numeric_spans=numeric_spans)
def filter_invalid_unicode(text):
"""Return an empty string and True if 'text' is in invalid unicode."""
return ("", True) if isinstance(text, bytes) else (text, False)
def filter_invalid_unicode_from_table(table):
"""
Removes invalid unicode from table. Checks whether a table cell text contains an invalid unicode encoding. If yes,
reset the table cell text to an empty str and log a warning for each invalid cell
Args:
table: table to clean.
"""
# to do: add table id support
if not hasattr(table, "table_id"):
table.table_id = 0
for row_index, row in table.iterrows():
for col_index, cell in enumerate(row):
cell, is_invalid = filter_invalid_unicode(cell)
if is_invalid:
logging.warning(
f"Scrub an invalid table body @ table_id: {table.table_id}, row_index: {row_index}, "
f"col_index: {col_index}",
)
for col_index, column in enumerate(table.columns):
column, is_invalid = filter_invalid_unicode(column)
if is_invalid:
logging.warning(f"Scrub an invalid table header @ table_id: {table.table_id}, col_index: {col_index}")
def add_numeric_table_values(table, min_consolidation_fraction=0.7, debug_info=None):
"""
Parses text in table column-wise and adds the consolidated values. Consolidation refers to finding values with a
common types (date or number)
Args:
table:
Table to annotate.
min_consolidation_fraction:
Fraction of cells in a column that need to have consolidated value.
debug_info:
Additional information used for logging.
"""
table = table.copy()
# First, filter table on invalid unicode
filter_invalid_unicode_from_table(table)
# Second, replace cell values by Cell objects
for row_index, row in table.iterrows():
for col_index, cell in enumerate(row):
table.iloc[row_index, col_index] = Cell(text=cell)
# Third, add numeric_value attributes to these Cell objects
for col_index, column in enumerate(table.columns):
column_values = _consolidate_numeric_values(
_get_column_values(table, col_index),
min_consolidation_fraction=min_consolidation_fraction,
debug_info=(debug_info, column),
)
for row_index, numeric_value in column_values.items():
table.iloc[row_index, col_index].numeric_value = numeric_value
return table
__all__ = ["TapasTokenizer"]
| Question |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methods1.py | {
"start": 1181,
"end": 2037
} | class ____:
a: ClassVar[Callable[[Any], None]] = lambda self: None
b1 = lambda self: None
b2: ClassVar = lambda self: None
c1 = func1
c2: ClassVar = func1
d1: CallableA = CallableA()
d2: ClassVar[CallableA] = CallableA()
e1 = deco1(func1)
e2: ClassVar = deco1(func1)
@deco1
def f1(self) -> None:
print("f1:", f"{self=}")
@Deco3
def g1(self) -> None:
print("g1:", f"{self=}")
@Deco4
def h1(self) -> None:
print("h1:", f"{self=}")
@deco2(DummyClass)
def i1(self, a: str, b: float) -> None:
print("i1:", f"{self=}")
@deco2(dummyFunc)
def j1(self, a: str, b: float) -> None:
print("j1:", f"{self=}")
a = ClassA()
a.a()
a.b1()
a.b2()
a.c1()
a.c2()
a.d1()
a.d2()
a.e1()
a.e2()
a.f1()
a.g1(a)
a.h1()
a.i1("", 0)
a.j1("", 0)
| ClassA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.