Python warnings.warn() Examples

The following are 40 code examples for showing how to use warnings.warn(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module warnings , or try the search function .

Example 1
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 2
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 3
Project: cherrypy   Author: cherrypy   File: helper.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 4
Project: kaldi-python-io   Author: funcwj   File: inst.py    License: Apache License 2.0 6 votes vote down vote up
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 5
Project: neural-fingerprinting   Author: StephanZheng   File: loss.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 6
Project: neural-fingerprinting   Author: StephanZheng   File: loss.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 7
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: neural-fingerprinting   Author: StephanZheng   File: utils_keras.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: neural-fingerprinting   Author: StephanZheng   File: utils_tf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: neural-fingerprinting   Author: StephanZheng   File: utils_tf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: multibootusb   Author: mbusb   File: monitor.py    License: GNU General Public License v2.0 6 votes vote down vote up
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
Project: multibootusb   Author: mbusb   File: _device.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 13
Project: multibootusb   Author: mbusb   File: _device.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 14
Project: multibootusb   Author: mbusb   File: _device.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 15
Project: multibootusb   Author: mbusb   File: _device.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 16
Project: multibootusb   Author: mbusb   File: _device.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 17
Project: mlearn   Author: materialsvirtuallab   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 18
Project: mlearn   Author: materialsvirtuallab   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 19
Project: mlearn   Author: materialsvirtuallab   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 20
Project: mlearn   Author: materialsvirtuallab   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: neuropythy   Author: noahbenson   File: conf.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 22
Project: indras_net   Author: gcallah   File: registry.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __setitem__(self, key, value):
        if key not in self.agents or self.agents[key] is None:
            self.agents[key] = value
            if value is None:
                warnings.warn("Trying to set the value of key {} to None.".
                              format(key), RuntimeWarning)
        else:
            pass
            # this fails the tests at the moment, so we need to debug
            # it is the tests that have a problem!
            # raise KeyError("The key \"{}\" already exists in the registry"
            #                .format(key)) 
Example 23
Project: vergeml   Author: mme   File: __main__.py    License: MIT License 5 votes vote down vote up
def _configure_logging(level=logging.INFO):
    logging.addLevelName(logging.DEBUG, 'Debug:')
    logging.addLevelName(logging.INFO, 'Info:')
    logging.addLevelName(logging.WARNING, 'Warning!')
    logging.addLevelName(logging.CRITICAL, 'Critical!')
    logging.addLevelName(logging.ERROR, 'Error!')

    logging.basicConfig(format='%(levelname)s %(message)s', level=logging.INFO)

    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
        # TODO hack to get rid of deprecation warning that appeared allthough filters
        # are set to ignore. Is there a more sane way?
        warnings.warn = lambda *args, **kwargs: None 
Example 24
Project: aegea   Author: kislyuk   File: orgs.py    License: Apache License 2.0 5 votes vote down vote up
def add_member(self, login):
        """Add ``login`` to this team.

        :returns: bool
        """
        warnings.warn(
            'This is no longer supported by the GitHub API, see '
            'https://developer.github.com/changes/2014-09-23-one-more-week'
            '-before-the-add-team-member-api-breaking-change/',
            DeprecationWarning)
        url = self._build_url('members', login, base_url=self._api)
        return self._boolean(self._put(url), 204, 404) 
Example 25
Project: aegea   Author: kislyuk   File: orgs.py    License: Apache License 2.0 5 votes vote down vote up
def remove_member(self, login):
        """Remove ``login`` from this team.

        :param str login: (required), login of the member to remove
        :returns: bool
        """
        warnings.warn(
            'This is no longer supported by the GitHub API, see '
            'https://developer.github.com/changes/2014-09-23-one-more-week'
            '-before-the-add-team-member-api-breaking-change/',
            DeprecationWarning)
        url = self._build_url('members', login, base_url=self._api)
        return self._boolean(self._delete(url), 204, 404) 
Example 26
Project: aegea   Author: kislyuk   File: orgs.py    License: Apache License 2.0 5 votes vote down vote up
def add_member(self, login, team):
        """Add ``login`` to ``team`` and thereby to this organization.

        .. warning::
            This method is no longer valid. To add a member to a team, you
            must now retrieve the team directly, and use the ``invite``
            method.

        Any user that is to be added to an organization, must be added
        to a team as per the GitHub api.

        .. note::
            This method is of complexity O(n). This iterates over all teams in
            your organization and only adds the user when the team name
            matches the team parameter above. If you want constant time, you
            should retrieve the team and call ``add_member`` on that team
            directly.

        :param str login: (required), login name of the user to be added
        :param str team: (required), team name
        :returns: bool
        """
        warnings.warn(
            'This is no longer supported by the GitHub API, see '
            'https://developer.github.com/changes/2014-09-23-one-more-week'
            '-before-the-add-team-member-api-breaking-change/',
            DeprecationWarning)
        for t in self.iter_teams():
            if team == t.name:
                return t.add_member(login)
        return False 
Example 27
Project: aegea   Author: kislyuk   File: tempfile.py    License: Apache License 2.0 5 votes vote down vote up
def _cleanup(cls, name, warn_message):
        _rmtree(name)
        _warnings.warn(warn_message, _ResourceWarning) 
Example 28
Project: xrft   Author: xgcm   File: xrft.py    License: MIT License 5 votes vote down vote up
def isotropic_powerspectrum(*args, **kwargs): # pragma: no cover
    """
    Deprecated function. See isotropic_power_spectrum doc
    """
    import warnings
    msg = "This function has been renamed and will disappear in the future."\
          +" Please use isotropic_power_spectrum instead"
    warnings.warn(msg, Warning)
    return isotropic_power_spectrum(*args, **kwargs) 
Example 29
Project: xrft   Author: xgcm   File: xrft.py    License: MIT License 5 votes vote down vote up
def isotropic_crossspectrum(*args, **kwargs): # pragma: no cover
    """
    Deprecated function. See isotropic_cross_spectrum doc
    """
    import warnings
    msg = "This function has been renamed and will disappear in the future."\
          +" Please use isotropic_cross_spectrum instead"
    warnings.warn(msg, Warning)
    return isotropic_cross_spectrum(*args, **kwargs) 
Example 30
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 31
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_app_config_brackets(self):
        """Check for App config with extraneous brackets in section names."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                continue
            for key in app.config.keys():
                if key.startswith('[') or key.endswith(']'):
                    warnings.warn(
                        'The application mounted at %r has config '
                        'section names with extraneous brackets: %r. '
                        'Config *files* need brackets; config *dicts* '
                        '(e.g. passed to tree.mount) do not.' % (sn, key)) 
Example 32
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 33
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _known_ns(self, app):
        ns = ['wsgi']
        ns.extend(app.toolboxes)
        ns.extend(app.namespaces)
        ns.extend(app.request_class.namespaces)
        ns.extend(cherrypy.config.namespaces)
        ns += self.extra_config_namespaces

        for section, conf in app.config.items():
            is_path_section = section.startswith('/')
            if is_path_section and isinstance(conf, dict):
                for k in conf:
                    atoms = k.split('.')
                    if len(atoms) > 1:
                        if atoms[0] not in ns:
                            # Spit out a special warning if a known
                            # namespace is preceded by "cherrypy."
                            if atoms[0] == 'cherrypy' and atoms[1] in ns:
                                msg = (
                                    'The config entry %r is invalid; '
                                    'try %r instead.\nsection: [%s]'
                                    % (k, '.'.join(atoms[1:]), section))
                            else:
                                msg = (
                                    'The config entry %r is invalid, '
                                    'because the %r config namespace '
                                    'is unknown.\n'
                                    'section: [%s]' % (k, atoms[0], section))
                            warnings.warn(msg)
                        elif atoms[0] == 'tools':
                            if atoms[1] not in dir(cherrypy.tools):
                                msg = (
                                    'The config entry %r may be invalid, '
                                    'because the %r tool was not found.\n'
                                    'section: [%s]' % (k, atoms[1], section))
                                warnings.warn(msg) 
Example 34
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_config_namespaces(self):
        """Process config and warn on each unknown config namespace."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            self._known_ns(app)

    # -------------------------- Config Types -------------------------- # 
Example 35
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _known_types(self, config):
        msg = ('The config entry %r in section %r is of type %r, '
               'which does not match the expected type %r.')

        for section, conf in config.items():
            if not isinstance(conf, dict):
                conf = {section: conf}
            for k, v in conf.items():
                if v is not None:
                    expected_type = self.known_config_types.get(k, None)
                    vtype = type(v)
                    if expected_type and vtype != expected_type:
                        warnings.warn(msg % (k, section, vtype.__name__,
                                             expected_type.__name__)) 
Example 36
Project: cherrypy   Author: cherrypy   File: _cpchecker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_localhost(self):
        """Warn if any socket_host is 'localhost'. See #711."""
        for k, v in cherrypy.config.items():
            if k == 'server.socket_host' and v == 'localhost':
                warnings.warn("The use of 'localhost' as a socket host can "
                              'cause problems on newer systems, since '
                              "'localhost' can map to either an IPv4 or an "
                              "IPv6 address. You should use '127.0.0.1' "
                              "or '[::1]' instead.") 
Example 37
Project: cherrypy   Author: cherrypy   File: servers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _safe_wait(host, port):
    """
    On systems where a loopback interface is not available and the
    server is bound to all interfaces, it's difficult to determine
    whether the server is in fact occupying the port. In this case,
    just issue a warning and move on. See issue #1100.
    """
    try:
        yield
    except portend.Timeout:
        if host == portend.client_host(host):
            raise
        msg = 'Unable to verify that the server is bound on %r' % port
        warnings.warn(msg) 
Example 38
Project: cherrypy   Author: cherrypy   File: profiler.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 39
Project: cherrypy   Author: cherrypy   File: profiler.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve(path=None, port=8080):
    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)

    cherrypy.config.update({'server.socket_port': int(port),
                            'server.thread_pool': 10,
                            'environment': 'production',
                            })
    cherrypy.quickstart(Profiler(path)) 
Example 40
Project: FRIDA   Author: LCAV   File: doa.py    License: MIT License 5 votes vote down vote up
def _check_num_src(self, num_src):
        # # check validity of inputs
        # if num_src > self.M:
        #     warnings.warn('Number of sources cannot be more than number of \
        #         microphones. Changing number of sources to ' +
        #         str(self.M) + '.')
        #     num_src = self.M
        if num_src < 1:
            warnings.warn('Number of sources must be at least 1. Changing \
                number of sources to 1.')
            num_src = 1
        valid = num_src
        return valid