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 | readthedocs__readthedocs.org | readthedocs/projects/migrations/0055_change_help_text_description.py | {
"start": 149,
"end": 610
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0054_urlconf_blank"),
]
operations = [
migrations.AlterField(
model_name="project",
name="description",
field=models.TextField(
blank=True,
help_text="Short description of this project",
verbose_name="Description",
),
),
]
| Migration |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 4785,
"end": 5477
} | class ____:
"""
Integration tests for disabled pagination.
"""
def setup_method(self):
class PassThroughSerializer(serializers.BaseSerializer):
def to_representation(self, item):
return item
self.view = generics.ListAPIView.as_view(
serializer_class=PassThroughSerializer,
queryset=range(1, 101),
pagination_class=None
)
def test_unpaginated_list(self):
request = factory.get('/', {'page': 2})
response = self.view(request)
assert response.status_code == status.HTTP_200_OK
assert response.data == list(range(1, 101))
| TestPaginationDisabledIntegration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 8433,
"end": 12040
} | class ____(IHaveNew):
name: str
cron_schedule: Union[str, Sequence[str]]
job_name: str
op_selection: Optional[Sequence[str]]
mode: Optional[str]
environment_vars: Mapping[str, str]
partition_set_name: Optional[str]
execution_timezone: Optional[str]
description: Optional[str]
default_status: Optional[DefaultScheduleStatus]
asset_selection: Optional[AssetSelection]
tags: Mapping[str, str]
metadata: Mapping[str, MetadataValue]
owners: Optional[Sequence[str]]
def __new__(
cls,
name: str,
cron_schedule: Union[str, Sequence[str]],
job_name: str,
op_selection: Optional[Sequence[str]],
mode: Optional[str],
environment_vars: Optional[Mapping[str, str]],
partition_set_name: Optional[str],
execution_timezone: Optional[str],
description: Optional[str] = None,
default_status: Optional[DefaultScheduleStatus] = None,
asset_selection: Optional[AssetSelection] = None,
tags: Optional[Mapping[str, str]] = None,
metadata: Optional[Mapping[str, MetadataValue]] = None,
owners: Optional[Sequence[str]] = None,
):
if asset_selection is not None:
check.invariant(
is_whitelisted_for_serdes_object(asset_selection),
"asset_selection must be serializable",
)
return super().__new__(
cls,
name=name,
cron_schedule=cron_schedule,
job_name=job_name,
op_selection=op_selection,
mode=mode,
environment_vars=environment_vars or {},
partition_set_name=partition_set_name,
execution_timezone=execution_timezone,
description=description,
# Leave default_status as None if it's STOPPED to maintain stable back-compat IDs
default_status=(
DefaultScheduleStatus.RUNNING
if default_status == DefaultScheduleStatus.RUNNING
else None
),
asset_selection=asset_selection,
tags=tags or {},
metadata=metadata or {},
owners=owners,
)
@classmethod
def from_def(
cls, schedule_def: ScheduleDefinition, repository_def: RepositoryDefinition
) -> Self:
if schedule_def.has_anonymous_job:
job_def = check.inst(
schedule_def.job,
UnresolvedAssetJobDefinition,
"Anonymous job should be UnresolvedAssetJobDefinition",
)
serializable_asset_selection = job_def.selection.to_serializable_asset_selection(
repository_def.asset_graph
)
else:
serializable_asset_selection = None
return cls(
name=schedule_def.name,
cron_schedule=schedule_def.cron_schedule,
job_name=schedule_def.job_name,
op_selection=schedule_def.target.op_selection,
mode=DEFAULT_MODE_NAME,
environment_vars=schedule_def.environment_vars,
partition_set_name=None,
execution_timezone=schedule_def.execution_timezone,
description=schedule_def.description,
default_status=schedule_def.default_status,
asset_selection=serializable_asset_selection,
tags=schedule_def.tags,
metadata=schedule_def.metadata,
owners=schedule_def.owners,
)
@whitelist_for_serdes(storage_name="ExternalScheduleExecutionErrorData")
@record
| ScheduleSnap |
python | scikit-learn__scikit-learn | sklearn/manifold/_mds.py | {
"start": 16149,
"end": 30926
} | class ____(BaseEstimator):
"""Multidimensional scaling.
Read more in the :ref:`User Guide <multidimensional_scaling>`.
Parameters
----------
n_components : int, default=2
Number of dimensions in which to immerse the dissimilarities.
metric_mds : bool, default=True
If ``True``, perform metric MDS; otherwise, perform nonmetric MDS.
When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as
missing values.
.. versionchanged:: 1.8
The parameter `metric` was renamed into `metric_mds`.
n_init : int, default=4
Number of times the SMACOF algorithm will be run with different
initializations. The final results will be the best output of the runs,
determined by the run with the smallest final stress.
.. versionchanged:: 1.9
The default value for `n_init` will change from 4 to 1 in version 1.9.
init : {'random', 'classical_mds'}, default='random'
The initialization approach. If `random`, random initialization is used.
If `classical_mds`, then classical MDS is run and used as initialization
for MDS (in this case, the value of `n_init` is ignored).
.. versionadded:: 1.8
.. versionchanged:: 1.10
The default value for `init` will change to `classical_mds`.
max_iter : int, default=300
Maximum number of iterations of the SMACOF algorithm for a single run.
verbose : int, default=0
Level of verbosity.
eps : float, default=1e-6
The tolerance with respect to stress (normalized by the sum of squared
embedding distances) at which to declare convergence.
.. versionchanged:: 1.7
The default value for `eps` has changed from 1e-3 to 1e-6, as a result
of a bugfix in the computation of the convergence criterion.
n_jobs : int, default=None
The number of jobs to use for the computation. If multiple
initializations are used (``n_init``), each run of the algorithm is
computed in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
random_state : int, RandomState instance or None, default=None
Determines the random number generator used to initialize the centers.
Pass an int for reproducible results across multiple function calls.
See :term:`Glossary <random_state>`.
dissimilarity : {'euclidean', 'precomputed'}
Dissimilarity measure to use:
- 'euclidean':
Pairwise Euclidean distances between points in the dataset.
- 'precomputed':
Pre-computed dissimilarities are passed directly to ``fit`` and
``fit_transform``.
.. deprecated:: 1.8
`dissimilarity` was renamed `metric` in 1.8 and will be removed in 1.10.
metric : str or callable, default='euclidean'
Metric to use for dissimilarity computation. Default is "euclidean".
If metric is a string, it must be one of the options allowed by
`scipy.spatial.distance.pdist` for its metric parameter, or a metric
listed in :func:`sklearn.metrics.pairwise.distance_metrics`
If metric is "precomputed", X is assumed to be a distance matrix and
must be square during fit.
If metric is a callable function, it takes two arrays representing 1D
vectors as inputs and must return one value indicating the distance
between those vectors. This works for Scipy's metrics, but is less
efficient than passing the metric name as a string.
.. versionchanged:: 1.8
Prior to 1.8, `metric=True/False` was used to select metric/non-metric
MDS, which is now the role of `metric_mds`. The support for ``True``
and ``False`` will be dropped in version 1.10, use `metric_mds` instead.
metric_params : dict, default=None
Additional keyword arguments for the dissimilarity computation.
.. versionadded:: 1.8
normalized_stress : bool or "auto" default="auto"
Whether to return normalized stress value (Stress-1) instead of raw
stress. By default, metric MDS returns raw stress while non-metric MDS
returns normalized stress.
.. versionadded:: 1.2
.. versionchanged:: 1.4
The default value changed from `False` to `"auto"` in version 1.4.
.. versionchanged:: 1.7
Normalized stress is now supported for metric MDS as well.
Attributes
----------
embedding_ : ndarray of shape (n_samples, n_components)
Stores the position of the dataset in the embedding space.
stress_ : float
The final value of the stress (sum of squared distance of the
disparities and the distances for all constrained points).
If `normalized_stress=True`, returns Stress-1.
A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good,
0.1 fair, and 0.2 poor [1]_.
dissimilarity_matrix_ : ndarray of shape (n_samples, n_samples)
Pairwise dissimilarities between the points. Symmetric matrix that:
- either uses a custom dissimilarity matrix by setting `dissimilarity`
to 'precomputed';
- or constructs a dissimilarity matrix from data using
Euclidean distances.
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
n_iter_ : int
The number of iterations corresponding to the best stress.
See Also
--------
sklearn.decomposition.PCA : Principal component analysis that is a linear
dimensionality reduction method.
sklearn.decomposition.KernelPCA : Non-linear dimensionality reduction using
kernels and PCA.
TSNE : T-distributed Stochastic Neighbor Embedding.
Isomap : Manifold learning based on Isometric Mapping.
LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding.
SpectralEmbedding : Spectral embedding for non-linear dimensionality.
References
----------
.. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J.
Psychometrika, 29 (1964)
.. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric
hypothesis" Kruskal, J. Psychometrika, 29, (1964)
.. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.;
Groenen P. Springer Series in Statistics (1997)
Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.manifold import MDS
>>> X, _ = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> embedding = MDS(n_components=2, n_init=1, init="random")
>>> X_transformed = embedding.fit_transform(X[:100])
>>> X_transformed.shape
(100, 2)
For a more detailed example of usage, see
:ref:`sphx_glr_auto_examples_manifold_plot_mds.py`.
For a comparison of manifold learning techniques, see
:ref:`sphx_glr_auto_examples_manifold_plot_compare_methods.py`.
"""
_parameter_constraints: dict = {
"n_components": [Interval(Integral, 1, None, closed="left")],
"metric_mds": ["boolean"],
"n_init": [
Interval(Integral, 1, None, closed="left"),
Hidden(StrOptions({"warn"})),
],
"init": [StrOptions({"random", "classical_mds"}), Hidden(StrOptions({"warn"}))],
"max_iter": [Interval(Integral, 1, None, closed="left")],
"verbose": ["verbose"],
"eps": [Interval(Real, 0.0, None, closed="left")],
"n_jobs": [None, Integral],
"random_state": ["random_state"],
"dissimilarity": [
StrOptions({"euclidean", "precomputed"}),
Hidden(StrOptions({"deprecated"})),
],
"metric": [str, callable, Hidden("boolean")],
"metric_params": [dict, None],
"normalized_stress": ["boolean", StrOptions({"auto"})],
}
def __init__(
self,
n_components=2,
*,
metric_mds=True,
n_init="warn",
init="warn",
max_iter=300,
verbose=0,
eps=1e-6,
n_jobs=None,
random_state=None,
dissimilarity="deprecated",
metric="euclidean",
metric_params=None,
normalized_stress="auto",
):
self.n_components = n_components
self.dissimilarity = dissimilarity
self.metric = metric
self.metric_params = metric_params
self.metric_mds = metric_mds
self.n_init = n_init
self.init = init
self.max_iter = max_iter
self.eps = eps
self.verbose = verbose
self.n_jobs = n_jobs
self.random_state = random_state
self.normalized_stress = normalized_stress
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.pairwise = (self.dissimilarity == "precomputed") | (
self.metric == "precomputed"
)
return tags
def fit(self, X, y=None, init=None):
"""
Compute the position of the points in the embedding space.
Parameters
----------
X : array-like of shape (n_samples, n_features) or \
(n_samples, n_samples)
Input data. If ``metric=='precomputed'``, the input should
be the dissimilarity matrix.
y : Ignored
Not used, present for API consistency by convention.
init : ndarray of shape (n_samples, n_components), default=None
Starting configuration of the embedding to initialize the SMACOF
algorithm. By default, the algorithm is initialized with a randomly
chosen array.
Returns
-------
self : object
Fitted estimator.
"""
self.fit_transform(X, init=init)
return self
@_fit_context(prefer_skip_nested_validation=True)
def fit_transform(self, X, y=None, init=None):
"""
Fit the data from `X`, and returns the embedded coordinates.
Parameters
----------
X : array-like of shape (n_samples, n_features) or \
(n_samples, n_samples)
Input data. If ``metric=='precomputed'``, the input should
be the dissimilarity matrix.
y : Ignored
Not used, present for API consistency by convention.
init : ndarray of shape (n_samples, n_components), default=None
Starting configuration of the embedding to initialize the SMACOF
algorithm. By default, the algorithm is initialized with a randomly
chosen array.
Returns
-------
X_new : ndarray of shape (n_samples, n_components)
X transformed in the new space.
"""
if self.n_init == "warn":
warnings.warn(
"The default value of `n_init` will change from 4 to 1 in 1.9. "
"To suppress this warning, provide some value of `n_init`.",
FutureWarning,
)
self._n_init = 4
else:
self._n_init = self.n_init
if self.init == "warn":
warnings.warn(
"The default value of `init` will change from 'random' to "
"'classical_mds' in 1.10. To suppress this warning, provide "
"some value of `init`.",
FutureWarning,
)
self._init = "random"
else:
self._init = self.init
if self.dissimilarity != "deprecated":
if not isinstance(self.metric, bool) and self.metric != "euclidean":
raise ValueError(
"You provided both `dissimilarity` and `metric`. Please use "
"only `metric`."
)
else:
warnings.warn(
"The `dissimilarity` parameter is deprecated and will be "
"removed in 1.10. Use `metric` instead.",
FutureWarning,
)
self._metric = self.dissimilarity
if isinstance(self.metric, bool):
warnings.warn(
f"Use metric_mds={self.metric} instead of metric={self.metric}. The "
"support for metric={True/False} will be dropped in 1.10.",
FutureWarning,
)
if self.dissimilarity == "deprecated":
self._metric = "euclidean"
self._metric_mds = self.metric
else:
if self.dissimilarity == "deprecated":
self._metric = self.metric
self._metric_mds = self.metric_mds
X = validate_data(self, X)
if X.shape[0] == X.shape[1] and self._metric != "precomputed":
warnings.warn(
"The provided input is a square matrix. Note that ``fit`` constructs "
"a dissimilarity matrix from data and will treat rows as samples "
"and columns as features. To use a pre-computed dissimilarity matrix, "
"set ``metric='precomputed'``."
)
if self._metric == "precomputed":
self.dissimilarity_matrix_ = X
self.dissimilarity_matrix_ = check_symmetric(
self.dissimilarity_matrix_, raise_exception=True
)
else:
self.dissimilarity_matrix_ = pairwise_distances(
X,
metric=self._metric,
**(self.metric_params if self.metric_params is not None else {}),
)
if init is not None:
init_array = init
elif self._init == "classical_mds":
cmds = ClassicalMDS(metric="precomputed")
init_array = cmds.fit_transform(self.dissimilarity_matrix_)
else:
init_array = None
self.embedding_, self.stress_, self.n_iter_ = smacof(
self.dissimilarity_matrix_,
metric=self._metric_mds,
n_components=self.n_components,
init=init_array,
n_init=self._n_init,
n_jobs=self.n_jobs,
max_iter=self.max_iter,
verbose=self.verbose,
eps=self.eps,
random_state=self.random_state,
return_n_iter=True,
normalized_stress=self.normalized_stress,
)
return self.embedding_
| MDS |
python | pypa__pip | src/pip/_vendor/urllib3/connectionpool.py | {
"start": 2909,
"end": 33197
} | class ____(ConnectionPool, RequestMethods):
"""
Thread-safe connection pool for one host.
:param host:
Host used for this HTTP Connection (e.g. "localhost"), passed into
:class:`http.client.HTTPConnection`.
:param port:
Port used for this HTTP Connection (None is equivalent to 80), passed
into :class:`http.client.HTTPConnection`.
:param strict:
Causes BadStatusLine to be raised if the status line can't be parsed
as a valid HTTP/1.0 or 1.1 status line, passed into
:class:`http.client.HTTPConnection`.
.. note::
Only works in Python 2. This parameter is ignored in Python 3.
:param timeout:
Socket timeout in seconds for each individual connection. This can
be a float or integer, which sets the timeout for the HTTP request,
or an instance of :class:`urllib3.util.Timeout` which gives you more
fine-grained control over request timeouts. After the constructor has
been parsed, this is always a `urllib3.util.Timeout` object.
:param maxsize:
Number of connections to save that can be reused. More than 1 is useful
in multithreaded situations. If ``block`` is set to False, more
connections will be created but they will not be saved once they've
been used.
:param block:
If set to True, no more than ``maxsize`` connections will be used at
a time. When no free connections are available, the call will block
until a connection has been released. This is a useful side effect for
particular multithreaded situations where one does not want to use more
than maxsize connections per host to prevent flooding.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param retries:
Retry configuration to use by default with requests in this pool.
:param _proxy:
Parsed proxy URL, should not be used directly, instead, see
:class:`urllib3.ProxyManager`
:param _proxy_headers:
A dictionary with proxy headers, should not be used directly,
instead, see :class:`urllib3.ProxyManager`
:param \\**conn_kw:
Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
:class:`urllib3.connection.HTTPSConnection` instances.
"""
scheme = "http"
ConnectionCls = HTTPConnection
ResponseCls = HTTPResponse
def __init__(
self,
host,
port=None,
strict=False,
timeout=Timeout.DEFAULT_TIMEOUT,
maxsize=1,
block=False,
headers=None,
retries=None,
_proxy=None,
_proxy_headers=None,
_proxy_config=None,
**conn_kw
):
ConnectionPool.__init__(self, host, port)
RequestMethods.__init__(self, headers)
self.strict = strict
if not isinstance(timeout, Timeout):
timeout = Timeout.from_float(timeout)
if retries is None:
retries = Retry.DEFAULT
self.timeout = timeout
self.retries = retries
self.pool = self.QueueCls(maxsize)
self.block = block
self.proxy = _proxy
self.proxy_headers = _proxy_headers or {}
self.proxy_config = _proxy_config
# Fill the queue up so that doing get() on it will block properly
for _ in xrange(maxsize):
self.pool.put(None)
# These are mostly for testing and debugging purposes.
self.num_connections = 0
self.num_requests = 0
self.conn_kw = conn_kw
if self.proxy:
# Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
# We cannot know if the user has added default socket options, so we cannot replace the
# list.
self.conn_kw.setdefault("socket_options", [])
self.conn_kw["proxy"] = self.proxy
self.conn_kw["proxy_config"] = self.proxy_config
# Do not pass 'self' as callback to 'finalize'.
# Then the 'finalize' would keep an endless living (leak) to self.
# By just passing a reference to the pool allows the garbage collector
# to free self if nobody else has a reference to it.
pool = self.pool
# Close all the HTTPConnections in the pool before the
# HTTPConnectionPool object is garbage collected.
weakref_finalize(self, _close_pool_connections, pool)
def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.debug(
"Starting new HTTP connection (%d): %s:%s",
self.num_connections,
self.host,
self.port or "80",
)
conn = self.ConnectionCls(
host=self.host,
port=self.port,
timeout=self.timeout.connect_timeout,
strict=self.strict,
**self.conn_kw
)
return conn
def _get_conn(self, timeout=None):
"""
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and raising
:class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
:prop:`.block` is ``True``.
"""
conn = None
try:
conn = self.pool.get(block=self.block, timeout=timeout)
except AttributeError: # self.pool is None
raise ClosedPoolError(self, "Pool is closed.")
except queue.Empty:
if self.block:
raise EmptyPoolError(
self,
"Pool reached maximum size and no more connections are allowed.",
)
pass # Oh well, we'll create a new connection then
# If this is a persistent connection, check if it got disconnected
if conn and is_connection_dropped(conn):
log.debug("Resetting dropped connection: %s", self.host)
conn.close()
if getattr(conn, "auto_open", 1) == 0:
# This is a proxied connection that has been mutated by
# http.client._tunnel() and cannot be reused (since it would
# attempt to bypass the proxy)
conn = None
return conn or self._new_conn()
def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connections are discarded frequently,
then maxsize should be increased.
If the pool is closed, then the connection will be closed and discarded.
"""
try:
self.pool.put(conn, block=False)
return # Everything is dandy, done.
except AttributeError:
# self.pool is None.
pass
except queue.Full:
# This should never happen if self.block == True
log.warning(
"Connection pool is full, discarding connection: %s. Connection pool size: %s",
self.host,
self.pool.qsize(),
)
# Connection never got put back into the pool, close it.
if conn:
conn.close()
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
pass
def _prepare_proxy(self, conn):
# Nothing to do for HTTP connections.
pass
def _get_timeout(self, timeout):
"""Helper that always returns a :class:`urllib3.util.Timeout`"""
if timeout is _Default:
return self.timeout.clone()
if isinstance(timeout, Timeout):
return timeout.clone()
else:
# User passed us an int/float. This is for backwards compatibility,
# can be removed later
return Timeout.from_float(timeout)
def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % timeout_value
)
# See the above comment about EAGAIN in Python 3. In Python 2 we have
# to specifically catch it and throw the timeout error
if hasattr(err, "errno") and err.errno in _blocking_errnos:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % timeout_value
)
# Catch possible read timeouts thrown as SSL errors. If not the
# case, rethrow the original. We need to do this because of:
# http://bugs.python.org/issue10272
if "timed out" in str(err) or "did not complete (read)" in str(
err
): # Python < 2.7.4
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % timeout_value
)
def _make_request(
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout)
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls http.client.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
try:
if chunked:
conn.request_chunked(method, url, **httplib_request_kw)
else:
conn.request(method, url, **httplib_request_kw)
# We are swallowing BrokenPipeError (errno.EPIPE) since the server is
# legitimately able to close the connection after sending a valid response.
# With this behaviour, the received response is still readable.
except BrokenPipeError:
# Python 3
pass
except IOError as e:
# Python 2 and macOS/Linux
# EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE/ECONNRESET are needed on macOS
# https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
if e.errno not in {
errno.EPIPE,
errno.ESHUTDOWN,
errno.EPROTOTYPE,
errno.ECONNRESET,
}:
raise
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, "sock", None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout
)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try:
# Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError:
# Python 3
try:
httplib_response = conn.getresponse()
except BaseException as e:
# Remove the TypeError from the exception chain in
# Python 3 (including for exceptions like SystemExit).
# Otherwise it looks like a bug in the code.
six.raise_from(e, None)
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, "_http_vsn_str", "HTTP/?")
log.debug(
'%s://%s:%s "%s %s %s" %s %s',
self.scheme,
self.host,
self.port,
method,
url,
http_version,
httplib_response.status,
httplib_response.length,
)
try:
assert_header_parsing(httplib_response.msg)
except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
log.warning(
"Failed to parse headers (url=%s): %s",
self._absolute_url(url),
hpe,
exc_info=True,
)
return httplib_response
def _absolute_url(self, path):
return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
def close(self):
"""
Close all pooled connections and disable the pool.
"""
if self.pool is None:
return
# Disable access to the pool
old_pool, self.pool = self.pool, None
# Close all the HTTPConnections in the pool.
_close_pool_connections(old_pool)
def is_same_host(self, url):
"""
Check if the given ``url`` is a member of the same host as this
connection pool.
"""
if url.startswith("/"):
return True
# TODO: Add optional support for socket.gethostbyname checking.
scheme, host, port = get_host(url)
if host is not None:
host = _normalize_host(host, scheme=scheme)
# Use explicit default port for comparison when none is given
if self.port and not port:
port = port_by_scheme.get(scheme)
elif not self.port and port == port_by_scheme.get(scheme):
port = None
return (scheme, host, port) == (self.scheme, self.host, self.port)
def urlopen(
self,
method,
url,
body=None,
headers=None,
retries=None,
redirect=True,
assert_same_host=True,
timeout=_Default,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw
):
"""
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethods`, such as :meth:`request`.
.. note::
`release_conn` will only behave as expected if
`preload_content=False` because we want to make
`preload_content=False` the default behaviour someday soon without
breaking backwards compatibility.
:param method:
HTTP request method (such as GET, POST, PUT, etc.)
:param url:
The URL to perform the request on.
:param body:
Data to send in the request body, either :class:`str`, :class:`bytes`,
an iterable of :class:`str`/:class:`bytes`, or a file-like object.
:param headers:
Dictionary of custom headers to send, such as User-Agent,
If-None-Match, etc. If None, pool headers are used. If provided,
these headers completely replace any pool-specific headers.
:param retries:
Configure the number of retries to allow before raising a
:class:`~urllib3.exceptions.MaxRetryError` exception.
Pass ``None`` to retry until you receive a response. Pass a
:class:`~urllib3.util.retry.Retry` object for fine-grained control
over different types of retries.
Pass an integer number to retry connection errors that many times,
but no other types of errors. Pass zero to never retry.
If ``False``, then retries are disabled and any exception is raised
immediately. Also, instead of raising a MaxRetryError on redirects,
the redirect response will be returned.
:type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
:param redirect:
If True, automatically handle redirects (status codes 301, 302,
303, 307, 308). Each redirect counts as a retry. Disabling retries
will disable redirect, too.
:param assert_same_host:
If ``True``, will make sure that the host of the pool requests is
consistent else will raise HostChangedError. When ``False``, you can
use the pool on an HTTP proxy and request foreign hosts.
:param timeout:
If specified, overrides the default timeout for this one
request. It may be a float (in seconds) or an instance of
:class:`urllib3.util.Timeout`.
:param pool_timeout:
If set and the pool is set to block=True, then this method will
block for ``pool_timeout`` seconds and raise EmptyPoolError if no
connection is available within the time period.
:param release_conn:
If False, then the urlopen call will not release the connection
back into the pool once a response is received (but will release if
you read the entire contents of the response such as when
`preload_content=True`). This is useful if you're not preloading
the response's content immediately. You will need to call
``r.release_conn()`` on the response ``r`` to return the connection
back into the pool. If None, it takes the value of
``response_kw.get('preload_content', True)``.
:param chunked:
If True, urllib3 will send the body using chunked transfer
encoding. Otherwise, urllib3 will send the body using the standard
content-length form. Defaults to False.
:param int body_pos:
Position to seek to in file-like body in the event of a retry or
redirect. Typically this won't need to be set because urllib3 will
auto-populate the value when needed.
:param \\**response_kw:
Additional parameters are passed to
:meth:`urllib3.response.HTTPResponse.from_httplib`
"""
parsed_url = parse_url(url)
destination_scheme = parsed_url.scheme
if headers is None:
headers = self.headers
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
if release_conn is None:
release_conn = response_kw.get("preload_content", True)
# Check host
if assert_same_host and not self.is_same_host(url):
raise HostChangedError(self, url, retries)
# Ensure that the URL we're connecting to is properly encoded
if url.startswith("/"):
url = six.ensure_str(_encode_target(url))
else:
url = six.ensure_str(parsed_url.url)
conn = None
# Track whether `conn` needs to be released before
# returning/raising/recursing. Update this variable if necessary, and
# leave `release_conn` constant throughout the function. That way, if
# the function recurses, the original value of `release_conn` will be
# passed down into the recursive call, and its value will be respected.
#
# See issue #651 [1] for details.
#
# [1] <https://github.com/urllib3/urllib3/issues/651>
release_this_conn = release_conn
http_tunnel_required = connection_requires_http_tunnel(
self.proxy, self.proxy_config, destination_scheme
)
# Merge the proxy headers. Only done when not using HTTP CONNECT. We
# have to copy the headers dict so we can safely change it without those
# changes being reflected in anyone else's copy.
if not http_tunnel_required:
headers = headers.copy()
headers.update(self.proxy_headers)
# Must keep the exception bound to a separate variable or else Python 3
# complains about UnboundLocalError.
err = None
# Keep track of whether we cleanly exited the except block. This
# ensures we do proper cleanup in finally.
clean_exit = False
# Rewind body position, if needed. Record current position
# for future rewinds in the event of a redirect/retry.
body_pos = set_file_position(body, body_pos)
try:
# Request a connection from the queue.
timeout_obj = self._get_timeout(timeout)
conn = self._get_conn(timeout=pool_timeout)
conn.timeout = timeout_obj.connect_timeout
is_new_proxy_conn = self.proxy is not None and not getattr(
conn, "sock", None
)
if is_new_proxy_conn and http_tunnel_required:
self._prepare_proxy(conn)
# Make the request on the httplib connection object.
httplib_response = self._make_request(
conn,
method,
url,
timeout=timeout_obj,
body=body,
headers=headers,
chunked=chunked,
)
# If we're going to release the connection in ``finally:``, then
# the response doesn't need to know about the connection. Otherwise
# it will also try to release it and we'll have a double-release
# mess.
response_conn = conn if not release_conn else None
# Pass method to Response for length checking
response_kw["request_method"] = method
# Import httplib's response into our own wrapper object
response = self.ResponseCls.from_httplib(
httplib_response,
pool=self,
connection=response_conn,
retries=retries,
**response_kw
)
# Everything went great!
clean_exit = True
except EmptyPoolError:
# Didn't get a connection from the pool, no need to clean up
clean_exit = True
release_this_conn = False
raise
except (
TimeoutError,
HTTPException,
SocketError,
ProtocolError,
BaseSSLError,
SSLError,
CertificateError,
) as e:
# Discard the connection for these exceptions. It will be
# replaced during the next _get_conn() call.
clean_exit = False
def _is_ssl_error_message_from_http_proxy(ssl_error):
# We're trying to detect the message 'WRONG_VERSION_NUMBER' but
# SSLErrors are kinda all over the place when it comes to the message,
# so we try to cover our bases here!
message = " ".join(re.split("[^a-z]", str(ssl_error).lower()))
return (
"wrong version number" in message
or "unknown protocol" in message
or "record layer failure" in message
)
# Try to detect a common user error with proxies which is to
# set an HTTP proxy to be HTTPS when it should be 'http://'
# (ie {'http': 'http://proxy', 'https': 'https://proxy'})
# Instead we add a nice error message and point to a URL.
if (
isinstance(e, BaseSSLError)
and self.proxy
and _is_ssl_error_message_from_http_proxy(e)
and conn.proxy
and conn.proxy.scheme == "https"
):
e = ProxyError(
"Your proxy appears to only use HTTP and not HTTPS, "
"try changing your proxy URL to be HTTP. See: "
"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
"#https-proxy-error-http-proxy",
SSLError(e),
)
elif isinstance(e, (BaseSSLError, CertificateError)):
e = SSLError(e)
elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
e = ProxyError("Cannot connect to proxy.", e)
elif isinstance(e, (SocketError, HTTPException)):
e = ProtocolError("Connection aborted.", e)
retries = retries.increment(
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
)
retries.sleep()
# Keep track of the error for the retry warning.
err = e
finally:
if not clean_exit:
# We hit some kind of exception, handled or otherwise. We need
# to throw the connection away unless explicitly told not to.
# Close the connection, set the variable to None, and make sure
# we put the None back in the pool to avoid leaking it.
conn = conn and conn.close()
release_this_conn = True
if release_this_conn:
# Put the connection back to be reused. If the connection is
# expired then it will be None, which will get replaced with a
# fresh connection during _get_conn.
self._put_conn(conn)
if not conn:
# Try again
log.warning(
"Retrying (%r) after connection broken by '%r': %s", retries, err, url
)
return self.urlopen(
method,
url,
body,
headers,
retries,
redirect,
assert_same_host,
timeout=timeout,
pool_timeout=pool_timeout,
release_conn=release_conn,
chunked=chunked,
body_pos=body_pos,
**response_kw
)
# Handle redirect?
redirect_location = redirect and response.get_redirect_location()
if redirect_location:
if response.status == 303:
# Change the method according to RFC 9110, Section 15.4.4.
method = "GET"
# And lose the body not to transfer anything sensitive.
body = None
headers = HTTPHeaderDict(headers)._prepare_for_method_change()
try:
retries = retries.increment(method, url, response=response, _pool=self)
except MaxRetryError:
if retries.raise_on_redirect:
response.drain_conn()
raise
return response
response.drain_conn()
retries.sleep_for_retry(response)
log.debug("Redirecting %s -> %s", url, redirect_location)
return self.urlopen(
method,
redirect_location,
body,
headers,
retries=retries,
redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout,
pool_timeout=pool_timeout,
release_conn=release_conn,
chunked=chunked,
body_pos=body_pos,
**response_kw
)
# Check if we should retry the HTTP response.
has_retry_after = bool(response.headers.get("Retry-After"))
if retries.is_retry(method, response.status, has_retry_after):
try:
retries = retries.increment(method, url, response=response, _pool=self)
except MaxRetryError:
if retries.raise_on_status:
response.drain_conn()
raise
return response
response.drain_conn()
retries.sleep(response)
log.debug("Retry: %s", url)
return self.urlopen(
method,
url,
body,
headers,
retries=retries,
redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout,
pool_timeout=pool_timeout,
release_conn=release_conn,
chunked=chunked,
body_pos=body_pos,
**response_kw
)
return response
| HTTPConnectionPool |
python | kamyu104__LeetCode-Solutions | Python/visit-array-positions-to-maximize-score.py | {
"start": 34,
"end": 387
} | class ____(object):
def maxScore(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
dp = [float("-inf")]*2
dp[nums[0]%2] = nums[0]
for i in xrange(1, len(nums)):
dp[nums[i]%2] = max(dp[nums[i]%2], dp[(nums[i]+1)%2]-x)+nums[i]
return max(dp)
| Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/jvm.py | {
"start": 54630,
"end": 66792
} | class ____(RegexLexer):
"""
For `Jasmin <http://jasmin.sourceforge.net/>`_ assembly code.
.. versionadded:: 2.0
"""
name = 'Jasmin'
aliases = ['jasmin', 'jasminxt']
filenames = ['*.j']
_whitespace = r' \n\t\r'
_ws = r'(?:[%s]+)' % _whitespace
_separator = r'%s:=' % _whitespace
_break = r'(?=[%s]|$)' % _separator
_name = r'[^%s]+' % _separator
_unqualified_name = r'(?:[^%s.;\[/]+)' % _separator
tokens = {
'default': [
(r'\n', Text, '#pop'),
(r"'", String.Single, ('#pop', 'quote')),
(r'"', String.Double, 'string'),
(r'=', Punctuation),
(r':', Punctuation, 'label'),
(_ws, Text),
(r';.*', Comment.Single),
(r'(\$[-+])?0x-?[\da-fA-F]+%s' % _break, Number.Hex),
(r'(\$[-+]|\+)?-?\d+%s' % _break, Number.Integer),
(r'-?(\d+\.\d*|\.\d+)([eE][-+]?\d+)?[fFdD]?'
r'[\x00-\x08\x0b\x0c\x0e-\x1f]*%s' % _break, Number.Float),
(r'\$%s' % _name, Name.Variable),
# Directives
(r'\.annotation%s' % _break, Keyword.Reserved, 'annotation'),
(r'(\.attribute|\.bytecode|\.debug|\.deprecated|\.enclosing|'
r'\.interface|\.line|\.signature|\.source|\.stack|\.var|abstract|'
r'annotation|bridge|class|default|enum|field|final|fpstrict|'
r'interface|native|private|protected|public|signature|static|'
r'synchronized|synthetic|transient|varargs|volatile)%s' % _break,
Keyword.Reserved),
(r'\.catch%s' % _break, Keyword.Reserved, 'caught-exception'),
(r'(\.class|\.implements|\.inner|\.super|inner|invisible|'
r'invisibleparam|outer|visible|visibleparam)%s' % _break,
Keyword.Reserved, 'class/convert-dots'),
(r'\.field%s' % _break, Keyword.Reserved,
('descriptor/convert-dots', 'field')),
(r'(\.end|\.limit|use)%s' % _break, Keyword.Reserved,
'no-verification'),
(r'\.method%s' % _break, Keyword.Reserved, 'method'),
(r'\.set%s' % _break, Keyword.Reserved, 'var'),
(r'\.throws%s' % _break, Keyword.Reserved, 'exception'),
(r'(from|offset|to|using)%s' % _break, Keyword.Reserved, 'label'),
(r'is%s' % _break, Keyword.Reserved,
('descriptor/convert-dots', 'var')),
(r'(locals|stack)%s' % _break, Keyword.Reserved, 'verification'),
(r'method%s' % _break, Keyword.Reserved, 'enclosing-method'),
# Instructions
(words((
'aaload', 'aastore', 'aconst_null', 'aload', 'aload_0', 'aload_1', 'aload_2',
'aload_3', 'aload_w', 'areturn', 'arraylength', 'astore', 'astore_0', 'astore_1',
'astore_2', 'astore_3', 'astore_w', 'athrow', 'baload', 'bastore', 'bipush',
'breakpoint', 'caload', 'castore', 'd2f', 'd2i', 'd2l', 'dadd', 'daload', 'dastore',
'dcmpg', 'dcmpl', 'dconst_0', 'dconst_1', 'ddiv', 'dload', 'dload_0', 'dload_1',
'dload_2', 'dload_3', 'dload_w', 'dmul', 'dneg', 'drem', 'dreturn', 'dstore', 'dstore_0',
'dstore_1', 'dstore_2', 'dstore_3', 'dstore_w', 'dsub', 'dup', 'dup2', 'dup2_x1',
'dup2_x2', 'dup_x1', 'dup_x2', 'f2d', 'f2i', 'f2l', 'fadd', 'faload', 'fastore', 'fcmpg',
'fcmpl', 'fconst_0', 'fconst_1', 'fconst_2', 'fdiv', 'fload', 'fload_0', 'fload_1',
'fload_2', 'fload_3', 'fload_w', 'fmul', 'fneg', 'frem', 'freturn', 'fstore', 'fstore_0',
'fstore_1', 'fstore_2', 'fstore_3', 'fstore_w', 'fsub', 'i2b', 'i2c', 'i2d', 'i2f', 'i2l',
'i2s', 'iadd', 'iaload', 'iand', 'iastore', 'iconst_0', 'iconst_1', 'iconst_2',
'iconst_3', 'iconst_4', 'iconst_5', 'iconst_m1', 'idiv', 'iinc', 'iinc_w', 'iload',
'iload_0', 'iload_1', 'iload_2', 'iload_3', 'iload_w', 'imul', 'ineg', 'int2byte',
'int2char', 'int2short', 'ior', 'irem', 'ireturn', 'ishl', 'ishr', 'istore', 'istore_0',
'istore_1', 'istore_2', 'istore_3', 'istore_w', 'isub', 'iushr', 'ixor', 'l2d', 'l2f',
'l2i', 'ladd', 'laload', 'land', 'lastore', 'lcmp', 'lconst_0', 'lconst_1', 'ldc2_w',
'ldiv', 'lload', 'lload_0', 'lload_1', 'lload_2', 'lload_3', 'lload_w', 'lmul', 'lneg',
'lookupswitch', 'lor', 'lrem', 'lreturn', 'lshl', 'lshr', 'lstore', 'lstore_0',
'lstore_1', 'lstore_2', 'lstore_3', 'lstore_w', 'lsub', 'lushr', 'lxor',
'monitorenter', 'monitorexit', 'nop', 'pop', 'pop2', 'ret', 'ret_w', 'return', 'saload',
'sastore', 'sipush', 'swap'), suffix=_break), Keyword.Reserved),
(r'(anewarray|checkcast|instanceof|ldc|ldc_w|new)%s' % _break,
Keyword.Reserved, 'class/no-dots'),
(r'invoke(dynamic|interface|nonvirtual|special|'
r'static|virtual)%s' % _break, Keyword.Reserved,
'invocation'),
(r'(getfield|putfield)%s' % _break, Keyword.Reserved,
('descriptor/no-dots', 'field')),
(r'(getstatic|putstatic)%s' % _break, Keyword.Reserved,
('descriptor/no-dots', 'static')),
(words((
'goto', 'goto_w', 'if_acmpeq', 'if_acmpne', 'if_icmpeq',
'if_icmpge', 'if_icmpgt', 'if_icmple', 'if_icmplt', 'if_icmpne',
'ifeq', 'ifge', 'ifgt', 'ifle', 'iflt', 'ifne', 'ifnonnull',
'ifnull', 'jsr', 'jsr_w'), suffix=_break),
Keyword.Reserved, 'label'),
(r'(multianewarray|newarray)%s' % _break, Keyword.Reserved,
'descriptor/convert-dots'),
(r'tableswitch%s' % _break, Keyword.Reserved, 'table')
],
'quote': [
(r"'", String.Single, '#pop'),
(r'\\u[\da-fA-F]{4}', String.Escape),
(r"[^'\\]+", String.Single)
],
'string': [
(r'"', String.Double, '#pop'),
(r'\\([nrtfb"\'\\]|u[\da-fA-F]{4}|[0-3]?[0-7]{1,2})',
String.Escape),
(r'[^"\\]+', String.Double)
],
'root': [
(r'\n+', Text),
(r"'", String.Single, 'quote'),
include('default'),
(r'(%s)([ \t\r]*)(:)' % _name,
bygroups(Name.Label, Text, Punctuation)),
(_name, String.Other)
],
'annotation': [
(r'\n', Text, ('#pop', 'annotation-body')),
(r'default%s' % _break, Keyword.Reserved,
('#pop', 'annotation-default')),
include('default')
],
'annotation-body': [
(r'\n+', Text),
(r'\.end%s' % _break, Keyword.Reserved, '#pop'),
include('default'),
(_name, String.Other, ('annotation-items', 'descriptor/no-dots'))
],
'annotation-default': [
(r'\n+', Text),
(r'\.end%s' % _break, Keyword.Reserved, '#pop'),
include('default'),
default(('annotation-items', 'descriptor/no-dots'))
],
'annotation-items': [
(r"'", String.Single, 'quote'),
include('default'),
(_name, String.Other)
],
'caught-exception': [
(r'all%s' % _break, Keyword, '#pop'),
include('exception')
],
'class/convert-dots': [
include('default'),
(r'(L)((?:%s[/.])*)(%s)(;)' % (_unqualified_name, _name),
bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation),
'#pop'),
(r'((?:%s[/.])*)(%s)' % (_unqualified_name, _name),
bygroups(Name.Namespace, Name.Class), '#pop')
],
'class/no-dots': [
include('default'),
(r'\[+', Punctuation, ('#pop', 'descriptor/no-dots')),
(r'(L)((?:%s/)*)(%s)(;)' % (_unqualified_name, _name),
bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation),
'#pop'),
(r'((?:%s/)*)(%s)' % (_unqualified_name, _name),
bygroups(Name.Namespace, Name.Class), '#pop')
],
'descriptor/convert-dots': [
include('default'),
(r'\[+', Punctuation),
(r'(L)((?:%s[/.])*)(%s?)(;)' % (_unqualified_name, _name),
bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation),
'#pop'),
(r'[^%s\[)L]+' % _separator, Keyword.Type, '#pop'),
default('#pop')
],
'descriptor/no-dots': [
include('default'),
(r'\[+', Punctuation),
(r'(L)((?:%s/)*)(%s)(;)' % (_unqualified_name, _name),
bygroups(Keyword.Type, Name.Namespace, Name.Class, Punctuation),
'#pop'),
(r'[^%s\[)L]+' % _separator, Keyword.Type, '#pop'),
default('#pop')
],
'descriptors/convert-dots': [
(r'\)', Punctuation, '#pop'),
default('descriptor/convert-dots')
],
'enclosing-method': [
(_ws, Text),
(r'(?=[^%s]*\()' % _separator, Text, ('#pop', 'invocation')),
default(('#pop', 'class/convert-dots'))
],
'exception': [
include('default'),
(r'((?:%s[/.])*)(%s)' % (_unqualified_name, _name),
bygroups(Name.Namespace, Name.Exception), '#pop')
],
'field': [
(r'static%s' % _break, Keyword.Reserved, ('#pop', 'static')),
include('default'),
(r'((?:%s[/.](?=[^%s]*[/.]))*)(%s[/.])?(%s)' %
(_unqualified_name, _separator, _unqualified_name, _name),
bygroups(Name.Namespace, Name.Class, Name.Variable.Instance),
'#pop')
],
'invocation': [
include('default'),
(r'((?:%s[/.](?=[^%s(]*[/.]))*)(%s[/.])?(%s)(\()' %
(_unqualified_name, _separator, _unqualified_name, _name),
bygroups(Name.Namespace, Name.Class, Name.Function, Punctuation),
('#pop', 'descriptor/convert-dots', 'descriptors/convert-dots',
'descriptor/convert-dots'))
],
'label': [
include('default'),
(_name, Name.Label, '#pop')
],
'method': [
include('default'),
(r'(%s)(\()' % _name, bygroups(Name.Function, Punctuation),
('#pop', 'descriptor/convert-dots', 'descriptors/convert-dots',
'descriptor/convert-dots'))
],
'no-verification': [
(r'(locals|method|stack)%s' % _break, Keyword.Reserved, '#pop'),
include('default')
],
'static': [
include('default'),
(r'((?:%s[/.](?=[^%s]*[/.]))*)(%s[/.])?(%s)' %
(_unqualified_name, _separator, _unqualified_name, _name),
bygroups(Name.Namespace, Name.Class, Name.Variable.Class), '#pop')
],
'table': [
(r'\n+', Text),
(r'default%s' % _break, Keyword.Reserved, '#pop'),
include('default'),
(_name, Name.Label)
],
'var': [
include('default'),
(_name, Name.Variable, '#pop')
],
'verification': [
include('default'),
(r'(Double|Float|Integer|Long|Null|Top|UninitializedThis)%s' %
_break, Keyword, '#pop'),
(r'Object%s' % _break, Keyword, ('#pop', 'class/no-dots')),
(r'Uninitialized%s' % _break, Keyword, ('#pop', 'label'))
]
}
def analyse_text(text):
score = 0
if re.search(r'^\s*\.class\s', text, re.MULTILINE):
score += 0.5
if re.search(r'^\s*[a-z]+_[a-z]+\b', text, re.MULTILINE):
score += 0.3
if re.search(r'^\s*\.(attribute|bytecode|debug|deprecated|enclosing|'
r'inner|interface|limit|set|signature|stack)\b', text,
re.MULTILINE):
score += 0.6
return score
| JasminLexer |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 3103,
"end": 3423
} | class ____(_JsProxyMetaClass, ABCMeta):
pass
# We want to raise an error if someone tries to instantiate JsProxy directly
# since it doesn't mean anything. But we have a few reasons to do so internally.
# So we raise an error unless this private token is passed as an argument.
_instantiate_token = object()
| _ABCMeta |
python | scipy__scipy | scipy/special/tests/test_orthogonal.py | {
"start": 10971,
"end": 32878
} | class ____:
def test_regression(self):
assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.)
assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.)
assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2]))
assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2]))
def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N,
rtol=1e-15, atol=5e-14):
# this test is copied from numpy's TestGauss in test_hermite.py
x, w, mu = root_func(N, True)
n = np.arange(N, dtype=np.dtype("long"))
v = eval_func(n[:,np.newaxis], x)
vv = np.dot(v*w, v.T)
vd = 1 / np.sqrt(vv.diagonal())
vv = vd[:, np.newaxis] * vv * vd
assert_allclose(vv, np.eye(N), rtol, atol)
# check that the integral of 1 is correct
assert_allclose(w.sum(), mu, rtol, atol)
# compare the results of integrating a function with quad.
def f(x):
return x ** 3 - 3 * x ** 2 + x - 2
resI = integrate.quad(lambda x: f(x)*weight_func(x), a, b)
resG = np.vdot(f(x), w)
rtol = 1e-6 if 1e-6 < resI[1] else resI[1] * 10
assert_allclose(resI[0], resG, rtol=rtol)
def test_roots_jacobi():
def rf(a, b):
return lambda n, mu: sc.roots_jacobi(n, a, b, mu)
def ef(a, b):
return lambda n, x: sc.eval_jacobi(n, a, b, x)
def wf(a, b):
return lambda x: (1 - x) ** a * (1 + x) ** b
vgq = verify_gauss_quad
vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5)
vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
25, atol=1e-12)
vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
100, atol=1e-11)
vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5)
vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13)
vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=2e-12)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12)
vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5)
vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13)
vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=3e-13)
vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5)
vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25,
atol=1.1e-14)
vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1.,
100, atol=1e-13)
vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13)
vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 25, atol=2e-13)
vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1.,
100, atol=1e-11)
vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 5, atol=2e-13)
vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 25, atol=1e-12)
vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 100, atol=1e-11)
vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 250, atol=1e-11)
vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 5,
atol=1e-12)
vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 25,
atol=1e-11)
vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 100,
atol=1e-10)
vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 5,
atol=1e-12)
vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 25,
atol=1e-11)
vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 100,
atol=1e-10)
vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 5,
atol=1e-12)
vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 25,
atol=1e-11)
vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 100,
atol=1e-10)
vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5)
vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 25,
atol=1e-13)
vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 100,
atol=1e-13)
# when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
xj, wj = sc.roots_jacobi(6, 0.0, 0.0)
xl, wl = sc.roots_legendre(6)
assert_allclose(xj, xl, 1e-14, 1e-14)
assert_allclose(wj, wl, 1e-14, 1e-14)
# when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
xj, wj = sc.roots_jacobi(6, 4.0, 4.0)
xc, wc = sc.roots_gegenbauer(6, 4.5)
assert_allclose(xj, xc, 1e-14, 1e-14)
assert_allclose(wj, wc, 1e-14, 1e-14)
x, w = sc.roots_jacobi(5, 2, 3, False)
y, v, m = sc.roots_jacobi(5, 2, 3, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(wf(2,3), -1, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_jacobi, 0, 1, 1)
assert_raises(ValueError, sc.roots_jacobi, 3.3, 1, 1)
assert_raises(ValueError, sc.roots_jacobi, 3, -2, 1)
assert_raises(ValueError, sc.roots_jacobi, 3, 1, -2)
assert_raises(ValueError, sc.roots_jacobi, 3, -2, -2)
def test_roots_sh_jacobi():
def rf(a, b):
return lambda n, mu: sc.roots_sh_jacobi(n, a, b, mu)
def ef(a, b):
return lambda n, x: sc.eval_sh_jacobi(n, a, b, x)
def wf(a, b):
return lambda x: (1.0 - x) ** (a - b) * x ** (b - 1.0)
vgq = verify_gauss_quad
vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., 5)
vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
25, atol=1e-12)
vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
100, atol=1e-11)
vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 5)
vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 25, atol=1e-13)
vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 100, atol=1e-12)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 5)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 25, atol=1.5e-13)
vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 100, atol=2e-12)
vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 5)
vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 25, atol=1e-13)
vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 100, atol=1e-12)
vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 5)
vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 25)
vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1.,
100, atol=1e-13)
vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 5, atol=1e-12)
vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 25, atol=1e-11)
vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 100, atol=1e-10)
vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 5, atol=3.5e-14)
vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 25, atol=2e-13)
vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1.,
100, atol=1e-12)
x, w = sc.roots_sh_jacobi(5, 3, 2, False)
y, v, m = sc.roots_sh_jacobi(5, 3, 2, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(wf(3,2), 0, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_sh_jacobi, 0, 1, 1)
assert_raises(ValueError, sc.roots_sh_jacobi, 3.3, 1, 1)
assert_raises(ValueError, sc.roots_sh_jacobi, 3, 1, 2) # p - q <= -1
assert_raises(ValueError, sc.roots_sh_jacobi, 3, 2, -1) # q <= 0
assert_raises(ValueError, sc.roots_sh_jacobi, 3, -2, -1) # both
def test_roots_hermite():
rootf = sc.roots_hermite
evalf = sc.eval_hermite
weightf = orth.hermite(5).weight_func
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
# Golub-Welsch branch
x, w = sc.roots_hermite(5, False)
y, v, m = sc.roots_hermite(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
assert_allclose(m, muI, rtol=muI_err)
# Asymptotic branch (switch over at n >= 150)
x, w = sc.roots_hermite(200, False)
y, v, m = sc.roots_hermite(200, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
assert_allclose(sum(v), m, 1e-14, 1e-14)
assert_raises(ValueError, sc.roots_hermite, 0)
assert_raises(ValueError, sc.roots_hermite, 3.3)
def test_roots_hermite_asy():
# Recursion for Hermite functions
def hermite_recursion(n, nodes):
H = np.zeros((n, nodes.size))
H[0,:] = np.pi**(-0.25) * np.exp(-0.5*nodes**2)
if n > 1:
H[1,:] = sqrt(2.0) * nodes * H[0,:]
for k in range(2, n):
H[k,:] = sqrt(2.0/k) * nodes * H[k-1,:] - sqrt((k-1.0)/k) * H[k-2,:]
return H
# This tests only the nodes
def test(N, rtol=1e-15, atol=1e-14):
x, w = orth._roots_hermite_asy(N)
H = hermite_recursion(N+1, x)
assert_allclose(H[-1,:], np.zeros(N), rtol, atol)
assert_allclose(sum(w), sqrt(np.pi), rtol, atol)
test(150, atol=1e-12)
test(151, atol=1e-12)
test(300, atol=1e-12)
test(301, atol=1e-12)
test(500, atol=1e-12)
test(501, atol=1e-12)
test(999, atol=1e-12)
test(1000, atol=1e-12)
test(2000, atol=1e-12)
test(5000, atol=1e-12)
def test_roots_hermitenorm():
rootf = sc.roots_hermitenorm
evalf = sc.eval_hermitenorm
weightf = orth.hermitenorm(5).weight_func
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
x, w = sc.roots_hermitenorm(5, False)
y, v, m = sc.roots_hermitenorm(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_hermitenorm, 0)
assert_raises(ValueError, sc.roots_hermitenorm, 3.3)
def test_roots_gegenbauer():
def rootf(a):
return lambda n, mu: sc.roots_gegenbauer(n, a, mu)
def evalf(a):
return lambda n, x: sc.eval_gegenbauer(n, a, x)
def weightf(a):
return lambda x: (1 - x ** 2) ** (a - 0.5)
vgq = verify_gauss_quad
vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 5)
vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 25, atol=1e-12)
vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 100, atol=1e-11)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 5)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 25, atol=1e-13)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 100, atol=1e-12)
vgq(rootf(1), evalf(1), weightf(1), -1., 1., 5)
vgq(rootf(1), evalf(1), weightf(1), -1., 1., 25, atol=1e-13)
vgq(rootf(1), evalf(1), weightf(1), -1., 1., 100, atol=1e-12)
vgq(rootf(10), evalf(10), weightf(10), -1., 1., 5)
vgq(rootf(10), evalf(10), weightf(10), -1., 1., 25, atol=1e-13)
vgq(rootf(10), evalf(10), weightf(10), -1., 1., 100, atol=1e-12)
vgq(rootf(50), evalf(50), weightf(50), -1., 1., 5, atol=1e-13)
vgq(rootf(50), evalf(50), weightf(50), -1., 1., 25, atol=1e-12)
vgq(rootf(50), evalf(50), weightf(50), -1., 1., 100, atol=1e-11)
# Alpha=170 is where the approximation used in roots_gegenbauer changes
vgq(rootf(170), evalf(170), weightf(170), -1., 1., 5, atol=1e-13)
vgq(rootf(170), evalf(170), weightf(170), -1., 1., 25, atol=1e-12)
vgq(rootf(170), evalf(170), weightf(170), -1., 1., 100, atol=1e-11)
vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 5, atol=1.25e-13)
vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 25, atol=1e-12)
vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 100, atol=1e-11)
# Test for failures, e.g. overflows, resulting from large alphas
vgq(rootf(238), evalf(238), weightf(238), -1., 1., 5, atol=1e-13)
vgq(rootf(238), evalf(238), weightf(238), -1., 1., 25, atol=1e-12)
vgq(rootf(238), evalf(238), weightf(238), -1., 1., 100, atol=1e-11)
vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 5, atol=1e-12)
vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 25, atol=1e-11)
vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 100, atol=1e-10)
# this is a special case that the old code supported.
# when alpha = 0, the gegenbauer polynomial is uniformly 0. but it goes
# to a scaled down copy of T_n(x) there.
vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 5)
vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 25)
vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 100, atol=1e-12)
x, w = sc.roots_gegenbauer(5, 2, False)
y, v, m = sc.roots_gegenbauer(5, 2, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf(2), -1, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_gegenbauer, 0, 2)
assert_raises(ValueError, sc.roots_gegenbauer, 3.3, 2)
assert_raises(ValueError, sc.roots_gegenbauer, 3, -.75)
def test_roots_chebyt():
weightf = orth.chebyt(5).weight_func
verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 5)
verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 25)
verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 100,
atol=1e-12)
x, w = sc.roots_chebyt(5, False)
y, v, m = sc.roots_chebyt(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -1, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_chebyt, 0)
assert_raises(ValueError, sc.roots_chebyt, 3.3)
def test_chebyt_symmetry():
x, w = sc.roots_chebyt(21)
pos, neg = x[:10], x[11:]
assert_equal(neg, -pos[::-1])
assert_equal(x[10], 0)
def test_roots_chebyu():
weightf = orth.chebyu(5).weight_func
verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 5)
verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 25)
verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 100)
x, w = sc.roots_chebyu(5, False)
y, v, m = sc.roots_chebyu(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -1, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_chebyu, 0)
assert_raises(ValueError, sc.roots_chebyu, 3.3)
def test_roots_chebyc():
weightf = orth.chebyc(5).weight_func
verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 5)
verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 25)
verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 100,
atol=1e-12)
x, w = sc.roots_chebyc(5, False)
y, v, m = sc.roots_chebyc(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -2, 2)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_chebyc, 0)
assert_raises(ValueError, sc.roots_chebyc, 3.3)
def test_roots_chebys():
weightf = orth.chebys(5).weight_func
verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 5)
verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 25)
verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 100)
x, w = sc.roots_chebys(5, False)
y, v, m = sc.roots_chebys(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -2, 2)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_chebys, 0)
assert_raises(ValueError, sc.roots_chebys, 3.3)
def test_roots_sh_chebyt():
weightf = orth.sh_chebyt(5).weight_func
verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 5)
verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 25)
verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1.,
100, atol=1e-13)
x, w = sc.roots_sh_chebyt(5, False)
y, v, m = sc.roots_sh_chebyt(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, 0, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_sh_chebyt, 0)
assert_raises(ValueError, sc.roots_sh_chebyt, 3.3)
def test_roots_sh_chebyu():
weightf = orth.sh_chebyu(5).weight_func
verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 5)
verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 25)
verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1.,
100, atol=1e-13)
x, w = sc.roots_sh_chebyu(5, False)
y, v, m = sc.roots_sh_chebyu(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, 0, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_sh_chebyu, 0)
assert_raises(ValueError, sc.roots_sh_chebyu, 3.3)
def test_roots_legendre():
weightf = orth.legendre(5).weight_func
verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., 5)
verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
25, atol=1e-13)
verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
100, atol=1e-12)
x, w = sc.roots_legendre(5, False)
y, v, m = sc.roots_legendre(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, -1, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_legendre, 0)
assert_raises(ValueError, sc.roots_legendre, 3.3)
def test_roots_sh_legendre():
weightf = orth.sh_legendre(5).weight_func
verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., 5)
verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
25, atol=1e-13)
verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
100, atol=1e-12)
x, w = sc.roots_sh_legendre(5, False)
y, v, m = sc.roots_sh_legendre(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, 0, 1)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_sh_legendre, 0)
assert_raises(ValueError, sc.roots_sh_legendre, 3.3)
def test_roots_laguerre():
weightf = orth.laguerre(5).weight_func
verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, 5)
verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
25, atol=1e-13)
verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
100, atol=1e-12)
x, w = sc.roots_laguerre(5, False)
y, v, m = sc.roots_laguerre(5, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf, 0, np.inf)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_laguerre, 0)
assert_raises(ValueError, sc.roots_laguerre, 3.3)
def test_roots_genlaguerre():
def rootf(a):
return lambda n, mu: sc.roots_genlaguerre(n, a, mu)
def evalf(a):
return lambda n, x: sc.eval_genlaguerre(n, a, x)
def weightf(a):
return lambda x: x ** a * np.exp(-x)
vgq = verify_gauss_quad
vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 5)
vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 25, atol=1e-13)
vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 100, atol=1e-12)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 5)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 25, atol=1e-13)
vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 100, atol=1.6e-13)
vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 5)
vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 25, atol=1e-13)
vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 100, atol=1.03e-13)
vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 5)
vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 25, atol=1e-13)
vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 100, atol=1e-12)
vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 5)
vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 25, atol=1e-13)
vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 100, rtol=1e-14, atol=2e-13)
x, w = sc.roots_genlaguerre(5, 2, False)
y, v, m = sc.roots_genlaguerre(5, 2, True)
assert_allclose(x, y, 1e-14, 1e-14)
assert_allclose(w, v, 1e-14, 1e-14)
muI, muI_err = integrate.quad(weightf(2.), 0., np.inf)
assert_allclose(m, muI, rtol=muI_err)
assert_raises(ValueError, sc.roots_genlaguerre, 0, 2)
assert_raises(ValueError, sc.roots_genlaguerre, 3.3, 2)
assert_raises(ValueError, sc.roots_genlaguerre, 3, -1.1)
def test_gh_6721():
# Regression test for gh_6721. This should not raise.
sc.chebyt(65)(0.2)
| TestGenlaguerre |
python | eventlet__eventlet | eventlet/green/http/server.py | {
"start": 35216,
"end": 46596
} | class ____(SimpleHTTPRequestHandler):
"""Complete HTTP server with GET, HEAD and POST commands.
GET and HEAD also support running CGI scripts.
The POST command is *only* implemented for CGI scripts.
"""
# Determine platform specifics
have_fork = hasattr(os, 'fork')
# Make rfile unbuffered -- we need to read one line and then pass
# the rest to a subprocess, so we can't use buffered input.
rbufsize = 0
def do_POST(self):
"""Serve a POST request.
This is only implemented for CGI scripts.
"""
if self.is_cgi():
self.run_cgi()
else:
self.send_error(
HTTPStatus.NOT_IMPLEMENTED,
"Can only POST to CGI scripts")
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPRequestHandler.send_head(self)
def is_cgi(self):
"""Test whether self.path corresponds to a CGI script.
Returns True and updates the cgi_info attribute to the tuple
(dir, rest) if self.path requires running a CGI script.
Returns False otherwise.
If any exception is raised, the caller should assume that
self.path was rejected as invalid and act accordingly.
The default implementation tests whether the normalized url
path begins with one of the strings in self.cgi_directories
(and the next character is a '/' or the end of the string).
"""
collapsed_path = _url_collapse_path(self.path)
dir_sep = collapsed_path.find('/', 1)
head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
if head in self.cgi_directories:
self.cgi_info = head, tail
return True
return False
cgi_directories = ['/cgi-bin', '/htbin']
def is_executable(self, path):
"""Test whether argument path is an executable file."""
return executable(path)
def is_python(self, path):
"""Test whether argument path is a Python script."""
head, tail = os.path.splitext(path)
return tail.lower() in (".py", ".pyw")
def run_cgi(self):
"""Execute a CGI script."""
dir, rest = self.cgi_info
path = dir + '/' + rest
i = path.find('/', len(dir)+1)
while i >= 0:
nextdir = path[:i]
nextrest = path[i+1:]
scriptdir = self.translate_path(nextdir)
if os.path.isdir(scriptdir):
dir, rest = nextdir, nextrest
i = path.find('/', len(dir)+1)
else:
break
# find an explicit query string, if present.
rest, _, query = rest.partition('?')
# dissect the part after the directory name into a script name &
# a possible additional path, to be stored in PATH_INFO.
i = rest.find('/')
if i >= 0:
script, rest = rest[:i], rest[i:]
else:
script, rest = rest, ''
scriptname = dir + '/' + script
scriptfile = self.translate_path(scriptname)
if not os.path.exists(scriptfile):
self.send_error(
HTTPStatus.NOT_FOUND,
"No such CGI script (%r)" % scriptname)
return
if not os.path.isfile(scriptfile):
self.send_error(
HTTPStatus.FORBIDDEN,
"CGI script is not a plain file (%r)" % scriptname)
return
ispy = self.is_python(scriptname)
if self.have_fork or not ispy:
if not self.is_executable(scriptfile):
self.send_error(
HTTPStatus.FORBIDDEN,
"CGI script is not executable (%r)" % scriptname)
return
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
# XXX Much of the following could be prepared ahead of time!
env = copy.deepcopy(os.environ)
env['SERVER_SOFTWARE'] = self.version_string()
env['SERVER_NAME'] = self.server.server_name
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PROTOCOL'] = self.protocol_version
env['SERVER_PORT'] = str(self.server.server_port)
env['REQUEST_METHOD'] = self.command
uqrest = urllib.parse.unquote(rest)
env['PATH_INFO'] = uqrest
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
env['SCRIPT_NAME'] = scriptname
if query:
env['QUERY_STRING'] = query
env['REMOTE_ADDR'] = self.client_address[0]
authorization = self.headers.get("authorization")
if authorization:
authorization = authorization.split()
if len(authorization) == 2:
import base64, binascii
env['AUTH_TYPE'] = authorization[0]
if authorization[0].lower() == "basic":
try:
authorization = authorization[1].encode('ascii')
authorization = base64.decodebytes(authorization).\
decode('ascii')
except (binascii.Error, UnicodeError):
pass
else:
authorization = authorization.split(':')
if len(authorization) == 2:
env['REMOTE_USER'] = authorization[0]
# XXX REMOTE_IDENT
if self.headers.get('content-type') is None:
env['CONTENT_TYPE'] = self.headers.get_content_type()
else:
env['CONTENT_TYPE'] = self.headers['content-type']
length = self.headers.get('content-length')
if length:
env['CONTENT_LENGTH'] = length
referer = self.headers.get('referer')
if referer:
env['HTTP_REFERER'] = referer
accept = []
for line in self.headers.getallmatchingheaders('accept'):
if line[:1] in "\t\n\r ":
accept.append(line.strip())
else:
accept = accept + line[7:].split(',')
env['HTTP_ACCEPT'] = ','.join(accept)
ua = self.headers.get('user-agent')
if ua:
env['HTTP_USER_AGENT'] = ua
co = filter(None, self.headers.get_all('cookie', []))
cookie_str = ', '.join(co)
if cookie_str:
env['HTTP_COOKIE'] = cookie_str
# XXX Other HTTP_* headers
# Since we're setting the env in the parent, provide empty
# values to override previously set values
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
env.setdefault(k, "")
self.send_response(HTTPStatus.OK, "Script output follows")
self.flush_headers()
decoded_query = query.replace('+', ' ')
if self.have_fork:
# Unix -- fork as we should
args = [script]
if '=' not in decoded_query:
args.append(decoded_query)
nobody = nobody_uid()
self.wfile.flush() # Always flush before forking
pid = os.fork()
if pid != 0:
# Parent
pid, sts = os.waitpid(pid, 0)
# throw away additional data [see bug #427345]
while select.select([self.rfile], [], [], 0)[0]:
if not self.rfile.read(1):
break
if sts:
self.log_error("CGI script exit status %#x", sts)
return
# Child
try:
try:
os.setuid(nobody)
except OSError:
pass
os.dup2(self.rfile.fileno(), 0)
os.dup2(self.wfile.fileno(), 1)
os.execve(scriptfile, args, env)
except:
self.server.handle_error(self.request, self.client_address)
os._exit(127)
else:
# Non-Unix -- use subprocess
cmdline = [scriptfile]
if self.is_python(scriptfile):
interp = sys.executable
if interp.lower().endswith("w.exe"):
# On Windows, use python.exe, not pythonw.exe
interp = interp[:-5] + interp[-4:]
cmdline = [interp, '-u'] + cmdline
if '=' not in query:
cmdline.append(query)
self.log_message("command: %s", subprocess.list2cmdline(cmdline))
try:
nbytes = int(length)
except (TypeError, ValueError):
nbytes = 0
p = subprocess.Popen(cmdline,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env = env
)
if self.command.lower() == "post" and nbytes > 0:
data = self.rfile.read(nbytes)
else:
data = None
# throw away additional data [see bug #427345]
while select.select([self.rfile._sock], [], [], 0)[0]:
if not self.rfile._sock.recv(1):
break
stdout, stderr = p.communicate(data)
self.wfile.write(stdout)
if stderr:
self.log_error('%s', stderr)
p.stderr.close()
p.stdout.close()
status = p.returncode
if status:
self.log_error("CGI script exit status %#x", status)
else:
self.log_message("CGI script exited OK")
def test(HandlerClass=BaseHTTPRequestHandler,
ServerClass=HTTPServer, protocol="HTTP/1.0", port=8000, bind=""):
"""Test the HTTP request handler class.
This runs an HTTP server on port 8000 (or the port argument).
"""
server_address = (bind, port)
HandlerClass.protocol_version = protocol
with ServerClass(server_address, HandlerClass) as httpd:
sa = httpd.socket.getsockname()
serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
print(serve_message.format(host=sa[0], port=sa[1]))
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--cgi', action='store_true',
help='Run as CGI Server')
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
if args.cgi:
handler_class = CGIHTTPRequestHandler
else:
handler_class = SimpleHTTPRequestHandler
test(HandlerClass=handler_class, port=args.port, bind=args.bind)
| CGIHTTPRequestHandler |
python | scikit-learn__scikit-learn | sklearn/cluster/_kmeans.py | {
"start": 58140,
"end": 81912
} | class ____(_BaseKMeans):
"""
Mini-Batch K-Means clustering.
Read more in the :ref:`User Guide <mini_batch_kmeans>`.
Parameters
----------
n_clusters : int, default=8
The number of clusters to form as well as the number of
centroids to generate.
init : {'k-means++', 'random'}, callable or array-like of shape \
(n_clusters, n_features), default='k-means++'
Method for initialization:
'k-means++' : selects initial cluster centroids using sampling based on
an empirical probability distribution of the points' contribution to the
overall inertia. This technique speeds up convergence. The algorithm
implemented is "greedy k-means++". It differs from the vanilla k-means++
by making several trials at each sampling step and choosing the best centroid
among them.
'random': choose `n_clusters` observations (rows) at random from data
for the initial centroids.
If an array is passed, it should be of shape (n_clusters, n_features)
and gives the initial centers.
If a callable is passed, it should take arguments X, n_clusters and a
random state and return an initialization.
For an evaluation of the impact of initialization, see the example
:ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`.
max_iter : int, default=100
Maximum number of iterations over the complete dataset before
stopping independently of any early stopping criterion heuristics.
batch_size : int, default=1024
Size of the mini batches.
For faster computations, you can set `batch_size > 256 * number_of_cores`
to enable :ref:`parallelism <lower-level-parallelism-with-openmp>`
on all cores.
.. versionchanged:: 1.0
`batch_size` default changed from 100 to 1024.
verbose : int, default=0
Verbosity mode.
compute_labels : bool, default=True
Compute label assignment and inertia for the complete dataset
once the minibatch optimization has converged in fit.
random_state : int, RandomState instance or None, default=None
Determines random number generation for centroid initialization and
random reassignment. Use an int to make the randomness deterministic.
See :term:`Glossary <random_state>`.
tol : float, default=0.0
Control early stopping based on the relative center changes as
measured by a smoothed, variance-normalized of the mean center
squared position changes. This early stopping heuristics is
closer to the one used for the batch variant of the algorithms
but induces a slight computational and memory overhead over the
inertia heuristic.
To disable convergence detection based on normalized center
change, set tol to 0.0 (default).
max_no_improvement : int, default=10
Control early stopping based on the consecutive number of mini
batches that does not yield an improvement on the smoothed inertia.
To disable convergence detection based on inertia, set
max_no_improvement to None.
init_size : int, default=None
Number of samples to randomly sample for speeding up the
initialization (sometimes at the expense of accuracy): the
only algorithm is initialized by running a batch KMeans on a
random subset of the data. This needs to be larger than n_clusters.
If `None`, the heuristic is `init_size = 3 * batch_size` if
`3 * batch_size < n_clusters`, else `init_size = 3 * n_clusters`.
n_init : 'auto' or int, default="auto"
Number of random initializations that are tried.
In contrast to KMeans, the algorithm is only run once, using the best of
the `n_init` initializations as measured by inertia. Several runs are
recommended for sparse high-dimensional problems (see
:ref:`kmeans_sparse_high_dim`).
When `n_init='auto'`, the number of runs depends on the value of init:
3 if using `init='random'` or `init` is a callable;
1 if using `init='k-means++'` or `init` is an array-like.
.. versionadded:: 1.2
Added 'auto' option for `n_init`.
.. versionchanged:: 1.4
Default value for `n_init` changed to `'auto'` in version.
reassignment_ratio : float, default=0.01
Control the fraction of the maximum number of counts for a center to
be reassigned. A higher value means that low count centers are more
easily reassigned, which means that the model will take longer to
converge, but should converge in a better clustering. However, too high
a value may cause convergence issues, especially with a small batch
size.
Attributes
----------
cluster_centers_ : ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labels_ : ndarray of shape (n_samples,)
Labels of each point (if compute_labels is set to True).
inertia_ : float
The value of the inertia criterion associated with the chosen
partition if compute_labels is set to True. If compute_labels is set to
False, it's an approximation of the inertia based on an exponentially
weighted average of the batch inertiae.
The inertia is defined as the sum of square distances of samples to
their cluster center, weighted by the sample weights if provided.
n_iter_ : int
Number of iterations over the full dataset.
n_steps_ : int
Number of minibatches processed.
.. versionadded:: 1.0
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
--------
KMeans : The classic implementation of the clustering method based on the
Lloyd's algorithm. It consumes the whole set of input data at each
iteration.
Notes
-----
See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf
When there are too few points in the dataset, some centers may be
duplicated, which means that a proper clustering in terms of the number
of requesting clusters and the number of returned clusters will not
always match. One solution is to set `reassignment_ratio=0`, which
prevents reassignments of clusters that are too small.
See :ref:`sphx_glr_auto_examples_cluster_plot_birch_vs_minibatchkmeans.py` for a
comparison with :class:`~sklearn.cluster.BIRCH`.
Examples
--------
>>> from sklearn.cluster import MiniBatchKMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 0], [4, 4],
... [4, 5], [0, 1], [2, 2],
... [3, 2], [5, 5], [1, -1]])
>>> # manually fit on batches
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6,
... n_init="auto")
>>> kmeans = kmeans.partial_fit(X[0:6,:])
>>> kmeans = kmeans.partial_fit(X[6:12,:])
>>> kmeans.cluster_centers_
array([[3.375, 3. ],
[0.75 , 0.5 ]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([1, 0], dtype=int32)
>>> # fit on the whole data
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6,
... max_iter=10,
... n_init="auto").fit(X)
>>> kmeans.cluster_centers_
array([[3.55102041, 2.48979592],
[1.06896552, 1. ]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([1, 0], dtype=int32)
For a comparison of Mini-Batch K-Means clustering with other clustering algorithms,
see :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py`
"""
_parameter_constraints: dict = {
**_BaseKMeans._parameter_constraints,
"batch_size": [Interval(Integral, 1, None, closed="left")],
"compute_labels": ["boolean"],
"max_no_improvement": [Interval(Integral, 0, None, closed="left"), None],
"init_size": [Interval(Integral, 1, None, closed="left"), None],
"reassignment_ratio": [Interval(Real, 0, None, closed="left")],
}
def __init__(
self,
n_clusters=8,
*,
init="k-means++",
max_iter=100,
batch_size=1024,
verbose=0,
compute_labels=True,
random_state=None,
tol=0.0,
max_no_improvement=10,
init_size=None,
n_init="auto",
reassignment_ratio=0.01,
):
super().__init__(
n_clusters=n_clusters,
init=init,
max_iter=max_iter,
verbose=verbose,
random_state=random_state,
tol=tol,
n_init=n_init,
)
self.max_no_improvement = max_no_improvement
self.batch_size = batch_size
self.compute_labels = compute_labels
self.init_size = init_size
self.reassignment_ratio = reassignment_ratio
def _check_params_vs_input(self, X):
super()._check_params_vs_input(X, default_n_init=3)
self._batch_size = min(self.batch_size, X.shape[0])
# init_size
self._init_size = self.init_size
if self._init_size is None:
self._init_size = 3 * self._batch_size
if self._init_size < self.n_clusters:
self._init_size = 3 * self.n_clusters
elif self._init_size < self.n_clusters:
warnings.warn(
(
f"init_size={self._init_size} should be larger than "
f"n_clusters={self.n_clusters}. Setting it to "
"min(3*n_clusters, n_samples)"
),
RuntimeWarning,
stacklevel=2,
)
self._init_size = 3 * self.n_clusters
self._init_size = min(self._init_size, X.shape[0])
# reassignment_ratio
if self.reassignment_ratio < 0:
raise ValueError(
"reassignment_ratio should be >= 0, got "
f"{self.reassignment_ratio} instead."
)
def _warn_mkl_vcomp(self, n_active_threads):
"""Warn when vcomp and mkl are both present"""
warnings.warn(
"MiniBatchKMeans is known to have a memory leak on "
"Windows with MKL, when there are less chunks than "
"available threads. You can prevent it by setting "
f"batch_size >= {self._n_threads * CHUNK_SIZE} or by "
"setting the environment variable "
f"OMP_NUM_THREADS={n_active_threads}"
)
def _mini_batch_convergence(
self, step, n_steps, n_samples, centers_squared_diff, batch_inertia
):
"""Helper function to encapsulate the early stopping logic"""
# Normalize inertia to be able to compare values when
# batch_size changes
batch_inertia /= self._batch_size
# count steps starting from 1 for user friendly verbose mode.
step = step + 1
# Ignore first iteration because it's inertia from initialization.
if step == 1:
if self.verbose:
print(
f"Minibatch step {step}/{n_steps}: mean batch "
f"inertia: {batch_inertia}"
)
return False
# Compute an Exponentially Weighted Average of the inertia to
# monitor the convergence while discarding minibatch-local stochastic
# variability: https://en.wikipedia.org/wiki/Moving_average
if self._ewa_inertia is None:
self._ewa_inertia = batch_inertia
else:
alpha = self._batch_size * 2.0 / (n_samples + 1)
alpha = min(alpha, 1)
self._ewa_inertia = self._ewa_inertia * (1 - alpha) + batch_inertia * alpha
# Log progress to be able to monitor convergence
if self.verbose:
print(
f"Minibatch step {step}/{n_steps}: mean batch inertia: "
f"{batch_inertia}, ewa inertia: {self._ewa_inertia}"
)
# Early stopping based on absolute tolerance on squared change of
# centers position
if self._tol > 0.0 and centers_squared_diff <= self._tol:
if self.verbose:
print(f"Converged (small centers change) at step {step}/{n_steps}")
return True
# Early stopping heuristic due to lack of improvement on smoothed
# inertia
if self._ewa_inertia_min is None or self._ewa_inertia < self._ewa_inertia_min:
self._no_improvement = 0
self._ewa_inertia_min = self._ewa_inertia
else:
self._no_improvement += 1
if (
self.max_no_improvement is not None
and self._no_improvement >= self.max_no_improvement
):
if self.verbose:
print(
"Converged (lack of improvement in inertia) at step "
f"{step}/{n_steps}"
)
return True
return False
def _random_reassign(self):
"""Check if a random reassignment needs to be done.
Do random reassignments each time 10 * n_clusters samples have been
processed.
If there are empty clusters we always want to reassign.
"""
self._n_since_last_reassign += self._batch_size
if (self._counts == 0).any() or self._n_since_last_reassign >= (
10 * self.n_clusters
):
self._n_since_last_reassign = 0
return True
return False
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y=None, sample_weight=None):
"""Compute the centroids on X by chunking it into mini-batches.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data
will be converted to C ordering, which will cause a memory copy
if the given data is not C-contiguous.
If a sparse matrix is passed, a copy will be made if it's not in
CSR format.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations
are assigned equal weight. `sample_weight` is not used during
initialization if `init` is a callable or a user provided array.
.. versionadded:: 0.20
Returns
-------
self : object
Fitted estimator.
"""
X = validate_data(
self,
X,
accept_sparse="csr",
dtype=[np.float64, np.float32],
order="C",
accept_large_sparse=False,
)
self._check_params_vs_input(X)
random_state = check_random_state(self.random_state)
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
self._n_threads = _openmp_effective_n_threads()
n_samples, n_features = X.shape
# Validate init array
init = self.init
if _is_arraylike_not_scalar(init):
init = check_array(init, dtype=X.dtype, copy=True, order="C")
self._validate_center_shape(X, init)
self._check_mkl_vcomp(X, self._batch_size)
# precompute squared norms of data points
x_squared_norms = row_norms(X, squared=True)
# Validation set for the init
validation_indices = random_state.randint(0, n_samples, self._init_size)
X_valid = X[validation_indices]
sample_weight_valid = sample_weight[validation_indices]
# perform several inits with random subsets
best_inertia = None
for init_idx in range(self._n_init):
if self.verbose:
print(f"Init {init_idx + 1}/{self._n_init} with method {init}")
# Initialize the centers using only a fraction of the data as we
# expect n_samples to be very large when using MiniBatchKMeans.
cluster_centers = self._init_centroids(
X,
x_squared_norms=x_squared_norms,
init=init,
random_state=random_state,
init_size=self._init_size,
sample_weight=sample_weight,
)
# Compute inertia on a validation set.
_, inertia = _labels_inertia_threadpool_limit(
X_valid,
sample_weight_valid,
cluster_centers,
n_threads=self._n_threads,
)
if self.verbose:
print(f"Inertia for init {init_idx + 1}/{self._n_init}: {inertia}")
if best_inertia is None or inertia < best_inertia:
init_centers = cluster_centers
best_inertia = inertia
centers = init_centers
centers_new = np.empty_like(centers)
# Initialize counts
self._counts = np.zeros(self.n_clusters, dtype=X.dtype)
# Attributes to monitor the convergence
self._ewa_inertia = None
self._ewa_inertia_min = None
self._no_improvement = 0
# Initialize number of samples seen since last reassignment
self._n_since_last_reassign = 0
n_steps = (self.max_iter * n_samples) // self._batch_size
with _get_threadpool_controller().limit(limits=1, user_api="blas"):
# Perform the iterative optimization until convergence
for i in range(n_steps):
# Sample a minibatch from the full dataset
minibatch_indices = random_state.randint(0, n_samples, self._batch_size)
# Perform the actual update step on the minibatch data
batch_inertia = _mini_batch_step(
X=X[minibatch_indices],
sample_weight=sample_weight[minibatch_indices],
centers=centers,
centers_new=centers_new,
weight_sums=self._counts,
random_state=random_state,
random_reassign=self._random_reassign(),
reassignment_ratio=self.reassignment_ratio,
verbose=self.verbose,
n_threads=self._n_threads,
)
if self._tol > 0.0:
centers_squared_diff = np.sum((centers_new - centers) ** 2)
else:
centers_squared_diff = 0
centers, centers_new = centers_new, centers
# Monitor convergence and do early stopping if necessary
if self._mini_batch_convergence(
i, n_steps, n_samples, centers_squared_diff, batch_inertia
):
break
self.cluster_centers_ = centers
self._n_features_out = self.cluster_centers_.shape[0]
self.n_steps_ = i + 1
self.n_iter_ = int(np.ceil(((i + 1) * self._batch_size) / n_samples))
if self.compute_labels:
self.labels_, self.inertia_ = _labels_inertia_threadpool_limit(
X,
sample_weight,
self.cluster_centers_,
n_threads=self._n_threads,
)
else:
self.inertia_ = self._ewa_inertia * n_samples
return self
@_fit_context(prefer_skip_nested_validation=True)
def partial_fit(self, X, y=None, sample_weight=None):
"""Update k means estimate on a single mini-batch X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data
will be converted to C ordering, which will cause a memory copy
if the given data is not C-contiguous.
If a sparse matrix is passed, a copy will be made if it's not in
CSR format.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations
are assigned equal weight. `sample_weight` is not used during
initialization if `init` is a callable or a user provided array.
Returns
-------
self : object
Return updated estimator.
"""
has_centers = hasattr(self, "cluster_centers_")
X = validate_data(
self,
X,
accept_sparse="csr",
dtype=[np.float64, np.float32],
order="C",
accept_large_sparse=False,
reset=not has_centers,
)
self._random_state = getattr(
self, "_random_state", check_random_state(self.random_state)
)
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
self.n_steps_ = getattr(self, "n_steps_", 0)
# precompute squared norms of data points
x_squared_norms = row_norms(X, squared=True)
if not has_centers:
# this instance has not been fitted yet (fit or partial_fit)
self._check_params_vs_input(X)
self._n_threads = _openmp_effective_n_threads()
# Validate init array
init = self.init
if _is_arraylike_not_scalar(init):
init = check_array(init, dtype=X.dtype, copy=True, order="C")
self._validate_center_shape(X, init)
self._check_mkl_vcomp(X, X.shape[0])
# initialize the cluster centers
self.cluster_centers_ = self._init_centroids(
X,
x_squared_norms=x_squared_norms,
init=init,
random_state=self._random_state,
init_size=self._init_size,
sample_weight=sample_weight,
)
# Initialize counts
self._counts = np.zeros(self.n_clusters, dtype=X.dtype)
# Initialize number of samples seen since last reassignment
self._n_since_last_reassign = 0
with _get_threadpool_controller().limit(limits=1, user_api="blas"):
_mini_batch_step(
X,
sample_weight=sample_weight,
centers=self.cluster_centers_,
centers_new=self.cluster_centers_,
weight_sums=self._counts,
random_state=self._random_state,
random_reassign=self._random_reassign(),
reassignment_ratio=self.reassignment_ratio,
verbose=self.verbose,
n_threads=self._n_threads,
)
if self.compute_labels:
self.labels_, self.inertia_ = _labels_inertia_threadpool_limit(
X,
sample_weight,
self.cluster_centers_,
n_threads=self._n_threads,
)
self.n_steps_ += 1
self._n_features_out = self.cluster_centers_.shape[0]
return self
| MiniBatchKMeans |
python | django-import-export__django-import-export | tests/core/migrations/0007_auto_20180628_0411.py | {
"start": 109,
"end": 1622
} | class ____(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("core", "0006_auto_20171130_0147"),
]
operations = [
migrations.CreateModel(
name="Person",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
],
),
migrations.CreateModel(
name="Role",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"user",
models.OneToOneField(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.AddField(
model_name="person",
name="role",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="core.Role"
),
),
]
| Migration |
python | dagster-io__dagster | python_modules/dagster/dagster/_vendored/dateutil/rrule.py | {
"start": 9109,
"end": 42829
} | class ____(rrulebase):
"""
That's the base of the rrule operation. It accepts all the keywords
defined in the RFC as its constructor parameters (except byday,
which was renamed to byweekday) and more. The constructor prototype is::
rrule(freq)
Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
or SECONDLY.
.. note::
Per RFC section 3.3.10, recurrence instances falling on invalid dates
and times are ignored rather than coerced:
Recurrence rules may generate recurrence instances with an invalid
date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM
on a day where the local time is moved forward by an hour at 1:00
AM). Such recurrence instances MUST be ignored and MUST NOT be
counted as part of the recurrence set.
This can lead to possibly surprising behavior when, for example, the
start date occurs at the end of the month:
>>> from dateutil.rrule import rrule, MONTHLY
>>> from datetime import datetime
>>> start_date = datetime(2014, 12, 31)
>>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date))
... # doctest: +NORMALIZE_WHITESPACE
[datetime.datetime(2014, 12, 31, 0, 0),
datetime.datetime(2015, 1, 31, 0, 0),
datetime.datetime(2015, 3, 31, 0, 0),
datetime.datetime(2015, 5, 31, 0, 0)]
Additionally, it supports the following keyword arguments:
:param dtstart:
The recurrence start. Besides being the base for the recurrence,
missing parameters in the final recurrence instances will also be
extracted from this date. If not given, datetime.now() will be used
instead.
:param interval:
The interval between each freq iteration. For example, when using
YEARLY, an interval of 2 means once every two years, but with HOURLY,
it means once every two hours. The default interval is 1.
:param wkst:
The week start day. Must be one of the MO, TU, WE constants, or an
integer, specifying the first day of the week. This will affect
recurrences based on weekly periods. The default week start is got
from calendar.firstweekday(), and may be modified by
calendar.setfirstweekday().
:param count:
If given, this determines how many occurrences will be generated.
.. note::
As of version 2.5.0, the use of the keyword ``until`` in conjunction
with ``count`` is deprecated, to make sure ``dateutil`` is fully
compliant with `RFC-5545 Sec. 3.3.10 <https://tools.ietf.org/
html/rfc5545#section-3.3.10>`_. Therefore, ``until`` and ``count``
**must not** occur in the same call to ``rrule``.
:param until:
If given, this must be a datetime instance specifying the upper-bound
limit of the recurrence. The last recurrence in the rule is the greatest
datetime that is less than or equal to the value specified in the
``until`` parameter.
.. note::
As of version 2.5.0, the use of the keyword ``until`` in conjunction
with ``count`` is deprecated, to make sure ``dateutil`` is fully
compliant with `RFC-5545 Sec. 3.3.10 <https://tools.ietf.org/
html/rfc5545#section-3.3.10>`_. Therefore, ``until`` and ``count``
**must not** occur in the same call to ``rrule``.
:param bysetpos:
If given, it must be either an integer, or a sequence of integers,
positive or negative. Each given integer will specify an occurrence
number, corresponding to the nth occurrence of the rule inside the
frequency period. For example, a bysetpos of -1 if combined with a
MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will
result in the last work day of every month.
:param bymonth:
If given, it must be either an integer, or a sequence of integers,
meaning the months to apply the recurrence to.
:param bymonthday:
If given, it must be either an integer, or a sequence of integers,
meaning the month days to apply the recurrence to.
:param byyearday:
If given, it must be either an integer, or a sequence of integers,
meaning the year days to apply the recurrence to.
:param byeaster:
If given, it must be either an integer, or a sequence of integers,
positive or negative. Each integer will define an offset from the
Easter Sunday. Passing the offset 0 to byeaster will yield the Easter
Sunday itself. This is an extension to the RFC specification.
:param byweekno:
If given, it must be either an integer, or a sequence of integers,
meaning the week numbers to apply the recurrence to. Week numbers
have the meaning described in ISO8601, that is, the first week of
the year is that containing at least four days of the new year.
:param byweekday:
If given, it must be either an integer (0 == MO), a sequence of
integers, one of the weekday constants (MO, TU, etc), or a sequence
of these constants. When given, these variables will define the
weekdays where the recurrence will be applied. It's also possible to
use an argument n for the weekday instances, which will mean the nth
occurrence of this weekday in the period. For example, with MONTHLY,
or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the
first friday of the month where the recurrence happens. Notice that in
the RFC documentation, this is specified as BYDAY, but was renamed to
avoid the ambiguity of that keyword.
:param byhour:
If given, it must be either an integer, or a sequence of integers,
meaning the hours to apply the recurrence to.
:param byminute:
If given, it must be either an integer, or a sequence of integers,
meaning the minutes to apply the recurrence to.
:param bysecond:
If given, it must be either an integer, or a sequence of integers,
meaning the seconds to apply the recurrence to.
:param cache:
If given, it must be a boolean value specifying to enable or disable
caching of results. If you will use the same rrule instance multiple
times, enabling caching will improve the performance considerably.
"""
def __init__(self, freq, dtstart=None,
interval=1, wkst=None, count=None, until=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None,
byhour=None, byminute=None, bysecond=None,
cache=False):
super(rrule, self).__init__(cache)
global easter
if not dtstart:
if until and until.tzinfo:
dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0)
else:
dtstart = datetime.datetime.now().replace(microsecond=0)
elif not isinstance(dtstart, datetime.datetime):
dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
else:
dtstart = dtstart.replace(microsecond=0)
self._dtstart = dtstart
self._tzinfo = dtstart.tzinfo
self._freq = freq
self._interval = interval
self._count = count
# Cache the original byxxx rules, if they are provided, as the _byxxx
# attributes do not necessarily map to the inputs, and this can be
# a problem in generating the strings. Only store things if they've
# been supplied (the string retrieval will just use .get())
self._original_rule = {}
if until and not isinstance(until, datetime.datetime):
until = datetime.datetime.fromordinal(until.toordinal())
self._until = until
if self._dtstart and self._until:
if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None):
# According to RFC5545 Section 3.3.10:
# https://tools.ietf.org/html/rfc5545#section-3.3.10
#
# > If the "DTSTART" property is specified as a date with UTC
# > time or a date with local time and time zone reference,
# > then the UNTIL rule part MUST be specified as a date with
# > UTC time.
raise ValueError(
'RRULE UNTIL values must be specified in UTC when DTSTART '
'is timezone-aware'
)
if count is not None and until:
warn("Using both 'count' and 'until' is inconsistent with RFC 5545"
" and has been deprecated in dateutil. Future versions will "
"raise an error.", DeprecationWarning)
if wkst is None:
self._wkst = calendar.firstweekday()
elif isinstance(wkst, integer_types):
self._wkst = wkst
else:
self._wkst = wkst.weekday
if bysetpos is None:
self._bysetpos = None
elif isinstance(bysetpos, integer_types):
if bysetpos == 0 or not (-366 <= bysetpos <= 366):
raise ValueError("bysetpos must be between 1 and 366, "
"or between -366 and -1")
self._bysetpos = (bysetpos,)
else:
self._bysetpos = tuple(bysetpos)
for pos in self._bysetpos:
if pos == 0 or not (-366 <= pos <= 366):
raise ValueError("bysetpos must be between 1 and 366, "
"or between -366 and -1")
if self._bysetpos:
self._original_rule['bysetpos'] = self._bysetpos
if (byweekno is None and byyearday is None and bymonthday is None and
byweekday is None and byeaster is None):
if freq == YEARLY:
if bymonth is None:
bymonth = dtstart.month
self._original_rule['bymonth'] = None
bymonthday = dtstart.day
self._original_rule['bymonthday'] = None
elif freq == MONTHLY:
bymonthday = dtstart.day
self._original_rule['bymonthday'] = None
elif freq == WEEKLY:
byweekday = dtstart.weekday()
self._original_rule['byweekday'] = None
# bymonth
if bymonth is None:
self._bymonth = None
else:
if isinstance(bymonth, integer_types):
bymonth = (bymonth,)
self._bymonth = tuple(sorted(set(bymonth)))
if 'bymonth' not in self._original_rule:
self._original_rule['bymonth'] = self._bymonth
# byyearday
if byyearday is None:
self._byyearday = None
else:
if isinstance(byyearday, integer_types):
byyearday = (byyearday,)
self._byyearday = tuple(sorted(set(byyearday)))
self._original_rule['byyearday'] = self._byyearday
# byeaster
if byeaster is not None:
if not easter:
# CHANGED IN VENDORED VERSION
from . import easter
if isinstance(byeaster, integer_types):
self._byeaster = (byeaster,)
else:
self._byeaster = tuple(sorted(byeaster))
self._original_rule['byeaster'] = self._byeaster
else:
self._byeaster = None
# bymonthday
if bymonthday is None:
self._bymonthday = ()
self._bynmonthday = ()
else:
if isinstance(bymonthday, integer_types):
bymonthday = (bymonthday,)
bymonthday = set(bymonthday) # Ensure it's unique
self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0))
self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0))
# Storing positive numbers first, then negative numbers
if 'bymonthday' not in self._original_rule:
self._original_rule['bymonthday'] = tuple(
itertools.chain(self._bymonthday, self._bynmonthday))
# byweekno
if byweekno is None:
self._byweekno = None
else:
if isinstance(byweekno, integer_types):
byweekno = (byweekno,)
self._byweekno = tuple(sorted(set(byweekno)))
self._original_rule['byweekno'] = self._byweekno
# byweekday / bynweekday
if byweekday is None:
self._byweekday = None
self._bynweekday = None
else:
# If it's one of the valid non-sequence types, convert to a
# single-element sequence before the iterator that builds the
# byweekday set.
if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"):
byweekday = (byweekday,)
self._byweekday = set()
self._bynweekday = set()
for wday in byweekday:
if isinstance(wday, integer_types):
self._byweekday.add(wday)
elif not wday.n or freq > MONTHLY:
self._byweekday.add(wday.weekday)
else:
self._bynweekday.add((wday.weekday, wday.n))
if not self._byweekday:
self._byweekday = None
elif not self._bynweekday:
self._bynweekday = None
if self._byweekday is not None:
self._byweekday = tuple(sorted(self._byweekday))
orig_byweekday = [weekday(x) for x in self._byweekday]
else:
orig_byweekday = ()
if self._bynweekday is not None:
self._bynweekday = tuple(sorted(self._bynweekday))
orig_bynweekday = [weekday(*x) for x in self._bynweekday]
else:
orig_bynweekday = ()
if 'byweekday' not in self._original_rule:
self._original_rule['byweekday'] = tuple(itertools.chain(
orig_byweekday, orig_bynweekday))
# byhour
if byhour is None:
if freq < HOURLY:
self._byhour = {dtstart.hour}
else:
self._byhour = None
else:
if isinstance(byhour, integer_types):
byhour = (byhour,)
if freq == HOURLY:
self._byhour = self.__construct_byset(start=dtstart.hour,
byxxx=byhour,
base=24)
else:
self._byhour = set(byhour)
self._byhour = tuple(sorted(self._byhour))
self._original_rule['byhour'] = self._byhour
# byminute
if byminute is None:
if freq < MINUTELY:
self._byminute = {dtstart.minute}
else:
self._byminute = None
else:
if isinstance(byminute, integer_types):
byminute = (byminute,)
if freq == MINUTELY:
self._byminute = self.__construct_byset(start=dtstart.minute,
byxxx=byminute,
base=60)
else:
self._byminute = set(byminute)
self._byminute = tuple(sorted(self._byminute))
self._original_rule['byminute'] = self._byminute
# bysecond
if bysecond is None:
if freq < SECONDLY:
self._bysecond = ((dtstart.second,))
else:
self._bysecond = None
else:
if isinstance(bysecond, integer_types):
bysecond = (bysecond,)
self._bysecond = set(bysecond)
if freq == SECONDLY:
self._bysecond = self.__construct_byset(start=dtstart.second,
byxxx=bysecond,
base=60)
else:
self._bysecond = set(bysecond)
self._bysecond = tuple(sorted(self._bysecond))
self._original_rule['bysecond'] = self._bysecond
if self._freq >= HOURLY:
self._timeset = None
else:
self._timeset = []
for hour in self._byhour:
for minute in self._byminute:
for second in self._bysecond:
self._timeset.append(
datetime.time(hour, minute, second,
tzinfo=self._tzinfo))
self._timeset.sort()
self._timeset = tuple(self._timeset)
def __str__(self):
"""
Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER.
"""
output = []
h, m, s = [None] * 3
if self._dtstart:
output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S'))
h, m, s = self._dtstart.timetuple()[3:6]
parts = ['FREQ=' + FREQNAMES[self._freq]]
if self._interval != 1:
parts.append('INTERVAL=' + str(self._interval))
if self._wkst:
parts.append('WKST=' + repr(weekday(self._wkst))[0:2])
if self._count is not None:
parts.append('COUNT=' + str(self._count))
if self._until:
parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S'))
if self._original_rule.get('byweekday') is not None:
# The str() method on weekday objects doesn't generate
# RFC5545-compliant strings, so we should modify that.
original_rule = dict(self._original_rule)
wday_strings = []
for wday in original_rule['byweekday']:
if wday.n:
wday_strings.append('{n:+d}{wday}'.format(
n=wday.n,
wday=repr(wday)[0:2]))
else:
wday_strings.append(repr(wday))
original_rule['byweekday'] = wday_strings
else:
original_rule = self._original_rule
partfmt = '{name}={vals}'
for name, key in [('BYSETPOS', 'bysetpos'),
('BYMONTH', 'bymonth'),
('BYMONTHDAY', 'bymonthday'),
('BYYEARDAY', 'byyearday'),
('BYWEEKNO', 'byweekno'),
('BYDAY', 'byweekday'),
('BYHOUR', 'byhour'),
('BYMINUTE', 'byminute'),
('BYSECOND', 'bysecond'),
('BYEASTER', 'byeaster')]:
value = original_rule.get(key)
if value:
parts.append(partfmt.format(name=name, vals=(','.join(str(v)
for v in value))))
output.append('RRULE:' + ';'.join(parts))
return '\n'.join(output)
def replace(self, **kwargs):
"""Return new rrule with same attributes except for those attributes given new
values by whichever keyword arguments are specified."""
new_kwargs = {"interval": self._interval,
"count": self._count,
"dtstart": self._dtstart,
"freq": self._freq,
"until": self._until,
"wkst": self._wkst,
"cache": False if self._cache is None else True }
new_kwargs.update(self._original_rule)
new_kwargs.update(kwargs)
return rrule(**new_kwargs)
def _iter(self):
year, month, day, hour, minute, second, weekday, yearday, _ = \
self._dtstart.timetuple()
# Some local variables to speed things up a bit
freq = self._freq
interval = self._interval
wkst = self._wkst
until = self._until
bymonth = self._bymonth
byweekno = self._byweekno
byyearday = self._byyearday
byweekday = self._byweekday
byeaster = self._byeaster
bymonthday = self._bymonthday
bynmonthday = self._bynmonthday
bysetpos = self._bysetpos
byhour = self._byhour
byminute = self._byminute
bysecond = self._bysecond
ii = _iterinfo(self)
ii.rebuild(year, month)
getdayset = {YEARLY: ii.ydayset,
MONTHLY: ii.mdayset,
WEEKLY: ii.wdayset,
DAILY: ii.ddayset,
HOURLY: ii.ddayset,
MINUTELY: ii.ddayset,
SECONDLY: ii.ddayset}[freq]
if freq < HOURLY:
timeset = self._timeset
else:
gettimeset = {HOURLY: ii.htimeset,
MINUTELY: ii.mtimeset,
SECONDLY: ii.stimeset}[freq]
if ((freq >= HOURLY and
self._byhour and hour not in self._byhour) or
(freq >= MINUTELY and
self._byminute and minute not in self._byminute) or
(freq >= SECONDLY and
self._bysecond and second not in self._bysecond)):
timeset = ()
else:
timeset = gettimeset(hour, minute, second)
total = 0
count = self._count
while True:
# Get dayset with the right frequency
dayset, start, end = getdayset(year, month, day)
# Do the "hard" work ;-)
filtered = False
for i in dayset[start:end]:
if ((bymonth and ii.mmask[i] not in bymonth) or
(byweekno and not ii.wnomask[i]) or
(byweekday and ii.wdaymask[i] not in byweekday) or
(ii.nwdaymask and not ii.nwdaymask[i]) or
(byeaster and not ii.eastermask[i]) or
((bymonthday or bynmonthday) and
ii.mdaymask[i] not in bymonthday and
ii.nmdaymask[i] not in bynmonthday) or
(byyearday and
((i < ii.yearlen and i+1 not in byyearday and
-ii.yearlen+i not in byyearday) or
(i >= ii.yearlen and i+1-ii.yearlen not in byyearday and
-ii.nextyearlen+i-ii.yearlen not in byyearday)))):
dayset[i] = None
filtered = True
# Output results
if bysetpos and timeset:
poslist = []
for pos in bysetpos:
if pos < 0:
daypos, timepos = divmod(pos, len(timeset))
else:
daypos, timepos = divmod(pos-1, len(timeset))
try:
i = [x for x in dayset[start:end]
if x is not None][daypos]
time = timeset[timepos]
except IndexError:
pass
else:
date = datetime.date.fromordinal(ii.yearordinal+i)
res = datetime.datetime.combine(date, time)
if res not in poslist:
poslist.append(res)
poslist.sort()
for res in poslist:
if until and res > until:
self._len = total
return
elif res >= self._dtstart:
if count is not None:
count -= 1
if count < 0:
self._len = total
return
total += 1
yield res
else:
for i in dayset[start:end]:
if i is not None:
date = datetime.date.fromordinal(ii.yearordinal + i)
for time in timeset:
res = datetime.datetime.combine(date, time)
if until and res > until:
self._len = total
return
elif res >= self._dtstart:
if count is not None:
count -= 1
if count < 0:
self._len = total
return
total += 1
yield res
# Handle frequency and interval
fixday = False
if freq == YEARLY:
year += interval
if year > datetime.MAXYEAR:
self._len = total
return
ii.rebuild(year, month)
elif freq == MONTHLY:
month += interval
if month > 12:
div, mod = divmod(month, 12)
month = mod
year += div
if month == 0:
month = 12
year -= 1
if year > datetime.MAXYEAR:
self._len = total
return
ii.rebuild(year, month)
elif freq == WEEKLY:
if wkst > weekday:
day += -(weekday+1+(6-wkst))+self._interval*7
else:
day += -(weekday-wkst)+self._interval*7
weekday = wkst
fixday = True
elif freq == DAILY:
day += interval
fixday = True
elif freq == HOURLY:
if filtered:
# Jump to one iteration before next day
hour += ((23-hour)//interval)*interval
if byhour:
ndays, hour = self.__mod_distance(value=hour,
byxxx=self._byhour,
base=24)
else:
ndays, hour = divmod(hour+interval, 24)
if ndays:
day += ndays
fixday = True
timeset = gettimeset(hour, minute, second)
elif freq == MINUTELY:
if filtered:
# Jump to one iteration before next day
minute += ((1439-(hour*60+minute))//interval)*interval
valid = False
rep_rate = (24*60)
for j in range(rep_rate // gcd(interval, rep_rate)):
if byminute:
nhours, minute = \
self.__mod_distance(value=minute,
byxxx=self._byminute,
base=60)
else:
nhours, minute = divmod(minute+interval, 60)
div, hour = divmod(hour+nhours, 24)
if div:
day += div
fixday = True
filtered = False
if not byhour or hour in byhour:
valid = True
break
if not valid:
raise ValueError('Invalid combination of interval and ' +
'byhour resulting in empty rule.')
timeset = gettimeset(hour, minute, second)
elif freq == SECONDLY:
if filtered:
# Jump to one iteration before next day
second += (((86399 - (hour * 3600 + minute * 60 + second))
// interval) * interval)
rep_rate = (24 * 3600)
valid = False
for j in range(0, rep_rate // gcd(interval, rep_rate)):
if bysecond:
nminutes, second = \
self.__mod_distance(value=second,
byxxx=self._bysecond,
base=60)
else:
nminutes, second = divmod(second+interval, 60)
div, minute = divmod(minute+nminutes, 60)
if div:
hour += div
div, hour = divmod(hour, 24)
if div:
day += div
fixday = True
if ((not byhour or hour in byhour) and
(not byminute or minute in byminute) and
(not bysecond or second in bysecond)):
valid = True
break
if not valid:
raise ValueError('Invalid combination of interval, ' +
'byhour and byminute resulting in empty' +
' rule.')
timeset = gettimeset(hour, minute, second)
if fixday and day > 28:
daysinmonth = calendar.monthrange(year, month)[1]
if day > daysinmonth:
while day > daysinmonth:
day -= daysinmonth
month += 1
if month == 13:
month = 1
year += 1
if year > datetime.MAXYEAR:
self._len = total
return
daysinmonth = calendar.monthrange(year, month)[1]
ii.rebuild(year, month)
def __construct_byset(self, start, byxxx, base):
"""
If a `BYXXX` sequence is passed to the constructor at the same level as
`FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some
specifications which cannot be reached given some starting conditions.
This occurs whenever the interval is not coprime with the base of a
given unit and the difference between the starting position and the
ending position is not coprime with the greatest common denominator
between the interval and the base. For example, with a FREQ of hourly
starting at 17:00 and an interval of 4, the only valid values for
BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not
coprime.
:param start:
Specifies the starting position.
:param byxxx:
An iterable containing the list of allowed values.
:param base:
The largest allowable value for the specified frequency (e.g.
24 hours, 60 minutes).
This does not preserve the type of the iterable, returning a set, since
the values should be unique and the order is irrelevant, this will
speed up later lookups.
In the event of an empty set, raises a :exception:`ValueError`, as this
results in an empty rrule.
"""
cset = set()
# Support a single byxxx value.
if isinstance(byxxx, integer_types):
byxxx = (byxxx, )
for num in byxxx:
i_gcd = gcd(self._interval, base)
# Use divmod rather than % because we need to wrap negative nums.
if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0:
cset.add(num)
if len(cset) == 0:
raise ValueError("Invalid rrule byxxx generates an empty set.")
return cset
def __mod_distance(self, value, byxxx, base):
"""
Calculates the next value in a sequence where the `FREQ` parameter is
specified along with a `BYXXX` parameter at the same "level"
(e.g. `HOURLY` specified with `BYHOUR`).
:param value:
The old value of the component.
:param byxxx:
The `BYXXX` set, which should have been generated by
`rrule._construct_byset`, or something else which checks that a
valid rule is present.
:param base:
The largest allowable value for the specified frequency (e.g.
24 hours, 60 minutes).
If a valid value is not found after `base` iterations (the maximum
number before the sequence would start to repeat), this raises a
:exception:`ValueError`, as no valid values were found.
This returns a tuple of `divmod(n*interval, base)`, where `n` is the
smallest number of `interval` repetitions until the next specified
value in `byxxx` is found.
"""
accumulator = 0
for ii in range(1, base + 1):
# Using divmod() over % to account for negative intervals
div, value = divmod(value + self._interval, base)
accumulator += div
if value in byxxx:
return (accumulator, value)
| rrule |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/subscription.py | {
"start": 793,
"end": 1067
} | class ____(graphene.Union):
class Meta:
types = (
GraphenePipelineRunLogsSubscriptionSuccess,
GraphenePipelineRunLogsSubscriptionFailure,
)
name = "PipelineRunLogsSubscriptionPayload"
| GraphenePipelineRunLogsSubscriptionPayload |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/models.py | {
"start": 1009,
"end": 1530
} | class ____:
"""The result of a QA check
Attributes:
check (Check): The QA check that was run
connector (Connector): The connector that was checked
status (CheckStatus): The status of the check
message (str): A message explaining the result of the check
"""
check: Check
connector: Connector
status: CheckStatus
message: str
def __repr__(self) -> str:
return f"{self.connector} - {self.status.value} - {self.check.name}: {self.message}."
| CheckResult |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 11478,
"end": 11549
} | class ____(_NumcodecsChecksumCodec, codec_name="crc32c"):
pass
| CRC32C |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 35713,
"end": 36107
} | class ____(torch.utils.data.Sampler):
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
def __iter__(self):
for x in torch.randperm(len(self.dataset)).split(self.batch_size):
yield x.tolist()
def __len__(self):
return int(math.ceil(len(self.dataset) / float(self.batch_size)))
| BulkLoadingSampler |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 36119,
"end": 36565
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["create"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[ConnectionBody], Field(description="A list of entities to be created.", title="Entities")
]
action_on_existence: BulkActionOnExistence | None = "fail"
| BulkCreateActionConnectionBody |
python | walkccc__LeetCode | solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py | {
"start": 0,
"end": 279
} | class ____:
def minimumTime(self, s: str) -> int:
n = len(s)
ans = n
left = 0 # the minimum time to remove the illegal cars so far
for i, c in enumerate(s):
left = min(left + int(c) * 2, i + 1)
ans = min(ans, left + n - 1 - i)
return ans
| Solution |
python | pallets__flask | tests/test_helpers.py | {
"start": 9596,
"end": 11224
} | class ____:
@pytest.mark.parametrize(
("debug", "expect"),
[
("", False),
("0", False),
("False", False),
("No", False),
("True", True),
],
)
def test_get_debug_flag(self, monkeypatch, debug, expect):
monkeypatch.setenv("FLASK_DEBUG", debug)
assert get_debug_flag() == expect
def test_make_response(self):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.helpers.make_response()
assert rv.status_code == 200
assert rv.mimetype == "text/html"
rv = flask.helpers.make_response("Hello")
assert rv.status_code == 200
assert rv.data == b"Hello"
assert rv.mimetype == "text/html"
@pytest.mark.parametrize("mode", ("r", "rb", "rt"))
def test_open_resource(mode):
app = flask.Flask(__name__)
with app.open_resource("static/index.html", mode) as f:
assert "<h1>Hello World!</h1>" in str(f.read())
@pytest.mark.parametrize("mode", ("w", "x", "a", "r+"))
def test_open_resource_exceptions(mode):
app = flask.Flask(__name__)
with pytest.raises(ValueError):
app.open_resource("static/index.html", mode)
@pytest.mark.parametrize("encoding", ("utf-8", "utf-16-le"))
def test_open_resource_with_encoding(tmp_path, encoding):
app = flask.Flask(__name__, root_path=os.fspath(tmp_path))
(tmp_path / "test").write_text("test", encoding=encoding)
with app.open_resource("test", mode="rt", encoding=encoding) as f:
assert f.read() == "test"
| TestHelpers |
python | spack__spack | var/spack/test_repos/spack_repo/find/packages/a0/package.py | {
"start": 217,
"end": 317
} | class ____(Package):
version("1.2")
version("1.1")
depends_on("b0")
depends_on("c0")
| A0 |
python | allegroai__clearml | examples/hyperdatasets/create_qa_entries.py | {
"start": 1134,
"end": 1574
} | class ____(DataSubEntry):
def __init__(self, name: str, text: str, role: str, preview_source: Optional[str] = None):
super().__init__(
name=name,
source=f"text://{uuid.uuid4().hex}", # or hash of text sha256(text)
preview_source=preview_source,
metadata={"text": text, "role": role},
)
# ClearML data entry aggregating the question/answer into a single frame
| QADataSubEntry |
python | sympy__sympy | sympy/plotting/backends/matplotlibbackend/matplotlib.py | {
"start": 1423,
"end": 12548
} | class ____(base_backend.Plot):
""" This class implements the functionalities to use Matplotlib with SymPy
plotting functions.
"""
def __init__(self, *series, **kwargs):
super().__init__(*series, **kwargs)
self.matplotlib = import_module('matplotlib',
import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
min_module_version='1.1.0', catch=(RuntimeError,))
self.plt = self.matplotlib.pyplot
self.cm = self.matplotlib.cm
self.LineCollection = self.matplotlib.collections.LineCollection
self.aspect = kwargs.get('aspect_ratio', 'auto')
if self.aspect != 'auto':
self.aspect = float(self.aspect[1]) / self.aspect[0]
# PlotGrid can provide its figure and axes to be populated with
# the data from the series.
self._plotgrid_fig = kwargs.pop("fig", None)
self._plotgrid_ax = kwargs.pop("ax", None)
def _create_figure(self):
def set_spines(ax):
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if self._plotgrid_fig is not None:
self.fig = self._plotgrid_fig
self.ax = self._plotgrid_ax
if not any(s.is_3D for s in self._series):
set_spines(self.ax)
else:
self.fig = self.plt.figure(figsize=self.size)
if any(s.is_3D for s in self._series):
self.ax = self.fig.add_subplot(1, 1, 1, projection="3d")
else:
self.ax = self.fig.add_subplot(1, 1, 1)
set_spines(self.ax)
@staticmethod
def get_segments(x, y, z=None):
""" Convert two list of coordinates to a list of segments to be used
with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`.
Parameters
==========
x : list
List of x-coordinates
y : list
List of y-coordinates
z : list
List of z-coordinates for a 3D line.
"""
np = import_module('numpy')
if z is not None:
dim = 3
points = (x, y, z)
else:
dim = 2
points = (x, y)
points = np.ma.array(points).T.reshape(-1, 1, dim)
return np.ma.concatenate([points[:-1], points[1:]], axis=1)
def _process_series(self, series, ax):
np = import_module('numpy')
mpl_toolkits = import_module(
'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']})
# XXX Workaround for matplotlib issue
# https://github.com/matplotlib/matplotlib/issues/17130
xlims, ylims, zlims = [], [], []
for s in series:
# Create the collections
if s.is_2Dline:
if s.is_parametric:
x, y, param = s.get_data()
else:
x, y = s.get_data()
if (isinstance(s.line_color, (int, float)) or
callable(s.line_color)):
segments = self.get_segments(x, y)
collection = self.LineCollection(segments)
collection.set_array(s.get_color_array())
ax.add_collection(collection)
else:
lbl = _str_or_latex(s.label)
line, = ax.plot(x, y, label=lbl, color=s.line_color)
elif s.is_contour:
ax.contour(*s.get_data())
elif s.is_3Dline:
x, y, z, param = s.get_data()
if (isinstance(s.line_color, (int, float)) or
callable(s.line_color)):
art3d = mpl_toolkits.mplot3d.art3d
segments = self.get_segments(x, y, z)
collection = art3d.Line3DCollection(segments)
collection.set_array(s.get_color_array())
ax.add_collection(collection)
else:
lbl = _str_or_latex(s.label)
ax.plot(x, y, z, label=lbl, color=s.line_color)
xlims.append(s._xlim)
ylims.append(s._ylim)
zlims.append(s._zlim)
elif s.is_3Dsurface:
if s.is_parametric:
x, y, z, u, v = s.get_data()
else:
x, y, z = s.get_data()
collection = ax.plot_surface(x, y, z,
cmap=getattr(self.cm, 'viridis', self.cm.jet),
rstride=1, cstride=1, linewidth=0.1)
if isinstance(s.surface_color, (float, int, Callable)):
color_array = s.get_color_array()
color_array = color_array.reshape(color_array.size)
collection.set_array(color_array)
else:
collection.set_color(s.surface_color)
xlims.append(s._xlim)
ylims.append(s._ylim)
zlims.append(s._zlim)
elif s.is_implicit:
points = s.get_data()
if len(points) == 2:
# interval math plotting
x, y = _matplotlib_list(points[0])
ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
else:
# use contourf or contour depending on whether it is
# an inequality or equality.
# XXX: ``contour`` plots multiple lines. Should be fixed.
ListedColormap = self.matplotlib.colors.ListedColormap
colormap = ListedColormap(["white", s.line_color])
xarray, yarray, zarray, plot_type = points
if plot_type == 'contour':
ax.contour(xarray, yarray, zarray, cmap=colormap)
else:
ax.contourf(xarray, yarray, zarray, cmap=colormap)
elif s.is_generic:
if s.type == "markers":
# s.rendering_kw["color"] = s.line_color
ax.plot(*s.args, **s.rendering_kw)
elif s.type == "annotations":
ax.annotate(*s.args, **s.rendering_kw)
elif s.type == "fill":
# s.rendering_kw["color"] = s.line_color
ax.fill_between(*s.args, **s.rendering_kw)
elif s.type == "rectangles":
# s.rendering_kw["color"] = s.line_color
ax.add_patch(
self.matplotlib.patches.Rectangle(
*s.args, **s.rendering_kw))
else:
raise NotImplementedError(
'{} is not supported in the SymPy plotting module '
'with matplotlib backend. Please report this issue.'
.format(ax))
Axes3D = mpl_toolkits.mplot3d.Axes3D
if not isinstance(ax, Axes3D):
ax.autoscale_view(
scalex=ax.get_autoscalex_on(),
scaley=ax.get_autoscaley_on())
else:
# XXX Workaround for matplotlib issue
# https://github.com/matplotlib/matplotlib/issues/17130
if xlims:
xlims = np.array(xlims)
xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1]))
ax.set_xlim(xlim)
else:
ax.set_xlim([0, 1])
if ylims:
ylims = np.array(ylims)
ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1]))
ax.set_ylim(ylim)
else:
ax.set_ylim([0, 1])
if zlims:
zlims = np.array(zlims)
zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1]))
ax.set_zlim(zlim)
else:
ax.set_zlim([0, 1])
# Set global options.
# TODO The 3D stuff
# XXX The order of those is important.
if self.xscale and not isinstance(ax, Axes3D):
ax.set_xscale(self.xscale)
if self.yscale and not isinstance(ax, Axes3D):
ax.set_yscale(self.yscale)
if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check
ax.set_autoscale_on(self.autoscale)
if self.axis_center:
val = self.axis_center
if isinstance(ax, Axes3D):
pass
elif val == 'center':
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
elif val == 'auto':
xl, xh = ax.get_xlim()
yl, yh = ax.get_ylim()
pos_left = ('data', 0) if xl*xh <= 0 else 'center'
pos_bottom = ('data', 0) if yl*yh <= 0 else 'center'
ax.spines['left'].set_position(pos_left)
ax.spines['bottom'].set_position(pos_bottom)
else:
ax.spines['left'].set_position(('data', val[0]))
ax.spines['bottom'].set_position(('data', val[1]))
if not self.axis:
ax.set_axis_off()
if self.legend:
if ax.legend():
ax.legend_.set_visible(self.legend)
if self.margin:
ax.set_xmargin(self.margin)
ax.set_ymargin(self.margin)
if self.title:
ax.set_title(self.title)
if self.xlabel:
xlbl = _str_or_latex(self.xlabel)
ax.set_xlabel(xlbl, position=(1, 0))
if self.ylabel:
ylbl = _str_or_latex(self.ylabel)
ax.set_ylabel(ylbl, position=(0, 1))
if isinstance(ax, Axes3D) and self.zlabel:
zlbl = _str_or_latex(self.zlabel)
ax.set_zlabel(zlbl, position=(0, 1))
# xlim and ylim should always be set at last so that plot limits
# doesn't get altered during the process.
if self.xlim:
ax.set_xlim(self.xlim)
if self.ylim:
ax.set_ylim(self.ylim)
self.ax.set_aspect(self.aspect)
def process_series(self):
"""
Iterates over every ``Plot`` object and further calls
_process_series()
"""
self._create_figure()
self._process_series(self._series, self.ax)
def show(self):
self.process_series()
#TODO after fixing https://github.com/ipython/ipython/issues/1255
# you can uncomment the next line and remove the pyplot.show() call
#self.fig.show()
if base_backend._show:
self.fig.tight_layout()
self.plt.show()
else:
self.close()
def save(self, path):
self.process_series()
self.fig.savefig(path)
def close(self):
self.plt.close(self.fig)
| MatplotlibBackend |
python | Textualize__textual | tests/input/test_input_messages.py | {
"start": 171,
"end": 2706
} | class ____(App[None]):
def __init__(self, initial: str | None = None) -> None:
super().__init__()
self.messages: list[str] = []
self._initial = initial
def compose(self) -> ComposeResult:
if self._initial:
yield Input(self._initial)
else:
yield Input()
@on(Input.Changed)
@on(Input.Submitted)
def log_message(self, event: Input.Submitted | Input.Changed) -> None:
assert event.control == event.input
self.messages.append(event.__class__.__name__)
async def test_no_startup_messages():
"""An input with no initial value should have no initial messages."""
async with InputApp().run_test() as pilot:
assert pilot.app.messages == []
async def test_startup_messages_with_initial_value():
"""An input with an initial value should send a changed event."""
async with InputApp("Hello, World!").run_test() as pilot:
assert pilot.app.messages == ["Changed"]
async def test_typing_from_empty_causes_changed():
"""An input with no initial value should send messages when entering text."""
input_text = "Hello, World!"
async with InputApp().run_test() as pilot:
await pilot.press(*input_text)
assert pilot.app.messages == ["Changed"] * len(input_text)
async def test_typing_from_pre_populated_causes_changed():
"""An input with initial value should send messages when entering text after an initial message."""
input_text = "Hello, World!"
async with InputApp(input_text).run_test() as pilot:
await pilot.press(*input_text)
assert pilot.app.messages == ["Changed"] + (["Changed"] * len(input_text))
async def test_submit_empty_input():
"""Pressing enter on an empty input should send a submitted event."""
async with InputApp().run_test() as pilot:
await pilot.press("enter")
assert pilot.app.messages == ["Submitted"]
async def test_submit_pre_populated_input():
"""Pressing enter on a pre-populated input should send a changed then submitted event."""
async with InputApp("The owls are not what they seem").run_test() as pilot:
await pilot.press("enter")
assert pilot.app.messages == ["Changed", "Submitted"]
async def test_paste_event_impact():
"""A paste event should result in a changed event."""
async with InputApp().run_test() as pilot:
await pilot.app._post_message(Paste("Hello, World"))
await pilot.pause()
assert pilot.app.messages == ["Changed"]
| InputApp |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 808109,
"end": 808550
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("name", "type", "url")
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
type = sgqlc.types.Field(
sgqlc.types.non_null(MigrationSourceType), graphql_name="type"
)
url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="url")
| MigrationSource |
python | numba__numba | numba/parfors/parfor_lowering.py | {
"start": 17725,
"end": 87652
} | class ____(InternalError):
def __init__(self, inst):
super().__init__(f"Unknown reduce instruction node: {inst}")
def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info):
"""Lower trivial inplace-binop reduction.
"""
for inst in reduce_info.redvar_info.reduce_nodes:
# Var assigns to Var?
if _lower_var_to_var_assign(lowerer, inst):
pass
# Is inplace-binop for the reduction?
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "inplace_binop"):
fn = inst.value.fn
redvar_result = _emit_binop_reduce_call(
fn, lowerer, thread_count_var, reduce_info,
)
lowerer.storevar(redvar_result, name=inst.target.name)
# Is binop for the reduction?
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "binop"):
fn = inst.value.fn
redvar_result = _emit_binop_reduce_call(
fn, lowerer, thread_count_var, reduce_info,
)
lowerer.storevar(redvar_result, name=inst.target.name)
# Otherwise?
else:
raise ParforsUnexpectedReduceNodeError(inst)
# XXX: This seems like a hack to stop the loop with this condition.
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
reduce_info.redvar_name):
break
if config.DEBUG_ARRAY_OPT_RUNTIME:
varname = reduce_info.redvar_name
lowerer.print_variable(
f"{parfor.loc}: parfor {fn.__name__} reduction {varname} =",
varname,
)
def _lower_non_trivial_reduce(parfor, lowerer, thread_count_var, reduce_info):
"""Lower non-trivial reduction such as call to `functools.reduce()`.
"""
init_name = f"{reduce_info.redvar_name}#init"
# The init_name variable is not defined at this point.
lowerer.fndesc.typemap.setdefault(init_name, reduce_info.redvar_typ)
# Emit a sequence of the reduction operation for each intermediate result
# of each thread.
num_thread_llval = lowerer.loadvar(thread_count_var.name)
with cgutils.for_range(lowerer.builder, num_thread_llval) as loop:
tid = loop.index
for inst in reduce_info.redvar_info.reduce_nodes:
# Var assigns to Var?
if _lower_var_to_var_assign(lowerer, inst):
pass
# The reduction operation?
elif (isinstance(inst, ir.Assign)
and any(var.name == init_name for var in inst.list_vars())):
elem = _emit_getitem_call(tid, lowerer, reduce_info)
lowerer.storevar(elem, init_name)
lowerer.lower_inst(inst)
# Otherwise?
else:
raise ParforsUnexpectedReduceNodeError(inst)
# XXX: This seems like a hack to stop the loop with this condition.
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
reduce_info.redvar_name):
break
if config.DEBUG_ARRAY_OPT_RUNTIME:
varname = reduce_info.redvar_name
lowerer.print_variable(
f"{parfor.loc}: parfor non-trivial reduction {varname} =",
varname,
)
def _lower_var_to_var_assign(lowerer, inst):
"""Lower Var->Var assignment.
Returns True if-and-only-if `inst` is a Var->Var assignment.
"""
if isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Var):
loaded = lowerer.loadvar(inst.value.name)
lowerer.storevar(loaded, name=inst.target.name)
return True
return False
def _emit_getitem_call(idx, lowerer, reduce_info):
"""Emit call to ``redarr_var[idx]``
"""
def reducer_getitem(redarr, index):
return redarr[index]
builder = lowerer.builder
ctx = lowerer.context
redarr_typ = reduce_info.redarr_typ
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
args = (arg_arr, idx)
sig = signature(reduce_info.redvar_typ, redarr_typ, types.intp)
elem = ctx.compile_internal(builder, reducer_getitem, sig, args)
return elem
def _emit_binop_reduce_call(binop, lowerer, thread_count_var, reduce_info):
"""Emit call to the ``binop`` for the reduction variable.
"""
def reduction_add(thread_count, redarr, init):
c = init
for i in range(thread_count):
c += redarr[i]
return c
def reduction_mul(thread_count, redarr, init):
c = init
for i in range(thread_count):
c *= redarr[i]
return c
kernel = {
operator.iadd: reduction_add,
operator.isub: reduction_add,
operator.add: reduction_add,
operator.sub: reduction_add,
operator.imul: reduction_mul,
operator.ifloordiv: reduction_mul,
operator.itruediv: reduction_mul,
operator.mul: reduction_mul,
operator.floordiv: reduction_mul,
operator.truediv: reduction_mul,
}[binop]
ctx = lowerer.context
builder = lowerer.builder
redarr_typ = reduce_info.redarr_typ
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
if config.DEBUG_ARRAY_OPT_RUNTIME:
init_var = reduce_info.redarr_var.scope.get(reduce_info.redvar_name)
res_print = ir.Print(
args=[reduce_info.redarr_var, init_var], vararg=None,
loc=lowerer.loc,
)
typemap = lowerer.fndesc.typemap
lowerer.fndesc.calltypes[res_print] = signature(
types.none, typemap[reduce_info.redarr_var.name],
typemap[init_var.name],
)
lowerer.lower_inst(res_print)
arg_thread_count = lowerer.loadvar(thread_count_var.name)
args = (arg_thread_count, arg_arr, reduce_info.init_val)
sig = signature(
reduce_info.redvar_typ, types.uintp, redarr_typ, reduce_info.redvar_typ,
)
redvar_result = ctx.compile_internal(builder, kernel, sig, args)
return redvar_result
def _is_right_op_and_rhs_is_init(inst, redvar_name, op):
"""Is ``inst`` an inplace-binop and the RHS is the reduction init?
"""
if not isinstance(inst, ir.Assign):
return False
rhs = inst.value
if not isinstance(rhs, ir.Expr):
return False
if rhs.op != op:
return False
if rhs.rhs.name != f"{redvar_name}#init":
return False
return True
def _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, redvar_name):
"""Fix reduction variable name mismatch due to SSA.
"""
# Only process reduction statements post-gufunc execution
# until we see an assignment with a left-hand side to the
# reduction variable's name. This fixes problems with
# cases where there are multiple assignments to the
# reduction variable in the parfor.
scope = parfor.init_block.scope
if isinstance(inst, ir.Assign):
try:
reduction_var = scope.get_exact(redvar_name)
except NotDefinedError:
# Ideally, this shouldn't happen. The redvar name
# missing from scope indicates an error from
# other rewrite passes.
is_same_source_var = redvar_name == inst.target.name
else:
# Because of SSA, the redvar and target var of
# the current assignment would be different even
# though they refer to the same source-level var.
redvar_unver_name = reduction_var.unversioned_name
target_unver_name = inst.target.unversioned_name
is_same_source_var = redvar_unver_name == target_unver_name
if is_same_source_var:
# If redvar is different from target var, add an
# assignment to put target var into redvar.
if redvar_name != inst.target.name:
val = lowerer.loadvar(inst.target.name)
lowerer.storevar(val, name=redvar_name)
return True
return False
def _create_shape_signature(
get_shape_classes,
num_inputs,
num_reductions,
args,
func_sig,
races,
typemap):
'''Create shape signature for GUFunc
'''
if config.DEBUG_ARRAY_OPT:
print("_create_shape_signature", num_inputs, num_reductions, args, races)
for i in args[1:]:
print("argument", i, type(i), get_shape_classes(i, typemap=typemap))
num_inouts = len(args) - num_reductions
# maximum class number for array shapes
classes = [get_shape_classes(var, typemap=typemap) if var not in races else (-1,) for var in args[1:]]
class_set = set()
for _class in classes:
if _class:
for i in _class:
class_set.add(i)
max_class = max(class_set) + 1 if class_set else 0
classes.insert(0, (max_class,)) # force set the class of 'sched' argument
class_set.add(max_class)
thread_num_class = max_class + 1
class_set.add(thread_num_class)
class_map = {}
# TODO: use prefix + class number instead of single char
alphabet = ord('a')
for n in class_set:
if n >= 0:
class_map[n] = chr(alphabet)
alphabet += 1
threadcount_ordinal = chr(alphabet)
alpha_dict = {'latest_alpha' : alphabet}
def bump_alpha(c, class_map):
if c >= 0:
return class_map[c]
else:
alpha_dict['latest_alpha'] += 1
return chr(alpha_dict['latest_alpha'])
gu_sin = []
gu_sout = []
count = 0
syms_sin = ()
if config.DEBUG_ARRAY_OPT:
print("args", args)
print("classes", classes)
print("threadcount_ordinal", threadcount_ordinal)
for cls, arg in zip(classes, args):
count = count + 1
if cls:
dim_syms = tuple(bump_alpha(c, class_map) for c in cls)
else:
dim_syms = ()
if (count > num_inouts):
# Add the threadcount_ordinal to represent the thread count
# to the start of the reduction array.
gu_sin.append(tuple([threadcount_ordinal] + list(dim_syms[1:])))
else:
gu_sin.append(dim_syms)
syms_sin += dim_syms
return (gu_sin, gu_sout)
def _print_block(block):
for i, inst in enumerate(block.body):
print(" ", i, " ", inst)
def _print_body(body_dict):
'''Pretty-print a set of IR blocks.
'''
topo_order = wrap_find_topo(body_dict)
for label in topo_order:
block = body_dict[label]
print("label: ", label)
_print_block(block)
def wrap_loop_body(loop_body):
blocks = loop_body.copy() # shallow copy is enough
first_label = min(blocks.keys())
last_label = max(blocks.keys())
loc = blocks[last_label].loc
blocks[last_label].body.append(ir.Jump(first_label, loc))
return blocks
def unwrap_loop_body(loop_body):
last_label = max(loop_body.keys())
loop_body[last_label].body = loop_body[last_label].body[:-1]
def add_to_def_once_sets(a_def, def_once, def_more):
'''If the variable is already defined more than once, do nothing.
Else if defined exactly once previously then transition this
variable to the defined more than once set (remove it from
def_once set and add to def_more set).
Else this must be the first time we've seen this variable defined
so add to def_once set.
'''
if a_def in def_more:
pass
elif a_def in def_once:
def_more.add(a_def)
def_once.remove(a_def)
else:
def_once.add(a_def)
def compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns):
'''Effect changes to the set of variables defined once or more than once
for a single block.
block - the block to process
def_once - set of variable names known to be defined exactly once
def_more - set of variable names known to be defined more than once
getattr_taken - dict mapping variable name to tuple of object and attribute taken
module_assigns - dict mapping variable name to the Global that they came from
'''
# The only "defs" occur in assignments, so find such instructions.
assignments = block.find_insts(ir.Assign)
# For each assignment...
for one_assign in assignments:
# Get the LHS/target of the assignment.
a_def = one_assign.target.name
# Add variable to def sets.
add_to_def_once_sets(a_def, def_once, def_more)
rhs = one_assign.value
if isinstance(rhs, ir.Global):
# Remember assignments of the form "a = Global(...)"
# Is this a module?
if isinstance(rhs.value, pytypes.ModuleType):
module_assigns[a_def] = rhs.value.__name__
if isinstance(rhs, ir.Expr) and rhs.op == 'getattr' and rhs.value.name in def_once:
# Remember assignments of the form "a = b.c"
getattr_taken[a_def] = (rhs.value.name, rhs.attr)
if isinstance(rhs, ir.Expr) and rhs.op == 'call' and rhs.func.name in getattr_taken:
# If "a" is being called then lookup the getattr definition of "a"
# as above, getting the module variable "b" (base_obj)
# and the attribute "c" (base_attr).
base_obj, base_attr = getattr_taken[rhs.func.name]
if base_obj in module_assigns:
# If we know the definition of the module variable then get the module
# name from module_assigns.
base_mod_name = module_assigns[base_obj]
if not is_const_call(base_mod_name, base_attr):
# Calling a method on an object could modify the object and is thus
# like a def of that object. We call is_const_call to see if this module/attribute
# combination is known to not modify the module state. If we don't know that
# the combination is safe then we have to assume there could be a modification to
# the module and thus add the module variable as defined more than once.
add_to_def_once_sets(base_obj, def_once, def_more)
else:
# Assume the worst and say that base_obj could be modified by the call.
add_to_def_once_sets(base_obj, def_once, def_more)
if isinstance(rhs, ir.Expr) and rhs.op == 'call':
# If a mutable object is passed to a function, then it may be changed and
# therefore can't be hoisted.
# For each argument to the function...
for argvar in rhs.args:
# Get the argument's type.
if isinstance(argvar, ir.Var):
argvar = argvar.name
avtype = typemap[argvar]
# If that type doesn't have a mutable attribute or it does and it's set to
# not mutable then this usage is safe for hoisting.
if getattr(avtype, 'mutable', False):
# Here we have a mutable variable passed to a function so add this variable
# to the def lists.
add_to_def_once_sets(argvar, def_once, def_more)
def wrap_find_topo(loop_body):
blocks = wrap_loop_body(loop_body)
topo_order = find_topo_order(blocks)
unwrap_loop_body(loop_body)
return topo_order
def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns):
'''Compute the set of variables defined exactly once in the given set of blocks
and use the given sets for storing which variables are defined once, more than
once and which have had a getattr call on them.
'''
# For each block in topological order...
topo_order = wrap_find_topo(loop_body)
for label in topo_order:
block = loop_body[label]
# Scan this block and effect changes to def_once, def_more, and getattr_taken
# based on the instructions in that block.
compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns)
# Have to recursively process parfors manually here.
for inst in block.body:
if isinstance(inst, parfor.Parfor):
# Recursively compute for the parfor's init block.
compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns)
# Recursively compute for the parfor's loop body.
compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
def compute_def_once(loop_body, typemap):
'''Compute the set of variables defined exactly once in the given set of blocks.
'''
def_once = set() # set to hold variables defined exactly once
def_more = set() # set to hold variables defined more than once
getattr_taken = {}
module_assigns = {}
compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
return def_once, def_more
def find_vars(var, varset):
assert isinstance(var, ir.Var)
varset.add(var.name)
return var
def _hoist_internal(inst, dep_on_param, call_table, hoisted, not_hoisted,
typemap, stored_arrays):
if inst.target.name in stored_arrays:
not_hoisted.append((inst, "stored array"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, "could not be hoisted because the created array is stored.")
return False
target_type = typemap[inst.target.name]
uses = set()
# Get vars used by this statement.
visit_vars_inner(inst.value, find_vars, uses)
# Filter out input parameters from the set of variable usages.
unhoistable = {assgn.target.name for assgn, _ in not_hoisted}
use_unhoist = uses & unhoistable
diff = uses.difference(dep_on_param)
diff |= use_unhoist
if config.DEBUG_ARRAY_OPT >= 1:
print("_hoist_internal:", inst, "uses:", uses, "diff:", diff)
if len(diff) == 0 and is_pure(inst.value, None, call_table):
if config.DEBUG_ARRAY_OPT >= 1:
print("Will hoist instruction", inst, target_type)
hoisted.append(inst)
if not isinstance(target_type, types.npytypes.Array):
dep_on_param += [inst.target.name]
return True
else:
if len(diff) > 0:
not_hoisted.append((inst, "dependency"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, "could not be hoisted because of a dependency.")
else:
not_hoisted.append((inst, "not pure"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, "could not be hoisted because it isn't pure.")
return False
def find_setitems_block(setitems, itemsset, block, typemap):
for inst in block.body:
if isinstance(inst, (ir.StaticSetItem, ir.SetItem)):
setitems.add(inst.target.name)
# If we store a non-mutable object into an array then that is safe to hoist.
# If the stored object is mutable and you hoist then multiple entries in the
# outer array could reference the same object and changing one index would then
# change other indices.
if getattr(typemap[inst.value.name], "mutable", False):
itemsset.add(inst.value.name)
elif isinstance(inst, parfor.Parfor):
find_setitems_block(setitems, itemsset, inst.init_block, typemap)
find_setitems_body(setitems, itemsset, inst.loop_body, typemap)
elif isinstance(inst, ir.Assign):
# If something of mutable type is given to a build_tuple or
# used in a call then consider it unanalyzable and so
# unavailable for hoisting.
rhs = inst.value
def add_to_itemset(item):
assert isinstance(item, ir.Var), rhs
if getattr(typemap[item.name], "mutable", False):
itemsset.add(item.name)
if isinstance(rhs, ir.Expr):
if rhs.op in ["build_tuple", "build_list", "build_set"]:
for item in rhs.items:
add_to_itemset(item)
elif rhs.op == "build_map":
for pair in rhs.items:
for item in pair:
add_to_itemset(item)
elif rhs.op == "call":
for item in list(rhs.args) + [x[1] for x in rhs.kws]:
add_to_itemset(item)
def find_setitems_body(setitems, itemsset, loop_body, typemap):
"""
Find the arrays that are written into (goes into setitems) and the
mutable objects (mostly arrays) that are written into other arrays
(goes into itemsset).
"""
for label, block in loop_body.items():
find_setitems_block(setitems, itemsset, block, typemap)
def empty_container_allocator_hoist(inst, dep_on_param, call_table, hoisted,
not_hoisted, typemap, stored_arrays):
if (isinstance(inst, ir.Assign) and
isinstance(inst.value, ir.Expr) and
inst.value.op == 'call' and
inst.value.func.name in call_table):
call_list = call_table[inst.value.func.name]
if call_list == ['empty', np]:
return _hoist_internal(inst, dep_on_param, call_table, hoisted,
not_hoisted, typemap, stored_arrays)
return False
def hoist(parfor_params, loop_body, typemap, wrapped_blocks):
dep_on_param = copy.copy(parfor_params)
hoisted = []
not_hoisted = []
# Compute the set of variable defined exactly once in the loop body.
def_once, def_more = compute_def_once(loop_body, typemap)
(call_table, reverse_call_table) = get_call_table(wrapped_blocks)
setitems = set()
itemsset = set()
find_setitems_body(setitems, itemsset, loop_body, typemap)
dep_on_param = list(set(dep_on_param).difference(setitems))
if config.DEBUG_ARRAY_OPT >= 1:
print("hoist - def_once:", def_once, "setitems:", setitems, "itemsset:", itemsset, "dep_on_param:", dep_on_param, "parfor_params:", parfor_params)
for si in setitems:
add_to_def_once_sets(si, def_once, def_more)
for label, block in loop_body.items():
new_block = []
for inst in block.body:
if empty_container_allocator_hoist(inst, dep_on_param, call_table,
hoisted, not_hoisted, typemap, itemsset):
continue
elif isinstance(inst, ir.Assign) and inst.target.name in def_once:
if _hoist_internal(inst, dep_on_param, call_table,
hoisted, not_hoisted, typemap, itemsset):
# don't add this instruction to the block since it is
# hoisted
continue
elif isinstance(inst, parfor.Parfor):
new_init_block = []
if config.DEBUG_ARRAY_OPT >= 1:
print("parfor")
inst.dump()
for ib_inst in inst.init_block.body:
if empty_container_allocator_hoist(ib_inst, dep_on_param,
call_table, hoisted, not_hoisted, typemap, itemsset):
continue
elif (isinstance(ib_inst, ir.Assign) and
ib_inst.target.name in def_once):
if _hoist_internal(ib_inst, dep_on_param, call_table,
hoisted, not_hoisted, typemap,
itemsset):
# don't add this instruction to the block since it is hoisted
continue
new_init_block.append(ib_inst)
inst.init_block.body = new_init_block
new_block.append(inst)
block.body = new_block
return hoisted, not_hoisted
def redtyp_is_scalar(redtype):
return not isinstance(redtype, types.npytypes.Array)
def redtyp_to_redarraytype(redtyp):
"""Go from a reducation variable type to a reduction array type used to hold
per-worker results.
"""
redarrdim = 1
# If the reduction type is an array then allocate reduction array with ndim+1 dimensions.
if isinstance(redtyp, types.npytypes.Array):
redarrdim += redtyp.ndim
# We don't create array of array but multi-dimensional reduction array with same dtype.
redtyp = redtyp.dtype
return types.npytypes.Array(redtyp, redarrdim, "C")
def redarraytype_to_sig(redarraytyp):
"""Given a reduction array type, find the type of the reduction argument to the gufunc.
"""
assert isinstance(redarraytyp, types.npytypes.Array)
return types.npytypes.Array(redarraytyp.dtype, redarraytyp.ndim, redarraytyp.layout)
def legalize_names_with_typemap(names, typemap):
""" We use ir_utils.legalize_names to replace internal IR variable names
containing illegal characters (e.g. period) with a legal character
(underscore) so as to create legal variable names.
The original variable names are in the typemap so we also
need to add the legalized name to the typemap as well.
"""
outdict = legalize_names(names)
# For each pair in the dict of legalized names...
for x, y in outdict.items():
# If the name had some legalization change to it...
if x != y:
# Set the type of the new name the same as the type of the old name.
typemap[y] = typemap[x]
return outdict
def to_scalar_from_0d(x):
if isinstance(x, types.ArrayCompatible):
if x.ndim == 0:
return x.dtype
return x
def _create_gufunc_for_parfor_body(
lowerer,
parfor,
typemap,
typingctx,
targetctx,
flags,
locals,
has_aliases,
index_var_typ,
races):
'''
Takes a parfor and creates a gufunc function for its body.
There are two parts to this function.
1) Code to iterate across the iteration space as defined by the schedule.
2) The parfor body that does the work for a single point in the iteration space.
Part 1 is created as Python text for simplicity with a sentinel assignment to mark the point
in the IR where the parfor body should be added.
This Python text is 'exec'ed into existence and its IR retrieved with run_frontend.
The IR is scanned for the sentinel assignment where that basic block is split and the IR
for the parfor body inserted.
'''
if config.DEBUG_ARRAY_OPT >= 1:
print("starting _create_gufunc_for_parfor_body")
loc = parfor.init_block.loc
# The parfor body and the main function body share ir.Var nodes.
# We have to do some replacements of Var names in the parfor body to make them
# legal parameter names. If we don't copy then the Vars in the main function also
# would incorrectly change their name.
loop_body = copy.copy(parfor.loop_body)
remove_dels(loop_body)
parfor_dim = len(parfor.loop_nests)
loop_indices = [l.index_variable.name for l in parfor.loop_nests]
# Get all the parfor params.
parfor_params = parfor.params
# Get just the outputs of the parfor.
parfor_outputs = numba.parfors.parfor.get_parfor_outputs(parfor, parfor_params)
# Get all parfor reduction vars, and operators.
typemap = lowerer.fndesc.typemap
parfor_redvars, parfor_reddict = numba.parfors.parfor.get_parfor_reductions(
lowerer.func_ir, parfor, parfor_params, lowerer.fndesc.calltypes)
# Compute just the parfor inputs as a set difference.
parfor_inputs = sorted(
list(
set(parfor_params) -
set(parfor_outputs) -
set(parfor_redvars)))
if config.DEBUG_ARRAY_OPT >= 1:
print("parfor_params = ", parfor_params, " ", type(parfor_params))
print("parfor_outputs = ", parfor_outputs, " ", type(parfor_outputs))
print("parfor_inputs = ", parfor_inputs, " ", type(parfor_inputs))
print("parfor_redvars = ", parfor_redvars, " ", type(parfor_redvars))
# -------------------------------------------------------------------------
# Convert tuples to individual parameters.
tuple_expanded_parfor_inputs = []
tuple_var_to_expanded_names = {}
expanded_name_to_tuple_var = {}
next_expanded_tuple_var = 0
parfor_tuple_params = []
# For each input to the parfor.
for pi in parfor_inputs:
# Get the type of the input.
pi_type = typemap[pi]
# If it is a UniTuple or Tuple we will do the conversion.
if isinstance(pi_type, types.UniTuple) or isinstance(pi_type, types.NamedUniTuple):
# Get the size and dtype of the tuple.
tuple_count = pi_type.count
tuple_dtype = pi_type.dtype
# Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length.
assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE)
this_var_expansion = []
for i in range(tuple_count):
# Generate a new name for the individual part of the tuple var.
expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var)
# Add that name to the new list of inputs to the gufunc.
tuple_expanded_parfor_inputs.append(expanded_name)
this_var_expansion.append(expanded_name)
# Remember a mapping from new param name to original tuple
# var and the index within the tuple.
expanded_name_to_tuple_var[expanded_name] = (pi, i)
next_expanded_tuple_var += 1
# Set the type of the new parameter.
typemap[expanded_name] = tuple_dtype
# Remember a mapping from the original tuple var to the
# individual parts.
tuple_var_to_expanded_names[pi] = this_var_expansion
parfor_tuple_params.append(pi)
elif isinstance(pi_type, types.Tuple) or isinstance(pi_type, types.NamedTuple):
# This is the same as above for UniTuple except that each part of
# the tuple can have a different type and we fetch that type with
# pi_type.types[offset].
tuple_count = pi_type.count
tuple_types = pi_type.types
# Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length.
assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE)
this_var_expansion = []
for i in range(tuple_count):
expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var)
tuple_expanded_parfor_inputs.append(expanded_name)
this_var_expansion.append(expanded_name)
expanded_name_to_tuple_var[expanded_name] = (pi, i)
next_expanded_tuple_var += 1
typemap[expanded_name] = tuple_types[i]
tuple_var_to_expanded_names[pi] = this_var_expansion
parfor_tuple_params.append(pi)
else:
tuple_expanded_parfor_inputs.append(pi)
parfor_inputs = tuple_expanded_parfor_inputs
if config.DEBUG_ARRAY_OPT >= 1:
print("parfor_inputs post tuple handling = ", parfor_inputs, " ", type(parfor_inputs))
# -------------------------------------------------------------------------
races = races.difference(set(parfor_redvars))
for race in races:
msg = ("Variable %s used in parallel loop may be written "
"to simultaneously by multiple workers and may result "
"in non-deterministic or unintended results." % race)
warnings.warn(NumbaParallelSafetyWarning(msg, loc))
replace_var_with_array(races, loop_body, typemap, lowerer.fndesc.calltypes)
# Reduction variables are represented as arrays, so they go under
# different names.
parfor_redarrs = []
parfor_red_arg_types = []
for var in parfor_redvars:
arr = var + "_arr"
parfor_redarrs.append(arr)
redarraytype = redtyp_to_redarraytype(typemap[var])
parfor_red_arg_types.append(redarraytype)
redarrsig = redarraytype_to_sig(redarraytype)
if arr in typemap:
assert(typemap[arr] == redarrsig)
else:
typemap[arr] = redarrsig
# Reorder all the params so that inputs go first then outputs.
parfor_params = parfor_inputs + parfor_outputs + parfor_redarrs
if config.DEBUG_ARRAY_OPT >= 1:
print("parfor_params = ", parfor_params, " ", type(parfor_params))
print("loop_indices = ", loop_indices, " ", type(loop_indices))
print("loop_body = ", loop_body, " ", type(loop_body))
_print_body(loop_body)
# Some Var are not legal parameter names so create a dict of potentially illegal
# param name to guaranteed legal name.
param_dict = legalize_names_with_typemap(parfor_params + parfor_redvars + parfor_tuple_params, typemap)
if config.DEBUG_ARRAY_OPT >= 1:
print(
"param_dict = ",
sorted(
param_dict.items()),
" ",
type(param_dict))
# Some loop_indices are not legal parameter names so create a dict of potentially illegal
# loop index to guaranteed legal name.
ind_dict = legalize_names_with_typemap(loop_indices, typemap)
# Compute a new list of legal loop index names.
legal_loop_indices = [ind_dict[v] for v in loop_indices]
if config.DEBUG_ARRAY_OPT >= 1:
print("ind_dict = ", sorted(ind_dict.items()), " ", type(ind_dict))
print(
"legal_loop_indices = ",
legal_loop_indices,
" ",
type(legal_loop_indices))
for pd in parfor_params:
print("pd = ", pd)
print("pd type = ", typemap[pd], " ", type(typemap[pd]))
# Get the types of each parameter.
param_types = [to_scalar_from_0d(typemap[v]) for v in parfor_params]
# Calculate types of args passed to gufunc.
func_arg_types = [typemap[v] for v in (parfor_inputs + parfor_outputs)] + parfor_red_arg_types
if config.DEBUG_ARRAY_OPT >= 1:
print("new param_types:", param_types)
print("new func_arg_types:", func_arg_types)
# Replace illegal parameter names in the loop body with legal ones.
replace_var_names(loop_body, param_dict)
# remember the name before legalizing as the actual arguments
parfor_args = parfor_params
# Change parfor_params to be legal names.
parfor_params = [param_dict[v] for v in parfor_params]
parfor_params_orig = parfor_params
parfor_params = []
ascontig = False
for pindex in range(len(parfor_params_orig)):
if (ascontig and
pindex < len(parfor_inputs) and
isinstance(param_types[pindex], types.npytypes.Array)):
parfor_params.append(parfor_params_orig[pindex]+"param")
else:
parfor_params.append(parfor_params_orig[pindex])
# Change parfor body to replace illegal loop index vars with legal ones.
replace_var_names(loop_body, ind_dict)
loop_body_var_table = get_name_var_table(loop_body)
sentinel_name = get_unused_var_name("__sentinel__", loop_body_var_table)
if config.DEBUG_ARRAY_OPT >= 1:
print(
"legal parfor_params = ",
parfor_params,
" ",
type(parfor_params))
# Determine the unique names of the scheduling and gufunc functions.
# sched_func_name = "__numba_parfor_sched_%s" % (hex(hash(parfor)).replace("-", "_"))
gufunc_name = "__numba_parfor_gufunc_%s" % (
hex(hash(parfor)).replace("-", "_"))
if config.DEBUG_ARRAY_OPT:
# print("sched_func_name ", type(sched_func_name), " ", sched_func_name)
print("gufunc_name ", type(gufunc_name), " ", gufunc_name)
gufunc_txt = ""
# Create the gufunc function.
gufunc_txt += "def " + gufunc_name + \
"(sched, " + (", ".join(parfor_params)) + "):\n"
globls = {"np": np, "numba": numba}
# First thing in the gufunc, we reconstruct tuples from their
# individual parts, e.g., orig_tup_name = (part1, part2,).
# The rest of the code of the function will use the original tuple name.
for tup_var, exp_names in tuple_var_to_expanded_names.items():
tup_type = typemap[tup_var]
gufunc_txt += " " + param_dict[tup_var]
# Determine if the tuple is a named tuple.
if (isinstance(tup_type, types.NamedTuple) or
isinstance(tup_type, types.NamedUniTuple)):
named_tup = True
else:
named_tup = False
if named_tup:
# It is a named tuple so try to find the global that defines the
# named tuple.
func_def = guard(get_definition, lowerer.func_ir, tup_var)
named_tuple_def = None
if config.DEBUG_ARRAY_OPT:
print("func_def:", func_def, type(func_def))
if func_def is not None:
if (isinstance(func_def, ir.Expr) and
func_def.op == 'call'):
named_tuple_def = guard(get_definition, lowerer.func_ir, func_def.func)
if config.DEBUG_ARRAY_OPT:
print("named_tuple_def:", named_tuple_def, type(named_tuple_def))
elif isinstance(func_def, ir.Arg):
named_tuple_def = typemap[func_def.name]
if config.DEBUG_ARRAY_OPT:
print("named_tuple_def:", named_tuple_def,
type(named_tuple_def), named_tuple_def.name)
if named_tuple_def is not None:
if (isinstance(named_tuple_def, ir.Global) or
isinstance(named_tuple_def, ir.FreeVar)):
gval = named_tuple_def.value
if config.DEBUG_ARRAY_OPT:
print("gval:", gval, type(gval))
globls[named_tuple_def.name] = gval
elif isinstance(named_tuple_def, types.containers.BaseNamedTuple):
named_tuple_name = named_tuple_def.name.split('(')[0]
if config.DEBUG_ARRAY_OPT:
print("name:", named_tuple_name,
named_tuple_def.instance_class,
type(named_tuple_def.instance_class))
globls[named_tuple_name] = named_tuple_def.instance_class
else:
if config.DEBUG_ARRAY_OPT:
print("Didn't find definition of namedtuple for globls.")
raise CompilerError("Could not find definition of " + str(tup_var),
tup_var.loc)
gufunc_txt += " = " + tup_type.instance_class.__name__ + "("
for name, field_name in zip(exp_names, tup_type.fields):
gufunc_txt += field_name + "=" + param_dict[name] + ","
else:
# Just a regular tuple so use (part0, part1, ...)
gufunc_txt += " = (" + ", ".join([param_dict[x] for x in exp_names])
if len(exp_names) == 1:
# Add comma for tuples with singular values. We can't unilaterally
# add a comma always because (,) isn't valid.
gufunc_txt += ","
gufunc_txt += ")\n"
for pindex in range(len(parfor_inputs)):
if ascontig and isinstance(param_types[pindex], types.npytypes.Array):
gufunc_txt += (" " + parfor_params_orig[pindex]
+ " = np.ascontiguousarray(" + parfor_params[pindex] + ")\n")
gufunc_thread_id_var = "ParallelAcceleratorGufuncThreadId"
if len(parfor_redarrs) > 0:
gufunc_txt += " " + gufunc_thread_id_var + " = "
gufunc_txt += "numba.np.ufunc.parallel._iget_thread_id()\n"
# Add initialization of reduction variables
for arr, var in zip(parfor_redarrs, parfor_redvars):
gufunc_txt += " " + param_dict[var] + \
"=" + param_dict[arr] + "[" + gufunc_thread_id_var + "]\n"
if config.DEBUG_ARRAY_OPT_RUNTIME:
gufunc_txt += " print(\"thread id =\", ParallelAcceleratorGufuncThreadId)\n"
gufunc_txt += " print(\"initial reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + "," + param_dict[var] + ".shape)\n"
gufunc_txt += " print(\"reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + "," + param_dict[arr] + ".shape)\n"
# For each dimension of the parfor, create a for loop in the generated gufunc function.
# Iterate across the proper values extracted from the schedule.
# The form of the schedule is start_dim0, start_dim1, ..., start_dimN, end_dim0,
# end_dim1, ..., end_dimN
for eachdim in range(parfor_dim):
for indent in range(eachdim + 1):
gufunc_txt += " "
sched_dim = eachdim
gufunc_txt += ("for " +
legal_loop_indices[eachdim] +
" in range(sched[" +
str(sched_dim) +
"], sched[" +
str(sched_dim +
parfor_dim) +
"] + np.uint8(1)):\n")
if config.DEBUG_ARRAY_OPT_RUNTIME:
for indent in range(parfor_dim + 1):
gufunc_txt += " "
gufunc_txt += "print("
for eachdim in range(parfor_dim):
gufunc_txt += "\"" + legal_loop_indices[eachdim] + "\"," + legal_loop_indices[eachdim] + ","
gufunc_txt += ")\n"
# Add the sentinel assignment so that we can find the loop body position
# in the IR.
for indent in range(parfor_dim + 1):
gufunc_txt += " "
gufunc_txt += sentinel_name + " = 0\n"
# Add assignments of reduction variables (for returning the value)
for arr, var in zip(parfor_redarrs, parfor_redvars):
if config.DEBUG_ARRAY_OPT_RUNTIME:
gufunc_txt += " print(\"final reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + ")\n"
gufunc_txt += " print(\"final reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + ")\n"
# After the gufunc loops, copy the accumulated temp value back to reduction array.
gufunc_txt += " " + param_dict[arr] + \
"[" + gufunc_thread_id_var + "] = " + param_dict[var] + "\n"
gufunc_txt += " return None\n"
if config.DEBUG_ARRAY_OPT:
print("gufunc_txt = ", type(gufunc_txt), "\n", gufunc_txt)
print("globls:", globls, type(globls))
# Force gufunc outline into existence.
locls = {}
exec(gufunc_txt, globls, locls)
gufunc_func = locls[gufunc_name]
if config.DEBUG_ARRAY_OPT:
print("gufunc_func = ", type(gufunc_func), "\n", gufunc_func)
# Get the IR for the gufunc outline.
gufunc_ir = compiler.run_frontend(gufunc_func)
if config.DEBUG_ARRAY_OPT:
print("gufunc_ir dump ", type(gufunc_ir))
gufunc_ir.dump()
print("loop_body dump ", type(loop_body))
_print_body(loop_body)
# rename all variables in gufunc_ir afresh
var_table = get_name_var_table(gufunc_ir.blocks)
new_var_dict = {}
reserved_names = [sentinel_name] + \
list(param_dict.values()) + legal_loop_indices
for name, var in var_table.items():
if not (name in reserved_names):
new_var_dict[name] = parfor.init_block.scope.redefine(name, loc).name
replace_var_names(gufunc_ir.blocks, new_var_dict)
if config.DEBUG_ARRAY_OPT:
print("gufunc_ir dump after renaming ")
gufunc_ir.dump()
gufunc_param_types = [types.npytypes.Array(
index_var_typ, 1, "C")] + param_types
if config.DEBUG_ARRAY_OPT:
print(
"gufunc_param_types = ",
type(gufunc_param_types),
"\n",
gufunc_param_types)
gufunc_stub_last_label = find_max_label(gufunc_ir.blocks) + 1
# Add gufunc stub last label to each parfor.loop_body label to prevent
# label conflicts.
loop_body = add_offset_to_labels(loop_body, gufunc_stub_last_label)
# new label for splitting sentinel block
new_label = find_max_label(loop_body) + 1
# If enabled, add a print statement after every assignment.
if config.DEBUG_ARRAY_OPT_RUNTIME:
for label, block in loop_body.items():
new_block = block.copy()
new_block.clear()
loc = block.loc
scope = block.scope
for inst in block.body:
new_block.append(inst)
# Append print after assignment
if isinstance(inst, ir.Assign):
# Only apply to numbers
if typemap[inst.target.name] not in types.number_domain:
continue
# Make constant string
strval = "{} =".format(inst.target.name)
strconsttyp = types.StringLiteral(strval)
lhs = scope.redefine("str_const", loc)
# lhs = ir.Var(scope, mk_unique_var("str_const"), loc)
assign_lhs = ir.Assign(value=ir.Const(value=strval, loc=loc),
target=lhs, loc=loc)
typemap[lhs.name] = strconsttyp
new_block.append(assign_lhs)
# Make print node
print_node = ir.Print(args=[lhs, inst.target], vararg=None, loc=loc)
new_block.append(print_node)
sig = numba.core.typing.signature(types.none,
typemap[lhs.name],
typemap[inst.target.name])
lowerer.fndesc.calltypes[print_node] = sig
loop_body[label] = new_block
if config.DEBUG_ARRAY_OPT:
print("parfor loop body")
_print_body(loop_body)
wrapped_blocks = wrap_loop_body(loop_body)
hoisted, not_hoisted = hoist(parfor_params, loop_body, typemap, wrapped_blocks)
start_block = gufunc_ir.blocks[min(gufunc_ir.blocks.keys())]
start_block.body = start_block.body[:-1] + hoisted + [start_block.body[-1]]
unwrap_loop_body(loop_body)
# store hoisted into diagnostics
diagnostics = lowerer.metadata['parfor_diagnostics']
diagnostics.hoist_info[parfor.id] = {'hoisted': hoisted,
'not_hoisted': not_hoisted}
if config.DEBUG_ARRAY_OPT:
print("After hoisting")
_print_body(loop_body)
# Search all the block in the gufunc outline for the sentinel assignment.
for label, block in gufunc_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 the sentinel.
block.body = block.body[i + 1:]
# But the current block gets a new label.
body_first_label = min(loop_body.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 loop_body.items():
gufunc_ir.blocks[l] = transfer_scope(b, scope)
body_last_label = max(loop_body.keys())
gufunc_ir.blocks[new_label] = block
gufunc_ir.blocks[label] = prev_block
# Add a jump from the last parfor body block to the block containing
# statements after the sentinel.
gufunc_ir.blocks[body_last_label].append(
ir.Jump(new_label, loc))
break
else:
continue
break
if config.DEBUG_ARRAY_OPT:
print("gufunc_ir last dump before renaming")
gufunc_ir.dump()
gufunc_ir.blocks = rename_labels(gufunc_ir.blocks)
remove_dels(gufunc_ir.blocks)
if config.DEBUG_ARRAY_OPT:
print("gufunc_ir last dump")
gufunc_ir.dump()
print("flags", flags)
print("typemap", typemap)
old_alias = flags.noalias
if not has_aliases:
if config.DEBUG_ARRAY_OPT:
print("No aliases found so adding noalias flag.")
flags.noalias = True
fixup_var_define_in_scope(gufunc_ir.blocks)
class ParforGufuncCompiler(compiler.CompilerBase):
def define_pipelines(self):
from numba.core.compiler_machinery import PassManager
dpb = compiler.DefaultPassBuilder
pm = PassManager("full_parfor_gufunc")
parfor_gufunc_passes = dpb.define_parfor_gufunc_pipeline(self.state)
pm.passes.extend(parfor_gufunc_passes.passes)
lowering_passes = dpb.define_parfor_gufunc_nopython_lowering_pipeline(self.state)
pm.passes.extend(lowering_passes.passes)
pm.finalize()
return [pm]
kernel_func = compiler.compile_ir(
typingctx,
targetctx,
gufunc_ir,
gufunc_param_types,
types.none,
flags,
locals,
pipeline_class=ParforGufuncCompiler)
flags.noalias = old_alias
kernel_sig = signature(types.none, *gufunc_param_types)
if config.DEBUG_ARRAY_OPT:
print("finished create_gufunc_for_parfor_body. kernel_sig = ", kernel_sig)
return kernel_func, parfor_args, kernel_sig, func_arg_types, expanded_name_to_tuple_var
def replace_var_with_array_in_block(vars, block, typemap, calltypes):
new_block = []
for inst in block.body:
if isinstance(inst, ir.Assign) and inst.target.name in vars:
loc = inst.loc
scope = inst.target.scope
const_node = ir.Const(0, loc)
const_var = scope.redefine("$const_ind_0", loc)
typemap[const_var.name] = types.uintp
const_assign = ir.Assign(const_node, const_var, loc)
new_block.append(const_assign)
val_var = scope.redefine("$val", loc)
typemap[val_var.name] = typemap[inst.target.name]
new_block.append(ir.Assign(inst.value, val_var, loc))
setitem_node = ir.SetItem(inst.target, const_var, val_var, loc)
calltypes[setitem_node] = signature(
types.none, types.npytypes.Array(typemap[inst.target.name], 1, "C"), types.intp, typemap[inst.target.name])
new_block.append(setitem_node)
continue
elif isinstance(inst, parfor.Parfor):
replace_var_with_array_internal(vars, {0: inst.init_block}, typemap, calltypes)
replace_var_with_array_internal(vars, inst.loop_body, typemap, calltypes)
new_block.append(inst)
return new_block
def replace_var_with_array_internal(vars, loop_body, typemap, calltypes):
for label, block in loop_body.items():
block.body = replace_var_with_array_in_block(vars, block, typemap, calltypes)
def replace_var_with_array(vars, loop_body, typemap, calltypes):
replace_var_with_array_internal(vars, loop_body, typemap, calltypes)
for v in vars:
el_typ = typemap[v]
typemap.pop(v, None)
typemap[v] = types.npytypes.Array(el_typ, 1, "C")
def call_parallel_gufunc(lowerer, cres, gu_signature, outer_sig, expr_args, expr_arg_types,
loop_ranges, redvars, reddict, redarrdict, init_block, index_var_typ, races,
exp_name_to_tuple_var):
'''
Adds the call to the gufunc function from the main function.
'''
context = lowerer.context
builder = lowerer.builder
from numba.np.ufunc.parallel import (build_gufunc_wrapper,
_launch_threads)
if config.DEBUG_ARRAY_OPT:
print("make_parallel_loop")
print("outer_sig = ", outer_sig.args, outer_sig.return_type,
outer_sig.recvr, outer_sig.pysig)
print("loop_ranges = ", loop_ranges)
print("expr_args", expr_args)
print("expr_arg_types", expr_arg_types)
print("gu_signature", gu_signature)
# Build the wrapper for GUFunc
args, return_type = sigutils.normalize_signature(outer_sig)
llvm_func = cres.library.get_function(cres.fndesc.llvm_func_name)
sin, sout = gu_signature
# These are necessary for build_gufunc_wrapper to find external symbols
_launch_threads()
info = build_gufunc_wrapper(llvm_func, cres, sin, sout,
cache=False, is_parfors=True)
wrapper_name = info.name
cres.library._ensure_finalized()
if config.DEBUG_ARRAY_OPT:
print("parallel function = ", wrapper_name, cres)
# loadvars for loop_ranges
def load_range(v):
if isinstance(v, ir.Var):
return lowerer.loadvar(v.name)
else:
return context.get_constant(types.uintp, v)
num_dim = len(loop_ranges)
for i in range(num_dim):
start, stop, step = loop_ranges[i]
start = load_range(start)
stop = load_range(stop)
assert(step == 1) # We do not support loop steps other than 1
step = load_range(step)
loop_ranges[i] = (start, stop, step)
if config.DEBUG_ARRAY_OPT:
print("call_parallel_gufunc loop_ranges[{}] = ".format(i), start,
stop, step)
cgutils.printf(builder, "loop range[{}]: %d %d (%d)\n".format(i),
start, stop, step)
# Commonly used LLVM types and constants
byte_t = llvmlite.ir.IntType(8)
byte_ptr_t = llvmlite.ir.PointerType(byte_t)
byte_ptr_ptr_t = llvmlite.ir.PointerType(byte_ptr_t)
intp_t = context.get_value_type(types.intp)
uintp_t = context.get_value_type(types.uintp)
intp_ptr_t = llvmlite.ir.PointerType(intp_t)
intp_ptr_ptr_t = llvmlite.ir.PointerType(intp_ptr_t)
uintp_ptr_t = llvmlite.ir.PointerType(uintp_t)
uintp_ptr_ptr_t = llvmlite.ir.PointerType(uintp_ptr_t)
zero = context.get_constant(types.uintp, 0)
one = context.get_constant(types.uintp, 1)
one_type = one.type
sizeof_intp = context.get_abi_sizeof(intp_t)
# Prepare sched, first pop it out of expr_args, outer_sig, and gu_signature
expr_args.pop(0)
sched_sig = sin.pop(0)
if config.DEBUG_ARRAY_OPT:
print("Parfor has potentially negative start", index_var_typ.signed)
if index_var_typ.signed:
sched_type = intp_t
sched_ptr_type = intp_ptr_t
sched_ptr_ptr_type = intp_ptr_ptr_t
else:
sched_type = uintp_t
sched_ptr_type = uintp_ptr_t
sched_ptr_ptr_type = uintp_ptr_ptr_t
# Call do_scheduling with appropriate arguments
dim_starts = cgutils.alloca_once(
builder, sched_type, size=context.get_constant(
types.uintp, num_dim), name="dim_starts")
dim_stops = cgutils.alloca_once(
builder, sched_type, size=context.get_constant(
types.uintp, num_dim), name="dim_stops")
for i in range(num_dim):
start, stop, step = loop_ranges[i]
if start.type != one_type:
start = builder.sext(start, one_type)
if stop.type != one_type:
stop = builder.sext(stop, one_type)
if step.type != one_type:
step = builder.sext(step, one_type)
# substract 1 because do-scheduling takes inclusive ranges
stop = builder.sub(stop, one)
builder.store(
start, builder.gep(
dim_starts, [
context.get_constant(
types.uintp, i)]))
builder.store(stop, builder.gep(dim_stops,
[context.get_constant(types.uintp, i)]))
# Prepare to call get/set parallel_chunksize and get the number of threads.
get_chunksize = cgutils.get_or_insert_function(
builder.module,
llvmlite.ir.FunctionType(uintp_t, []),
name="get_parallel_chunksize")
set_chunksize = cgutils.get_or_insert_function(
builder.module,
llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [uintp_t]),
name="set_parallel_chunksize")
get_num_threads = cgutils.get_or_insert_function(
builder.module,
llvmlite.ir.FunctionType(llvmlite.ir.IntType(types.intp.bitwidth), []),
"get_num_threads")
# Get the current number of threads.
num_threads = builder.call(get_num_threads, [])
# Get the current chunksize so we can use it and restore the value later.
current_chunksize = builder.call(get_chunksize, [])
with cgutils.if_unlikely(builder, builder.icmp_signed('<=', num_threads,
num_threads.type(0))):
cgutils.printf(builder, "num_threads: %d\n", num_threads)
context.call_conv.return_user_exc(builder, RuntimeError,
("Invalid number of threads. "
"This likely indicates a bug in Numba.",))
# Call get_sched_size from gufunc_scheduler.cpp that incorporates the size of the work,
# the number of threads and the selected chunk size. This will tell us how many entries
# in the schedule we will need.
get_sched_size_fnty = llvmlite.ir.FunctionType(uintp_t, [uintp_t, uintp_t, intp_ptr_t, intp_ptr_t])
get_sched_size = cgutils.get_or_insert_function(
builder.module,
get_sched_size_fnty,
name="get_sched_size")
num_divisions = builder.call(get_sched_size, [num_threads,
context.get_constant(types.uintp, num_dim),
dim_starts,
dim_stops])
# Set the chunksize to zero so that any nested calls get the default chunk size behavior.
builder.call(set_chunksize, [zero])
# Each entry in the schedule is 2 times the number of dimensions long.
multiplier = context.get_constant(types.uintp, num_dim * 2)
# Compute the total number of entries in the schedule.
sched_size = builder.mul(num_divisions, multiplier)
# Prepare to dynamically allocate memory to hold the schedule.
alloc_sched_fnty = llvmlite.ir.FunctionType(sched_ptr_type, [uintp_t])
alloc_sched_func = cgutils.get_or_insert_function(
builder.module,
alloc_sched_fnty,
name="allocate_sched")
# Call gufunc_scheduler.cpp to allocate the schedule.
# This may or may not do pooling.
alloc_space = builder.call(alloc_sched_func, [sched_size])
# Allocate a slot in the entry block to store the schedule pointer.
sched = cgutils.alloca_once(builder, sched_ptr_type)
# Store the schedule pointer into that slot.
builder.store(alloc_space, sched)
debug_flag = 1 if config.DEBUG_ARRAY_OPT else 0
scheduling_fnty = llvmlite.ir.FunctionType(
intp_ptr_t, [uintp_t, intp_ptr_t, intp_ptr_t, uintp_t, sched_ptr_type, intp_t])
if index_var_typ.signed:
do_scheduling = cgutils.get_or_insert_function(builder.module,
scheduling_fnty,
name="do_scheduling_signed")
else:
do_scheduling = cgutils.get_or_insert_function(builder.module,
scheduling_fnty,
name="do_scheduling_unsigned")
# Call the scheduling routine that decides how to break up the work.
builder.call(
do_scheduling, [
context.get_constant(
types.uintp, num_dim), dim_starts, dim_stops, num_divisions,
builder.load(sched), context.get_constant(
types.intp, debug_flag)])
# Get the LLVM vars for the Numba IR reduction array vars.
redarrs = [lowerer.loadvar(redarrdict[x].name) for x in redvars]
nredvars = len(redvars)
ninouts = len(expr_args) - nredvars
def load_potential_tuple_var(x):
"""Given a variable name, if that variable is not a new name
introduced as the extracted part of a tuple then just return
the variable loaded from its name. However, if the variable
does represent part of a tuple, as recognized by the name of
the variable being present in the exp_name_to_tuple_var dict,
then we load the original tuple var instead that we get from
the dict and then extract the corresponding element of the
tuple, also stored and returned to use in the dict (i.e., offset).
"""
if x in exp_name_to_tuple_var:
orig_tup, offset = exp_name_to_tuple_var[x]
tup_var = lowerer.loadvar(orig_tup)
res = builder.extract_value(tup_var, offset)
return res
else:
return lowerer.loadvar(x)
# ----------------------------------------------------------------------------
# Prepare arguments: args, shapes, steps, data
all_args = [load_potential_tuple_var(x) for x in expr_args[:ninouts]] + redarrs
num_args = len(all_args)
num_inps = len(sin) + 1
args = cgutils.alloca_once(
builder,
byte_ptr_t,
size=context.get_constant(
types.intp,
1 + num_args),
name="pargs")
array_strides = []
# sched goes first
builder.store(builder.bitcast(builder.load(sched), byte_ptr_t), args)
array_strides.append(context.get_constant(types.intp, sizeof_intp))
rv_to_arg_dict = {}
# followed by other arguments
for i in range(num_args):
arg = all_args[i]
var = expr_args[i]
aty = expr_arg_types[i]
dst = builder.gep(args, [context.get_constant(types.intp, i + 1)])
if i >= ninouts: # reduction variables
ary = context.make_array(aty)(context, builder, arg)
strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim)
# Start from 1 because we skip the first dimension of length num_threads just like sched.
for j in range(len(strides)):
array_strides.append(strides[j])
builder.store(builder.bitcast(ary.data, byte_ptr_t), dst)
elif isinstance(aty, types.ArrayCompatible):
if var in races:
typ = (context.get_data_type(aty.dtype)
if aty.dtype != types.boolean
else llvmlite.ir.IntType(1))
rv_arg = cgutils.alloca_once(builder, typ)
builder.store(arg, rv_arg)
builder.store(builder.bitcast(rv_arg, byte_ptr_t), dst)
rv_to_arg_dict[var] = (arg, rv_arg)
array_strides.append(context.get_constant(types.intp, context.get_abi_sizeof(typ)))
else:
ary = context.make_array(aty)(context, builder, arg)
strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim)
for j in range(len(strides)):
array_strides.append(strides[j])
builder.store(builder.bitcast(ary.data, byte_ptr_t), dst)
else:
if i < num_inps:
# Scalar input, need to store the value in an array of size 1
if isinstance(aty, types.Optional):
# Unpack optional type
unpacked_aty = aty.type
arg = context.cast(builder, arg, aty, unpacked_aty)
else:
unpacked_aty = aty
typ = (context.get_data_type(unpacked_aty)
if not isinstance(unpacked_aty, types.Boolean)
else llvmlite.ir.IntType(1))
ptr = cgutils.alloca_once(builder, typ)
builder.store(arg, ptr)
else:
# Scalar output, must allocate
typ = (context.get_data_type(aty)
if not isinstance(aty, types.Boolean)
else llvmlite.ir.IntType(1))
ptr = cgutils.alloca_once(builder, typ)
builder.store(builder.bitcast(ptr, byte_ptr_t), dst)
# ----------------------------------------------------------------------------
# Next, we prepare the individual dimension info recorded in gu_signature
sig_dim_dict = {}
occurrences = []
occurrences = [sched_sig[0]]
sig_dim_dict[sched_sig[0]] = context.get_constant(types.intp, 2 * num_dim)
assert len(expr_args) == len(all_args)
assert len(expr_args) == len(expr_arg_types)
assert len(expr_args) == len(sin + sout)
assert len(expr_args) == len(outer_sig.args[1:])
for var, arg, aty, gu_sig in zip(expr_args, all_args,
expr_arg_types, sin + sout):
if isinstance(aty, types.npytypes.Array):
i = aty.ndim - len(gu_sig)
else:
i = 0
if config.DEBUG_ARRAY_OPT:
print("var =", var, "gu_sig =", gu_sig, "type =", aty, "i =", i)
for dim_sym in gu_sig:
if config.DEBUG_ARRAY_OPT:
print("var = ", var, " type = ", aty)
if var in races:
sig_dim_dict[dim_sym] = context.get_constant(types.intp, 1)
else:
ary = context.make_array(aty)(context, builder, arg)
shapes = cgutils.unpack_tuple(builder, ary.shape, aty.ndim)
sig_dim_dict[dim_sym] = shapes[i]
if not (dim_sym in occurrences):
if config.DEBUG_ARRAY_OPT:
print("dim_sym = ", dim_sym, ", i = ", i)
cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym])
occurrences.append(dim_sym)
i = i + 1
# ----------------------------------------------------------------------------
# Prepare shapes, which is a single number (outer loop size), followed by
# the size of individual shape variables.
nshapes = len(sig_dim_dict) + 1
shapes = cgutils.alloca_once(builder, intp_t, size=nshapes, name="pshape")
# For now, outer loop size is the same as number of threads
builder.store(num_divisions, shapes)
# Individual shape variables go next
i = 1
for dim_sym in occurrences:
if config.DEBUG_ARRAY_OPT:
cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym])
builder.store(
sig_dim_dict[dim_sym], builder.gep(
shapes, [
context.get_constant(
types.intp, i)]))
i = i + 1
# ----------------------------------------------------------------------------
# Prepare steps for each argument. Note that all steps are counted in
# bytes.
num_steps = num_args + 1 + len(array_strides)
steps = cgutils.alloca_once(
builder, intp_t, size=context.get_constant(
types.intp, num_steps), name="psteps")
# First goes the step size for sched, which is 2 * num_dim
builder.store(context.get_constant(types.intp, 2 * num_dim * sizeof_intp),
steps)
# The steps for all others are 0, except for reduction results.
for i in range(num_args):
# steps are strides from one thread to the next
stepsize = zero
dst = builder.gep(steps, [context.get_constant(types.intp, 1 + i)])
builder.store(stepsize, dst)
for j in range(len(array_strides)):
dst = builder.gep(
steps, [
context.get_constant(
types.intp, 1 + num_args + j)])
builder.store(array_strides[j], dst)
# ----------------------------------------------------------------------------
# prepare data
data = cgutils.get_null_value(byte_ptr_t)
fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(),
[byte_ptr_ptr_t, intp_ptr_t,
intp_ptr_t, byte_ptr_t])
fn = cgutils.get_or_insert_function(builder.module, fnty, wrapper_name)
context.active_code_library.add_linking_library(info.library)
if config.DEBUG_ARRAY_OPT:
cgutils.printf(builder, "before calling kernel %p\n", fn)
builder.call(fn, [args, shapes, steps, data])
if config.DEBUG_ARRAY_OPT:
cgutils.printf(builder, "after calling kernel %p\n", fn)
builder.call(set_chunksize, [current_chunksize])
# Deallocate the schedule's memory.
dealloc_sched_fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [sched_ptr_type])
dealloc_sched_func = cgutils.get_or_insert_function(
builder.module,
dealloc_sched_fnty,
name="deallocate_sched")
builder.call(dealloc_sched_func, [builder.load(sched)])
for k, v in rv_to_arg_dict.items():
arg, rv_arg = v
only_elem_ptr = builder.gep(rv_arg, [context.get_constant(types.intp, 0)])
builder.store(builder.load(only_elem_ptr), lowerer.getvar(k))
context.active_code_library.add_linking_library(cres.library)
| ParforsUnexpectedReduceNodeError |
python | PyCQA__isort | tests/unit/test_io.py | {
"start": 131,
"end": 1475
} | class ____:
@pytest.mark.skipif(sys.platform == "win32", reason="Can't run file encoding test in AppVeyor")
def test_read(self, tmpdir):
test_file_content = """# -*- encoding: ascii -*-
import Ὡ
"""
test_file = tmpdir.join("file.py")
test_file.write(test_file_content)
with pytest.raises(UnicodeDecodeError):
with io.File.read(str(test_file)) as file_handler:
file_handler.stream.read()
def test_from_content(self, tmpdir):
test_file = tmpdir.join("file.py")
test_file.write_text("import os", "utf8")
file_obj = io.File.from_contents("import os", filename=str(test_file))
assert file_obj
assert file_obj.extension == "py"
def test_open(self, tmpdir):
with pytest.raises(FileNotFoundError):
io.File._open("THISCANTBEAREALFILEὩὩὩὩὩὩὩὩὩὩὩὩ.ὩὩὩὩὩ")
def raise_arbitrary_exception(*args, **kwargs):
raise RuntimeError("test")
test_file = tmpdir.join("file.py")
test_file.write("import os")
assert io.File._open(str(test_file))
# correctly responds to error determining encoding
with patch("tokenize.detect_encoding", raise_arbitrary_exception):
with pytest.raises(UnsupportedEncoding):
io.File._open(str(test_file))
| TestFile |
python | pytorch__pytorch | torch/ao/quantization/quantizer/quantizer.py | {
"start": 4586,
"end": 6617
} | class ____(ABC):
def transform_for_annotation(
self, model: torch.fx.GraphModule
) -> torch.fx.GraphModule:
"""Allows for user defined transforms to run before annotating the graph.
This allows quantizer to allow quantizing part of the model that are otherwise not quantizable.
For example quantizer can
a) decompose a compound operator like scaled dot product attention,
into bmm and softmax if quantizer knows how to quantize bmm/softmax but not sdpa
or b) transform scalars to tensor to allow quantizing scalares.
Note: this is an optional method
"""
return model
# annotate nodes in the graph with observer or fake quant constructors
# to convey the desired way of quantization
@abstractmethod
def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:
pass
# validate the annotated graph is supported by the backend
@abstractmethod
def validate(self, model: torch.fx.GraphModule) -> None:
pass
def prepare_obs_or_fq_callback(
self,
model: torch.fx.GraphModule,
edge_or_node_to_obs_or_fq: dict[EdgeOrNode, ObserverOrFakeQuantize],
) -> None:
"""A callback that will be called after the observers or fake quants are created
for each sharing group, but before they are inserted into the graph. The
callback can be used to make final quantization adjustments, such as enforcing
specific scale and zero point on model input or output.
Args:
* `model`: the graph module being prepared.
* `edge_or_node_to_obs_or_fq`: a dictionary mapping each annotated edge and
node to the corresponding observer or fake quant object. Note that multiple
edges and/or nodes can map to the same observer / fake quant instance if
they were annotated with SharedQuantizationSpec. This dictionary can be
modified by the callback.
"""
return
| Quantizer |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 64522,
"end": 67283
} | class ____(Field[_EnumT]):
"""An Enum field (de)serializing enum members by symbol (name) or by value.
:param enum: Enum class
:param by_value: Whether to (de)serialize by value or by name,
or Field class or instance to use to (de)serialize by value. Defaults to False.
If `by_value` is `False` (default), enum members are (de)serialized by symbol (name).
If it is `True`, they are (de)serialized by value using `marshmallow.fields.Raw`.
If it is a field instance or class, they are (de)serialized by value using this field.
.. versionadded:: 3.18.0
"""
default_error_messages = {
"unknown": "Must be one of: {choices}.",
}
def __init__(
self,
enum: type[_EnumT],
*,
by_value: bool | Field | type[Field] = False,
**kwargs: Unpack[_BaseFieldKwargs],
):
super().__init__(**kwargs)
self.enum = enum
self.by_value = by_value
# Serialization by name
if by_value is False:
self.field: Field = String()
self.choices_text = ", ".join(
str(self.field._serialize(m, None, None)) for m in enum.__members__
)
# Serialization by value
else:
if by_value is True:
self.field = Raw()
else:
try:
self.field = _resolve_field_instance(by_value)
except _FieldInstanceResolutionError as error:
raise ValueError(
'"by_value" must be either a bool or a subclass or instance of '
"marshmallow.fields.Field."
) from error
self.choices_text = ", ".join(
str(self.field._serialize(m.value, None, None)) for m in enum
)
def _serialize(
self, value: _EnumT | None, attr: str | None, obj: typing.Any, **kwargs
) -> typing.Any | None:
if value is None:
return None
if self.by_value:
val = value.value
else:
val = value.name
return self.field._serialize(val, attr, obj, **kwargs)
def _deserialize(self, value, attr, data, **kwargs) -> _EnumT:
if isinstance(value, self.enum):
return value
val = self.field._deserialize(value, attr, data, **kwargs)
if self.by_value:
try:
return self.enum(val)
except ValueError as error:
raise self.make_error("unknown", choices=self.choices_text) from error
try:
return getattr(self.enum, val)
except AttributeError as error:
raise self.make_error("unknown", choices=self.choices_text) from error
| Enum |
python | scipy__scipy | scipy/_build_utils/tempita/_tempita.py | {
"start": 1977,
"end": 2282
} | class ____(Exception):
pass
def get_file_template(name, from_template):
path = os.path.join(os.path.dirname(from_template.name), name)
return from_template.__class__.from_filename(
path, namespace=from_template.namespace,
get_template=from_template.get_template)
| _TemplateBreak |
python | cosmicpython__book | tests.py | {
"start": 4365,
"end": 7407
} | class ____:
filename: str
tag: str
contents: str
classes: list
is_diff: bool
callouts = re.compile(r' #?(\(\d\) ?)+$', flags=re.MULTILINE)
callouts_alone = re.compile(r'^\(\d\)$')
@property
def fixed_contents(self):
fixed = self.contents
fixed = self.callouts.sub('', fixed)
fixed = '\n'.join(
l for l in fixed.splitlines()
if not self.callouts_alone.match(l)
)
return fixed
@property
def lines(self):
return self.fixed_contents.split('\n')
def parse_listings(chapter_name):
raw_contents = Path(f'{chapter_name}.html').read_text()
parsed_html = html.fromstring(raw_contents)
for listing_node in parsed_html.cssselect('.exampleblock'):
[block_node] = listing_node.cssselect('.listingblock')
classes = block_node.get('class').split()
if 'skip' in classes:
continue
if 'tree' in classes:
filename = None
else:
[title_node] = listing_node.cssselect('.title')
title = title_node.text_content()
print('found listing', title)
try:
filename = re.search(r'.+ \((.+)\)', title).group(1)
except AttributeError as e:
raise AssertionError(f'Could not find filename in title {title}') from e
is_diff = bool(listing_node.cssselect('code[data-lang="diff"]'))
tag = listing_node.get('id')
[code_node] = block_node.cssselect('.content pre')
yield Listing(
filename, tag, contents=code_node.text_content(), classes=classes,
is_diff=is_diff
)
def file_contents_for_branch(filename, chapter_name):
return subprocess.run(
['git', 'show', f'{chapter_name}:{filename}'],
cwd=Path(__file__).parent / 'code',
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True
).stdout.decode()
def file_contents_for_previous_chapter(filename, chapter_name):
previous = previous_chapter(chapter_name)
return file_contents_for_branch(filename, previous)
def file_contents_for_tag(filename, chapter_name, tag):
output = subprocess.run(
['git', 'show', f'{chapter_name}^{{/\\[{tag}\\]}}:{filename}'],
cwd=Path(__file__).parent / 'code',
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True
).stdout.decode()
assert output.strip(), f'no commit found for [{tag}]'
return output
def diff_for_tag(filename, chapter_name, tag):
if tag.endswith('_diff'):
tag = tag[:-5]
output = subprocess.run(
['git', 'show', f'{chapter_name}^{{/\\[{tag}\\]}}', '--', filename],
cwd=Path(__file__).parent / 'code',
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True
).stdout.decode()
assert output.strip(), f'no commit found for [{tag}]'
return '\n'.join(l.rstrip() for l in output.splitlines())
| Listing |
python | coleifer__peewee | peewee.py | {
"start": 29688,
"end": 30252
} | class ____(BaseTable):
def __init__(self, lhs, rhs, join_type=JOIN.INNER, on=None, alias=None):
super(Join, self).__init__(alias=alias)
self.lhs = lhs
self.rhs = rhs
self.join_type = join_type
self._on = on
def on(self, predicate):
self._on = predicate
return self
def __sql__(self, ctx):
(ctx
.sql(self.lhs)
.literal(' %s ' % self.join_type)
.sql(self.rhs))
if self._on is not None:
ctx.literal(' ON ').sql(self._on)
return ctx
| Join |
python | spyder-ide__spyder | spyder/api/plugin_registration/registry.py | {
"start": 1076,
"end": 1493
} | class ____(SpyderConfigurationAccessor):
# Fake class constants used to register the configuration page
CONF_WIDGET_CLASS = PluginsConfigPage
NAME = 'plugin_registry'
CONF_VERSION = None
ADDITIONAL_CONF_OPTIONS = None
ADDITIONAL_CONF_TABS = None
CONF_SECTION = ""
def apply_plugin_settings(self, _unused):
pass
def apply_conf(self, _unused):
pass
| PreferencesAdapter |
python | nedbat__coveragepy | coverage/files.py | {
"start": 12245,
"end": 19357
} | class ____:
"""A collection of aliases for paths.
When combining data files from remote machines, often the paths to source
code are different, for example, due to OS differences, or because of
serialized checkouts on continuous integration machines.
A `PathAliases` object tracks a list of pattern/result pairs, and can
map a path through those aliases to produce a unified path.
"""
def __init__(
self,
debugfn: Callable[[str], None] | None = None,
relative: bool = False,
) -> None:
# A list of (original_pattern, regex, result)
self.aliases: list[tuple[str, re.Pattern[str], str]] = []
self.debugfn = debugfn or (lambda msg: 0)
self.relative = relative
self.pprinted = False
def pprint(self) -> None:
"""Dump the important parts of the PathAliases, for debugging."""
self.debugfn(f"Aliases (relative={self.relative}):")
for original_pattern, regex, result in self.aliases:
self.debugfn(f" Rule: {original_pattern!r} -> {result!r} using regex {regex.pattern!r}")
def add(self, pattern: str, result: str) -> None:
"""Add the `pattern`/`result` pair to the list of aliases.
`pattern` is an `glob`-style pattern. `result` is a simple
string. When mapping paths, if a path starts with a match against
`pattern`, then that match is replaced with `result`. This models
isomorphic source trees being rooted at different places on two
different machines.
`pattern` can't end with a wildcard component, since that would
match an entire tree, and not just its root.
"""
original_pattern = pattern
pattern_sep = sep(pattern)
if len(pattern) > 1:
pattern = pattern.rstrip(r"\/")
# The pattern can't end with a wildcard component.
if pattern.endswith("*"):
raise ConfigError("Pattern must not end with wildcards.")
# The pattern is meant to match a file path. Let's make it absolute
# unless it already is, or is meant to match any prefix.
if not self.relative:
if not pattern.startswith("*") and not isabs_anywhere(pattern + pattern_sep):
pattern = abs_file(pattern)
if not pattern.endswith(pattern_sep):
pattern += pattern_sep
# Make a regex from the pattern.
regex = globs_to_regex([pattern], case_insensitive=True, partial=True)
# Normalize the result: it must end with a path separator.
result_sep = sep(result)
result = result.rstrip(r"\/") + result_sep
self.aliases.append((original_pattern, regex, result))
def map(self, path: str, exists: Callable[[str], bool] = source_exists) -> str:
"""Map `path` through the aliases.
`path` is checked against all of the patterns. The first pattern to
match is used to replace the root of the path with the result root.
Only one pattern is ever used. If no patterns match, `path` is
returned unchanged.
The separator style in the result is made to match that of the result
in the alias.
`exists` is a function to determine if the resulting path actually
exists.
Returns the mapped path. If a mapping has happened, this is a
canonical path. If no mapping has happened, it is the original value
of `path` unchanged.
"""
if not self.pprinted:
self.pprint()
self.pprinted = True
for original_pattern, regex, result in self.aliases:
if m := regex.match(path):
new = path.replace(m[0], result)
new = new.replace(sep(path), sep(result))
if not self.relative:
new = canonical_filename(new)
dot_start = result.startswith(("./", ".\\")) and len(result) > 2
if new.startswith(("./", ".\\")) and not dot_start:
new = new[2:]
if not exists(new):
self.debugfn(
f"Rule {original_pattern!r} changed {path!r} to {new!r} "
+ "which doesn't exist, continuing",
)
continue
self.debugfn(
f"Matched path {path!r} to rule {original_pattern!r} -> {result!r}, "
+ f"producing {new!r}",
)
return new
# If we get here, no pattern matched.
if self.relative:
path = relative_filename(path)
if self.relative and not isabs_anywhere(path):
# Auto-generate a pattern to implicitly match relative files
parts = re.split(r"[/\\]", path)
if len(parts) > 1:
dir1 = parts[0]
pattern = f"*/{dir1}"
regex_pat = rf"^(.*[\\/])?{re.escape(dir1)}[\\/]"
result = f"{dir1}{os.sep}"
# Only add a new pattern if we don't already have this pattern.
if not any(p == pattern for p, _, _ in self.aliases):
self.debugfn(
f"Generating rule: {pattern!r} -> {result!r} using regex {regex_pat!r}",
)
self.aliases.append((pattern, re.compile(regex_pat), result))
return self.map(path, exists=exists)
self.debugfn(f"No rules match, path {path!r} is unchanged")
return path
def find_python_files(dirname: str, include_namespace_packages: bool) -> Iterable[str]:
"""Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname` was specified directly, so the user knows
best, but sub-directories are checked for a __init__.py to be sure we only
find the importable files.
If `include_namespace_packages` is True, then the check for __init__.py
files is skipped.
Files with strange characters are skipped, since they couldn't have been
imported, and are probably editor side-files.
"""
for i, (dirpath, dirnames, filenames) in enumerate(os.walk(dirname)):
if not include_namespace_packages:
if i > 0 and "__init__.py" not in filenames:
# If a directory doesn't have __init__.py, then it isn't
# importable and neither are its files
del dirnames[:]
continue
for filename in filenames:
# We're only interested in files that look like reasonable Python
# files: Must end with .py or .pyw, and must not have certain funny
# characters that probably mean they are editor junk.
if re.match(r"^[^.#~!$@%^&*()+=,]+\.pyw?$", filename):
yield os.path.join(dirpath, filename)
# Globally set the relative directory.
set_relative_directory()
| PathAliases |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_serialization_micro.py | {
"start": 15654,
"end": 17689
} | class ____:
a: str
b: bytes
c: int
d: float
dataclass_schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.str_schema()),
core_schema.dataclass_field(name='b', schema=core_schema.bytes_schema()),
core_schema.dataclass_field(name='c', schema=core_schema.int_schema()),
core_schema.dataclass_field(name='d', schema=core_schema.float_schema()),
],
),
['a', 'b', 'c', 'd'],
)
@pytest.mark.benchmark(group='dataclass-ser')
def test_dataclass_serialization_python(benchmark):
s = SchemaSerializer(dataclass_schema)
dc = Foo(a='hello', b=b'more', c=123, d=1.23)
assert s.to_python(dc) == {'a': 'hello', 'b': b'more', 'c': 123, 'd': 1.23}
benchmark(s.to_python, dc)
@pytest.mark.benchmark(group='dataclass-ser')
def test_dataclass_serialization_json(benchmark):
s = SchemaSerializer(dataclass_schema)
dc = Foo(a='hello', b=b'more', c=123, d=1.23)
assert s.to_python(dc) == {'a': 'hello', 'b': b'more', 'c': 123, 'd': 1.23}
benchmark(s.to_json, dc)
@pytest.mark.benchmark(group='dataclass-ser')
def test_dataclass_to_json(benchmark):
dc = Foo(a='hello', b=b'more', c=123, d=1.23)
benchmark(to_json, dc)
@pytest.mark.benchmark(group='function')
def test_function_wrap_python(benchmark):
def f(value, serializer, _info):
return f'result={serializer(len(value))}'
s = SchemaSerializer(
core_schema.int_schema(serialization=core_schema.wrap_serializer_function_ser_schema(f, info_arg=True))
)
benchmark(s.to_python, 'foo')
@pytest.mark.benchmark(group='function')
def test_function_wrap_json(benchmark):
def f(value, serializer, _info):
return f'result={serializer(len(value))}'
s = SchemaSerializer(
core_schema.int_schema(serialization=core_schema.wrap_serializer_function_ser_schema(f, info_arg=True))
)
benchmark(s.to_json, 'foo')
| Foo |
python | ray-project__ray | rllib/utils/tf_run_builder.py | {
"start": 262,
"end": 3879
} | class ____:
"""Used to incrementally build up a TensorFlow run.
This is particularly useful for batching ops from multiple different
policies in the multi-agent setting.
"""
def __init__(self, session, debug_name):
self.session = session
self.debug_name = debug_name
self.feed_dict = {}
self.fetches = []
self._executed = None
def add_feed_dict(self, feed_dict):
assert not self._executed
for k in feed_dict:
if k in self.feed_dict:
raise ValueError("Key added twice: {}".format(k))
self.feed_dict.update(feed_dict)
def add_fetches(self, fetches):
assert not self._executed
base_index = len(self.fetches)
self.fetches.extend(fetches)
return list(range(base_index, len(self.fetches)))
def get(self, to_fetch):
if self._executed is None:
try:
self._executed = _run_timeline(
self.session,
self.fetches,
self.debug_name,
self.feed_dict,
os.environ.get("TF_TIMELINE_DIR"),
)
except Exception as e:
logger.exception(
"Error fetching: {}, feed_dict={}".format(
self.fetches, self.feed_dict
)
)
raise e
if isinstance(to_fetch, int):
return self._executed[to_fetch]
elif isinstance(to_fetch, list):
return [self.get(x) for x in to_fetch]
elif isinstance(to_fetch, tuple):
return tuple(self.get(x) for x in to_fetch)
else:
raise ValueError("Unsupported fetch type: {}".format(to_fetch))
_count = 0
def _run_timeline(sess, ops, debug_name, feed_dict=None, timeline_dir=None):
if feed_dict is None:
feed_dict = {}
if timeline_dir:
from tensorflow.python.client import timeline
try:
run_options = tf1.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
except AttributeError:
run_options = None
# In local mode, tf1.RunOptions is not available, see #26511
if log_once("tf1.RunOptions_not_available"):
logger.exception(
"Can not access tf.RunOptions.FULL_TRACE. This may be because "
"you have used `ray.init(local_mode=True)`. RLlib will use "
"timeline without `options=tf.RunOptions.FULL_TRACE`."
)
run_metadata = tf1.RunMetadata()
start = time.time()
fetches = sess.run(
ops, options=run_options, run_metadata=run_metadata, feed_dict=feed_dict
)
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
global _count
outf = os.path.join(
timeline_dir,
"timeline-{}-{}-{}.json".format(debug_name, os.getpid(), _count % 10),
)
_count += 1
trace_file = open(outf, "w")
logger.info(
"Wrote tf timeline ({} s) to {}".format(
time.time() - start, os.path.abspath(outf)
)
)
trace_file.write(trace.generate_chrome_trace_format())
else:
if log_once("tf_timeline"):
logger.info(
"Executing TF run without tracing. To dump TF timeline traces "
"to disk, set the TF_TIMELINE_DIR environment variable."
)
fetches = sess.run(ops, feed_dict=feed_dict)
return fetches
| _TFRunBuilder |
python | doocs__leetcode | solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py | {
"start": 0,
"end": 367
} | class ____:
def findMin(self, nums: List[int]) -> int:
if nums[0] <= nums[-1]:
return nums[0]
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[0] <= nums[mid]:
left = mid + 1
else:
right = mid
return nums[left]
| Solution |
python | vyperlang__vyper | vyper/semantics/types/function.py | {
"start": 33635,
"end": 35694
} | class ____(VyperType):
"""
Member function type definition.
This class has no corresponding primitive.
(examples for (x <DynArray[int128, 3]>).append(1))
Arguments:
underlying_type: the type this method is attached to. ex. DynArray[int128, 3]
name: the name of this method. ex. "append"
arg_types: the argument types this method accepts. ex. [int128]
return_type: the return type of this method. ex. None
"""
typeclass = "member_function"
_is_callable = True
# keep LGTM linter happy
def __eq__(self, other):
return super().__eq__(other)
def __init__(
self,
underlying_type: VyperType,
name: str,
arg_types: List[VyperType],
return_type: Optional[VyperType],
is_modifying: bool,
) -> None:
super().__init__()
self.underlying_type = underlying_type
self.name = name
self.arg_types = arg_types
self.return_type = return_type
self.is_modifying = is_modifying
@property
def modifiability(self):
return Modifiability.MODIFIABLE if self.is_modifying else Modifiability.RUNTIME_CONSTANT
@property
def _id(self):
return self.name
def __repr__(self):
return f"{self.underlying_type} member function '{self.name}'"
def fetch_call_return(self, node: vy_ast.Call) -> Optional[VyperType]:
validate_call_args(node, len(self.arg_types))
assert len(node.args) == len(self.arg_types) # validate_call_args postcondition
for arg, expected_type in zip(node.args, self.arg_types):
# CMC 2022-04-01 this should probably be in the validation module
validate_expected_type(arg, expected_type)
return self.return_type
def _generate_method_id(name: str, canonical_abi_types: List[str]) -> Dict[str, int]:
function_sig = f"{name}({','.join(canonical_abi_types)})"
selector = keccak256(function_sig.encode())[:4].hex()
return {function_sig: int(selector, 16)}
| MemberFunctionT |
python | davidhalter__jedi | jedi/inference/arguments.py | {
"start": 9944,
"end": 10289
} | class ____(AbstractArguments):
def __init__(self, values_list):
self._values_list = values_list
def unpack(self, funcdef=None):
for values in self._values_list:
yield None, LazyKnownValues(values)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self._values_list)
| ValuesArguments |
python | getsentry__sentry | src/sentry/integrations/jira/models/create_issue_metadata.py | {
"start": 4232,
"end": 5291
} | class ____:
id: str
description: str
name: str
subtask: bool
icon_url: str
url: str
fields: dict[str, JiraField]
@classmethod
def from_dict(cls, data: dict[str, Any]) -> JiraIssueTypeMetadata:
jira_id = data["id"]
description = data["description"]
name = data["name"]
subtask = data["subtask"]
icon_url = data["iconUrl"]
url = data["self"]
raw_fields = data["fields"]
fields = JiraField.from_dict_list(raw_fields)
return cls(
id=jira_id,
name=name,
description=description,
subtask=subtask,
icon_url=icon_url,
url=url,
fields=fields,
)
@classmethod
def from_jira_meta_config(cls, meta_config: dict[str, Any]) -> dict[str, JiraIssueTypeMetadata]:
issue_types_list = meta_config.get("issuetypes", {})
issue_configs = [cls.from_dict(it) for it in issue_types_list]
return {it.id: it for it in issue_configs}
| JiraIssueTypeMetadata |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 14103,
"end": 14736
} | class ____(EnhancementMatch):
def __init__(self, inner: FrameMatch):
self.inner = inner
@property
def description(self) -> str:
return f"| [ {self.inner.description} ]"
def _to_config_structure(self, version: int) -> str:
return f"|[{self.inner._to_config_structure(version)}]"
def matches_frame(
self,
frames: list[MatchFrame],
idx: int,
exception_data: dict[str, Any],
cache: ReturnValueCache,
) -> bool:
return idx < len(frames) - 1 and self.inner.matches_frame(
frames, idx + 1, exception_data, cache
)
| CalleeMatch |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 4482,
"end": 4609
} | class ____(Web3ValidationError):
"""
Raised when an RPC call returns >32 bytes of extraData.
"""
| ExtraDataLengthError |
python | ray-project__ray | python/ray/autoscaler/_private/vsphere/cluster_operator_client.py | {
"start": 1231,
"end": 1336
} | class ____(Enum):
INITIALIZED = "initialized"
RUNNING = "running"
FAIL = "failure"
| VMNodeStatus |
python | ZoranPandovski__al-go-rithms | data_structures/Linked_list/Python/Palindrome_Linked_List.py | {
"start": 102,
"end": 1243
} | class ____:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# single node case
if head.next is None:
return True
# two pointer to find the middle point of linked list
first_pointer = head
second_pointer = head.next
while second_pointer and second_pointer.next:
first_pointer = first_pointer.next
second_pointer = second_pointer.next.next
# reverse the second half of linked list
prev_node = None
current_node = first_pointer.next
while current_node != None:
temp = current_node.next
current_node.next = prev_node
prev_node = current_node
current_node = temp
# judge if is palindrome
last = prev_node
while last != None:
if head.val != last.val:
return False
head = head.next
last = last.next
return True
'''
Input: head = [1,2,2,1]
Output: true
-----------------------
Input: head = [1,2]
Output: false
'''
| Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 9581,
"end": 9981
} | class ____(BaseModel):
"""
Schema for Trigger DAG Run API request.
"""
model_config = ConfigDict(
extra="forbid",
)
logical_date: Annotated[AwareDatetime | None, Field(title="Logical Date")] = None
conf: Annotated[dict[str, Any] | None, Field(title="Conf")] = None
reset_dag_run: Annotated[bool | None, Field(title="Reset Dag Run")] = False
| TriggerDAGRunPayload |
python | huggingface__transformers | src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py | {
"start": 19601,
"end": 21790
} | class ____(Dinov2WithRegistersPreTrainedModel):
def __init__(self, config: Dinov2WithRegistersConfig):
super().__init__(config)
self.config = config
self.embeddings = Dinov2WithRegistersEmbeddings(config)
self.encoder = Dinov2WithRegistersEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> Dinov2WithRegistersPatchEmbeddings:
return self.embeddings.patch_embeddings
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
bool_masked_pos: Optional[torch.Tensor] = None,
output_hidden_states: Optional[bool] = None,
**kwargs,
) -> BaseModelOutputWithPooling:
r"""
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
pre-training.
"""
if output_hidden_states is None:
output_hidden_states = self.config.output_hidden_states
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
encoder_outputs: BaseModelOutput = self.encoder(embedding_output, output_hidden_states=output_hidden_states)
sequence_output = encoder_outputs.last_hidden_state
sequence_output = self.layernorm(sequence_output)
pooled_output = sequence_output[:, 0, :]
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
)
@auto_docstring(
custom_intro="""
Dinov2WithRegisters Model transformer with an image classification head on top (a linear layer on top of the final hidden state
of the [CLS] token) e.g. for ImageNet.
"""
)
| Dinov2WithRegistersModel |
python | getsentry__sentry | src/sentry/utils/event_frames.py | {
"start": 397,
"end": 937
} | class ____:
lineno: int | None = None
in_app: bool | None = None
abs_path: str | None = None
filename: str | None = None
function: str | None = None
package: str | None = None
module: str | None = None
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> EventFrame:
return cls(**{k: v for k, v in data.items() if k in inspect.signature(cls).parameters})
# mypy hack to work around callable assuing the first arg of callable is 'self'
# https://github.com/python/mypy/issues/5485
| EventFrame |
python | doocs__leetcode | solution/1400-1499/1478.Allocate Mailboxes/Solution.py | {
"start": 0,
"end": 590
} | class ____:
def minDistance(self, houses: List[int], k: int) -> int:
houses.sort()
n = len(houses)
g = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
g[i][j] = g[i + 1][j - 1] + houses[j] - houses[i]
f = [[inf] * (k + 1) for _ in range(n)]
for i in range(n):
f[i][1] = g[0][i]
for j in range(2, min(k + 1, i + 2)):
for p in range(i):
f[i][j] = min(f[i][j], f[p][j - 1] + g[p + 1][i])
return f[-1][k]
| Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_base_link.py | {
"start": 1749,
"end": 1902
} | class ____(BaseGoogleLink):
key = EXPECTED_GOOGLE_LINK_KEY
name = EXPECTED_GOOGLE_LINK_NAME
format_str = EXPECTED_GOOGLE_LINK_FORMAT
| GoogleLink |
python | neetcode-gh__leetcode | python/0128-longest-consecutive-sequence.py | {
"start": 0,
"end": 411
} | class ____:
def longestConsecutive(self, nums: List[int]) -> int:
numSet = set(nums)
longest = 0
for n in numSet:
# check if its the start of a sequence
if (n - 1) not in numSet:
length = 1
while (n + length) in numSet:
length += 1
longest = max(length, longest)
return longest
| Solution |
python | PyCQA__pylint | doc/data/messages/b/bad-mcs-classmethod-argument/good.py | {
"start": 0,
"end": 66
} | class ____(type):
@classmethod
def foo(mcs):
pass
| Meta |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/functions.py | {
"start": 1270,
"end": 5245
} | class ____(converter.Base):
"""Wraps function bodies around autograph-specific boilerplate."""
def _function_scope_options(self, fn_scope):
"""Returns the options with which to create function scopes."""
# Top-level function receive the options that were directly requested.
# All others receive the options corresponding to a recursive conversion.
# Note: this mainly controls the user_requested flag, which is important
# primarily because the FunctionScope context also creates a
# ControlStatusCtx(autograph=ENABLED) when user_requested is True. See
# function_wrappers.py.
if fn_scope.level == 2:
return self.ctx.user.options
return self.ctx.user.options.call_options()
def visit_Lambda(self, node):
with self.state[_Function] as fn_scope:
node = self.generic_visit(node)
# TODO(mdan): Fix the tests so that we can always add this decorator.
if fn_scope.level > 2:
return templates.replace_as_expression(
'ag__.autograph_artifact(l)', l=node)
scope = anno.getanno(node, anno.Static.SCOPE)
function_context_name = self.ctx.namer.new_symbol('lscope',
scope.referenced)
fn_scope.context_name = function_context_name
anno.setanno(node, 'function_context_name', function_context_name)
template = """
ag__.with_function_scope(
lambda function_context: body, function_context_name, options)
"""
node.body = templates.replace_as_expression(
template,
options=self._function_scope_options(fn_scope).to_ast(),
function_context=function_context_name,
function_context_name=gast.Constant(function_context_name, kind=None),
body=node.body)
return node
def visit_FunctionDef(self, node):
with self.state[_Function] as fn_scope:
scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE)
function_context_name = self.ctx.namer.new_symbol('fscope',
scope.referenced)
fn_scope.context_name = function_context_name
anno.setanno(node, 'function_context_name', function_context_name)
node = self.generic_visit(node)
if fn_scope.level <= 2:
# Top-level functions lose their decorator because the conversion is
# always just-in-time and by the time it happens the decorators are
# already set to be applied.
node.decorator_list = []
else:
# TODO(mdan): Fix the tests so that we can always add this decorator.
# Inner functions are converted already, so we insert a decorator to
# prevent double conversion. Double conversion would work too, but this
# saves the overhead.
node.decorator_list.append(
parser.parse_expression('ag__.autograph_artifact'))
docstring_node = None
if node.body:
first_statement = node.body[0]
if (isinstance(first_statement, gast.Expr) and
isinstance(first_statement.value, gast.Constant)):
docstring_node = first_statement
node.body = node.body[1:]
template = """
with ag__.FunctionScope(
function_name, context_name, options) as function_context:
body
"""
wrapped_body = templates.replace(
template,
function_name=gast.Constant(node.name, kind=None),
context_name=gast.Constant(function_context_name, kind=None),
options=self._function_scope_options(fn_scope).to_ast(),
function_context=function_context_name,
body=node.body)
if docstring_node is not None:
wrapped_body = [docstring_node] + wrapped_body
node.body = wrapped_body
return node
def transform(node, ctx):
node = qual_names.resolve(node)
node = activity.resolve(node, ctx, None)
return FunctionTransformer(ctx).visit(node)
| FunctionTransformer |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_string.py | {
"start": 16610,
"end": 31560
} | class ____:
def test_to_string_decimal(self):
# GH#23614
df = DataFrame({"A": [6.0, 3.1, 2.2]})
expected = " A\n0 6,0\n1 3,1\n2 2,2"
assert df.to_string(decimal=",") == expected
def test_to_string_left_justify_cols(self):
df = DataFrame({"x": [3234, 0.253]})
df_s = df.to_string(justify="left")
expected = " x \n0 3234.000\n1 0.253"
assert df_s == expected
def test_to_string_format_na(self):
df = DataFrame(
{
"A": [np.nan, -1, -2.1234, 3, 4],
"B": [np.nan, "foo", "foooo", "fooooo", "bar"],
}
)
result = df.to_string()
expected = (
" A B\n"
"0 NaN NaN\n"
"1 -1.0000 foo\n"
"2 -2.1234 foooo\n"
"3 3.0000 fooooo\n"
"4 4.0000 bar"
)
assert result == expected
df = DataFrame(
{
"A": [np.nan, -1.0, -2.0, 3.0, 4.0],
"B": [np.nan, "foo", "foooo", "fooooo", "bar"],
}
)
result = df.to_string()
expected = (
" A B\n"
"0 NaN NaN\n"
"1 -1.0 foo\n"
"2 -2.0 foooo\n"
"3 3.0 fooooo\n"
"4 4.0 bar"
)
assert result == expected
def test_to_string_with_dict_entries(self):
df = DataFrame({"A": [{"a": 1, "b": 2}]})
val = df.to_string()
assert "'a': 1" in val
assert "'b': 2" in val
def test_to_string_with_categorical_columns(self):
# GH#35439
data = [[4, 2], [3, 2], [4, 3]]
cols = ["aaaaaaaaa", "b"]
df = DataFrame(data, columns=cols)
df_cat_cols = DataFrame(data, columns=CategoricalIndex(cols))
assert df.to_string() == df_cat_cols.to_string()
def test_repr_embedded_ndarray(self):
arr = np.empty(10, dtype=[("err", object)])
for i in range(len(arr)):
arr["err"][i] = np.random.default_rng(2).standard_normal(i)
df = DataFrame(arr)
repr(df["err"])
repr(df)
df.to_string()
def test_to_string_truncate(self):
# GH 9784 - dont truncate when calling DataFrame.to_string
df = DataFrame(
[
{
"a": "foo",
"b": "bar",
"c": "let's make this a very VERY long line that is longer "
"than the default 50 character limit",
"d": 1,
},
{"a": "foo", "b": "bar", "c": "stuff", "d": 1},
]
)
df.set_index(["a", "b", "c"])
assert df.to_string() == (
" a b "
" c d\n"
"0 foo bar let's make this a very VERY long line t"
"hat is longer than the default 50 character limit 1\n"
"1 foo bar "
" stuff 1"
)
with option_context("max_colwidth", 20):
# the display option has no effect on the to_string method
assert df.to_string() == (
" a b "
" c d\n"
"0 foo bar let's make this a very VERY long line t"
"hat is longer than the default 50 character limit 1\n"
"1 foo bar "
" stuff 1"
)
assert df.to_string(max_colwidth=20) == (
" a b c d\n"
"0 foo bar let's make this ... 1\n"
"1 foo bar stuff 1"
)
@pytest.mark.parametrize(
"input_array, expected",
[
({"A": ["a"]}, "A\na"),
({"A": ["a", "b"], "B": ["c", "dd"]}, "A B\na c\nb dd"),
({"A": ["a", 1], "B": ["aa", 1]}, "A B\na aa\n1 1"),
],
)
def test_format_remove_leading_space_dataframe(self, input_array, expected):
# GH#24980
df = DataFrame(input_array).to_string(index=False)
assert df == expected
@pytest.mark.parametrize(
"data,expected",
[
(
{"col1": [1, 2], "col2": [3, 4]},
" col1 col2\n0 1 3\n1 2 4",
),
(
{"col1": ["Abc", 0.756], "col2": [np.nan, 4.5435]},
" col1 col2\n0 Abc NaN\n1 0.756 4.5435",
),
(
{"col1": [np.nan, "a"], "col2": [0.009, 3.543], "col3": ["Abc", 23]},
" col1 col2 col3\n0 NaN 0.009 Abc\n1 a 3.543 23",
),
],
)
def test_to_string_max_rows_zero(self, data, expected):
# GH#35394
result = DataFrame(data=data).to_string(max_rows=0)
assert result == expected
@pytest.mark.parametrize(
"max_cols, max_rows, expected",
[
(
10,
None,
" 0 1 2 3 4 ... 6 7 8 9 10\n"
" 0 0 0 0 0 ... 0 0 0 0 0\n"
" 0 0 0 0 0 ... 0 0 0 0 0\n"
" 0 0 0 0 0 ... 0 0 0 0 0\n"
" 0 0 0 0 0 ... 0 0 0 0 0",
),
(
None,
2,
" 0 1 2 3 4 5 6 7 8 9 10\n"
" 0 0 0 0 0 0 0 0 0 0 0\n"
" .. .. .. .. .. .. .. .. .. .. ..\n"
" 0 0 0 0 0 0 0 0 0 0 0",
),
(
10,
2,
" 0 1 2 3 4 ... 6 7 8 9 10\n"
" 0 0 0 0 0 ... 0 0 0 0 0\n"
" .. .. .. .. .. ... .. .. .. .. ..\n"
" 0 0 0 0 0 ... 0 0 0 0 0",
),
(
9,
2,
" 0 1 2 3 ... 7 8 9 10\n"
" 0 0 0 0 ... 0 0 0 0\n"
" .. .. .. .. ... .. .. .. ..\n"
" 0 0 0 0 ... 0 0 0 0",
),
(
1,
1,
" 0 ...\n 0 ...\n.. ...",
),
],
)
def test_truncation_no_index(self, max_cols, max_rows, expected):
df = DataFrame([[0] * 11] * 4)
assert (
df.to_string(index=False, max_cols=max_cols, max_rows=max_rows) == expected
)
def test_to_string_no_index(self):
# GH#16839, GH#13032
df = DataFrame({"x": [11, 22], "y": [33, -44], "z": ["AAA", " "]})
df_s = df.to_string(index=False)
# Leading space is expected for positive numbers.
expected = " x y z\n11 33 AAA\n22 -44 "
assert df_s == expected
df_s = df[["y", "x", "z"]].to_string(index=False)
expected = " y x z\n 33 11 AAA\n-44 22 "
assert df_s == expected
def test_to_string_unicode_columns(self, float_frame):
df = DataFrame({"\u03c3": np.arange(10.0)})
buf = StringIO()
df.to_string(buf=buf)
buf.getvalue()
buf = StringIO()
df.info(buf=buf)
buf.getvalue()
result = float_frame.to_string()
assert isinstance(result, str)
@pytest.mark.parametrize("na_rep", ["NaN", "Ted"])
def test_to_string_na_rep_and_float_format(self, na_rep):
# GH#13828
df = DataFrame([["A", 1.2225], ["A", None]], columns=["Group", "Data"])
result = df.to_string(na_rep=na_rep, float_format="{:.2f}".format)
expected = dedent(
f"""\
Group Data
0 A 1.22
1 A {na_rep}"""
)
assert result == expected
def test_to_string_string_dtype(self):
# GH#50099
pytest.importorskip("pyarrow")
df = DataFrame(
{"x": ["foo", "bar", "baz"], "y": ["a", "b", "c"], "z": [1, 2, 3]}
)
df = df.astype(
{"x": "string[pyarrow]", "y": "string[python]", "z": "int64[pyarrow]"}
)
result = df.dtypes.to_string()
expected = dedent(
"""\
x string
y string
z int64[pyarrow]"""
)
assert result == expected
def test_to_string_utf8_columns(self):
n = "\u05d0".encode()
df = DataFrame([1, 2], columns=[n])
with option_context("display.max_rows", 1):
repr(df)
def test_to_string_unicode_two(self):
dm = DataFrame({"c/\u03c3": []})
buf = StringIO()
dm.to_string(buf)
def test_to_string_unicode_three(self):
dm = DataFrame(["\xc2"])
buf = StringIO()
dm.to_string(buf)
def test_to_string_with_float_index(self):
index = Index([1.5, 2, 3, 4, 5])
df = DataFrame(np.arange(5), index=index)
result = df.to_string()
expected = " 0\n1.5 0\n2.0 1\n3.0 2\n4.0 3\n5.0 4"
assert result == expected
def test_to_string(self):
# big mixed
biggie = DataFrame(
{
"A": np.random.default_rng(2).standard_normal(200),
"B": Index([f"{i}?!" for i in range(200)]),
},
)
biggie.loc[:20, "A"] = np.nan
biggie.loc[:20, "B"] = np.nan
s = biggie.to_string()
buf = StringIO()
retval = biggie.to_string(buf=buf)
assert retval is None
assert buf.getvalue() == s
assert isinstance(s, str)
# print in right order
result = biggie.to_string(
columns=["B", "A"], col_space=17, float_format="%.5f".__mod__
)
lines = result.split("\n")
header = lines[0].strip().split()
joined = "\n".join([re.sub(r"\s+", " ", x).strip() for x in lines[1:]])
recons = read_csv(StringIO(joined), names=header, header=None, sep=" ")
tm.assert_series_equal(recons["B"], biggie["B"])
assert recons["A"].count() == biggie["A"].count()
assert (np.abs(recons["A"].dropna() - biggie["A"].dropna()) < 0.1).all()
# FIXME: don't leave commented-out
# expected = ['B', 'A']
# assert header == expected
result = biggie.to_string(columns=["A"], col_space=17)
header = result.split("\n")[0].strip().split()
expected = ["A"]
assert header == expected
biggie.to_string(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"})
biggie.to_string(columns=["B", "A"], float_format=str)
biggie.to_string(columns=["B", "A"], col_space=12, float_format=str)
frame = DataFrame(index=np.arange(200))
frame.to_string()
# TODO: split or simplify this test?
@pytest.mark.xfail(using_string_dtype(), reason="fix when arrow is default")
def test_to_string_index_with_nan(self):
# GH#2850
df = DataFrame(
{
"id1": {0: "1a3", 1: "9h4"},
"id2": {0: np.nan, 1: "d67"},
"id3": {0: "78d", 1: "79d"},
"value": {0: 123, 1: 64},
}
)
# multi-index
y = df.set_index(["id1", "id2", "id3"])
result = y.to_string()
expected = (
" value\nid1 id2 id3 \n"
"1a3 NaN 78d 123\n9h4 d67 79d 64"
)
assert result == expected
# index
y = df.set_index("id2")
result = y.to_string()
expected = (
" id1 id3 value\nid2 \n"
"NaN 1a3 78d 123\nd67 9h4 79d 64"
)
assert result == expected
# with append (this failed in 0.12)
y = df.set_index(["id1", "id2"]).set_index("id3", append=True)
result = y.to_string()
expected = (
" value\nid1 id2 id3 \n"
"1a3 NaN 78d 123\n9h4 d67 79d 64"
)
assert result == expected
# all-nan in mi
df2 = df.copy()
df2.loc[:, "id2"] = np.nan
y = df2.set_index("id2")
result = y.to_string()
expected = (
" id1 id3 value\nid2 \n"
"NaN 1a3 78d 123\nNaN 9h4 79d 64"
)
assert result == expected
# partial nan in mi
df2 = df.copy()
df2.loc[:, "id2"] = np.nan
y = df2.set_index(["id2", "id3"])
result = y.to_string()
expected = (
" id1 value\nid2 id3 \n"
"NaN 78d 1a3 123\n 79d 9h4 64"
)
assert result == expected
df = DataFrame(
{
"id1": {0: np.nan, 1: "9h4"},
"id2": {0: np.nan, 1: "d67"},
"id3": {0: np.nan, 1: "79d"},
"value": {0: 123, 1: 64},
}
)
y = df.set_index(["id1", "id2", "id3"])
result = y.to_string()
expected = (
" value\nid1 id2 id3 \n"
"NaN NaN NaN 123\n9h4 d67 79d 64"
)
assert result == expected
def test_to_string_nonunicode_nonascii_alignment(self):
df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]])
rep_str = df.to_string()
lines = rep_str.split("\n")
assert len(lines[1]) == len(lines[2])
def test_unicode_problem_decoding_as_ascii(self):
df = DataFrame({"c/\u03c3": Series({"test": np.nan})})
str(df.to_string())
def test_to_string_repr_unicode(self):
buf = StringIO()
unicode_values = ["\u03c3"] * 10
unicode_values = np.array(unicode_values, dtype=object)
df = DataFrame({"unicode": unicode_values})
df.to_string(col_space=10, buf=buf)
# it works!
repr(df)
# it works even if sys.stdin in None
_stdin = sys.stdin
try:
sys.stdin = None
repr(df)
finally:
sys.stdin = _stdin
def test_nested_dataframe(self):
df1 = DataFrame({"level1": [["row1"], ["row2"]]})
df2 = DataFrame({"level3": [{"level2": df1}]})
result = df2.to_string()
expected = " level3\n0 {'level2': ['level1']}"
assert result == expected
| TestDataFrameToString |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/utils.py | {
"start": 5276,
"end": 11734
} | class ____(BaseModel):
embedding_model: Union[
Literal["open-clip", "colpali", "jina", "imagebind"], EmbeddingFunction
]
kwargs: dict = Field(
default_factory=dict,
)
@model_validator(mode="after")
def validate_embedding_model(self) -> Self:
if isinstance(self.embedding_model, str):
try:
self.embedding_model = (
get_registry().get(self.embedding_model).create(**self.kwargs)
)
except Exception as e:
raise ValueError(
f"An exception occurred while creating the embeddings function: {e}"
)
return self
def get_lancedb_text_embedding_model(
embedding_model: Literal[
"bedrock-text",
"cohere",
"gemini-text",
"instructor",
"ollama",
"openai",
"sentence-transformers",
"gte-text",
"huggingface",
"colbert",
"jina",
"watsonx",
"voyageai",
],
**kwargs: Any,
):
"""
Get a pre-defined LanceDB text embedding model.
Args:
embedding_model (str): name of the embedding model.
**kwargs (Any): keyword arguments that are necessary for the initialization of the embedding model you want to use.
Returns:
EmbeddingFunction: a LanceDB embedding function.
"""
return LanceDBTextModel(embedding_model=embedding_model, kwargs=kwargs)
def get_lancedb_multimodal_embedding_model(
embedding_model: Literal["open-clip", "colpali", "jina", "imagebind"], **kwargs: Any
):
"""
Get a pre-defined LanceDB multimodal embedding model.
Args:
embedding_model (str): name of the embedding model.
**kwargs (Any): keyword arguments that are necessary for the initialization of the embedding model you want to use.
Returns:
EmbeddingFunction: a LanceDB embedding function.
"""
return LanceDBMultiModalModel(embedding_model=embedding_model, kwargs=kwargs)
def query_text(table: Table, query: str, **kwargs: Any) -> List[NodeWithScore]:
"""
Query a text-based table.
Args:
query (str): a string representing a text query.
"""
data = table.search(query).to_list()
documents: List[NodeWithScore] = []
for d in data:
if "text" in d:
documents.append(
NodeWithScore(
node=Document(text=d["text"], id_=d["id"]), score=d["_distance"]
)
)
else:
documents.append(
NodeWithScore(
ImageDocument(
image_url=d["image_uri"],
image=d["image_bytes"],
id_=d["id"],
metadata={"label": d["label"]},
),
score=d["_distance"],
)
)
return documents
def query_multimodal(
table: Table,
query: Union[ImageDocument, Image.Image, str, ImageBlock],
**kwargs: Any,
) -> List[NodeWithScore]:
"""
Query a multimodal table.
Args:
query (Union[ImageDocument, Image.Image, str, ImageBlock]): An ImageDocument or an ImageBlock, a PIL Image or a string representing an image URL.
"""
if isinstance(query, (ImageBlock, ImageDocument)):
image_buffer = query.resolve_image()
image_query = Image.open(image_buffer)
elif isinstance(query, Image.Image):
image_query = query
elif isinstance(query, str):
image_bytes = httpx.get(query).content
image_query = Image.open(io.BytesIO(image_bytes))
else:
raise ValueError("Image type not supported.")
data = table.search(image_query).to_list()
documents: List[NodeWithScore] = []
for d in data:
documents.append(
NodeWithScore(
ImageDocument(
image_url=d["image_uri"],
image=d["image_bytes"],
id_=d["id"],
metadata={"label": d["label"]},
),
score=d["_distance"],
)
)
return documents
async def aquery_text(
table: AsyncTable, query: str, **kwargs: Any
) -> List[NodeWithScore]:
"""
Query a text-based table.
Args:
query (str): a string representing a text query.
"""
dt = await table.search(query)
data = await dt.to_list()
documents: List[NodeWithScore] = []
for d in data:
if "text" in d:
documents.append(
NodeWithScore(
node=Document(text=d["text"], id_=d["id"]), score=d["_distance"]
)
)
else:
documents.append(
NodeWithScore(
ImageDocument(
image_url=d["image_uri"],
image=d["image_bytes"],
id_=d["id"],
metadata={"label": d["label"]},
),
score=d["_distance"],
)
)
return documents
async def aquery_multimodal(
table: AsyncTable,
query: Union[ImageDocument, Image.Image, str, ImageBlock],
**kwargs: Any,
) -> List[NodeWithScore]:
"""
Query a multimodal table.
Args:
query (Union[ImageDocument, Image.Image, str, ImageBlock]): An ImageDocument or an ImageBlock, a PIL Image or a string representing an image URL.
"""
if isinstance(query, (ImageBlock, ImageDocument)):
image_buffer = query.resolve_image()
image_query = Image.open(image_buffer)
elif isinstance(query, Image.Image):
image_query = query
elif isinstance(query, str):
image_bytes = httpx.get(query).content
image_query = Image.open(io.BytesIO(image_bytes))
else:
raise ValueError("Image type not supported.")
dt = await table.search(image_query)
data = await dt.to_list()
documents: List[NodeWithScore] = []
for d in data:
documents.append(
NodeWithScore(
ImageDocument(
image_url=d["image_uri"],
image=d["image_bytes"],
id_=d["id"],
metadata={"label": d["label"]},
),
score=d["_distance"],
)
)
return documents
| LanceDBMultiModalModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/cloud_composer.py | {
"start": 6189,
"end": 13386
} | class ____(BaseTrigger):
"""The trigger wait for the DAG run completion."""
def __init__(
self,
project_id: str,
region: str,
environment_id: str,
composer_dag_id: str,
start_date: datetime,
end_date: datetime,
allowed_states: list[str],
composer_dag_run_id: str | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
poll_interval: int = 10,
composer_airflow_version: int = 2,
use_rest_api: bool = False,
):
super().__init__()
self.project_id = project_id
self.region = region
self.environment_id = environment_id
self.composer_dag_id = composer_dag_id
self.start_date = start_date
self.end_date = end_date
self.allowed_states = allowed_states
self.composer_dag_run_id = composer_dag_run_id
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
self.poll_interval = poll_interval
self.composer_airflow_version = composer_airflow_version
self.use_rest_api = use_rest_api
def serialize(self) -> tuple[str, dict[str, Any]]:
return (
"airflow.providers.google.cloud.triggers.cloud_composer.CloudComposerDAGRunTrigger",
{
"project_id": self.project_id,
"region": self.region,
"environment_id": self.environment_id,
"composer_dag_id": self.composer_dag_id,
"start_date": self.start_date,
"end_date": self.end_date,
"allowed_states": self.allowed_states,
"composer_dag_run_id": self.composer_dag_run_id,
"gcp_conn_id": self.gcp_conn_id,
"impersonation_chain": self.impersonation_chain,
"poll_interval": self.poll_interval,
"composer_airflow_version": self.composer_airflow_version,
"use_rest_api": self.use_rest_api,
},
)
async def _pull_dag_runs(self) -> list[dict]:
"""Pull the list of dag runs."""
if self.use_rest_api:
try:
environment = await self.gcp_hook.get_environment(
project_id=self.project_id,
region=self.region,
environment_id=self.environment_id,
)
except NotFound as not_found_err:
self.log.info("The Composer environment %s does not exist.", self.environment_id)
raise AirflowException(not_found_err)
composer_airflow_uri = environment.config.airflow_uri
self.log.info(
"Pulling the DAG %s runs from the %s environment...",
self.composer_dag_id,
self.environment_id,
)
dag_runs_response = await self.gcp_hook.get_dag_runs(
composer_airflow_uri=composer_airflow_uri,
composer_dag_id=self.composer_dag_id,
)
dag_runs = dag_runs_response["dag_runs"]
else:
cmd_parameters = (
["-d", self.composer_dag_id, "-o", "json"]
if self.composer_airflow_version < 3
else [self.composer_dag_id, "-o", "json"]
)
dag_runs_cmd = await self.gcp_hook.execute_airflow_command(
project_id=self.project_id,
region=self.region,
environment_id=self.environment_id,
command="dags",
subcommand="list-runs",
parameters=cmd_parameters,
)
cmd_result = await self.gcp_hook.wait_command_execution_result(
project_id=self.project_id,
region=self.region,
environment_id=self.environment_id,
execution_cmd_info=ExecuteAirflowCommandResponse.to_dict(dag_runs_cmd),
)
dag_runs = json.loads(cmd_result["output"][0]["content"])
return dag_runs
def _check_dag_runs_states(
self,
dag_runs: list[dict],
start_date: datetime,
end_date: datetime,
) -> bool:
for dag_run in dag_runs:
if (
start_date.timestamp()
< parser.parse(
dag_run["execution_date" if self.composer_airflow_version < 3 else "logical_date"]
).timestamp()
< end_date.timestamp()
) and dag_run["state"] not in self.allowed_states:
return False
return True
def _get_async_hook(self) -> CloudComposerAsyncHook:
return CloudComposerAsyncHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
def _check_composer_dag_run_id_states(self, dag_runs: list[dict]) -> bool:
for dag_run in dag_runs:
if (
dag_run["dag_run_id" if self.use_rest_api else "run_id"] == self.composer_dag_run_id
and dag_run["state"] in self.allowed_states
):
return True
return False
async def run(self):
self.gcp_hook: CloudComposerAsyncHook = self._get_async_hook()
try:
while True:
if datetime.now(self.end_date.tzinfo).timestamp() > self.end_date.timestamp():
dag_runs = await self._pull_dag_runs()
if len(dag_runs) == 0:
self.log.info("Dag runs are empty. Sensor waits for dag runs...")
self.log.info("Sleeping for %s seconds.", self.poll_interval)
await asyncio.sleep(self.poll_interval)
continue
if self.composer_dag_run_id:
self.log.info(
"Sensor waits for allowed states %s for specified RunID: %s",
self.allowed_states,
self.composer_dag_run_id,
)
if self._check_composer_dag_run_id_states(dag_runs=dag_runs):
yield TriggerEvent({"status": "success"})
return
else:
self.log.info("Sensor waits for allowed states: %s", self.allowed_states)
if self._check_dag_runs_states(
dag_runs=dag_runs,
start_date=self.start_date,
end_date=self.end_date,
):
yield TriggerEvent({"status": "success"})
return
self.log.info("Sleeping for %s seconds.", self.poll_interval)
await asyncio.sleep(self.poll_interval)
except AirflowException as ex:
yield TriggerEvent(
{
"status": "error",
"message": str(ex),
}
)
return
| CloudComposerDAGRunTrigger |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 33119,
"end": 35021
} | class ____(NonStrictDataModel):
"""
:param sets: List of augmentation sets
:type sets: Sequence[AugmentationSet]
:param crop_around_rois: Crop image data around all frame ROIs
:type crop_around_rois: bool
"""
_schema = {
"properties": {
"crop_around_rois": {
"description": "Crop image data around all frame ROIs",
"type": ["boolean", "null"],
},
"sets": {
"description": "List of augmentation sets",
"items": {"$ref": "#/definitions/augmentation_set"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, sets=None, crop_around_rois=None, **kwargs):
super(Augmentation, self).__init__(**kwargs)
self.sets = sets
self.crop_around_rois = crop_around_rois
@schema_property("sets")
def sets(self):
return self._property_sets
@sets.setter
def sets(self, value):
if value is None:
self._property_sets = None
return
self.assert_isinstance(value, "sets", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
AugmentationSet.from_dict(v) if isinstance(v, dict) else v
for v in value
]
else:
self.assert_isinstance(value, "sets", AugmentationSet, is_array=True)
self._property_sets = value
@schema_property("crop_around_rois")
def crop_around_rois(self):
return self._property_crop_around_rois
@crop_around_rois.setter
def crop_around_rois(self, value):
if value is None:
self._property_crop_around_rois = None
return
self.assert_isinstance(value, "crop_around_rois", (bool,))
self._property_crop_around_rois = value
| Augmentation |
python | tensorflow__tensorflow | tensorflow/python/framework/function_test.py | {
"start": 58360,
"end": 60022
} | class ____(test.TestCase):
@test_util.run_v1_only("make_template not supported in TF2")
def testBasic(self):
self.assertTemplateVariableSharing(use_resource=True, defun_first=False)
@test_util.run_v1_only("make_template not supported in TF2")
def testBasicRef(self):
self.assertTemplateVariableSharing(use_resource=False, defun_first=False)
@test_util.run_v1_only("make_template not supported in TF2")
def testBasicDefunFirst(self):
self.assertTemplateVariableSharing(use_resource=True, defun_first=True)
@test_util.run_v1_only("make_template not supported in TF2")
def testBasicRefDefunFirst(self):
self.assertTemplateVariableSharing(use_resource=False, defun_first=True)
def assertTemplateVariableSharing(self, use_resource, defun_first):
parameters = []
def MakeModel(x):
w = variable_scope.get_variable(
"w", (64, 64),
initializer=init_ops.random_uniform_initializer(seed=312),
use_resource=use_resource)
b = variable_scope.get_variable(
"b", (64),
initializer=init_ops.zeros_initializer(),
use_resource=use_resource)
parameters.extend((w, b))
return math_ops.sigmoid(math_ops.matmul(x, w) + b)
model = template.make_template("f", MakeModel, create_scope_now_=True)
@function.Defun()
def ModelDefun(x):
return model(x)
x = array_ops.placeholder(dtypes.float32)
if defun_first:
ModelDefun(x)
model(x)
else:
model(x)
ModelDefun(x)
w1, b1, w2, b2 = parameters # pylint: disable=unbalanced-tuple-unpacking
self.assertIs(w1, w2)
self.assertIs(b1, b2)
| TemplateTest |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 22826,
"end": 23657
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a block type."""
name: str = Field(default=..., description="A block type's name")
slug: BlockTypeSlug = Field(default=..., description="A block type's slug")
logo_url: Optional[objects.HttpUrl] = Field(
default=None, description="Web URL for the block type's logo"
)
documentation_url: Optional[objects.HttpUrl] = Field(
default=None, description="Web URL for the block type's documentation"
)
description: Optional[str] = Field(
default=None,
description="A short blurb about the corresponding block's intended use",
)
code_example: Optional[str] = Field(
default=None,
description="A code snippet demonstrating use of the corresponding block",
)
| BlockTypeCreate |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 322339,
"end": 324460
} | class ____(LoopNode, StatNode):
# while statement
#
# condition ExprNode
# body StatNode
# else_clause StatNode
child_attrs = ["condition", "body", "else_clause"]
def analyse_declarations(self, env):
self.body.analyse_declarations(env)
if self.else_clause:
self.else_clause.analyse_declarations(env)
def analyse_expressions(self, env):
if self.condition:
self.condition = self.condition.analyse_temp_boolean_expression(env)
self.body = self.body.analyse_expressions(env)
if self.else_clause:
self.else_clause = self.else_clause.analyse_expressions(env)
return self
def generate_execution_code(self, code):
code.mark_pos(self.pos)
old_loop_labels = code.new_loop_labels()
code.putln(
"while (1) {")
if self.condition:
self.condition.generate_evaluation_code(code)
self.condition.generate_disposal_code(code)
code.putln(
"if (!%s) break;" % self.condition.result())
self.condition.free_temps(code)
self.body.generate_execution_code(code)
code.put_label(code.continue_label)
code.putln("}")
break_label = code.break_label
code.set_loop_labels(old_loop_labels)
if self.else_clause:
code.mark_pos(self.else_clause.pos)
code.putln("/*else*/ {")
self.else_clause.generate_execution_code(code)
code.putln("}")
code.put_label(break_label)
def generate_function_definitions(self, env, code):
if self.condition:
self.condition.generate_function_definitions(env, code)
self.body.generate_function_definitions(env, code)
if self.else_clause is not None:
self.else_clause.generate_function_definitions(env, code)
def annotate(self, code):
if self.condition:
self.condition.annotate(code)
self.body.annotate(code)
if self.else_clause:
self.else_clause.annotate(code)
| WhileStatNode |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 1848,
"end": 1939
} | class ____(OKMessage):
run_spec: ShuffleRunSpec | ToPickle[ShuffleRunSpec]
| RunSpecMessage |
python | allegroai__clearml | clearml/utilities/pyhocon/config_tree.py | {
"start": 419,
"end": 16474
} | class ____(OrderedDict):
KEY_SEP = '.'
def __init__(self, *args, **kwds):
self.root = kwds.pop('root') if 'root' in kwds else False
if self.root:
self.history = {}
super(ConfigTree, self).__init__(*args, **kwds)
for key, value in self.items():
if isinstance(value, ConfigValues):
value.parent = self
value.index = key
@staticmethod
def merge_configs(a, b, copy_trees=False):
"""Merge config b into a
:param a: target config
:type a: ConfigTree
:param b: source config
:type b: ConfigTree
:return: merged config a
"""
for key, value in b.items():
# if key is in both a and b and both values are dictionary then merge it otherwise override it
if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree):
if copy_trees:
a[key] = a[key].copy()
ConfigTree.merge_configs(a[key], b[key], copy_trees=copy_trees)
else:
if isinstance(value, ConfigValues):
value.parent = a
value.key = key
if key in a:
value.overriden_value = a[key]
a[key] = value
if a.root:
if b.root:
a.history[key] = a.history.get(key, []) + b.history.get(key, [value])
else:
a.history[key] = a.history.get(key, []) + [value]
return a
def _put(self, key_path, value, append=False):
key_elt = key_path[0]
if len(key_path) == 1:
# if value to set does not exist, override
# if they are both configs then merge
# if not then override
if key_elt in self and isinstance(self[key_elt], ConfigTree) and isinstance(value, ConfigTree):
if self.root:
new_value = ConfigTree.merge_configs(ConfigTree(), self[key_elt], copy_trees=True)
new_value = ConfigTree.merge_configs(new_value, value, copy_trees=True)
self._push_history(key_elt, new_value)
self[key_elt] = new_value
else:
ConfigTree.merge_configs(self[key_elt], value)
elif append:
# If we have t=1
# and we try to put t.a=5 then t is replaced by {a: 5}
l_value = self.get(key_elt, None)
if isinstance(l_value, ConfigValues):
l_value.tokens.append(value)
l_value.recompute()
elif isinstance(l_value, ConfigTree) and isinstance(value, ConfigValues):
value.overriden_value = l_value
value.tokens.insert(0, l_value)
value.recompute()
value.parent = self
value.key = key_elt
self._push_history(key_elt, value)
self[key_elt] = value
elif isinstance(l_value, list) and isinstance(value, ConfigValues):
self._push_history(key_elt, value)
value.overriden_value = l_value
value.parent = self
value.key = key_elt
self[key_elt] = value
elif isinstance(l_value, list):
self[key_elt] = l_value + value
self._push_history(key_elt, l_value)
elif l_value is None:
self._push_history(key_elt, value)
self[key_elt] = value
else:
raise ConfigWrongTypeException(
u"Cannot concatenate the list {key}: {value} to {prev_value} of {type}".format(
key='.'.join(key_path),
value=value,
prev_value=l_value,
type=l_value.__class__.__name__)
)
else:
# if there was an override keep overide value
if isinstance(value, ConfigValues):
value.parent = self
value.key = key_elt
value.overriden_value = self.get(key_elt, None)
self._push_history(key_elt, value)
self[key_elt] = value
else:
next_config_tree = super(ConfigTree, self).get(key_elt)
if not isinstance(next_config_tree, ConfigTree):
# create a new dictionary or overwrite a previous value
next_config_tree = ConfigTree()
self._push_history(key_elt, next_config_tree)
self[key_elt] = next_config_tree
next_config_tree._put(key_path[1:], value, append)
def _push_history(self, key, value):
if self.root:
hist = self.history.get(key)
if hist is None:
hist = self.history[key] = []
hist.append(value)
def _get(self, key_path, key_index=0, default=UndefinedKey):
key_elt = key_path[key_index]
elt = super(ConfigTree, self).get(key_elt, UndefinedKey)
if elt is UndefinedKey:
if default is UndefinedKey:
raise ConfigMissingException(u"No configuration setting found for key {key}".format(
key='.'.join(key_path[: key_index + 1])))
else:
return default
if key_index == len(key_path) - 1:
if isinstance(elt, NoneValue):
return None
elif isinstance(elt, list):
return [None if isinstance(x, NoneValue) else x for x in elt]
else:
return elt
elif isinstance(elt, ConfigTree):
return elt._get(key_path, key_index + 1, default)
else:
if default is UndefinedKey:
raise ConfigWrongTypeException(
u"{key} has type {type} rather than dict".format(key='.'.join(key_path[:key_index + 1]),
type=type(elt).__name__))
else:
return default
@staticmethod
def parse_key(string):
"""
Split a key into path elements:
- a.b.c => a, b, c
- a."b.c" => a, QuotedKey("b.c") if . is any of the special characters: $}[]:=+#`^?!@*&.
- "a" => a
- a.b."c" => a, b, c (special case)
:param string: either string key (parse '.' as sub-key) or int / float as regular keys
:return:
"""
if isinstance(string, (int, float)):
return [string]
special_characters = '$}[]:=+#`^?!@*&.'
tokens = re.findall(
r'"[^"]+"|[^{special_characters}]+'.format(special_characters=re.escape(special_characters)),
string)
def contains_special_character(token):
return any((c in special_characters) for c in token)
return [token if contains_special_character(token) else token.strip('"') for token in tokens]
def put(self, key, value, append=False):
"""Put a value in the tree (dot separated)
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param value: value to put
"""
self._put(ConfigTree.parse_key(key), value, append)
def get(self, key, default=UndefinedKey):
"""Get a value from the tree
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:return: value in the tree located at key
"""
return self._get(ConfigTree.parse_key(key), 0, default)
def get_string(self, key, default=UndefinedKey):
"""Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring
"""
value = self.get(key, default)
if value is None:
return None
string_value = unicode(value)
if isinstance(value, bool):
string_value = string_value.lower()
return string_value
def pop(self, key, default=UndefinedKey):
"""Remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse_key
and pops the last value out of the dict.
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: object
:param default: default value if key not found
:return: value in the tree located at key
"""
if default != UndefinedKey and key not in self:
return default
value = self.get(key, UndefinedKey)
lst = ConfigTree.parse_key(key)
parent = self.KEY_SEP.join(lst[0:-1])
child = lst[-1]
if parent:
self.get(parent).__delitem__(child)
else:
self.__delitem__(child)
return value
def get_int(self, key, default=UndefinedKey):
"""Return int representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: int
:return: int value
:type return: int
"""
value = self.get(key, default)
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'int'".format(key=key, type=type(value).__name__))
def get_float(self, key, default=UndefinedKey):
"""Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
:type return: float
"""
value = self.get(key, default)
try:
return float(value) if value is not None else None
except (TypeError, ValueError):
raise ConfigException(
u"{key} has type '{type}' rather than 'float'".format(key=key, type=type(value).__name__))
def get_bool(self, key, default=UndefinedKey):
"""Return boolean representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: bool
:return: boolean value
:type return: bool
"""
# String conversions as per API-recommendations:
# https://github.com/typesafehub/config/blob/master/HOCON.md#automatic-type-conversions
bool_conversions = {
None: None,
'true': True, 'yes': True, 'on': True,
'false': False, 'no': False, 'off': False
}
string_value = self.get_string(key, default)
if string_value is not None:
string_value = string_value.lower()
try:
return bool_conversions[string_value]
except KeyError:
raise ConfigException(
u"{key} does not translate to a Boolean value".format(key=key))
def get_list(self, key, default=UndefinedKey):
"""Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:type return: list
"""
value = self.get(key, default)
if isinstance(value, list):
return value
elif isinstance(value, ConfigTree):
lst = []
for k, v in sorted(value.items(), key=lambda kv: kv[0]):
if re.match(r'^[1-9][0-9]*$|0', k):
lst.append(v)
else:
raise ConfigException(u"{key} does not translate to a list".format(key=key))
return lst
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'list'".format(key=key, type=type(value).__name__))
def get_config(self, key, default=UndefinedKey):
"""Return tree config representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: config
:return: config value
:type return: ConfigTree
"""
value = self.get(key, default)
if isinstance(value, dict):
return value
elif value is None:
return None
else:
raise ConfigException(
u"{key} has type '{type}' rather than 'config'".format(key=key, type=type(value).__name__))
def __getitem__(self, item):
val = self.get(item)
if val is UndefinedKey:
raise KeyError(item)
return val
try:
from collections import _OrderedDictItemsView
except ImportError: # pragma: nocover
pass
else:
def items(self): # pragma: nocover
return self._OrderedDictItemsView(self)
def __getattr__(self, item):
val = self.get(item, NonExistentKey)
if val is NonExistentKey:
return super(ConfigTree, self).__getattr__(item)
return val
def __contains__(self, item):
return self._get(self.parse_key(item), default=NoneValue) is not NoneValue
def with_fallback(self, config, resolve=True):
"""
return a new config with fallback on config
:param config: config or filename of the config to fallback on
:param resolve: resolve substitutions
:return: new config with fallback on config
"""
if isinstance(config, ConfigTree):
result = ConfigTree.merge_configs(copy.deepcopy(config), copy.deepcopy(self))
else:
from . import ConfigFactory
result = ConfigTree.merge_configs(ConfigFactory.parse_file(config, resolve=False), copy.deepcopy(self))
if resolve:
from . import ConfigParser
ConfigParser.resolve_substitutions(result)
return result
def as_plain_ordered_dict(self):
"""return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are not surrounded with '"' in the plain OrderedDict.
:return: this config as an OrderedDict
:type return: OrderedDict
"""
def plain_value(v):
if isinstance(v, list):
return [plain_value(e) for e in v]
elif isinstance(v, ConfigTree):
return v.as_plain_ordered_dict()
else:
if isinstance(v, ConfigValues):
raise ConfigException("The config tree contains unresolved elements")
return v
return OrderedDict((key.strip('"') if isinstance(key, (unicode, basestring)) else key, plain_value(value))
for key, value in self.items())
| ConfigTree |
python | sympy__sympy | sympy/physics/quantum/gate.py | {
"start": 26743,
"end": 30464
} | class ____(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
========
>>> from sympy.physics.quantum.gate import CNOT
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import Qubit
>>> c = CNOT(1,0)
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|11>
"""
gate_name = 'CNOT'
gate_name_latex = r'\text{CNOT}'
simplify_cgate = True
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Gate._eval_args(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.label) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return (self.label[1],)
@property
def controls(self):
"""A tuple of control qubits."""
return (self.label[0],)
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return XGate(self.label[1])
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
# The default printing of Gate works better than those of CGate, so we
# go around the overridden methods in CGate.
def _print_label(self, printer, *args):
return Gate._print_label(self, printer, *args)
def _pretty(self, printer, *args):
return Gate._pretty(self, printer, *args)
def _latex(self, printer, *args):
return Gate._latex(self, printer, *args)
#-------------------------------------------------------------------------
# Commutator/AntiCommutator
#-------------------------------------------------------------------------
def _eval_commutator_ZGate(self, other, **hints):
"""[CNOT(i, j), Z(i)] == 0."""
if self.controls[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_TGate(self, other, **hints):
"""[CNOT(i, j), T(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_PhaseGate(self, other, **hints):
"""[CNOT(i, j), S(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_XGate(self, other, **hints):
"""[CNOT(i, j), X(j)] == 0."""
if self.targets[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_CNotGate(self, other, **hints):
"""[CNOT(i, j), CNOT(i,k)] == 0."""
if self.controls[0] == other.controls[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
| CNotGate |
python | python-excel__xlrd | tests/test_xldate_to_datetime.py | {
"start": 250,
"end": 6129
} | class ____(unittest.TestCase):
"""
Testcases to test the _xldate_to_datetime() function against dates
extracted from Excel files, with 1900/1904 epochs.
"""
def test_dates_and_times_1900_epoch(self):
"""
Test the _xldate_to_datetime() function for dates and times in
the Excel standard 1900 epoch.
"""
# Test Excel dates strings and corresponding serial date numbers taken
# from an Excel file.
excel_dates = [
# Excel's 0.0 date in the 1900 epoch is 1 day before 1900.
('1899-12-31T00:00:00.000', 0),
# Date/time before the false Excel 1900 leapday.
('1900-02-28T02:11:11.986', 59.09111094906),
# Date/time after the false Excel 1900 leapday.
('1900-03-01T05:46:44.068', 61.24078782403),
# Random date/times in Excel's 0-9999.9999+ range.
('1982-08-25T00:15:20.213', 30188.010650613425),
('2065-04-19T00:16:48.290', 60376.011670023145),
('3222-06-11T03:08:08.251', 483014.13065105322),
('4379-08-03T06:14:48.580', 905652.26028449077),
('5949-12-30T12:59:54.263', 1479232.5416002662),
# End of Excel's date range.
('9999-12-31T23:59:59.000', 2958465.999988426),
]
# Convert the Excel date strings to datetime objects and compare
# against the dateitme return value of xldate.xldate_as_datetime().
for excel_date in excel_dates:
exp = datetime.strptime(excel_date[0], "%Y-%m-%dT%H:%M:%S.%f")
got = xldate.xldate_as_datetime(excel_date[1], not_1904)
self.assertEqual(got, exp)
def test_dates_only_1900_epoch(self):
"""
Test the _xldate_to_datetime() function for dates in the Excel
standard 1900 epoch.
"""
# Test Excel dates strings and corresponding serial date numbers taken
# from an Excel file.
excel_dates = [
# Excel's day 0 in the 1900 epoch is 1 day before 1900.
('1899-12-31', 0),
# Excel's day 1 in the 1900 epoch.
('1900-01-01', 1),
# Date/time before the false Excel 1900 leapday.
('1900-02-28', 59),
# Date/time after the false Excel 1900 leapday.
('1900-03-01', 61),
# Random date/times in Excel's 0-9999.9999+ range.
('1902-09-27', 1001),
('1999-12-31', 36525),
('2000-01-01', 36526),
('4000-12-31', 767376),
('4321-01-01', 884254),
('9999-01-01', 2958101),
# End of Excel's date range.
('9999-12-31', 2958465),
]
# Convert the Excel date strings to datetime objects and compare
# against the dateitme return value of xldate.xldate_as_datetime().
for excel_date in excel_dates:
exp = datetime.strptime(excel_date[0], "%Y-%m-%d")
got = xldate.xldate_as_datetime(excel_date[1], not_1904)
self.assertEqual(got, exp)
def test_dates_only_1904_epoch(self):
"""
Test the _xldate_to_datetime() function for dates in the Excel
Mac/1904 epoch.
"""
# Test Excel dates strings and corresponding serial date numbers taken
# from an Excel file.
excel_dates = [
# Excel's day 0 in the 1904 epoch.
('1904-01-01', 0),
# Random date/times in Excel's 0-9999.9999+ range.
('1904-01-31', 30),
('1904-08-31', 243),
('1999-02-28', 34757),
('1999-12-31', 35063),
('2000-01-01', 35064),
('2400-12-31', 181526),
('4000-01-01', 765549),
('9999-01-01', 2956639),
# End of Excel's date range.
('9999-12-31', 2957003),
]
# Convert the Excel date strings to datetime objects and compare
# against the dateitme return value of xldate.xldate_as_datetime().
for excel_date in excel_dates:
exp = datetime.strptime(excel_date[0], "%Y-%m-%d")
got = xldate.xldate_as_datetime(excel_date[1], is_1904)
self.assertEqual(got, exp)
def test_times_only(self):
"""
Test the _xldate_to_datetime() function for times only, i.e, the
fractional part of the Excel date when the serial date is 0.
"""
# Test Excel dates strings and corresponding serial date numbers taken
# from an Excel file. The 1899-12-31 date is Excel's day 0.
excel_dates = [
# Random times in Excel's 0-0.9999+ range for 1 day.
('1899-12-31T00:00:00.000', 0),
('1899-12-31T00:15:20.213', 1.0650613425925924E-2),
('1899-12-31T02:24:37.095', 0.10042934027777778),
('1899-12-31T04:56:35.792', 0.2059698148148148),
('1899-12-31T07:31:20.407', 0.31343063657407405),
('1899-12-31T09:37:23.945', 0.40097158564814817),
('1899-12-31T12:09:48.602', 0.50681252314814818),
('1899-12-31T14:37:57.451', 0.60969271990740748),
('1899-12-31T17:04:02.415', 0.71113906250000003),
('1899-12-31T19:14:24.673', 0.80167445601851861),
('1899-12-31T21:39:05.944', 0.90215212962962965),
('1899-12-31T23:17:12.632', 0.97028509259259266),
('1899-12-31T23:59:59.999', 0.99999998842592586),
]
# Convert the Excel date strings to datetime objects and compare
# against the dateitme return value of xldate.xldate_as_datetime().
for excel_date in excel_dates:
exp = datetime.strptime(excel_date[0], "%Y-%m-%dT%H:%M:%S.%f")
got = xldate.xldate_as_datetime(excel_date[1], not_1904)
self.assertEqual(got, exp)
| TestConvertToDateTime |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py | {
"start": 2336,
"end": 2888
} | class ____(BaseEvent):
"""Event fired when attachment processing completes successfully."""
page_id: str = Field(description="ID of the parent page")
attachment_id: str = Field(description="ID of the attachment")
attachment_name: str = Field(description="Name of the attachment")
attachment_type: str = Field(description="MIME type of the attachment")
attachment_size: int = Field(description="Size of the attachment in bytes")
attachment_link: str = Field(description="Link to the attachment")
| SNOWKBAttachmentProcessedEvent |
python | Pylons__pyramid | tests/test_predicates.py | {
"start": 3102,
"end": 5517
} | class ____(unittest.TestCase):
def _makeOne(self, val):
from pyramid.predicates import RequestParamPredicate
return RequestParamPredicate(val, None)
def test___call___true_exists(self):
inst = self._makeOne('abc')
request = Dummy()
request.params = {'abc': 1}
result = inst(None, request)
self.assertTrue(result)
def test___call___true_withval(self):
inst = self._makeOne('abc=1')
request = Dummy()
request.params = {'abc': '1'}
result = inst(None, request)
self.assertTrue(result)
def test___call___true_multi(self):
inst = self._makeOne(('abc', '=def =2= '))
request = Dummy()
request.params = {'abc': '1', '=def': '2='}
result = inst(None, request)
self.assertTrue(result)
def test___call___false_multi(self):
inst = self._makeOne(('abc=3', 'def =2 '))
request = Dummy()
request.params = {'abc': '3', 'def': '1'}
result = inst(None, request)
self.assertFalse(result)
def test___call___false(self):
inst = self._makeOne('abc')
request = Dummy()
request.params = {}
result = inst(None, request)
self.assertFalse(result)
def test_text_exists(self):
inst = self._makeOne('abc')
self.assertEqual(inst.text(), 'request_param abc')
def test_text_exists_equal_sign(self):
inst = self._makeOne('=abc')
self.assertEqual(inst.text(), 'request_param =abc')
def test_text_withval(self):
inst = self._makeOne('abc= 1')
self.assertEqual(inst.text(), 'request_param abc=1')
def test_text_multi(self):
inst = self._makeOne(('abc= 1', 'def'))
self.assertEqual(inst.text(), 'request_param abc=1,def')
def test_text_multi_equal_sign(self):
inst = self._makeOne(('abc= 1', '=def= 2'))
self.assertEqual(inst.text(), 'request_param =def=2,abc=1')
def test_phash_exists(self):
inst = self._makeOne('abc')
self.assertEqual(inst.phash(), 'request_param abc')
def test_phash_exists_equal_sign(self):
inst = self._makeOne('=abc')
self.assertEqual(inst.phash(), 'request_param =abc')
def test_phash_withval(self):
inst = self._makeOne('abc= 1')
self.assertEqual(inst.phash(), "request_param abc=1")
| TestRequestParamPredicate |
python | geekcomputers__Python | BrowserHistory/backend.py | {
"start": 272,
"end": 2870
} | class ____:
"""
This class designs the operations of a browser history
It works by using a doubly linked list to hold the urls with optimized
navigation using step counters and memory management
"""
def __init__(self, homepage: str):
"""
Returns - None
Input - str
----------
- Initialize doubly linked list which will serve as the
browser history and sets the current page
- Initialize navigation counters
"""
self._head = DLL(homepage)
self._curr = self._head
self._back_count = 0
self._forward_count = 0
def visit(self, url: str) -> None:
"""
Returns - None
Input - str
----------
- Adds the current url to the DLL
- Sets both the next and previous values
- Cleans up forward history to prevent memory leaks
- Resets forward count and increments back count
"""
# Clear forward history to prevent memory leaks
self._curr.nxt = None
self._forward_count = 0
# Create and link new node
url_node = DLL(url)
self._curr.nxt = url_node
url_node.prev = self._curr
# Update current node and counts
self._curr = url_node
self._back_count += 1
def back(self, steps: int) -> str:
"""
Returns - str
Input - int
----------
- Moves backwards through history up to available steps
- Updates navigation counters
- Returns current page URL
"""
# Only traverse available nodes
steps = min(steps, self._back_count)
while steps > 0:
self._curr = self._curr.prev
steps -= 1
self._back_count -= 1
self._forward_count += 1
return self._curr.val
def forward(self, steps: int) -> str:
"""
Returns - str
Input - int
----------
- Moves forward through history up to available steps
- Updates navigation counters
- Returns current page URL
"""
# Only traverse available nodes
steps = min(steps, self._forward_count)
while steps > 0:
self._curr = self._curr.nxt
steps -= 1
self._forward_count -= 1
self._back_count += 1
return self._curr.val
if __name__ == "__main__":
obj = BrowserHistory("google.com")
obj.visit("twitter.com")
param_2 = obj.back(1)
param_3 = obj.forward(1)
print(param_2)
print(param_3)
| BrowserHistory |
python | getsentry__sentry | tests/sentry/deletions/tasks/test_hybrid_cloud.py | {
"start": 16459,
"end": 22365
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
Monitor.objects.all().delete()
with assume_test_silo_mode_of(User):
User.objects.all().delete()
def test_get_ids_for_tombstone_cascade_cross_db(self) -> None:
data = setup_cross_db_deletion_data()
unaffected_data = []
for i in range(3):
unaffected_data.append(setup_cross_db_deletion_data())
user = data["user"]
user_id = user.id
monitor = data["monitor"]
with assume_test_silo_mode_of(User), outbox_runner():
user.delete()
tombstone = RegionTombstone.objects.get(
object_identifier=user_id, table_name=User._meta.db_table
)
highest_tombstone_id = RegionTombstone.objects.aggregate(Max("id"))
monitor_owner_field = Monitor._meta.get_field("owner_user_id")
ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
tombstone_cls=RegionTombstone,
model=Monitor,
field=monitor_owner_field,
tombstone_watermark_batch=WatermarkBatch(
low=0,
up=highest_tombstone_id["id__max"] + 1,
has_more=False,
transaction_id="foobar",
),
)
assert ids == [monitor.id]
assert oldest_obj == tombstone.created_at
def test_get_ids_for_tombstone_cascade_cross_db_watermark_bounds(self) -> None:
cascade_data = [setup_cross_db_deletion_data() for _ in range(3)]
# Create some additional filler data
[setup_cross_db_deletion_data() for _ in range(3)]
in_order_tombstones = []
for data in cascade_data:
user = data["user"]
user_id = user.id
with assume_test_silo_mode_of(User), outbox_runner():
user.delete()
in_order_tombstones.append(
RegionTombstone.objects.get(
object_identifier=user_id, table_name=User._meta.db_table
)
)
bounds_with_expected_results_tests = [
(
{"low": 0, "up": in_order_tombstones[1].id},
[cascade_data[0]["monitor"].id, cascade_data[1]["monitor"].id],
),
(
{"low": in_order_tombstones[1].id, "up": in_order_tombstones[2].id},
[cascade_data[2]["monitor"].id],
),
(
{"low": 0, "up": in_order_tombstones[0].id - 1},
[],
),
(
{"low": in_order_tombstones[2].id + 1, "up": in_order_tombstones[2].id + 5},
[],
),
(
{"low": -1, "up": in_order_tombstones[2].id + 1},
[
cascade_data[0]["monitor"].id,
cascade_data[1]["monitor"].id,
cascade_data[2]["monitor"].id,
],
),
]
for bounds, bounds_with_expected_results in bounds_with_expected_results_tests:
monitor_owner_field = Monitor._meta.get_field("owner_user_id")
ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
tombstone_cls=RegionTombstone,
model=Monitor,
field=monitor_owner_field,
tombstone_watermark_batch=WatermarkBatch(
low=bounds["low"],
up=bounds["up"],
has_more=False,
transaction_id="foobar",
),
)
assert ids == bounds_with_expected_results
def test_get_ids_for_tombstone_cascade_cross_db_with_multiple_tombstone_types(self) -> None:
data = setup_cross_db_deletion_data()
unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
# Pollute the tombstone data with references to relationships in other
# tables matching other User IDs just to ensure we are filtering on the
# correct table name.
for udata in unaffected_data:
unaffected_user = udata["user"]
RegionTombstone.objects.create(
table_name="something_table", object_identifier=unaffected_user.id
)
user, monitor = itemgetter("user", "monitor")(data)
user_id = user.id
with assume_test_silo_mode_of(User), outbox_runner():
user.delete()
tombstone = RegionTombstone.objects.get(
object_identifier=user_id, table_name=User._meta.db_table
)
highest_tombstone_id = RegionTombstone.objects.aggregate(Max("id"))
ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
tombstone_cls=RegionTombstone,
model=Monitor,
field=Monitor._meta.get_field("owner_user_id"),
tombstone_watermark_batch=WatermarkBatch(
low=0,
up=highest_tombstone_id["id__max"] + 1,
has_more=False,
transaction_id="foobar",
),
)
assert ids == [monitor.id]
assert oldest_obj == tombstone.created_at
def reserve_model_ids(model: type[Model], minimum_id: int) -> None:
# Utility that increments the primary key of the given model to the provided
# minimum. This ensures we can never have an ID collision when hardcoding ID
# values.
with assume_test_silo_mode_of(model), transaction.atomic(using=router.db_for_write(model)):
with connections[router.db_for_write(model)].cursor() as cursor:
last_id = None
while last_id is None or last_id < minimum_id:
cursor.execute("SELECT nextval(%s)", [f"{model._meta.db_table}_id_seq"])
last_id = cursor.fetchone()[0]
@region_silo_test
| TestGetIdsForTombstoneCascadeCrossDbTombstoneWatermarking |
python | sqlalchemy__sqlalchemy | test/orm/test_deferred.py | {
"start": 83894,
"end": 89121
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(ComparableEntity, Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
x = Column(Integer)
y = deferred(Column(Integer))
z = deferred(Column(Integer), raiseload=True)
@classmethod
def insert_data(cls, connection):
A = cls.classes.A
s = Session(connection)
s.add(A(id=1, x=2, y=3, z=4))
s.commit()
def test_mapper_raise(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).first()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.z' is not available due to raiseload=True",
getattr,
a1,
"z",
)
eq_(a1.x, 2)
def test_mapper_defer_unraise(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.z)).first()
assert "z" not in a1.__dict__
eq_(a1.z, 4)
eq_(a1.x, 2)
def test_mapper_undefer_unraise(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(undefer(A.z)).first()
assert "z" in a1.__dict__
eq_(a1.z, 4)
eq_(a1.x, 2)
def test_deferred_raise_option_raise_column_plain(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.x)).first()
a1.x
s.close()
a1 = s.query(A).options(defer(A.x, raiseload=True)).first()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.x' is not available due to raiseload=True",
getattr,
a1,
"x",
)
def test_load_only_raise_option_raise_column_plain(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.x)).first()
a1.x
s.close()
a1 = s.query(A).options(load_only(A.y, A.z, raiseload=True)).first()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.x' is not available due to raiseload=True",
getattr,
a1,
"x",
)
def test_deferred_raise_option_load_column_unexpire(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.x, raiseload=True)).first()
s.expire(a1, ["x"])
# after expire(), options are cleared. relationship w/ raiseload
# works this way also
eq_(a1.x, 2)
def test_mapper_raise_after_expire_attr(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).first()
s.expire(a1, ["z"])
# raises even after expire()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.z' is not available due to raiseload=True",
getattr,
a1,
"z",
)
def test_mapper_raise_after_expire_obj(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).first()
s.expire(a1)
# raises even after expire()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.z' is not available due to raiseload=True",
getattr,
a1,
"z",
)
def test_mapper_raise_after_modify_attr_expire_obj(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).first()
a1.z = 10
s.expire(a1)
# raises even after expire()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.z' is not available due to raiseload=True",
getattr,
a1,
"z",
)
def test_deferred_raise_option_load_after_expire_obj(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.y, raiseload=True)).first()
s.expire(a1)
# after expire(), options are cleared. relationship w/ raiseload
# works this way also
eq_(a1.y, 3)
def test_option_raiseload_unexpire_modified_obj(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.y, raiseload=True)).first()
a1.y = 10
s.expire(a1)
# after expire(), options are cleared. relationship w/ raiseload
# works this way also
eq_(a1.y, 3)
def test_option_raise_deferred(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.y, raiseload=True)).first()
assert_raises_message(
sa.exc.InvalidRequestError,
"'A.y' is not available due to raiseload=True",
getattr,
a1,
"y",
)
def test_does_expire_cancel_normal_defer_option(self):
A = self.classes.A
s = fixture_session()
a1 = s.query(A).options(defer(A.x)).first()
# expire object
s.expire(a1)
# unexpire object
eq_(a1.id, 1)
assert "x" in a1.__dict__
| RaiseLoadTest |
python | kamyu104__LeetCode-Solutions | Python/task-scheduler-ii.py | {
"start": 63,
"end": 428
} | class ____(object):
def taskSchedulerII(self, tasks, space):
"""
:type tasks: List[int]
:type space: int
:rtype: int
"""
lookup = collections.defaultdict(int)
result = 0
for t in tasks:
result = max(lookup[t], result+1)
lookup[t] = result+space+1
return result
| Solution |
python | ray-project__ray | python/ray/_private/runtime_env/rocprof_sys.py | {
"start": 1885,
"end": 6485
} | class ____(RuntimeEnvPlugin):
name = "_rocprof_sys"
def __init__(self, resources_dir: str):
self.rocprof_sys_cmd = []
self.rocprof_sys_env = {}
# replace this with better way to get logs dir
session_dir, runtime_dir = os.path.split(resources_dir)
self._rocprof_sys_dir = Path(session_dir) / "logs" / "rocprof_sys"
try_to_create_directory(self._rocprof_sys_dir)
async def _check_rocprof_sys_script(
self, rocprof_sys_config: Dict[str, str]
) -> Tuple[bool, str]:
"""
Function to validate if rocprof_sys_config is a valid rocprof_sys profile options
Args:
rocprof_sys_config: dictionary mapping rocprof_sys option to it's value
Returns:
a tuple consists of a boolean indicating if the rocprof_sys_config
is valid option and an error message if the rocprof_sys_config is invalid
"""
# use empty as rocprof_sys report test filename
test_folder = str(Path(self._rocprof_sys_dir) / "test")
rocprof_sys_cmd, rocprof_sys_env = parse_rocprof_sys_config(rocprof_sys_config)
rocprof_sys_env_copy = copy.deepcopy(rocprof_sys_env)
rocprof_sys_env_copy["ROCPROFSYS_OUTPUT_PATH"] = test_folder
rocprof_sys_env_copy.update(os.environ)
try_to_create_directory(test_folder)
# Create a test python file to run rocprof_sys
with open(f"{test_folder}/test.py", "w") as f:
f.write("import time\n")
try:
rocprof_sys_cmd = rocprof_sys_cmd + [f"{test_folder}/test.py"]
process = await asyncio.create_subprocess_exec(
*rocprof_sys_cmd,
env=rocprof_sys_env_copy,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = await process.communicate()
error_msg = stderr.strip() if stderr.strip() != "" else stdout.strip()
# cleanup temp file
clean_up_cmd = ["rm", "-r", test_folder]
cleanup_process = await asyncio.create_subprocess_exec(
*clean_up_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
_, _ = await cleanup_process.communicate()
if process.returncode == 0:
return True, None
else:
return False, error_msg
except FileNotFoundError:
return False, ("rocprof_sys is not installed")
async def create(
self,
uri: Optional[str],
runtime_env: "RuntimeEnv", # noqa: F821
context: RuntimeEnvContext,
logger: logging.Logger = default_logger,
) -> int:
rocprof_sys_config = runtime_env.rocprof_sys()
if not rocprof_sys_config:
return 0
if rocprof_sys_config and sys.platform != "linux":
raise RuntimeEnvSetupError("rocprof-sys CLI is only available in Linux.\n")
if isinstance(rocprof_sys_config, str):
if rocprof_sys_config == "default":
rocprof_sys_config = ROCPROFSYS_DEFAULT_CONFIG
else:
raise RuntimeEnvSetupError(
f"Unsupported rocprof_sys config: {rocprof_sys_config}. "
"The supported config is 'default' or "
"Dictionary of rocprof_sys options"
)
is_valid_rocprof_sys_config, error_msg = await self._check_rocprof_sys_script(
rocprof_sys_config
)
if not is_valid_rocprof_sys_config:
logger.warning(error_msg)
raise RuntimeEnvSetupError(
"rocprof-sys profile failed to run with the following "
f"error message:\n {error_msg}"
)
# add set output path to logs dir
if "env" not in rocprof_sys_config:
rocprof_sys_config["env"] = {}
rocprof_sys_config["env"]["ROCPROFSYS_OUTPUT_PATH"] = str(
Path(self._rocprof_sys_dir)
)
self.rocprof_sys_cmd, self.rocprof_sys_env = parse_rocprof_sys_config(
rocprof_sys_config
)
return 0
def modify_context(
self,
uris: List[str],
runtime_env: "RuntimeEnv", # noqa: F821
context: RuntimeEnvContext,
logger: Optional[logging.Logger] = default_logger,
):
logger.info("Running rocprof-sys profiler")
context.py_executable = " ".join(self.rocprof_sys_cmd)
context.env_vars.update(self.rocprof_sys_env)
| RocProfSysPlugin |
python | django-debug-toolbar__django-debug-toolbar | tests/base.py | {
"start": 3840,
"end": 4204
} | class ____(TestCase):
"""Base TestCase for tests involving clients making requests."""
def setUp(self):
# The HistoryPanel keeps track of previous stores in memory.
# This bleeds into other tests and violates their idempotency.
# Clear the store before each test.
get_store().clear()
super().setUp()
| IntegrationTestCase |
python | tiangolo__fastapi | docs_src/body_multiple_params/tutorial001_py310.py | {
"start": 84,
"end": 546
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
q: str | None = None,
item: Item | None = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if item:
results.update({"item": item})
return results
| Item |
python | scipy__scipy | scipy/optimize/_shgo_lib/_vertex.py | {
"start": 5715,
"end": 6236
} | class ____(VertexBase):
"""Vertex class to be used for a pure simplicial complex with no associated
differential geometry (single level domain that exists in R^n)"""
def __init__(self, x, nn=None, index=None):
super().__init__(x, nn=nn, index=index)
def connect(self, v):
if v is not self and v not in self.nn:
self.nn.add(v)
v.nn.add(self)
def disconnect(self, v):
if v in self.nn:
self.nn.remove(v)
v.nn.remove(self)
| VertexCube |
python | pallets__click | src/click/_winconsole.py | {
"start": 5699,
"end": 8464
} | class ____:
def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
self._text_stream = text_stream
self.buffer = byte_stream
@property
def name(self) -> str:
return self.buffer.name
def write(self, x: t.AnyStr) -> int:
if isinstance(x, str):
return self._text_stream.write(x)
try:
self.flush()
except Exception:
pass
return self.buffer.write(x)
def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:
for line in lines:
self.write(line)
def __getattr__(self, name: str) -> t.Any:
return getattr(self._text_stream, name)
def isatty(self) -> bool:
return self.buffer.isatty()
def __repr__(self) -> str:
return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
text_stream = _NonClosingTextIOWrapper(
io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
text_stream = _NonClosingTextIOWrapper(
io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
text_stream = _NonClosingTextIOWrapper(
io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
0: _get_text_stdin,
1: _get_text_stdout,
2: _get_text_stderr,
}
def _is_console(f: t.TextIO) -> bool:
if not hasattr(f, "fileno"):
return False
try:
fileno = f.fileno()
except (OSError, io.UnsupportedOperation):
return False
handle = msvcrt.get_osfhandle(fileno)
return bool(GetConsoleMode(handle, byref(DWORD())))
def _get_windows_console_stream(
f: t.TextIO, encoding: str | None, errors: str | None
) -> t.TextIO | None:
if (
get_buffer is None
or encoding not in {"utf-16-le", None}
or errors not in {"strict", None}
or not _is_console(f)
):
return None
func = _stream_factories.get(f.fileno())
if func is None:
return None
b = getattr(f, "buffer", None)
if b is None:
return None
return func(b)
| ConsoleStream |
python | coleifer__peewee | peewee.py | {
"start": 45484,
"end": 45665
} | class ____(Expression):
def __add__(self, rhs):
return self.concat(rhs)
def __radd__(self, lhs):
return StringExpression(lhs, OP.CONCAT, self)
| StringExpression |
python | Textualize__textual | src/textual/_immutable_sequence_view.py | {
"start": 211,
"end": 1859
} | class ____(Generic[T]):
"""Class to wrap a sequence of some sort, but not allow modification."""
def __init__(self, wrap: Sequence[T]) -> None:
"""Initialise the immutable sequence.
Args:
wrap: The sequence being wrapped.
"""
self._wrap = wrap
if TYPE_CHECKING:
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, index: slice) -> ImmutableSequenceView[T]: ...
def __getitem__(self, index: int | slice) -> T | ImmutableSequenceView[T]:
return (
self._wrap[index]
if isinstance(index, int)
else ImmutableSequenceView[T](self._wrap[index])
)
def __iter__(self) -> Iterator[T]:
return iter(self._wrap)
def __len__(self) -> int:
return len(self._wrap)
def __length_hint__(self) -> int:
return len(self)
def __bool__(self) -> bool:
return bool(self._wrap)
def __contains__(self, item: T) -> bool:
return item in self._wrap
def index(self, item: T, start: int = 0, stop: int = maxsize) -> int:
"""Return the index of the given item.
Args:
item: The item to find in the sequence.
start: Optional start location.
stop: Optional stop location.
Returns:
The index of the item in the sequence.
Raises:
ValueError: If the item is not in the sequence.
"""
return self._wrap.index(item, start, stop)
def __reversed__(self) -> Iterator[T]:
return reversed(self._wrap)
| ImmutableSequenceView |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 497576,
"end": 506480
} | class ____(ExprNode):
# operator string
# operand1 ExprNode
# operand2 ExprNode
#
# Processing during analyse_expressions phase:
#
# analyse_c_operation
# Called when neither operand is a pyobject.
# - Check operand types and coerce if needed.
# - Determine result type and result code fragment.
# - Allocate temporary for result if needed.
subexprs = ['operand1', 'operand2']
inplace = False
def calculate_constant_result(self):
func = compile_time_binary_operators[self.operator]
self.constant_result = func(
self.operand1.constant_result,
self.operand2.constant_result)
def compile_time_value(self, denv):
func = get_compile_time_binop(self)
operand1 = self.operand1.compile_time_value(denv)
operand2 = self.operand2.compile_time_value(denv)
try:
return func(operand1, operand2)
except Exception as e:
self.compile_time_value_error(e)
def infer_type(self, env):
return self.result_type(self.operand1.infer_type(env),
self.operand2.infer_type(env), env)
def analyse_types(self, env):
self.operand1 = self.operand1.analyse_types(env)
self.operand2 = self.operand2.analyse_types(env)
return self.analyse_operation(env)
def analyse_operation(self, env):
if self.is_pythran_operation(env):
self.type = self.result_type(self.operand1.type,
self.operand2.type, env)
assert self.type.is_pythran_expr
self.is_temp = 1
elif self.is_py_operation():
self.coerce_operands_to_pyobjects(env)
self.type = self.result_type(self.operand1.type,
self.operand2.type, env)
self.is_temp = 1
if not self.type.is_pyobject:
original_type, self.type = self.type, py_object_type
# Hopefully this can be optimized out in some cases
return self.coerce_to(original_type, env)
elif self.is_cpp_operation():
self.analyse_cpp_operation(env)
else:
self.analyse_c_operation(env)
return self # when modifying this function, remember that the
# DivNode and ModNode expect it to return either self, or something
# that wraps self - they relying on modifying self afterwards.
def is_py_operation(self):
return self.is_py_operation_types(self.operand1.type, self.operand2.type)
def is_py_operation_types(self, type1, type2):
return type1.is_pyobject or type2.is_pyobject or type1.is_ctuple or type2.is_ctuple
def is_pythran_operation(self, env):
return self.is_pythran_operation_types(self.operand1.type, self.operand2.type, env)
def is_pythran_operation_types(self, type1, type2, env):
# Support only expr op supported_type, or supported_type op expr
return has_np_pythran(env) and \
(is_pythran_supported_operation_type(type1) and is_pythran_supported_operation_type(type2)) and \
(is_pythran_expr(type1) or is_pythran_expr(type2))
def is_cpp_operation(self):
return (self.operand1.type.is_cpp_class
or self.operand2.type.is_cpp_class)
def analyse_cpp_operation(self, env):
entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
if not entry:
self.type_error()
return
func_type = entry.type
self.exception_check = func_type.exception_check
self.exception_value = func_type.exception_value
if self.exception_check == '+':
# Used by NumBinopNodes to break up expressions involving multiple
# operators so that exceptions can be handled properly.
self.is_temp = 1
if needs_cpp_exception_conversion(self):
env.use_utility_code(UtilityCode.load_cached("CppExceptionConversion", "CppSupport.cpp"))
if func_type.is_ptr:
func_type = func_type.base_type
if len(func_type.args) == 1:
self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
else:
self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
self.type = func_type.return_type
def result_type(self, type1, type2, env):
if self.is_pythran_operation_types(type1, type2, env):
return PythranExpr(pythran_binop_type(self.operator, type1, type2))
if self.is_py_operation_types(type1, type2):
if type2.is_string:
type2 = Builtin.bytes_type
elif type2.is_pyunicode_ptr:
type2 = Builtin.unicode_type
if type1.is_string:
type1 = Builtin.bytes_type
elif type1.is_pyunicode_ptr:
type1 = Builtin.unicode_type
if type1.is_builtin_type or type2.is_builtin_type:
if type1 is type2 and type1 is not type_type and self.operator in '**%+|&^':
# FIXME: at least these operators should be safe - others?
return type1
result_type = self.infer_builtin_types_operation(type1, type2)
if result_type is not None:
return result_type
return py_object_type
elif type1.is_error or type2.is_error:
return PyrexTypes.error_type
else:
return self.compute_c_result_type(type1, type2)
def infer_builtin_types_operation(self, type1, type2):
return None
def nogil_check(self, env):
if self.is_py_operation():
self.gil_error()
def coerce_operands_to_pyobjects(self, env):
self.operand1 = self.operand1.coerce_to_pyobject(env)
self.operand2 = self.operand2.coerce_to_pyobject(env)
def check_const(self):
return self.operand1.check_const() and self.operand2.check_const()
def is_ephemeral(self):
return (super().is_ephemeral() or
self.operand1.is_ephemeral() or self.operand2.is_ephemeral())
def generate_result_code(self, code):
type1 = self.operand1.type
type2 = self.operand2.type
if self.type.is_pythran_expr:
code.putln("// Pythran binop")
code.putln("__Pyx_call_destructor(%s);" % self.result())
if self.operator == '**':
code.putln("new (&%s) decltype(%s){pythonic::numpy::functor::power{}(%s, %s)};" % (
self.result(),
self.result(),
self.operand1.pythran_result(),
self.operand2.pythran_result()))
else:
code.putln("new (&%s) decltype(%s){%s %s %s};" % (
self.result(),
self.result(),
self.operand1.pythran_result(),
self.operator,
self.operand2.pythran_result()))
elif type1.is_pyobject or type2.is_pyobject:
function = self.py_operation_function(code)
extra_args = ", Py_None" if self.operator == '**' else ""
op1_result = self.operand1.py_result() if type1.is_pyobject else self.operand1.result()
op2_result = self.operand2.py_result() if type2.is_pyobject else self.operand2.result()
code.putln(
"%s = %s(%s, %s%s); %s" % (
self.result(),
function,
op1_result,
op2_result,
extra_args,
code.error_goto_if_null(self.result(), self.pos)))
self.generate_gotref(code)
elif self.is_temp:
# C++ overloaded operators with exception values are currently all
# handled through temporaries.
if self.is_cpp_operation() and self.exception_check == '+':
translate_cpp_exception(code, self.pos,
"%s = %s;" % (self.result(), self.calculate_result_code()),
self.result() if self.type.is_pyobject else None,
self.exception_value, self.in_nogil_context)
else:
code.putln("%s = %s;" % (self.result(), self.calculate_result_code()))
def type_error(self):
if not (self.operand1.type.is_error
or self.operand2.type.is_error):
error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
(self.operator, self.operand1.type,
self.operand2.type))
self.type = PyrexTypes.error_type
| BinopNode |
python | django__django | tests/model_fields/models.py | {
"start": 15060,
"end": 15153
} | class ____(models.Model):
field = models.UUIDField(blank=True, null=True)
| NullableUUIDModel |
python | pytorch__pytorch | test/test_dynamic_shapes.py | {
"start": 109734,
"end": 118069
} | class ____(TestCase):
"""
Tests the guards-related methods used by the inductor FX graph cache.
"""
def test_guards_gt_lt(self):
shape_env = ShapeEnv()
s0 = create_symint(shape_env, 6)
s1 = create_symint(shape_env, 7)
s2 = create_symint(shape_env, 5)
guard_int(sym_int(s0 > 5))
guard_int(sym_int(s0 < 7))
guards = shape_env.produce_guards_expression([s0])
self.assertTrue(shape_env.evaluate_guards_expression(guards, [hint_int(s0)]))
self.assertFalse(shape_env.evaluate_guards_expression(guards, [hint_int(s1)]))
self.assertFalse(shape_env.evaluate_guards_expression(guards, [hint_int(s2)]))
def test_guards_float_print(self):
shape_env = ShapeEnv()
s0 = create_symint(shape_env, 3)
guard_bool(2 / s0 == 2 / 3)
guards = shape_env.produce_guards_expression([s0])
self.assertTrue(shape_env.evaluate_guards_expression(guards, [hint_int(s0)]))
@skipIfTorchDynamo("Not a TorchDynamo suitable test")
@torch._dynamo.config.patch("capture_scalar_outputs", True)
def test_guard_or_true(self):
from torch.fx.experimental.symbolic_shapes import guard_or_true
def func(a, b):
x = a.item()
if guard_or_true(x == 1):
return b * 10
else:
return b * 20
# eager.
self.assertEqual(func(torch.tensor([1]), torch.tensor([1])), torch.tensor([10]))
self.assertEqual(func(torch.tensor([2]), torch.tensor([1])), torch.tensor([20]))
# compile with unbacked.
unbacked_func = torch.compile(func, dynamic=True, fullgraph=True)
a = torch.tensor([1])
b = torch.tensor([1])
unbacked_func(a, b)
# always return b*10
self.assertEqual(
unbacked_func(torch.tensor([1]), torch.tensor([1])), torch.tensor([10])
)
self.assertEqual(
unbacked_func(torch.tensor([2]), torch.tensor([1])), torch.tensor([10])
)
# Test that statically known true works.
def func2(a, b):
x = a.item()
if guard_or_true(x != x):
return b * 10
else:
return b * 20
unbacked_func2 = torch.compile(func2, dynamic=True, fullgraph=True)
a = torch.tensor([1])
b = torch.tensor([1])
unbacked_func2(a, b)
# always return b*20
self.assertEqual(
unbacked_func2(torch.tensor([1]), torch.tensor([1])), torch.tensor([20])
)
self.assertEqual(
unbacked_func2(torch.tensor([2]), torch.tensor([1])), torch.tensor([20])
)
# Test backed_size_oblivious
with torch.fx.experimental._config.patch("backed_size_oblivious", True):
def func3(a, b):
if guard_or_true(a.size()[0] != 9):
return b * 10
else:
return b * 20
compiled = torch.compile(func3, dynamic=True, fullgraph=True)
a = torch.rand(9, 2)
b = torch.rand(3, 4)
self.assertEqual(func3(a, b), b * 20)
self.assertEqual(compiled(a, b), b * 10)
@skipIfTorchDynamo("Not a TorchDynamo suitable test")
@torch._dynamo.config.patch("capture_scalar_outputs", True)
def test_guard_or_false(self):
from torch.fx.experimental.symbolic_shapes import guard_or_false
def func(a, b):
x = a.item()
if guard_or_false(x == 1):
return b * 10
else:
return b * 20
# eager.
self.assertEqual(func(torch.tensor([1]), torch.tensor([1])), torch.tensor([10]))
self.assertEqual(func(torch.tensor([2]), torch.tensor([1])), torch.tensor([20]))
# compile with unbacked.
unbacked_func = torch.compile(func, dynamic=True, fullgraph=True)
a = torch.tensor([1])
b = torch.tensor([1])
unbacked_func(a, b)
# always return b*20
self.assertEqual(
unbacked_func(torch.tensor([1]), torch.tensor([1])), torch.tensor([20])
)
self.assertEqual(
unbacked_func(torch.tensor([2]), torch.tensor([1])), torch.tensor([20])
)
# Test that statically known true works.
def func2(a, b):
x = a.item()
if guard_or_false(x == x):
return b * 10
else:
return b * 20
unbacked_func2 = torch.compile(func2, dynamic=True, fullgraph=True)
a = torch.tensor([1])
b = torch.tensor([1])
unbacked_func2(a, b)
# always return b*10
self.assertEqual(
unbacked_func2(torch.tensor([1]), torch.tensor([1])), torch.tensor([10])
)
self.assertEqual(
unbacked_func2(torch.tensor([2]), torch.tensor([1])), torch.tensor([10])
)
# Test backed_size_oblivious
with torch.fx.experimental._config.patch("backed_size_oblivious", True):
def func3(a, b):
if guard_or_false(a.size()[0] == 9):
return b * 10
else:
return b * 20
compiled = torch.compile(func3, dynamic=True, fullgraph=True)
a = torch.rand(9, 2)
b = torch.rand(3, 4)
self.assertEqual(func3(a, b), b * 10)
self.assertEqual(compiled(a, b), b * 20)
def test_guards_float_div(self):
shape_env = ShapeEnv()
s0 = create_symint(shape_env, 8)
s1 = create_symint(shape_env, 7)
guard_int(sym_int(s0 / 2.0))
guards = shape_env.produce_guards_expression([s0])
self.assertIn("math.trunc(", guards)
self.assertIn("float(", guards)
self.assertTrue(shape_env.evaluate_guards_expression(guards, [hint_int(s0)]))
self.assertFalse(shape_env.evaluate_guards_expression(guards, [hint_int(s1)]))
@unittest.skipIf(
TEST_XPU, "Skipped on XPU"
) # https://github.com/intel/torch-xpu-ops/issues/2169"
@skipIfTorchDynamo("Attempt to trace generator")
@torch.fx.experimental._config.patch("use_duck_shape", False)
def test_size_comparison_no_recompile(self):
"""
Test that size comparisons don't cause recompilation.
When comparing x.size() == b.size() with different sizes,
the compiled function should only compile once.
We should not guard in sizes of the inner elements.
"""
cnt = CompileCounter()
@torch.compile(fullgraph=True, dynamic=True, backend=cnt)
def f(x, b):
if x.size() == b.size():
return x
return x * 2
# First call: shapes differ (1, 2) vs (2, 4, 9), so if branch is False
f(torch.rand(10, 2), torch.rand(20, 4, 9))
# Second call: shapes differ again (1, 2) vs (1, 4, 9), so if branch is False
f(torch.rand(10, 2), torch.rand(10, 4, 9))
# Should only compile once despite different input shapes
self.assertEqual(
cnt.frame_count,
1,
f"Expected 1 compilation, got {cnt.frame_count}. "
f"Size comparison should not cause recompilation.",
)
def test_remove_symbols_without_guarding(self):
from torch._functorch.partitioners import _remove_symbols_without_guarding
shape_env = ShapeEnv()
x = create_fake_tensor_with_dynamic_size(
torch.randn(5, 8),
shape_env,
dynamic_sizes=[
DimDynamic.DYNAMIC,
DimDynamic.DYNAMIC,
],
dynamic_strides=[
DimDynamic.INFER_STRIDE,
DimDynamic.INFER_STRIDE,
],
)
self.assertEqual(f"{x.stride()}", "(s49, 1)")
self.assertEqual(f"{x.shape}", "torch.Size([s26, s49])")
x_clean = _remove_symbols_without_guarding(x, 4096)
self.assertEqual(f"{x_clean.stride()}", "(8, 1)")
self.assertEqual(f"{x_clean.shape}", "torch.Size([5, 8])")
def custom_pass(graph: torch.fx.Graph) -> torch.fx.Graph:
for node in graph.nodes:
if node.name == "arg3_1":
assert node.meta["val"].size()[0] == 2
return graph
| TestGuardsExpressions |
python | python__mypy | mypy/test/test_find_sources.py | {
"start": 1921,
"end": 13693
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.tempdir = tempfile.mkdtemp()
self.oldcwd = os.getcwd()
os.chdir(self.tempdir)
def tearDown(self) -> None:
os.chdir(self.oldcwd)
shutil.rmtree(self.tempdir)
def test_crawl_no_namespace(self) -> None:
options = Options()
options.namespace_packages = False
finder = SourceFinder(FakeFSCache({"/setup.py"}), options)
assert crawl(finder, "/setup.py") == ("setup", "/")
finder = SourceFinder(FakeFSCache({"/a/setup.py"}), options)
assert crawl(finder, "/a/setup.py") == ("setup", "/a")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("setup", "/a/b")
finder = SourceFinder(FakeFSCache({"/a/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/setup.py") == ("a.setup", "/")
finder = SourceFinder(FakeFSCache({"/a/invalid-name/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/invalid-name/setup.py") == ("setup", "/a/invalid-name")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("setup", "/a/b")
finder = SourceFinder(
FakeFSCache({"/a/b/c/setup.py", "/a/__init__.py", "/a/b/c/__init__.py"}), options
)
assert crawl(finder, "/a/b/c/setup.py") == ("c.setup", "/a/b")
def test_crawl_namespace(self) -> None:
options = Options()
options.namespace_packages = True
finder = SourceFinder(FakeFSCache({"/setup.py"}), options)
assert crawl(finder, "/setup.py") == ("setup", "/")
finder = SourceFinder(FakeFSCache({"/a/setup.py"}), options)
assert crawl(finder, "/a/setup.py") == ("setup", "/a")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("setup", "/a/b")
finder = SourceFinder(FakeFSCache({"/a/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/setup.py") == ("a.setup", "/")
finder = SourceFinder(FakeFSCache({"/a/invalid-name/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/invalid-name/setup.py") == ("setup", "/a/invalid-name")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("a.b.setup", "/")
finder = SourceFinder(
FakeFSCache({"/a/b/c/setup.py", "/a/__init__.py", "/a/b/c/__init__.py"}), options
)
assert crawl(finder, "/a/b/c/setup.py") == ("a.b.c.setup", "/")
def test_crawl_namespace_explicit_base(self) -> None:
options = Options()
options.namespace_packages = True
options.explicit_package_bases = True
finder = SourceFinder(FakeFSCache({"/setup.py"}), options)
assert crawl(finder, "/setup.py") == ("setup", "/")
finder = SourceFinder(FakeFSCache({"/a/setup.py"}), options)
assert crawl(finder, "/a/setup.py") == ("setup", "/a")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("setup", "/a/b")
finder = SourceFinder(FakeFSCache({"/a/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/setup.py") == ("a.setup", "/")
finder = SourceFinder(FakeFSCache({"/a/invalid-name/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/invalid-name/setup.py") == ("setup", "/a/invalid-name")
finder = SourceFinder(FakeFSCache({"/a/b/setup.py", "/a/__init__.py"}), options)
assert crawl(finder, "/a/b/setup.py") == ("a.b.setup", "/")
finder = SourceFinder(
FakeFSCache({"/a/b/c/setup.py", "/a/__init__.py", "/a/b/c/__init__.py"}), options
)
assert crawl(finder, "/a/b/c/setup.py") == ("a.b.c.setup", "/")
# set mypy path, so we actually have some explicit base dirs
options.mypy_path = ["/a/b"]
finder = SourceFinder(FakeFSCache({"/a/b/c/setup.py"}), options)
assert crawl(finder, "/a/b/c/setup.py") == ("c.setup", "/a/b")
finder = SourceFinder(
FakeFSCache({"/a/b/c/setup.py", "/a/__init__.py", "/a/b/c/__init__.py"}), options
)
assert crawl(finder, "/a/b/c/setup.py") == ("c.setup", "/a/b")
options.mypy_path = ["/a/b", "/a/b/c"]
finder = SourceFinder(FakeFSCache({"/a/b/c/setup.py"}), options)
assert crawl(finder, "/a/b/c/setup.py") == ("setup", "/a/b/c")
def test_crawl_namespace_multi_dir(self) -> None:
options = Options()
options.namespace_packages = True
options.explicit_package_bases = True
options.mypy_path = ["/a", "/b"]
finder = SourceFinder(FakeFSCache({"/a/pkg/a.py", "/b/pkg/b.py"}), options)
assert crawl(finder, "/a/pkg/a.py") == ("pkg.a", "/a")
assert crawl(finder, "/b/pkg/b.py") == ("pkg.b", "/b")
def test_find_sources_in_dir_no_namespace(self) -> None:
options = Options()
options.namespace_packages = False
files = {
"/pkg/a1/b/c/d/e.py",
"/pkg/a1/b/f.py",
"/pkg/a2/__init__.py",
"/pkg/a2/b/c/d/e.py",
"/pkg/a2/b/f.py",
}
finder = SourceFinder(FakeFSCache(files), options)
assert find_sources_in_dir(finder, "/") == [
("a2", "/pkg"),
("e", "/pkg/a1/b/c/d"),
("e", "/pkg/a2/b/c/d"),
("f", "/pkg/a1/b"),
("f", "/pkg/a2/b"),
]
def test_find_sources_in_dir_namespace(self) -> None:
options = Options()
options.namespace_packages = True
files = {
"/pkg/a1/b/c/d/e.py",
"/pkg/a1/b/f.py",
"/pkg/a2/__init__.py",
"/pkg/a2/b/c/d/e.py",
"/pkg/a2/b/f.py",
}
finder = SourceFinder(FakeFSCache(files), options)
assert find_sources_in_dir(finder, "/") == [
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("a2.b.f", "/pkg"),
("e", "/pkg/a1/b/c/d"),
("f", "/pkg/a1/b"),
]
def test_find_sources_in_dir_namespace_explicit_base(self) -> None:
options = Options()
options.namespace_packages = True
options.explicit_package_bases = True
options.mypy_path = ["/"]
files = {
"/pkg/a1/b/c/d/e.py",
"/pkg/a1/b/f.py",
"/pkg/a2/__init__.py",
"/pkg/a2/b/c/d/e.py",
"/pkg/a2/b/f.py",
}
finder = SourceFinder(FakeFSCache(files), options)
assert find_sources_in_dir(finder, "/") == [
("pkg.a1.b.c.d.e", "/"),
("pkg.a1.b.f", "/"),
("pkg.a2", "/"),
("pkg.a2.b.c.d.e", "/"),
("pkg.a2.b.f", "/"),
]
options.mypy_path = ["/pkg"]
finder = SourceFinder(FakeFSCache(files), options)
assert find_sources_in_dir(finder, "/") == [
("a1.b.c.d.e", "/pkg"),
("a1.b.f", "/pkg"),
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("a2.b.f", "/pkg"),
]
def test_find_sources_in_dir_namespace_multi_dir(self) -> None:
options = Options()
options.namespace_packages = True
options.explicit_package_bases = True
options.mypy_path = ["/a", "/b"]
finder = SourceFinder(FakeFSCache({"/a/pkg/a.py", "/b/pkg/b.py"}), options)
assert find_sources_in_dir(finder, "/") == [("pkg.a", "/a"), ("pkg.b", "/b")]
def test_find_sources_exclude(self) -> None:
options = Options()
options.namespace_packages = True
# default
for excluded_dir in ["site-packages", ".whatever", "node_modules", ".x/.z"]:
fscache = FakeFSCache({"/dir/a.py", f"/dir/venv/{excluded_dir}/b.py"})
assert find_sources(["/"], options, fscache) == [("a", "/dir")]
with pytest.raises(InvalidSourceList):
find_sources(["/dir/venv/"], options, fscache)
assert find_sources([f"/dir/venv/{excluded_dir}"], options, fscache) == [
("b", f"/dir/venv/{excluded_dir}")
]
assert find_sources([f"/dir/venv/{excluded_dir}/b.py"], options, fscache) == [
("b", f"/dir/venv/{excluded_dir}")
]
files = {
"/pkg/a1/b/c/d/e.py",
"/pkg/a1/b/f.py",
"/pkg/a2/__init__.py",
"/pkg/a2/b/c/d/e.py",
"/pkg/a2/b/f.py",
}
# file name
options.exclude = [r"/f\.py$"]
fscache = FakeFSCache(files)
assert find_sources(["/"], options, fscache) == [
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("e", "/pkg/a1/b/c/d"),
]
assert find_sources(["/pkg/a1/b/f.py"], options, fscache) == [("f", "/pkg/a1/b")]
assert find_sources(["/pkg/a2/b/f.py"], options, fscache) == [("a2.b.f", "/pkg")]
# directory name
options.exclude = ["/a1/"]
fscache = FakeFSCache(files)
assert find_sources(["/"], options, fscache) == [
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("a2.b.f", "/pkg"),
]
with pytest.raises(InvalidSourceList):
find_sources(["/pkg/a1"], options, fscache)
with pytest.raises(InvalidSourceList):
find_sources(["/pkg/a1/"], options, fscache)
with pytest.raises(InvalidSourceList):
find_sources(["/pkg/a1/b"], options, fscache)
options.exclude = ["/a1/$"]
assert find_sources(["/pkg/a1"], options, fscache) == [
("e", "/pkg/a1/b/c/d"),
("f", "/pkg/a1/b"),
]
# paths
options.exclude = ["/pkg/a1/"]
fscache = FakeFSCache(files)
assert find_sources(["/"], options, fscache) == [
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("a2.b.f", "/pkg"),
]
with pytest.raises(InvalidSourceList):
find_sources(["/pkg/a1"], options, fscache)
# OR two patterns together
for orred in [["/(a1|a3)/"], ["a1", "a3"], ["a3", "a1"]]:
options.exclude = orred
fscache = FakeFSCache(files)
assert find_sources(["/"], options, fscache) == [
("a2", "/pkg"),
("a2.b.c.d.e", "/pkg"),
("a2.b.f", "/pkg"),
]
options.exclude = ["b/c/"]
fscache = FakeFSCache(files)
assert find_sources(["/"], options, fscache) == [
("a2", "/pkg"),
("a2.b.f", "/pkg"),
("f", "/pkg/a1/b"),
]
# nothing should be ignored as a result of this
big_exclude1 = [
"/pkg/a/",
"/2",
"/1",
"/pk/",
"/kg",
"/g.py",
"/bc",
"/xxx/pkg/a2/b/f.py",
"xxx/pkg/a2/b/f.py",
]
big_exclude2 = ["|".join(big_exclude1)]
for big_exclude in [big_exclude1, big_exclude2]:
options.exclude = big_exclude
fscache = FakeFSCache(files)
assert len(find_sources(["/"], options, fscache)) == len(files)
files = {
"pkg/a1/b/c/d/e.py",
"pkg/a1/b/f.py",
"pkg/a2/__init__.py",
"pkg/a2/b/c/d/e.py",
"pkg/a2/b/f.py",
}
fscache = FakeFSCache(files)
assert len(find_sources(["."], options, fscache)) == len(files)
| SourceFinderSuite |
python | huggingface__transformers | src/transformers/models/deepseek_vl/modular_deepseek_vl.py | {
"start": 1482,
"end": 4390
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DeepseekVLModel`]. It is used to instantiate a
DeepseekVL model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the DeepseekVL
[deepseek-community/deepseek-vl-1.3b-chat](https://huggingface.co/deepseek-community/deepseek-vl-1.3b-chat) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
The config object or dictionary of the text backbone.
vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SiglipVisionConfig`):
The config object or dictionary of the vision backbone.
image_token_id (`int`, *optional*, defaults to 100015):
The index representing image tokens in the model's token vocabulary.
Example:
```python
>>> from transformers import DeepseekVLConfig, DeepseekVLModel
>>> # Initializing a DeepseekVL deepseek-community/deepseek-vl-1.3b-chat style configuration
>>> configuration = DeepseekVLConfig()
>>> # Initializing a model (with random weights) from the deepseek-community/deepseek-vl-1.3b-chat style configuration
>>> model = DeepseekVLModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "deepseek_vl"
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
def __init__(
self,
text_config: Optional[AutoConfig] = None,
vision_config: Optional[AutoConfig] = None,
image_token_id: int = 100015,
**kwargs,
):
if text_config is None:
text_config = {}
logger.info("`text_config` is `None`. Initializing the `LlamaConfig` with default values.")
if vision_config is None:
vision_config = {}
logger.info("`vision_config` is `None`. Initializing the `SiglipVisionConfig` with default values.")
if isinstance(text_config, dict):
text_config["model_type"] = text_config.get("model_type", "llama")
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
if isinstance(vision_config, dict):
vision_config["model_type"] = vision_config.get("model_type", "siglip_vision_model")
vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
self.text_config = text_config
self.vision_config = vision_config
self.image_token_id = image_token_id
super().__init__(**kwargs)
| DeepseekVLConfig |
python | streamlit__streamlit | lib/streamlit/elements/write.py | {
"start": 1550,
"end": 23035
} | class ____:
@gather_metrics("write_stream")
def write_stream(
self,
stream: Callable[..., Any]
| Generator[Any, Any, Any]
| Iterable[Any]
| AsyncGenerator[Any, Any],
*,
cursor: str | None = None,
) -> list[Any] | str:
r"""Stream a generator, iterable, or stream-like sequence to the app.
``st.write_stream`` iterates through the given sequences and writes all
chunks to the app. String chunks will be written using a typewriter effect.
Other data types will be written using ``st.write``.
Parameters
----------
stream : Callable, Generator, Iterable, OpenAI Stream, or LangChain Stream
The generator or iterable to stream.
If you pass an async generator, Streamlit will internally convert
it to a sync generator. If the generator depends on a cached object
with async references, this can raise an error.
.. note::
To use additional LLM libraries, you can create a wrapper to
manually define a generator function and include custom output
parsing.
cursor : str or None
A string to append to text as it's being written. If this is
``None`` (default), no cursor is shown. Otherwise, the string is
rendered as Markdown and appears as a cursor at the end of the
streamed text. For example, you can use an emoji, emoji shortcode,
or Material icon.
The first line of the cursor string can contain GitHub-flavored
Markdown of the following types: Bold, Italics, Strikethroughs,
Inline Code, Links, and Images. Images display like icons, with a
max height equal to the font height. If you pass a multiline
string, additional lines display after the text with the full
Markdown rendering capabilities of ``st.markdown``.
See the ``body`` parameter of |st.markdown|_ for additional,
supported Markdown directives.
.. |st.markdown| replace:: ``st.markdown``
.. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown
Returns
-------
str or list
The full response. If the streamed output only contains text, this
is a string. Otherwise, this is a list of all the streamed objects.
The return value is fully compatible as input for ``st.write``.
Example
-------
You can pass an OpenAI stream as shown in our tutorial, `Build a \
basic LLM chat app <https://docs.streamlit.io/develop/tutorials/llms\
/build-conversational-apps#build-a-chatgpt-like-app>`_. Alternatively,
you can pass a generic generator function as input:
>>> import time
>>> import numpy as np
>>> import pandas as pd
>>> import streamlit as st
>>>
>>> _LOREM_IPSUM = \"\"\"
>>> Lorem ipsum dolor sit amet, **consectetur adipiscing** elit, sed do eiusmod tempor
>>> incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
>>> nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
>>> \"\"\"
>>>
>>>
>>> def stream_data():
>>> for word in _LOREM_IPSUM.split(" "):
>>> yield word + " "
>>> time.sleep(0.02)
>>>
>>> yield pd.DataFrame(
>>> np.random.randn(5, 10),
>>> columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
>>> )
>>>
>>> for word in _LOREM_IPSUM.split(" "):
>>> yield word + " "
>>> time.sleep(0.02)
>>>
>>>
>>> if st.button("Stream data"):
>>> st.write_stream(stream_data)
.. output::
https://doc-write-stream-data.streamlit.app/
height: 550px
"""
# Just apply some basic checks for common iterable types that should
# not be passed in here.
if isinstance(stream, str) or dataframe_util.is_dataframe_like(stream):
raise StreamlitAPIException(
"`st.write_stream` expects a generator or stream-like object as input "
f"not {type(stream)}. Please use `st.write` instead for "
"this data type."
)
cursor_str = cursor or ""
stream_container: DeltaGenerator | None = None
streamed_response: str = ""
written_content: list[Any] = StreamingOutput()
def flush_stream_response() -> None:
"""Write the full response to the app."""
nonlocal streamed_response
nonlocal stream_container
if streamed_response and stream_container:
# Replace the stream_container element the full response
stream_container.markdown(streamed_response)
written_content.append(streamed_response)
stream_container = None
streamed_response = ""
# Make sure we have a generator and not just a generator function.
if inspect.isgeneratorfunction(stream) or inspect.isasyncgenfunction(stream):
stream = stream()
# If the stream is an async generator, convert it to a sync generator:
if inspect.isasyncgen(stream):
stream = type_util.async_generator_to_sync(stream)
try:
iter(stream) # type: ignore
except TypeError as exc:
raise StreamlitAPIException(
f"The provided input (type: {type(stream)}) cannot be iterated. "
"Please make sure that it is a generator, generator function or iterable."
) from exc
# Iterate through the generator and write each chunk to the app
# with a type writer effect.
for chunk in stream: # type: ignore
if type_util.is_openai_chunk(chunk):
# Try to convert OpenAI chat completion chunk to a string:
try:
if len(chunk.choices) == 0 or chunk.choices[0].delta is None:
# The choices list can be empty. E.g. when using the
# AzureOpenAI client, the first chunk will always be empty.
chunk = "" # noqa: PLW2901
else:
chunk = chunk.choices[0].delta.content or "" # noqa: PLW2901
except AttributeError as err:
raise StreamlitAPIException(
"Failed to parse the OpenAI ChatCompletionChunk. "
"The most likely cause is a change of the chunk object structure "
"due to a recent OpenAI update. You might be able to fix this "
"by downgrading the OpenAI library or upgrading Streamlit. Also, "
"please report this issue to: https://github.com/streamlit/streamlit/issues."
) from err
if type_util.is_type(chunk, "langchain_core.messages.ai.AIMessageChunk"):
# Try to convert LangChain message chunk to a string:
try:
chunk = chunk.content or "" # noqa: PLW2901 # type: ignore[possibly-unbound-attribute]
except AttributeError as err:
raise StreamlitAPIException(
"Failed to parse the LangChain AIMessageChunk. "
"The most likely cause is a change of the chunk object structure "
"due to a recent LangChain update. You might be able to fix this "
"by downgrading the OpenAI library or upgrading Streamlit. Also, "
"please report this issue to: https://github.com/streamlit/streamlit/issues."
) from err
if isinstance(chunk, str):
if not chunk:
# Empty strings can be ignored
continue
first_text = False
if not stream_container:
stream_container = self.dg.empty()
first_text = True
streamed_response += chunk
# Only add the streaming symbol on the second text chunk
stream_container.markdown(
streamed_response + ("" if first_text else cursor_str),
)
elif callable(chunk):
flush_stream_response()
chunk()
else:
flush_stream_response()
self.write(chunk)
written_content.append(chunk)
flush_stream_response()
if not written_content:
# If nothing was streamed, return an empty string.
return ""
if len(written_content) == 1 and isinstance(written_content[0], str):
# If the output only contains a single string, return it as a string
return written_content[0]
# Otherwise return it as a list of write-compatible objects
return written_content
@gather_metrics("write")
def write(self, *args: Any, unsafe_allow_html: bool = False) -> None:
"""Displays arguments in the app.
This is the Swiss Army knife of Streamlit commands: it does different
things depending on what you throw at it. Unlike other Streamlit
commands, ``st.write()`` has some unique properties:
- You can pass in multiple arguments, all of which will be displayed.
- Its behavior depends on the input type(s).
Parameters
----------
*args : any
One or many objects to display in the app.
.. list-table:: Each type of argument is handled as follows:
:header-rows: 1
* - Type
- Handling
* - ``str``
- Uses ``st.markdown()``.
* - dataframe-like, ``dict``, or ``list``
- Uses ``st.dataframe()``.
* - ``Exception``
- Uses ``st.exception()``.
* - function, module, or class
- Uses ``st.help()``.
* - ``DeltaGenerator``
- Uses ``st.help()``.
* - Altair chart
- Uses ``st.altair_chart()``.
* - Bokeh figure
- Uses ``st.bokeh_chart()``.
* - Graphviz graph
- Uses ``st.graphviz_chart()``.
* - Keras model
- Converts model and uses ``st.graphviz_chart()``.
* - Matplotlib figure
- Uses ``st.pyplot()``.
* - Plotly figure
- Uses ``st.plotly_chart()``.
* - ``PIL.Image``
- Uses ``st.image()``.
* - generator or stream (like ``openai.Stream``)
- Uses ``st.write_stream()``.
* - SymPy expression
- Uses ``st.latex()``.
* - An object with ``._repr_html()``
- Uses ``st.html()``.
* - Database cursor
- Displays DB API 2.0 cursor results in a table.
* - Any
- Displays ``str(arg)`` as inline code.
unsafe_allow_html : bool
Whether to render HTML within ``*args``. This only applies to
strings or objects falling back on ``_repr_html_()``. If this is
``False`` (default), any HTML tags found in ``body`` will be
escaped and therefore treated as raw text. If this is ``True``, any
HTML expressions within ``body`` will be rendered.
Adding custom HTML to your app impacts safety, styling, and
maintainability.
.. note::
If you only want to insert HTML or CSS without Markdown text,
we recommend using ``st.html`` instead.
Returns
-------
None
Examples
--------
Its basic use case is to draw Markdown-formatted text, whenever the
input is a string:
>>> import streamlit as st
>>>
>>> st.write("Hello, *World!* :sunglasses:")
.. output::
https://doc-write1.streamlit.app/
height: 150px
As mentioned earlier, ``st.write()`` also accepts other data formats, such as
numbers, data frames, styled data frames, and assorted objects:
>>> import streamlit as st
>>> import pandas as pd
>>>
>>> st.write(1234)
>>> st.write(
... pd.DataFrame(
... {
... "first column": [1, 2, 3, 4],
... "second column": [10, 20, 30, 40],
... }
... )
... )
.. output::
https://doc-write2.streamlit.app/
height: 350px
Finally, you can pass in multiple arguments to do things like:
>>> import streamlit as st
>>>
>>> st.write("1 + 1 = ", 2)
>>> st.write("Below is a DataFrame:", data_frame, "Above is a dataframe.")
.. output::
https://doc-write3.streamlit.app/
height: 410px
Oh, one more thing: ``st.write`` accepts chart objects too! For example:
>>> import altair as alt
>>> import pandas as pd
>>> import streamlit as st
>>> from numpy.random import default_rng as rng
>>>
>>> df = pd.DataFrame(rng(0).standard_normal((200, 3)), columns=["a", "b", "c"])
>>> chart = (
... alt.Chart(df)
... .mark_circle()
... .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
... )
>>>
>>> st.write(chart)
.. output::
https://doc-vega-lite-chart.streamlit.app/
height: 300px
"""
if len(args) == 1 and isinstance(args[0], str):
# Optimization: If there is only one arg, and it's a string,
# we can just call markdown directly and skip the buffer logic.
# This also prevents unnecessary usage of `st.empty()`.
# This covers > 80% of all `st.write` uses.
self.dg.markdown(args[0], unsafe_allow_html=unsafe_allow_html)
return
string_buffer: list[str] = []
# This bans some valid cases like: e = st.empty(); e.write("a", "b").
# BUT: 1) such cases are rare, 2) this rule is easy to understand,
# and 3) this rule should be removed once we have st.container()
if not self.dg._is_top_level and len(args) > 1:
raise StreamlitAPIException(
"Cannot replace a single element with multiple elements.\n\n"
"The `write()` method only supports multiple elements when "
"inserting elements rather than replacing. That is, only "
"when called as `st.write()` or `st.sidebar.write()`."
)
def flush_buffer() -> None:
if string_buffer:
text_content = " ".join(string_buffer)
# The usage of empty here prevents
# some grey out effects:
text_container = self.dg.empty()
text_container.markdown(
text_content,
unsafe_allow_html=unsafe_allow_html,
)
string_buffer[:] = []
for arg in args:
# Order matters!
if isinstance(arg, str):
string_buffer.append(arg)
elif isinstance(arg, StreamingOutput):
flush_buffer()
for item in arg:
if callable(item):
flush_buffer()
item()
else:
self.write(item, unsafe_allow_html=unsafe_allow_html)
elif isinstance(arg, Exception):
flush_buffer()
self.dg.exception(arg)
elif type_util.is_delta_generator(arg):
flush_buffer()
self.dg.help(arg)
elif dataframe_util.is_dataframe_like(arg):
flush_buffer()
self.dg.dataframe(arg)
elif type_util.is_altair_chart(arg):
flush_buffer()
self.dg.altair_chart(arg)
elif type_util.is_type(arg, "matplotlib.figure.Figure"):
flush_buffer()
self.dg.pyplot(arg)
elif type_util.is_plotly_chart(arg):
flush_buffer()
self.dg.plotly_chart(arg)
elif type_util.is_type(arg, "bokeh.plotting.figure.Figure"):
flush_buffer()
self.dg.bokeh_chart(arg)
elif type_util.is_graphviz_chart(arg):
flush_buffer()
self.dg.graphviz_chart(arg)
elif type_util.is_sympy_expression(arg):
flush_buffer()
self.dg.latex(arg)
elif type_util.is_pillow_image(arg):
flush_buffer()
self.dg.image(arg)
elif type_util.is_keras_model(arg):
from tensorflow.python.keras.utils import ( # type: ignore
vis_utils,
)
flush_buffer()
dot = vis_utils.model_to_dot(arg)
self.dg.graphviz_chart(dot.to_string())
elif (
isinstance(
arg,
(
dict,
list,
map,
enumerate,
types.MappingProxyType,
UserDict,
ChainMap,
UserList,
ItemsView,
KeysView,
ValuesView,
),
)
or type_util.is_custom_dict(arg)
or type_util.is_namedtuple(arg)
or type_util.is_pydantic_model(arg)
):
flush_buffer()
self.dg.json(arg)
elif type_util.is_pydeck(arg):
flush_buffer()
self.dg.pydeck_chart(arg)
elif isinstance(arg, StringIO):
flush_buffer()
self.dg.markdown(arg.getvalue())
elif (
inspect.isgenerator(arg)
or inspect.isgeneratorfunction(arg)
or inspect.isasyncgenfunction(arg)
or inspect.isasyncgen(arg)
or type_util.is_type(arg, "openai.Stream")
):
flush_buffer()
self.write_stream(arg)
elif isinstance(arg, HELP_TYPES) or dataclasses.is_dataclass(arg):
flush_buffer()
self.dg.help(arg)
elif inspect.isclass(arg):
flush_buffer()
# We cast arg to type here to appease mypy, due to bug in mypy:
# https://github.com/python/mypy/issues/12933
self.dg.help(cast("type", arg))
elif unsafe_allow_html and type_util.has_callable_attr(arg, "_repr_html_"):
self.dg.html(arg._repr_html_())
elif type_util.has_callable_attr(
arg, "to_pandas"
) or type_util.has_callable_attr(arg, "__dataframe__"):
# This object can very likely be converted to a DataFrame
# using the to_pandas, to_arrow, or the dataframe interchange
# protocol.
flush_buffer()
self.dg.dataframe(arg)
else:
stringified_arg = str(arg)
if is_mem_address_str(stringified_arg):
flush_buffer()
self.dg.help(arg)
elif "\n" in stringified_arg:
# With a multi-line string, use a preformatted block
# To fully escape backticks, we wrap with backticks larger than
# the largest sequence of backticks in the string.
backtick_count = max(3, max_char_sequence(stringified_arg, "`") + 1)
backtick_wrapper = "`" * backtick_count
string_buffer.append(
f"{backtick_wrapper}\n{stringified_arg}\n{backtick_wrapper}"
)
else:
# With a single-line string, use a preformatted text
# To fully escape backticks, we wrap with backticks larger than
# the largest sequence of backticks in the string.
backtick_count = max_char_sequence(stringified_arg, "`") + 1
backtick_wrapper = "`" * backtick_count
string_buffer.append(
f"{backtick_wrapper}{stringified_arg}{backtick_wrapper}"
)
flush_buffer()
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
| WriteMixin |
python | spack__spack | lib/spack/spack/repo.py | {
"start": 78472,
"end": 78576
} | class ____(RepoError):
"""Raised when we encounter a package spack doesn't have."""
| UnknownEntityError |
python | tornadoweb__tornado | tornado/iostream.py | {
"start": 2553,
"end": 3218
} | class ____(IOError):
"""Exception raised by `IOStream` methods when the stream is closed.
Note that the close callback is scheduled to run *after* other
callbacks on the stream (to allow for buffered data to be processed),
so you may see this error before you see the close callback.
The ``real_error`` attribute contains the underlying error that caused
the stream to close (if any).
.. versionchanged:: 4.3
Added the ``real_error`` attribute.
"""
def __init__(self, real_error: Optional[BaseException] = None) -> None:
super().__init__("Stream is closed")
self.real_error = real_error
| StreamClosedError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 268831,
"end": 269342
} | class ____(sgqlc.types.Input):
"""Ways in which lists of reactions can be ordered upon return."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(ReactionOrderField), graphql_name="field")
"""The field in which to order reactions by."""
direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction")
"""The direction in which to order reactions by the specified field."""
| ReactionOrder |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_grid.py | {
"start": 679,
"end": 10468
} | class ____:
"""
A grid of Axes.
In Matplotlib, the Axes location (and size) is specified in normalized
figure coordinates. This may not be ideal for images that needs to be
displayed with a given aspect ratio; for example, it is difficult to
display multiple images of a same size with some fixed padding between
them. AxesGrid can be used in such case.
Attributes
----------
axes_all : list of Axes
A flat list of Axes. Note that you can also access this directly
from the grid. The following is equivalent ::
grid[i] == grid.axes_all[i]
len(grid) == len(grid.axes_all)
axes_column : list of list of Axes
A 2D list of Axes where the first index is the column. This results
in the usage pattern ``grid.axes_column[col][row]``.
axes_row : list of list of Axes
A 2D list of Axes where the first index is the row. This results
in the usage pattern ``grid.axes_row[row][col]``.
axes_llc : Axes
The Axes in the lower left corner.
n_axes : int
Number of Axes in the grid.
"""
_defaultAxesClass = Axes
@_api.rename_parameter("3.11", "ngrids", "n_axes")
def __init__(self, fig,
rect,
nrows_ncols,
n_axes=None,
direction="row",
axes_pad=0.02,
*,
share_all=False,
share_x=True,
share_y=True,
label_mode="L",
axes_class=None,
aspect=False,
):
"""
Parameters
----------
fig : `.Figure`
The parent figure.
rect : (float, float, float, float), (int, int, int), int, or \
`~.SubplotSpec`
The axes position, as a ``(left, bottom, width, height)`` tuple,
as a three-digit subplot position code (e.g., ``(1, 2, 1)`` or
``121``), or as a `~.SubplotSpec`.
nrows_ncols : (int, int)
Number of rows and columns in the grid.
n_axes : int, optional
If given, only the first *n_axes* axes in the grid are created.
direction : {"row", "column"}, default: "row"
Whether axes are created in row-major ("row by row") or
column-major order ("column by column"). This also affects the
order in which axes are accessed using indexing (``grid[index]``).
axes_pad : float or (float, float), default: 0.02
Padding or (horizontal padding, vertical padding) between axes, in
inches.
share_all : bool, default: False
Whether all axes share their x- and y-axis. Overrides *share_x*
and *share_y*.
share_x : bool, default: True
Whether all axes of a column share their x-axis.
share_y : bool, default: True
Whether all axes of a row share their y-axis.
label_mode : {"L", "1", "all", "keep"}, default: "L"
Determines which axes will get tick labels:
- "L": All axes on the left column get vertical tick labels;
all axes on the bottom row get horizontal tick labels.
- "1": Only the bottom left axes is labelled.
- "all": All axes are labelled.
- "keep": Do not do anything.
axes_class : subclass of `matplotlib.axes.Axes`, default: `.mpl_axes.Axes`
The type of Axes to create.
aspect : bool, default: False
Whether the axes aspect ratio follows the aspect ratio of the data
limits.
"""
self._nrows, self._ncols = nrows_ncols
if n_axes is None:
n_axes = self._nrows * self._ncols
else:
if not 0 < n_axes <= self._nrows * self._ncols:
raise ValueError(
"n_axes must be positive and not larger than nrows*ncols")
self._horiz_pad_size, self._vert_pad_size = map(
Size.Fixed, np.broadcast_to(axes_pad, 2))
_api.check_in_list(["column", "row"], direction=direction)
self._direction = direction
if axes_class is None:
axes_class = self._defaultAxesClass
elif isinstance(axes_class, (list, tuple)):
cls, kwargs = axes_class
axes_class = functools.partial(cls, **kwargs)
kw = dict(horizontal=[], vertical=[], aspect=aspect)
if isinstance(rect, (Number, SubplotSpec)):
self._divider = SubplotDivider(fig, rect, **kw)
elif len(rect) == 3:
self._divider = SubplotDivider(fig, *rect, **kw)
elif len(rect) == 4:
self._divider = Divider(fig, rect, **kw)
else:
raise TypeError("Incorrect rect format")
rect = self._divider.get_position()
axes_array = np.full((self._nrows, self._ncols), None, dtype=object)
for i in range(n_axes):
col, row = self._get_col_row(i)
if share_all:
sharex = sharey = axes_array[0, 0]
else:
sharex = axes_array[0, col] if share_x else None
sharey = axes_array[row, 0] if share_y else None
axes_array[row, col] = axes_class(
fig, rect, sharex=sharex, sharey=sharey)
self.axes_all = axes_array.ravel(
order="C" if self._direction == "row" else "F").tolist()[:n_axes]
self.axes_row = [[ax for ax in row if ax] for row in axes_array]
self.axes_column = [[ax for ax in col if ax] for col in axes_array.T]
self.axes_llc = self.axes_column[0][-1]
self._init_locators()
for ax in self.axes_all:
fig.add_axes(ax)
self.set_label_mode(label_mode)
def _init_locators(self):
self._divider.set_horizontal(
[Size.Scaled(1), self._horiz_pad_size] * (self._ncols-1) + [Size.Scaled(1)])
self._divider.set_vertical(
[Size.Scaled(1), self._vert_pad_size] * (self._nrows-1) + [Size.Scaled(1)])
for i in range(self.n_axes):
col, row = self._get_col_row(i)
self.axes_all[i].set_axes_locator(
self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row)))
def _get_col_row(self, n):
if self._direction == "column":
col, row = divmod(n, self._nrows)
else:
row, col = divmod(n, self._ncols)
return col, row
n_axes = property(lambda self: len(self.axes_all))
ngrids = _api.deprecated('3.11')(property(lambda self: len(self.axes_all)))
# Good to propagate __len__ if we have __getitem__
def __len__(self):
return len(self.axes_all)
def __getitem__(self, i):
return self.axes_all[i]
def get_geometry(self):
"""
Return the number of rows and columns of the grid as (nrows, ncols).
"""
return self._nrows, self._ncols
def set_axes_pad(self, axes_pad):
"""
Set the padding between the axes.
Parameters
----------
axes_pad : (float, float)
The padding (horizontal pad, vertical pad) in inches.
"""
self._horiz_pad_size.fixed_size = axes_pad[0]
self._vert_pad_size.fixed_size = axes_pad[1]
def get_axes_pad(self):
"""
Return the axes padding.
Returns
-------
hpad, vpad
Padding (horizontal pad, vertical pad) in inches.
"""
return (self._horiz_pad_size.fixed_size,
self._vert_pad_size.fixed_size)
def set_aspect(self, aspect):
"""Set the aspect of the SubplotDivider."""
self._divider.set_aspect(aspect)
def get_aspect(self):
"""Return the aspect of the SubplotDivider."""
return self._divider.get_aspect()
def set_label_mode(self, mode):
"""
Define which axes have tick labels.
Parameters
----------
mode : {"L", "1", "all", "keep"}
The label mode:
- "L": All axes on the left column get vertical tick labels;
all axes on the bottom row get horizontal tick labels.
- "1": Only the bottom left axes is labelled.
- "all": All axes are labelled.
- "keep": Do not do anything.
"""
_api.check_in_list(["all", "L", "1", "keep"], mode=mode)
if mode == "keep":
return
for i, j in np.ndindex(self._nrows, self._ncols):
try:
ax = self.axes_row[i][j]
except IndexError:
continue
if isinstance(ax.axis, MethodType):
bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"])
left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"])
else:
bottom_axis = ax.axis["bottom"]
left_axis = ax.axis["left"]
display_at_bottom = (i == self._nrows - 1 if mode == "L" else
i == self._nrows - 1 and j == 0 if mode == "1" else
True) # if mode == "all"
display_at_left = (j == 0 if mode == "L" else
i == self._nrows - 1 and j == 0 if mode == "1" else
True) # if mode == "all"
bottom_axis.toggle(ticklabels=display_at_bottom, label=display_at_bottom)
left_axis.toggle(ticklabels=display_at_left, label=display_at_left)
def get_divider(self):
return self._divider
def set_axes_locator(self, locator):
self._divider.set_locator(locator)
def get_axes_locator(self):
return self._divider.get_locator()
| Grid |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 192510,
"end": 193067
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("repository_id", "topic_names", "client_mutation_id")
repository_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="repositoryId"
)
topic_names = sgqlc.types.Field(
sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))),
graphql_name="topicNames",
)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| UpdateTopicsInput |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 21144,
"end": 26187
} | class ____(nn.Module):
r"""
Compute a single vector summary of a sequence hidden states.
Args:
config ([`RoFormerConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default values it uses):
- **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
- `"last"` -- Take the last token hidden state (like XLNet)
- `"first"` -- Take the first token hidden state (like Bert)
- `"mean"` -- Take the mean of all tokens hidden states
- `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
- `"attn"` -- Not implemented now, use multi-head attention
- **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
- **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
(otherwise to `config.hidden_size`).
- **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
another string or `None` will add no activation.
- **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
- **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
"""
def __init__(self, config: RoFormerConfig):
super().__init__()
self.summary_type = getattr(config, "summary_type", "last")
if self.summary_type == "attn":
# We should use a standard multi-head attention module with absolute positional embedding for that.
# Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
# We can probably just use the multi-head attention module of PyTorch >=1.1.0
raise NotImplementedError
self.summary = nn.Identity()
if hasattr(config, "summary_use_proj") and config.summary_use_proj:
if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
num_classes = config.num_labels
else:
num_classes = config.hidden_size
self.summary = nn.Linear(config.hidden_size, num_classes)
activation_string = getattr(config, "summary_activation", None)
self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
self.first_dropout = nn.Identity()
if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
self.first_dropout = nn.Dropout(config.summary_first_dropout)
self.last_dropout = nn.Identity()
if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
self.last_dropout = nn.Dropout(config.summary_last_dropout)
def forward(
self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None
) -> torch.FloatTensor:
"""
Compute a single vector summary of a sequence hidden states.
Args:
hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
The hidden states of the last layer.
cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
Returns:
`torch.FloatTensor`: The summary of the sequence hidden states.
"""
if self.summary_type == "last":
output = hidden_states[:, -1]
elif self.summary_type == "first":
output = hidden_states[:, 0]
elif self.summary_type == "mean":
output = hidden_states.mean(dim=1)
elif self.summary_type == "cls_index":
if cls_index is None:
cls_index = torch.full_like(
hidden_states[..., :1, :],
hidden_states.shape[-2] - 1,
dtype=torch.long,
)
else:
cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
# shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
elif self.summary_type == "attn":
raise NotImplementedError
output = self.first_dropout(output)
output = self.summary(output)
output = self.activation(output)
output = self.last_dropout(output)
return output
| RoFormerSequenceSummary |
python | PyCQA__pylint | tests/regrtest_data/wrong_import_position.py | {
"start": 147,
"end": 220
} | class ____(object):
"""A class before an import."""
import os
| Something |
python | ansible__ansible | test/units/module_utils/common/test_collections.py | {
"start": 2693,
"end": 4618
} | class ____:
def test_scalar(self):
imdict = ImmutableDict({1: 2})
assert imdict[1] == 2
def test_string(self):
imdict = ImmutableDict({u'café': u'くらとみ'})
assert imdict[u'café'] == u'くらとみ'
def test_container(self):
imdict = ImmutableDict({(1, 2): ['1', '2']})
assert imdict[(1, 2)] == ['1', '2']
def test_from_tuples(self):
imdict = ImmutableDict((('a', 1), ('b', 2)))
assert frozenset(imdict.items()) == frozenset((('a', 1), ('b', 2)))
def test_from_kwargs(self):
imdict = ImmutableDict(a=1, b=2)
assert frozenset(imdict.items()) == frozenset((('a', 1), ('b', 2)))
def test_immutable(self):
imdict = ImmutableDict({1: 2})
expected_reason = r"^'ImmutableDict' object does not support item assignment$"
with pytest.raises(TypeError, match=expected_reason):
imdict[1] = 3
with pytest.raises(TypeError, match=expected_reason):
imdict[5] = 3
def test_hashable(self):
# ImmutableDict is hashable when all of its values are hashable
imdict = ImmutableDict({u'café': u'くらとみ'})
assert hash(imdict)
def test_nonhashable(self):
# ImmutableDict is unhashable when one of its values is unhashable
imdict = ImmutableDict({u'café': u'くらとみ', 1: [1, 2]})
expected_reason = r"unhashable type: 'list'"
with pytest.raises(TypeError, match=expected_reason):
hash(imdict)
def test_len(self):
imdict = ImmutableDict({1: 2, 'a': 'b'})
assert len(imdict) == 2
def test_repr(self):
initial_data = {1: 2, 'a': 'b'}
initial_data_repr = repr(initial_data)
imdict = ImmutableDict(initial_data)
actual_repr = repr(imdict)
expected_repr = "ImmutableDict({0})".format(initial_data_repr)
assert actual_repr == expected_repr
| TestImmutableDict |
python | celery__celery | t/unit/backends/test_asynchronous.py | {
"start": 8066,
"end": 8851
} | class ____(GreenletDrainerTests):
@pytest.fixture(autouse=True)
def setup_drainer(self):
self.drainer = self.get_drainer('gevent')
@cached_property
def sleep(self):
from gevent import sleep
return sleep
def result_consumer_drain_events(self, timeout=None):
import gevent
# `drain_events` of asynchronous backends with pubsub have to sleep
# while waiting events for not more then `interval` timeout,
# but events may coming sooner
gevent.sleep(timeout/10)
def schedule_thread(self, thread):
import gevent
g = gevent.spawn(thread)
gevent.sleep(0)
return g
def teardown_thread(self, thread):
import gevent
gevent.wait([thread])
| test_GeventDrainer |
python | sqlalchemy__sqlalchemy | test/ext/test_extendedattr.py | {
"start": 4457,
"end": 17131
} | class ____(_ExtBase, fixtures.ORMTest):
@classmethod
def setup_test_class(cls):
global MyBaseClass, MyClass
class MyBaseClass:
__sa_instrumentation_manager__ = (
instrumentation.InstrumentationManager
)
class MyClass:
# This proves that a staticmethod will work here; don't
# flatten this back to a class assignment!
def __sa_instrumentation_manager__(cls):
return MyTypesManager(cls)
__sa_instrumentation_manager__ = staticmethod(
__sa_instrumentation_manager__
)
# This proves SA can handle a class with non-string dict keys
# Since python 3.13 non-string key raise a runtime warning.
if util.cpython and not util.py313:
locals()[42] = 99 # Don't remove this line!
def __init__(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
def __getattr__(self, key):
if is_instrumented(self, key):
return get_attribute(self, key)
else:
try:
return self._goofy_dict[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
if is_instrumented(self, key):
set_attribute(self, key, value)
else:
self._goofy_dict[key] = value
def __hasattr__(self, key):
if is_instrumented(self, key):
return True
else:
return key in self._goofy_dict
def __delattr__(self, key):
if is_instrumented(self, key):
del_attribute(self, key)
else:
del self._goofy_dict[key]
def teardown_test(self):
clear_mappers()
def test_instance_dict(self):
class User(MyClass):
pass
register_class(User)
_register_attribute(User, "user_id", uselist=False, useobject=False)
_register_attribute(User, "user_name", uselist=False, useobject=False)
_register_attribute(
User, "email_address", uselist=False, useobject=False
)
u = User()
u.user_id = 7
u.user_name = "john"
u.email_address = "lala@123.com"
eq_(
u.__dict__,
{
"_my_state": u._my_state,
"_goofy_dict": {
"user_id": 7,
"user_name": "john",
"email_address": "lala@123.com",
},
},
)
def test_basic(self):
for base in (object, MyBaseClass, MyClass):
class User(base):
pass
register_class(User)
_register_attribute(
User, "user_id", uselist=False, useobject=False
)
_register_attribute(
User, "user_name", uselist=False, useobject=False
)
_register_attribute(
User, "email_address", uselist=False, useobject=False
)
u = User()
u.user_id = 7
u.user_name = "john"
u.email_address = "lala@123.com"
eq_(u.user_id, 7)
eq_(u.user_name, "john")
eq_(u.email_address, "lala@123.com")
attributes.instance_state(u)._commit_all(
attributes.instance_dict(u)
)
eq_(u.user_id, 7)
eq_(u.user_name, "john")
eq_(u.email_address, "lala@123.com")
u.user_name = "heythere"
u.email_address = "foo@bar.com"
eq_(u.user_id, 7)
eq_(u.user_name, "heythere")
eq_(u.email_address, "foo@bar.com")
def test_deferred(self):
for base in (object, MyBaseClass, MyClass):
class Foo(base):
pass
data = {"a": "this is a", "b": 12}
def loader(state, keys, passive):
for k in keys:
state.dict[k] = data[k]
return attributes.ATTR_WAS_SET
manager = register_class(Foo)
manager.expired_attribute_loader = loader
_register_attribute(Foo, "a", uselist=False, useobject=False)
_register_attribute(Foo, "b", uselist=False, useobject=False)
if base is object:
assert Foo not in (
instrumentation._instrumentation_factory._state_finders
)
else:
assert Foo in (
instrumentation._instrumentation_factory._state_finders
)
f = Foo()
attributes.instance_state(f)._expire(
attributes.instance_dict(f), set()
)
eq_(f.a, "this is a")
eq_(f.b, 12)
f.a = "this is some new a"
attributes.instance_state(f)._expire(
attributes.instance_dict(f), set()
)
eq_(f.a, "this is a")
eq_(f.b, 12)
attributes.instance_state(f)._expire(
attributes.instance_dict(f), set()
)
f.a = "this is another new a"
eq_(f.a, "this is another new a")
eq_(f.b, 12)
attributes.instance_state(f)._expire(
attributes.instance_dict(f), set()
)
eq_(f.a, "this is a")
eq_(f.b, 12)
del f.a
eq_(f.a, None)
eq_(f.b, 12)
attributes.instance_state(f)._commit_all(
attributes.instance_dict(f)
)
eq_(f.a, None)
eq_(f.b, 12)
def test_inheritance(self):
"""tests that attributes are polymorphic"""
for base in (object, MyBaseClass, MyClass):
class Foo(base):
pass
class Bar(Foo):
pass
register_class(Foo)
register_class(Bar)
def func1(state, passive):
return "this is the foo attr"
def func2(state, passive):
return "this is the bar attr"
def func3(state, passive):
return "this is the shared attr"
_register_attribute(
Foo, "element", uselist=False, callable_=func1, useobject=True
)
_register_attribute(
Foo, "element2", uselist=False, callable_=func3, useobject=True
)
_register_attribute(
Bar, "element", uselist=False, callable_=func2, useobject=True
)
x = Foo()
y = Bar()
assert x.element == "this is the foo attr"
assert y.element == "this is the bar attr", y.element
assert x.element2 == "this is the shared attr"
assert y.element2 == "this is the shared attr"
def test_collection_with_backref(self):
for base in (object, MyBaseClass, MyClass):
class Post(base):
pass
class Blog(base):
pass
register_class(Post)
register_class(Blog)
_register_attribute(
Post,
"blog",
uselist=False,
backref="posts",
trackparent=True,
useobject=True,
)
_register_attribute(
Blog,
"posts",
uselist=True,
backref="blog",
trackparent=True,
useobject=True,
)
b = Blog()
(p1, p2, p3) = (Post(), Post(), Post())
b.posts.append(p1)
b.posts.append(p2)
b.posts.append(p3)
self.assert_(b.posts == [p1, p2, p3])
self.assert_(p2.blog is b)
p3.blog = None
self.assert_(b.posts == [p1, p2])
p4 = Post()
p4.blog = b
self.assert_(b.posts == [p1, p2, p4])
p4.blog = b
p4.blog = b
self.assert_(b.posts == [p1, p2, p4])
# assert no failure removing None
p5 = Post()
p5.blog = None
del p5.blog
def test_history(self):
for base in (object, MyBaseClass, MyClass):
class Foo(base):
pass
class Bar(base):
pass
register_class(Foo)
register_class(Bar)
_register_attribute(Foo, "name", uselist=False, useobject=False)
_register_attribute(
Foo, "bars", uselist=True, trackparent=True, useobject=True
)
_register_attribute(Bar, "name", uselist=False, useobject=False)
f1 = Foo()
f1.name = "f1"
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "name"
),
(["f1"], (), ()),
)
b1 = Bar()
b1.name = "b1"
f1.bars.append(b1)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "bars"
),
([b1], [], []),
)
attributes.instance_state(f1)._commit_all(
attributes.instance_dict(f1)
)
attributes.instance_state(b1)._commit_all(
attributes.instance_dict(b1)
)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "name"
),
((), ["f1"], ()),
)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "bars"
),
((), [b1], ()),
)
f1.name = "f1mod"
b2 = Bar()
b2.name = "b2"
f1.bars.append(b2)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "name"
),
(["f1mod"], (), ["f1"]),
)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "bars"
),
([b2], [b1], []),
)
f1.bars.remove(b1)
eq_(
attributes.get_state_history(
attributes.instance_state(f1), "bars"
),
([b2], [], [b1]),
)
def test_null_instrumentation(self):
class Foo(MyBaseClass):
pass
register_class(Foo)
_register_attribute(Foo, "name", uselist=False, useobject=False)
_register_attribute(
Foo, "bars", uselist=True, trackparent=True, useobject=True
)
assert Foo.name == attributes.manager_of_class(Foo)["name"]
assert Foo.bars == attributes.manager_of_class(Foo)["bars"]
def test_alternate_finders(self):
"""Ensure the generic finder front-end deals with edge cases."""
class Unknown:
pass
class Known(MyBaseClass):
pass
register_class(Known)
k, u = Known(), Unknown()
assert instrumentation.opt_manager_of_class(Unknown) is None
assert instrumentation.opt_manager_of_class(Known) is not None
assert instrumentation.opt_manager_of_class(None) is None
assert attributes.instance_state(k) is not None
assert_raises((AttributeError, KeyError), attributes.instance_state, u)
assert_raises(
(AttributeError, KeyError), attributes.instance_state, None
)
def test_unmapped_not_type_error(self):
"""extension version of the same test in test_mapper.
fixes #3408
"""
assert_raises_message(
sa.exc.ArgumentError,
"Class object expected, got '5'.",
class_mapper,
5,
)
def test_unmapped_not_type_error_iter_ok(self):
"""extension version of the same test in test_mapper.
fixes #3408
"""
assert_raises_message(
sa.exc.ArgumentError,
r"Class object expected, got '\(5, 6\)'.",
class_mapper,
(5, 6),
)
| UserDefinedExtensionTest |
python | getsentry__sentry | src/social_auth/backends/__init__.py | {
"start": 8528,
"end": 13175
} | class ____:
"""Base authentication class, new authenticators should subclass
and implement needed methods.
AUTH_BACKEND Authorization backend related with this service
"""
AUTH_BACKEND: type[SocialAuthBackend]
def __init__(self, request, redirect):
self.request = request
# TODO(python3): use {**x, **y} syntax once 2.7 support is dropped
data = request.GET.copy()
data.update(request.POST)
self.data = data
self.redirect = redirect
def auth_url(self):
"""Must return redirect URL to auth provider"""
raise NotImplementedError("Implement in subclass")
def auth_html(self):
"""Must return login HTML content returned by provider"""
raise NotImplementedError("Implement in subclass")
def auth_complete(self, *args, **kwargs):
"""Completes logging process, must return user instance"""
raise NotImplementedError("Implement in subclass")
def to_session_dict(self, next_idx, *args, **kwargs):
"""Returns dict to store on session for partial pipeline."""
backend = kwargs["backend"]
kwargs["backend"] = f"{backend.__module__}.{backend.__class__.__name__}"
return {
"next": next_idx,
"backend": self.AUTH_BACKEND.name,
"args": tuple(map(model_to_ctype, args)),
"kwargs": {key: model_to_ctype(val) for key, val in kwargs.items()},
}
def from_session_dict(self, session_data, *args, **kwargs):
"""Takes session saved data to continue pipeline and merges with any
new extra argument needed. Returns tuple with next pipeline index
entry, arguments and keyword arguments to continue the process."""
args = args[:] + tuple(map(ctype_to_model, session_data["args"]))
kwargs = kwargs.copy()
saved_kwargs = {key: ctype_to_model(val) for key, val in session_data["kwargs"].items()}
saved_kwargs.update((key, val) for key, val in kwargs.items())
if isinstance(saved_kwargs.get("backend"), str):
backend_path = saved_kwargs["backend"]
if backend_path in settings.AUTHENTICATION_BACKENDS:
saved_kwargs["backend"] = load_backend(backend_path)
return (session_data["next"], args, saved_kwargs)
def continue_pipeline(self, *args, **kwargs):
"""Continue previous halted pipeline"""
kwargs.update({"auth": self, self.AUTH_BACKEND.name: True})
return authenticate(*args, **kwargs)
def request_token_extra_arguments(self):
"""Return extra arguments needed on request-token process,
setting is per backend and defined by:
<backend name in uppercase>_REQUEST_TOKEN_EXTRA_ARGUMENTS.
"""
backend_name = self.AUTH_BACKEND.name.upper().replace("-", "_")
return setting(backend_name + "_REQUEST_TOKEN_EXTRA_ARGUMENTS", {})
def auth_extra_arguments(self):
"""Return extra arguments needed on auth process, setting is per
backend and defined by:
<backend name in uppercase>_AUTH_EXTRA_ARGUMENTS.
The defaults can be overridden by GET parameters.
"""
backend_name = self.AUTH_BACKEND.name.upper().replace("-", "_")
extra_arguments = setting(backend_name + "_AUTH_EXTRA_ARGUMENTS", {})
for key, value in extra_arguments.items():
if key in self.data:
extra_arguments[key] = self.data[key]
elif value:
extra_arguments[key] = value
return extra_arguments
@property
def uses_redirect(self):
"""Return True if this provider uses redirect url method,
otherwise return false."""
return True
@classmethod
def enabled(cls):
"""Return backend enabled status, all enabled by default"""
return True
def disconnect(self, user, association_id=None):
"""Deletes current backend from user if associated.
Override if extra operations are needed.
"""
name = self.AUTH_BACKEND.name
do_revoke = setting("SOCIAL_AUTH_REVOKE_TOKENS_ON_DISCONNECT")
filter_args = {}
if association_id:
filter_args["id"] = association_id
else:
filter_args["provider"] = name
instances = UserSocialAuth.get_social_auth_for_user(user).filter(**filter_args)
if do_revoke:
for instance in instances:
instance.revoke_token(drop_token=False)
instances.delete()
def build_absolute_uri(self, path=None):
return absolute_uri(path)
| BaseAuth |
python | pydata__xarray | xarray/tests/test_treenode.py | {
"start": 4448,
"end": 6057
} | class ____:
def test_get_child(self) -> None:
john: TreeNode = TreeNode(
children={
"Mary": TreeNode(
children={"Sue": TreeNode(children={"Steven": TreeNode()})}
)
}
)
mary = john.children["Mary"]
sue = mary.children["Sue"]
steven = sue.children["Steven"]
# get child
assert john._get_item("Mary") is mary
assert mary._get_item("Sue") is sue
# no child exists
with pytest.raises(KeyError):
john._get_item("Kate")
# get grandchild
assert john._get_item("Mary/Sue") is sue
# get great-grandchild
assert john._get_item("Mary/Sue/Steven") is steven
# get from middle of tree
assert mary._get_item("Sue/Steven") is steven
def test_get_upwards(self) -> None:
john: TreeNode = TreeNode(
children={
"Mary": TreeNode(children={"Sue": TreeNode(), "Kate": TreeNode()})
}
)
mary = john.children["Mary"]
sue = mary.children["Sue"]
kate = mary.children["Kate"]
assert sue._get_item("../") is mary
assert sue._get_item("../../") is john
# relative path
assert sue._get_item("../Kate") is kate
def test_get_from_root(self) -> None:
john: TreeNode = TreeNode(
children={"Mary": TreeNode(children={"Sue": TreeNode()})}
)
mary = john.children["Mary"]
sue = mary.children["Sue"]
assert sue._get_item("/Mary") is mary
| TestGetNodes |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_combined03.py | {
"start": 315,
"end": 1474
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_combined03.xlsx")
self.ignore_elements = {"xl/charts/chart1.xml": ["<c:dispBlanksAs"]}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart1 = workbook.add_chart({"type": "column"})
chart2 = workbook.add_chart({"type": "line"})
data = [
[2, 7, 3, 6, 2],
[20, 25, 10, 10, 20],
[4, 2, 5, 2, 1],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart1.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart1.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart2.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart1.combine(chart2)
worksheet.insert_chart("E9", chart1)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 17530,
"end": 21086
} | class ____:
"""Test cases for ExecutionEngine.download_async()."""
@pytest.fixture
def engine(self) -> ExecutionEngine:
crawler = get_crawler(MySpider)
engine = ExecutionEngine(crawler, lambda _: None)
engine.downloader.close()
engine.downloader = Mock()
engine._slot = Mock()
engine._slot.inprogress = set()
return engine
@staticmethod
async def _download(engine: ExecutionEngine, request: Request) -> Response:
return await engine.download_async(request)
@deferred_f_from_coro_f
async def test_download_async_success(self, engine):
"""Test basic successful async download of a request."""
request = Request("http://example.com")
response = Response("http://example.com", body=b"test body")
engine.spider = Mock()
engine.downloader.fetch.return_value = defer.succeed(response)
engine._slot.add_request = Mock()
engine._slot.remove_request = Mock()
result = await self._download(engine, request)
assert result == response
engine._slot.add_request.assert_called_once_with(request)
engine._slot.remove_request.assert_called_once_with(request)
engine.downloader.fetch.assert_called_once_with(request)
@deferred_f_from_coro_f
async def test_download_async_redirect(self, engine):
"""Test async download with a redirect request."""
original_request = Request("http://example.com")
redirect_request = Request("http://example.com/redirect")
final_response = Response("http://example.com/redirect", body=b"redirected")
# First call returns redirect request, second call returns final response
engine.downloader.fetch.side_effect = [
defer.succeed(redirect_request),
defer.succeed(final_response),
]
engine.spider = Mock()
engine._slot.add_request = Mock()
engine._slot.remove_request = Mock()
result = await self._download(engine, original_request)
assert result == final_response
assert engine.downloader.fetch.call_count == 2
engine._slot.add_request.assert_has_calls(
[call(original_request), call(redirect_request)]
)
engine._slot.remove_request.assert_has_calls(
[call(original_request), call(redirect_request)]
)
@deferred_f_from_coro_f
async def test_download_async_no_spider(self, engine):
"""Test async download attempt when no spider is available."""
request = Request("http://example.com")
engine.spider = None
with pytest.raises(RuntimeError, match="No open spider to crawl:"):
await self._download(engine, request)
@deferred_f_from_coro_f
async def test_download_async_failure(self, engine):
"""Test async download when the downloader raises an exception."""
request = Request("http://example.com")
error = RuntimeError("Download failed")
engine.spider = Mock()
engine.downloader.fetch.return_value = defer.fail(error)
engine._slot.add_request = Mock()
engine._slot.remove_request = Mock()
with pytest.raises(RuntimeError, match="Download failed"):
await self._download(engine, request)
engine._slot.add_request.assert_called_once_with(request)
engine._slot.remove_request.assert_called_once_with(request)
@pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning")
| TestEngineDownloadAsync |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 165959,
"end": 166177
} | class ____(RecvmsgTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket.socket, "recvmsg_into")
| RecvmsgUDPLITETest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_bank_accounts.py | {
"start": 15393,
"end": 22043
} | class ____(TestCase):
@HttpMocker()
def test_given_no_state_and_successful_sync_when_read_then_set_state_to_now(self, http_mocker: HttpMocker) -> None:
# If stripe takes some time to ingest the data, we should recommend to use a lookback window when syncing the bank_accounts stream
# to make sure that we don't lose data between the first and the second sync
http_mocker.get(
_customers_request().with_expands(_EXPANDS).with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(),
_customers_response()
.with_record(_a_customer().with_field(_SOURCES_FIELD, _as_dict(_bank_accounts_response().with_record(_a_bank_account()))))
.build(),
)
output = self._read(_config().with_start_date(_A_START_DATE), _NO_STATE)
most_recent_state = output.most_recent_state
assert most_recent_state.stream_descriptor == StreamDescriptor(name=_STREAM_NAME)
assert int(most_recent_state.stream_state.state["updated"]) == int(_NOW.timestamp())
@HttpMocker()
def test_given_state_when_read_then_query_events_using_types_and_state_value_plus_1(self, http_mocker: HttpMocker) -> None:
start_date = _NOW - timedelta(days=40)
state_datetime = _NOW - timedelta(days=5)
cursor_value = int(state_datetime.timestamp()) + 1
http_mocker.get(
_events_request().with_created_gte(state_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response()
.with_record(_an_event().with_cursor(cursor_value).with_field(_DATA_FIELD, _a_bank_account().build()))
.build(),
)
output = self._read(
_config().with_start_date(start_date),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
most_recent_state = output.most_recent_state
assert most_recent_state.stream_descriptor == StreamDescriptor(name=_STREAM_NAME)
assert most_recent_state.stream_state.updated == str(cursor_value)
@HttpMocker()
def test_given_state_and_pagination_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
state_datetime = _NOW - timedelta(days=5)
http_mocker.get(
_events_request().with_created_gte(state_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response()
.with_pagination()
.with_record(_an_event().with_id("last_record_id_from_first_page").with_field(_DATA_FIELD, _a_bank_account().build()))
.build(),
)
http_mocker.get(
_events_request()
.with_starting_after("last_record_id_from_first_page")
.with_created_gte(state_datetime)
.with_created_lte(_NOW)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._a_bank_account_event()).build(),
)
output = self._read(
_config(),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
assert len(output.records) == 2
@HttpMocker()
def test_given_state_and_small_slice_range_when_read_then_perform_multiple_queries(self, http_mocker: HttpMocker) -> None:
state_datetime = _NOW - timedelta(days=5)
slice_range = timedelta(days=3)
slice_datetime = state_datetime + slice_range
http_mocker.get(
_events_request()
.with_created_gte(state_datetime)
.with_created_lte(slice_datetime - _AVOIDING_INCLUSIVE_BOUNDARIES)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._a_bank_account_event()).build(),
)
http_mocker.get(
_events_request().with_created_gte(slice_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response().with_record(self._a_bank_account_event()).with_record(self._a_bank_account_event()).build(),
)
output = self._read(
_config().with_start_date(_NOW - timedelta(days=30)).with_slice_range_in_days(slice_range.days),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
assert len(output.records) == 3
@HttpMocker()
def test_given_state_earlier_than_30_days_when_read_then_query_events_using_types_and_event_lower_boundary(
self, http_mocker: HttpMocker
) -> None:
# this seems odd as we would miss some data between start_date and events_lower_boundary. In that case, we should hit the
# customer endpoint
start_date = _NOW - timedelta(days=40)
state_value = _NOW - timedelta(days=39)
events_lower_boundary = _NOW - timedelta(days=30)
http_mocker.get(
_events_request()
.with_created_gte(events_lower_boundary)
.with_created_lte(_NOW)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._a_bank_account_event()).build(),
)
self._read(
_config().with_start_date(start_date),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_value.timestamp())}).build(),
)
# request matched http_mocker
@HttpMocker()
def test_given_source_is_not_bank_account_when_read_then_filter_record(self, http_mocker: HttpMocker) -> None:
state_datetime = _NOW - timedelta(days=5)
http_mocker.get(
_events_request().with_created_gte(state_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response().with_record(_an_event().with_field(_DATA_FIELD, _NOT_A_BANK_ACCOUNT.build())).build(),
)
output = self._read(
_config(),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
assert len(output.records) == 0
def _a_bank_account_event(self) -> RecordBuilder:
return _an_event().with_field(_DATA_FIELD, _a_bank_account().build())
def _read(self, config: ConfigBuilder, state: Optional[Dict[str, Any]], expecting_exception: bool = False) -> EntrypointOutput:
return _read(config, SyncMode.incremental, state, expecting_exception)
| IncrementalTest |
python | ray-project__ray | rllib/examples/envs/classes/mock_env.py | {
"start": 2012,
"end": 2709
} | class ____(gym.Env):
"""Mock environment for testing purposes.
Observation=ts (discrete space!), reward=100.0, episode-len is
configurable. Actions are ignored.
"""
def __init__(self, episode_length):
self.episode_length = episode_length
self.i = 0
self.observation_space = gym.spaces.Discrete(100)
self.action_space = gym.spaces.Discrete(2)
def reset(self, *, seed=None, options=None):
self.i = 0
return self.i, {"timestep": 0}
def step(self, action):
self.i += 1
terminated = truncated = self.i >= self.episode_length
return self.i, self.i, terminated, truncated, {"timestep": self.i}
| MockEnv3 |
python | ipython__ipython | tests/test_zzz_autoreload.py | {
"start": 25692,
"end": 25862
} | class ____(object):
def __init__(self, x):
self.x = x
def bar(self, y):
return self.x + y + 1
@property
def quux(self):
return 43
| Baz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.