Python warnings.warn() Examples
The following are 30
code examples of warnings.warn().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
warnings
, or try the search function
.

Example #1
Source File: inst.py From kaldi-python-io with Apache License 2.0 | 9 votes |
def pipe_fopen(command, mode, background=True): if mode not in ["rb", "r"]: raise RuntimeError("Now only support input from pipe") p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) def background_command_waiter(command, p): p.wait() if p.returncode != 0: warnings.warn("Command \"{0}\" exited with status {1}".format( command, p.returncode)) _thread.interrupt_main() if background: thread = threading.Thread(target=background_command_waiter, args=(command, p)) # exits abnormally if main thread is terminated . thread.daemon = True thread.start() else: background_command_waiter(command, p) return p.stdout
Example #2
Source File: conf.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def rc(): ''' config.rc() yields the data imported from the Neuropythy rc file, if any. ''' if config._rc is None: # First: We check to see if we have been given a custom nptyhrc file: npythyrc_path = os.path.expanduser('~/.npythyrc') if 'NPYTHYRC' in os.environ: npythyrc_path = os.path.expanduser(os.path.expandvars(os.environ['NPYTHYRC'])) # the default config: if os.path.isfile(npythyrc_path): try: config._rc = loadrc(npythyrc_path) config._rc['npythyrc_loaded'] = True except Exception as err: warnings.warn('Could not load neuropythy RC file: %s' % npythyrc_path) config._rc = {'npythyrc_loaded':False, 'npythyrc_error': err} else: config._rc = {'npythyrc_loaded':False} config._rc['npythyrc'] = npythyrc_path return config._rc
Example #3
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_app_config_entries_dont_start_with_script_name(self): """Check for App config with sections that repeat script_name.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue if sn == '': continue sn_atoms = sn.strip('/').split('/') for key in app.config.keys(): key_atoms = key.strip('/').split('/') if key_atoms[:len(sn_atoms)] == sn_atoms: warnings.warn( 'The application mounted at %r has config ' 'entries that start with its script name: %r' % (sn, key))
Example #4
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_site_config_entries_in_app_config(self): """Check for mounted Applications that have site-scoped config.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue msg = [] for section, entries in app.config.items(): if section.startswith('/'): for key, value in entries.items(): for n in ('engine.', 'server.', 'tree.', 'checker.'): if key.startswith(n): msg.append('[%s] %s = %s' % (section, key, value)) if msg: msg.insert(0, 'The application mounted at %r contains the ' 'following config entries, which are only allowed ' 'in site-wide config. Move them to a [global] ' 'section and pass them to cherrypy.config.update() ' 'instead of tree.mount().' % sn) warnings.warn(os.linesep.join(msg))
Example #5
Source File: helper.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_app(self, app=None): """Obtain a new (decorated) WSGI app to hook into the origin server.""" if app is None: app = cherrypy.tree if self.validate: try: from wsgiref import validate except ImportError: warnings.warn( 'Error importing wsgiref. The validator will not run.') else: # wraps the app in the validator app = validate.validator(app) return app
Example #6
Source File: loss.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fprop(self, x, y, **kwargs): if self.attack is not None: x = x, self.attack(x) else: x = x, # Catching RuntimeError: Variable -= value not supported by tf.eager. try: y -= self.smoothing * (y - 1. / tf.cast(y.shape[-1], tf.float32)) except RuntimeError: y.assign_sub(self.smoothing * (y - 1. / tf.cast(y.shape[-1], tf.float32))) logits = [self.model.get_logits(x, **kwargs) for x in x] loss = sum( softmax_cross_entropy_with_logits(labels=y, logits=logit) for logit in logits) warnings.warn("LossCrossEntropy is deprecated, switch to " "CrossEntropy. LossCrossEntropy may be removed on " "or after 2019-03-06.") return loss
Example #7
Source File: utils.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def to_categorical(y, num_classes=None): """ Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to num_classes). :param num_classes: num_classes: total number of classes. :return: A binary matrix representation of the input. """ y = np.array(y, dtype='int').ravel() if not num_classes: num_classes = np.max(y) + 1 warnings.warn("FutureWarning: the default value of the second" "argument in function \"to_categorical\" is deprecated." "On 2018-9-19, the second argument" "will become mandatory.") n = y.shape[0] categorical = np.zeros((n, num_classes)) categorical[np.arange(n), y] = 1 return categorical
Example #8
Source File: utils_keras.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_logits_name(self): """ Looks for the name of the layer producing the logits. :return: name of layer producing the logits """ softmax_name = self._get_softmax_name() softmax_layer = self.model.get_layer(softmax_name) if not isinstance(softmax_layer, Activation): # In this case, the activation is part of another layer return softmax_name if hasattr(softmax_layer, 'inbound_nodes'): warnings.warn( "Please update your version to keras >= 2.1.3; " "support for earlier keras versions will be dropped on " "2018-07-22") node = softmax_layer.inbound_nodes[0] else: node = softmax_layer._inbound_nodes[0] logits_name = node.inbound_layers[0].name return logits_name
Example #9
Source File: utils_tf.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def model_loss(y, model, mean=True): """ Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return vector with per sample loss """ warnings.warn('This function is deprecated.') op = model.op if op.type == "Softmax": logits, = op.inputs else: logits = model out = softmax_cross_entropy_with_logits(logits=logits, labels=y) if mean: out = reduce_mean(out) return out
Example #10
Source File: utils_tf.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def infer_devices(devices=None): """ Returns the list of devices that multi-replica code should use. :param devices: list of string device names, e.g. ["/GPU:0"] If the user specifies this, `infer_devices` checks that it is valid, and then uses this user-specified list. If the user does not specify this, infer_devices uses: - All available GPUs, if there are any - CPU otherwise """ if devices is None: devices = get_available_gpus() if len(devices) == 0: warnings.warn("No GPUS, running on CPU") # Set device to empy string, tf will figure out whether to use # XLA or not, etc., automatically devices = [""] else: assert len(devices) > 0 for device in devices: assert isinstance(device, str), type(device) return devices
Example #11
Source File: monitor.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def enable_receiving(self): """ Switch the monitor into listing mode. Connect to the event source and receive incoming events. Only after calling this method, the monitor listens for incoming events. .. note:: This method is implicitly called by :meth:`__iter__`. You don't need to call it explicitly, if you are iterating over the monitor. .. deprecated:: 0.16 Will be removed in 1.0. Use :meth:`start()` instead. """ import warnings warnings.warn('Will be removed in 1.0. Use Monitor.start() instead.', DeprecationWarning) self.start()
Example #12
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def traverse(self): """ Traverse all parent devices of this device from bottom to top. Return an iterable yielding all parent devices as :class:`Device` objects, *not* including the current device. The last yielded :class:`Device` is the top of the device hierarchy. .. deprecated:: 0.16 Will be removed in 1.0. Use :attr:`ancestors` instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use Device.ancestors instead.', DeprecationWarning, stacklevel=2 ) return self.ancestors
Example #13
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def __iter__(self): """ Iterate over the names of all properties defined for this device. Return a generator yielding the names of all properties of this device as unicode strings. .. deprecated:: 0.21 Will be removed in 1.0. Access properties with Device.properties. """ import warnings warnings.warn( 'Will be removed in 1.0. Access properties with Device.properties.', DeprecationWarning, stacklevel=2 ) return self.properties.__iter__()
Example #14
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def __getitem__(self, prop): """ Get the given property from this device. ``prop`` is a unicode or byte string containing the name of the property. Return the property value as unicode string, or raise a :exc:`~exceptions.KeyError`, if the given property is not defined for this device. .. deprecated:: 0.21 Will be removed in 1.0. Access properties with Device.properties. """ import warnings warnings.warn( 'Will be removed in 1.0. Access properties with Device.properties.', DeprecationWarning, stacklevel=2 ) return self.properties.__getitem__(prop)
Example #15
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def asint(self, prop): """ Get the given property from this device as integer. ``prop`` is a unicode or byte string containing the name of the property. Return the property value as integer. Raise a :exc:`~exceptions.KeyError`, if the given property is not defined for this device, or a :exc:`~exceptions.ValueError`, if the property value cannot be converted to an integer. .. deprecated:: 0.21 Will be removed in 1.0. Use Device.properties.asint() instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use Device.properties.asint instead.', DeprecationWarning, stacklevel=2 ) return self.properties.asint(prop)
Example #16
Source File: models.py From mlearn with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fit(self, inputs, outputs, weights=None, override=False): """ Fit model. Args: inputs (list/Array): List/Array of input training objects. outputs (list/Array): List/Array of output values (supervisory signals). weights (list/Array): List/Array of weights. Default to None, i.e., unweighted. override (bool): Whether to calculate the feature vectors from given inputs. Default to False. Set to True if you want to retrain the model with a different set of training inputs. """ if self._xtrain is None or override: xtrain = self.describer.describe_all(inputs) else: warnings.warn("Feature vectors retrieved from cache " "and input training objects ignored. " "To override the old cache with feature vectors " "of new training objects, set override=True.") xtrain = self._xtrain self.model.fit(xtrain, outputs, weights) self._xtrain = xtrain
Example #17
Source File: models.py From mlearn with BSD 3-Clause "New" or "Revised" License | 6 votes |
def predict(self, inputs, override=False): """ Predict outputs with fitted model. Args: inputs (list/Array): List/Array of input testing objects. override (bool): Whether to calculate the feature vectors from given inputs. Default to False. Set to True if you want to test the model with a different set of testing inputs. Returns: Predicted output array from inputs. """ if self._xtest is None or override: xtest = self.describer.describe_all(inputs) else: warnings.warn("Feature vectors retrieved from cache " "and input testing objects ignored. " "To override the old cache with feature vectors " "of new testing objects, set override=True.") xtest = self._xtest self._xtest = xtest return self.model.predict(xtest)
Example #18
Source File: models.py From mlearn with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fit(self, inputs, outputs, override=False): """ Args: inputs (list): List of input training objects. outputs (list): List/Array of output values (supervisory signals). override: (bool) Whether to calculate the feature vectors from given inputs. Default to False. Set to True if you want to retrain the model with a different set of training inputs. """ if not self._xtrain or override: xtrain = self.describer.describe_all(inputs) else: warnings.warn("Feature vectors retrieved from cache " "and input training objects ignored. " "To override the old cache with feature vectors " "of new training objects, set override=True.") xtrain = self._xtrain self.model.fit(xtrain, outputs) self._xtrain = xtrain
Example #19
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def from_sys_path(cls, context, sys_path): #pragma: no cover """ .. versionchanged:: 0.4 Raise :exc:`NoSuchDeviceError` instead of returning ``None``, if no device was found for ``sys_path``. .. versionchanged:: 0.5 Raise :exc:`DeviceNotFoundAtPathError` instead of :exc:`NoSuchDeviceError`. .. deprecated:: 0.18 Use :class:`Devices.from_sys_path` instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use equivalent Devices method instead.', DeprecationWarning, stacklevel=2 ) return Devices.from_sys_path(context, sys_path)
Example #20
Source File: models.py From mlearn with BSD 3-Clause "New" or "Revised" License | 6 votes |
def predict(self, inputs, override=False, **kwargs): """ Args: inputs (List): List of input testing objects. override: (bool) Whether to calculate the feature vectors from given inputs. Default to False. Set to True if you want to test the model with a different set of testing inputs. kwargs: kwargs to be passed to predict method, e.g. return_std, return_cov. Returns: Predicted output array from inputs. """ if self._xtest is None or override: xtest = self.describer.describe_all(inputs) else: warnings.warn("Feature vectors retrieved from cache " "and input testing objects ignored. " "To override the old cache with feature vectors " "of new testing objects, set override=True.") xtest = self._xtest self._xtest = xtest return self.model.predict(xtest, **kwargs)
Example #21
Source File: loss.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fprop(self, x, y, **kwargs): x_adv = self.attack(x) d1 = self.model.fprop(x, **kwargs) d2 = self.model.fprop(x_adv, **kwargs) pairing_loss = [tf.reduce_mean(tf.square(a - b)) for a, b in zip(d1[Model.O_FEATURES], d2[Model.O_FEATURES])] pairing_loss = tf.reduce_mean(pairing_loss) loss = softmax_cross_entropy_with_logits( labels=y, logits=d1[Model.O_LOGITS]) loss += softmax_cross_entropy_with_logits( labels=y, logits=d2[Model.O_LOGITS]) warnings.warn("LossFeaturePairing is deprecated, switch to " "FeaturePairing. LossFeaturePairing may be removed " "on or after 2019-03-06.") return loss + self.weight * pairing_loss
Example #22
Source File: utils_tf.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 5 votes |
def batch_eval(*args, **kwargs): # Inside function to avoid circul import from cleverhans.evaluation import batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on or after " "2019-03-09.")
Example #23
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def check_compatibility(self): """Process config and warn on each obsolete or deprecated entry.""" self._compat(cherrypy.config) for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue self._compat(app.config) # ------------------------ Known Namespaces ------------------------ #
Example #24
Source File: profiler.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, nextapp, path=None, aggregate=False): """Make a WSGI middleware app which wraps 'nextapp' with profiling. nextapp the WSGI application to wrap, usually an instance of cherrypy.Application. path where to dump the profiling output. aggregate if True, profile data for all HTTP requests will go in a single file. If False (the default), each HTTP request will dump its profile data into a separate file. """ if profile is None or pstats is None: msg = ('Your installation of Python does not have a profile ' "module. If you're on Debian, try " '`sudo apt-get install python-profiler`. ' 'See http://www.cherrypy.org/wiki/ProfilingOnDebian ' 'for details.') warnings.warn(msg) self.nextapp = nextapp self.aggregate = aggregate if aggregate: self.profiler = ProfileAggregator(path) else: self.profiler = Profiler(path)
Example #25
Source File: monitor.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def __init__(self, monitor, event_handler=None, callback=None, *args, **kwargs): """ Create a new observer for the given ``monitor``. ``monitor`` is the :class:`Monitor` to observe. ``callback`` is the callable to invoke on events, with the signature ``callback(device)`` where ``device`` is the :class:`Device` that caused the event. .. warning:: ``callback`` is invoked in the observer thread, hence the observer is blocked while callback executes. ``args`` and ``kwargs`` are passed unchanged to the constructor of :class:`~threading.Thread`. .. deprecated:: 0.16 The ``event_handler`` argument will be removed in 1.0. Use the ``callback`` argument instead. .. versionchanged:: 0.16 Add ``callback`` argument. """ if callback is None and event_handler is None: raise ValueError('callback missing') elif callback is not None and event_handler is not None: raise ValueError('Use either callback or event handler') Thread.__init__(self, *args, **kwargs) self.monitor = monitor # observer threads should not keep the interpreter alive self.daemon = True self._stop_event = None if event_handler is not None: import warnings warnings.warn('"event_handler" argument will be removed in 1.0. ' 'Use Monitor.poll() instead.', DeprecationWarning) callback = lambda d: event_handler(d.action, d) self._callback = callback
Example #26
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def from_path(cls, context, path): #pragma: no cover """ .. versionadded:: 0.4 .. deprecated:: 0.18 Use :class:`Devices.from_path` instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use equivalent Devices method instead.', DeprecationWarning, stacklevel=2 ) return Devices.from_path(context, path)
Example #27
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def check_skipped_app_config(self): """Check for mounted Applications that have no config.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: msg = 'The Application mounted at %r has an empty config.' % sn if self.global_config_contained_paths: msg += (' It looks like the config you passed to ' 'cherrypy.config.update() contains application-' 'specific sections. You must explicitly pass ' 'application config via ' 'cherrypy.tree.mount(..., config=app_config)') warnings.warn(msg) return
Example #28
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def from_name(cls, context, subsystem, sys_name): #pragma: no cover """ .. versionadded:: 0.5 .. deprecated:: 0.18 Use :class:`Devices.from_name` instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use equivalent Devices method instead.', DeprecationWarning, stacklevel=2 ) return Devices.from_name(context, subsystem, sys_name)
Example #29
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def from_device_number(cls, context, typ, number): #pragma: no cover """ .. versionadded:: 0.11 .. deprecated:: 0.18 Use :class:`Devices.from_device_number` instead. """ import warnings warnings.warn( 'Will be removed in 1.0. Use equivalent Devices method instead.', DeprecationWarning, stacklevel=2 ) return Devices.from_device_number(context, typ, number)
Example #30
Source File: monitor.py From multibootusb with GNU General Public License v2.0 | 5 votes |
def __iter__(self): """ Wait for incoming events and receive them upon arrival. This methods implicitly calls :meth:`start()`, and starts polling the :meth:`fileno` of this monitor. If a event comes in, it receives the corresponding device and yields it to the caller. The returned iterator is endless, and continues receiving devices without ever stopping. Yields ``(action, device)`` (see :meth:`receive_device` for a description). .. deprecated:: 0.16 Will be removed in 1.0. Use an explicit loop over :meth:`poll()` instead, or monitor asynchronously with :class:`MonitorObserver`. """ import warnings warnings.warn('Will be removed in 1.0. Use an explicit loop over ' '"poll()" instead, or monitor asynchronously with ' '"MonitorObserver".', DeprecationWarning) self.start() while True: device = self.poll() if device is not None: yield device.action, device