本文整理汇总了Python中warnings.warn函数的典型用法代码示例。如果您正苦于以下问题:Python warn函数的具体用法?Python warn怎么用?Python warn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _is_a
def _is_a(self, x):
"""
Check if a Sage object ``x`` belongs to ``self``.
This methods is a helper for :meth:`__contains__` and the
constructor :meth:`_element_constructor_`.
EXAMPLES::
sage: U4 = DisjointUnionEnumeratedSets(
....: Family(NonNegativeIntegers(), Compositions))
sage: U4._is_a(Composition([3,2,1,1]))
doctest:...: UserWarning: Disjoint union of Lazy family (<class 'sage.combinat.composition.Compositions'>(i))_{i in Non negative integers} is an infinite union
The default implementation of __contains__ can loop forever. Please overload it.
True
"""
if self._keepkey:
return (isinstance(x, tuple) and
x[0] in self._family.keys() and
x[1] in self._family[x[0]])
else:
from warnings import warn
if self._family.cardinality() == Infinity:
warn("%s is an infinite union\nThe default implementation of __contains__ can loop forever. Please overload it."%(self))
return any(x in a for a in self._family)
示例2: serialize
def serialize(v):
global _have_warned_about_timestamps
try:
converted = calendar.timegm(v.utctimetuple())
converted = converted * 1e3 + getattr(v, 'microsecond', 0) / 1e3
except AttributeError:
# Ints and floats are valid timestamps too
if type(v) not in _number_types:
raise TypeError('DateType arguments must be a datetime or timestamp')
if not _have_warned_about_timestamps:
_have_warned_about_timestamps = True
warnings.warn("timestamp columns in Cassandra hold a number of "
"milliseconds since the unix epoch. Currently, when executing "
"prepared statements, this driver multiplies timestamp "
"values by 1000 so that the result of time.time() "
"can be used directly. However, the driver cannot "
"match this behavior for non-prepared statements, "
"so the 2.0 version of the driver will no longer multiply "
"timestamps by 1000. It is suggested that you simply use "
"datetime.datetime objects for 'timestamp' values to avoid "
"any ambiguity and to guarantee a smooth upgrade of the "
"driver.")
converted = v * 1e3
return int64_pack(long(converted))
示例3: tcp_server
def tcp_server(listensocket, server, *args, **kw):
"""
Given a socket, accept connections forever, spawning greenlets
and executing *server* for each new incoming connection.
When *listensocket* is closed, the ``tcp_server()`` greenlet will end.
listensocket
The socket from which to accept connections.
server
The callable to call when a new connection is made.
\*args
The positional arguments to pass to *server*.
\*\*kw
The keyword arguments to pass to *server*.
"""
import warnings
warnings.warn("gevent.socket.tcp_server is deprecated", DeprecationWarning, stacklevel=2)
try:
try:
while True:
client_socket = listensocket.accept()
spawn_raw(server, client_socket, *args, **kw)
except error, e:
# Broken pipe means it was shutdown
if e[0] != 32:
raise
finally:
listensocket.close()
示例4: __init__
def __init__(self, filepath, monitor='val_loss', verbose=0,
save_best_only=False, mode='auto'):
super(Callback, self).__init__()
self.monitor = monitor
self.verbose = verbose
self.filepath = filepath
self.save_best_only = save_best_only
if mode not in ['auto', 'min', 'max']:
warnings.warn('ModelCheckpoint mode %s is unknown, '
'fallback to auto mode.' % (mode),
RuntimeWarning)
mode = 'auto'
if mode == 'min':
self.monitor_op = np.less
self.best = np.Inf
elif mode == 'max':
self.monitor_op = np.greater
self.best = -np.Inf
else:
if 'acc' in self.monitor:
self.monitor_op = np.greater
self.best = -np.Inf
else:
self.monitor_op = np.less
self.best = np.Inf
示例5: __init__
def __init__(self, address, *, prefix=b'',
RE=None, zmq=None, serializer=pickle.dumps):
if RE is not None:
warnings.warn("The RE argument to Publisher is deprecated and "
"will be removed in a future release of bluesky. "
"Update your code to subscribe this Publisher "
"instance to (and, if needed, unsubscribe from) to "
"the RunEngine manually.")
if isinstance(prefix, str):
raise ValueError("prefix must be bytes, not string")
if b' ' in prefix:
raise ValueError("prefix {!r} may not contain b' '".format(prefix))
if zmq is None:
import zmq
if isinstance(address, str):
address = address.split(':', maxsplit=1)
self.address = (address[0], int(address[1]))
self.RE = RE
url = "tcp://%s:%d" % self.address
self._prefix = bytes(prefix)
self._context = zmq.Context()
self._socket = self._context.socket(zmq.PUB)
self._socket.connect(url)
if RE:
self._subscription_token = RE.subscribe(self)
self._serializer = serializer
示例6: mean_scaling
def mean_scaling(Y, axis=0):
"""Scaling of the data to have percent of baseline change along the
specified axis
Parameters
----------
Y : array of shape (n_time_points, n_voxels)
The input data.
Returns
-------
Y : array of shape (n_time_points, n_voxels),
The data after mean-scaling, de-meaning and multiplication by 100.
mean : array of shape (n_voxels,)
The data mean.
"""
mean = Y.mean(axis=axis)
if (mean == 0).any():
warn('Mean values of 0 observed.'
'The data have probably been centered.'
'Scaling might not work as expected')
mean = np.maximum(mean, 1)
Y = 100 * (Y / mean - 1)
return Y, mean
示例7: TH2_to_FITS
def TH2_to_FITS(hist, flipx=True):
"""Convert ROOT 2D histogram to FITS format.
Parameters
----------
hist : ROOT.TH2
2-dim ROOT histogram
Returns
-------
hdu : `~astropy.io.fits.ImageHDU`
Histogram in FITS format.
Examples
--------
>>> import ROOT
>>> from gammapy.utils.root import TH2_to_FITS
>>> root_hist = ROOT.TH2F()
>>> fits_hdu = TH2_to_FITS(root_hist)
>>> fits_hdu.writetofits('my_image.fits')
"""
header = TH2_to_FITS_header(hist, flipx)
if header['CDELT1'] > 0:
warnings.warn('CDELT1 > 0 might not be handled properly.'
'A TH2 representing an astro image should have '
'a reversed x-axis, i.e. xlow > xhi')
data = TH2_to_FITS_data(hist, flipx)
hdu = fits.ImageHDU(data=data, header=header)
return hdu
示例8: train
def train(self, features, labels, normalisedlabels=False):
idxs = self.selector(features, labels)
if len(idxs) == 0:
import warnings
warnings.warn('milk.featureselection: No features selected! Using all features as fall-back.')
idxs = np.arange(len(features[0]))
return filterfeatures(idxs)
示例9: Window_
def Window_(self, **criteria):
warnings.warn(
"WindowSpecification.Window() WindowSpecification.Window_(), "
"WindowSpecification.window() and WindowSpecification.window_() "
"are deprecated, please switch to WindowSpecification.ChildWindow()",
DeprecationWarning)
return self.ChildWindow(**criteria)
示例10: column_or_1d
def column_or_1d(y, warn=False):
""" Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
"""
shape = np.shape(y)
if len(shape) == 1:
return np.ravel(y)
if len(shape) == 2 and shape[1] == 1:
if warn:
warnings.warn("A column-vector y was passed when a 1d array was"
" expected. Please change the shape of y to "
"(n_samples, ), for example using ravel().",
DataConversionWarning, stacklevel=2)
return np.ravel(y)
raise ValueError("bad input shape {0}".format(shape))
示例11: __init__
def __init__(self, unit="ns", tz=None):
if isinstance(unit, DatetimeTZDtype):
unit, tz = unit.unit, unit.tz
if unit != 'ns':
if isinstance(unit, str) and tz is None:
# maybe a string like datetime64[ns, tz], which we support for
# now.
result = type(self).construct_from_string(unit)
unit = result.unit
tz = result.tz
msg = (
"Passing a dtype alias like 'datetime64[ns, {tz}]' "
"to DatetimeTZDtype is deprecated. Use "
"'DatetimeTZDtype.construct_from_string()' instead."
)
warnings.warn(msg.format(tz=tz), FutureWarning, stacklevel=2)
else:
raise ValueError("DatetimeTZDtype only supports ns units")
if tz:
tz = timezones.maybe_get_tz(tz)
tz = timezones.tz_standardize(tz)
elif tz is not None:
raise pytz.UnknownTimeZoneError(tz)
elif tz is None:
raise TypeError("A 'tz' is required.")
self._unit = unit
self._tz = tz
示例12: variable
def variable(value, dtype=_FLOATX, name=None):
'''Instantiates a tensor.
# Arguments
value: numpy array, initial value of the tensor.
dtype: tensor type.
name: optional name string for the tensor.
# Returns
Tensor variable instance.
'''
v = tf.Variable(value, dtype=_convert_string_dtype(dtype), name=name)
if _MANUAL_VAR_INIT:
return v
if tf.get_default_graph() is get_session().graph:
try:
get_session().run(v.initializer)
except tf.errors.InvalidArgumentError:
warnings.warn('Could not automatically initialize variable, '
'make sure you do it manually (e.g. via '
'`tf.initialize_all_variables()`).')
else:
warnings.warn('The default TensorFlow graph is not the graph '
'associated with the TensorFlow session currently '
'registered with Keras, and as such Keras '
'was not able to automatically initialize a variable. '
'You should consider registering the proper session '
'with Keras via `K.set_session(sess)`.')
return v
示例13: load
def load(self, path=None, force=True):
"""Load state from local file.
If no path is specified, attempts to load from ``self.path``.
:type path: str
:arg path: local file to load from
:type force: bool
:param force:
if ``force=False``, only load from ``self.path`` if file
has changed since last load.
.. deprecated:: 1.6
This keyword will be removed in Passlib 1.8;
Applications should use :meth:`load_if_changed` instead.
"""
if path is not None:
with open(path, "rb") as fh:
self._mtime = 0
self._load_lines(fh)
elif not force:
warn("%(name)s.load(force=False) is deprecated as of Passlib 1.6,"
"and will be removed in Passlib 1.8; "
"use %(name)s.load_if_changed() instead." %
dict(name=self.__class__.__name__),
DeprecationWarning, stacklevel=2)
return self.load_if_changed()
elif self._path:
with open(self._path, "rb") as fh:
self._mtime = os.path.getmtime(self._path)
self._load_lines(fh)
else:
raise RuntimeError("%s().path is not set, an explicit path is required" %
self.__class__.__name__)
return True
示例14: __init__
def __init__(self, path=None, new=False, autoload=True, autosave=False,
encoding="utf-8", return_unicode=PY3,
):
# set encoding
if not encoding:
warn("``encoding=None`` is deprecated as of Passlib 1.6, "
"and will cause a ValueError in Passlib 1.8, "
"use ``return_unicode=False`` instead.",
DeprecationWarning, stacklevel=2)
encoding = "utf-8"
return_unicode = False
elif not is_ascii_codec(encoding):
# htpasswd/htdigest files assumes 1-byte chars, and use ":" separator,
# so only ascii-compatible encodings are allowed.
raise ValueError("encoding must be 7-bit ascii compatible")
self.encoding = encoding
# set other attrs
self.return_unicode = return_unicode
self.autosave = autosave
self._path = path
self._mtime = 0
# init db
if not autoload:
warn("``autoload=False`` is deprecated as of Passlib 1.6, "
"and will be removed in Passlib 1.8, use ``new=True`` instead",
DeprecationWarning, stacklevel=2)
new = True
if path and not new:
self.load()
else:
self._records = OrderedDict()
示例15: form_for_instance
def form_for_instance(instance, form=BaseForm, fields=None,
formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
"""
Returns a Form class for the given Django model instance.
Provide ``form`` if you want to use a custom BaseForm subclass.
Provide ``formfield_callback`` if you want to define different logic for
determining the formfield for a given database field. It's a callable that
takes a database Field instance, plus **kwargs, and returns a form Field
instance with the given kwargs (i.e. 'initial').
"""
warn("form_for_instance is deprecated. Use ModelForm instead.",
PendingDeprecationWarning, stacklevel=3)
model = instance.__class__
opts = model._meta
field_list = []
for f in opts.fields + opts.many_to_many:
if not f.editable:
continue
if fields and not f.name in fields:
continue
current_value = f.value_from_object(instance)
formfield = formfield_callback(f, initial=current_value)
if formfield:
field_list.append((f.name, formfield))
base_fields = SortedDict(field_list)
return type(opts.object_name + 'InstanceForm', (form,),
{'base_fields': base_fields, '_model': model,
'save': make_instance_save(instance, fields, 'changed')})