當前位置: 首頁>>代碼示例>>Python>>正文


Python warnings.catch_warnings方法代碼示例

本文整理匯總了Python中warnings.catch_warnings方法的典型用法代碼示例。如果您正苦於以下問題:Python warnings.catch_warnings方法的具體用法?Python warnings.catch_warnings怎麽用?Python warnings.catch_warnings使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在warnings的用法示例。


在下文中一共展示了warnings.catch_warnings方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_global_norm_clip

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_global_norm_clip():
    stypes = ['default', 'row_sparse']
    def check_global_norm_clip(stype, check_isfinite):
        x1 = mx.nd.ones((3,3)).tostype(stype)
        x2 = mx.nd.ones((4,4)).tostype(stype)
        norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)
        assert norm == 5.0
        assert_almost_equal(x1.asnumpy(), np.ones((3,3))/5)
        assert_almost_equal(x2.asnumpy(), np.ones((4,4))/5)

        x3 = mx.nd.array([1.0, 2.0, float('nan')]).tostype(stype)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite)
            assert len(w) == check_isfinite

    for stype in stypes:
        for check_isfinite in [True, False]:
            check_global_norm_clip(stype, check_isfinite) 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:21,代碼來源:test_gluon.py

示例2: simple_moving_average

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def simple_moving_average(data, period):
    """
    Simple Moving Average.

    Formula:
    SUM(data / N)
    """
    check_for_period_error(data, period)
    # Mean of Empty Slice RuntimeWarning doesn't affect output so it is
    # supressed
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=RuntimeWarning)
        sma = list(map(
            lambda idx:
            np.mean(data[idx-(period-1):idx+1]),
            range(0, len(data))
            ))
    sma = fill_for_noncomputable_vals(data, sma)
    return sma 
開發者ID:kkuette,項目名稱:TradzQAI,代碼行數:21,代碼來源:simple_moving_average.py

示例3: test_connection_error

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_connection_error(self):
        """Check connection errors"""

        kwargs = {
            'user': 'nouser',
            'password': 'nopassword',
            'database': None,
            'host': self.kwargs['host'],
            'port': self.kwargs['port']
        }

        cmd = Init(**kwargs)
        code = cmd.run(self.name)
        self.assertEqual(code, CODE_DATABASE_ERROR)

        with warnings.catch_warnings(record=True):
            output = sys.stderr.getvalue().strip()
            self.assertRegexpMatches(output,
                                     DB_ACCESS_ERROR % {'user': 'nouser'}) 
開發者ID:chaoss,項目名稱:grimoirelab-sortinghat,代碼行數:21,代碼來源:test_cmd_init.py

示例4: testAssertWarnsCallable

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def testAssertWarnsCallable(self):
        def _runtime_warn():
            warnings.warn("foo", RuntimeWarning)
        # Success when the right warning is triggered, even several times
        self.assertWarns(RuntimeWarning, _runtime_warn)
        self.assertWarns(RuntimeWarning, _runtime_warn)
        # A tuple of warning classes is accepted
        self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn)
        # *args and **kwargs also work
        self.assertWarns(RuntimeWarning,
                         warnings.warn, "foo", category=RuntimeWarning)
        # Failure when no warning is triggered
        with self.assertRaises(self.failureException):
            self.assertWarns(RuntimeWarning, lambda: 0)
        # Failure when another warning is triggered
        with warnings.catch_warnings():
            # Force default filter (in case tests are run with -We)
            warnings.simplefilter("default", RuntimeWarning)
            with self.assertRaises(self.failureException):
                self.assertWarns(DeprecationWarning, _runtime_warn)
        # Filters for other warnings are not modified
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)
            with self.assertRaises(RuntimeWarning):
                self.assertWarns(DeprecationWarning, _runtime_warn) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:27,代碼來源:test_case.py

示例5: test_import_star

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_import_star(self):
        """'import *' in nested functions."""
        # NICE_TO_HAVE
        codes = [
            func_gen(
                'func1',
                body=func_gen('func2', body='from math import *\nTrue')),
            func_gen(
                'func1',
                body='from math import *\n' + func_gen('func2', body='True')),
        ]
        sys.setrecursionlimit(1000)  # needed for weird PyPy versions
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=SyntaxWarning)
            for code in codes:
                self.throws(code, IMPORTSTAR)
        sys.setrecursionlimit(initial_recursion_limit) 
開發者ID:SylvainDe,項目名稱:DidYouMean-Python,代碼行數:19,代碼來源:didyoumean_sugg_tests.py

示例6: test_run_async_exit_code

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_run_async_exit_code(self):

        def run_with_exit_code_0(process_idx):
            sys.exit(0)

        def run_with_exit_code_11(process_idx):
            os.kill(os.getpid(), signal.SIGSEGV)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_0)
            # There should be no AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 0)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_11)
            # There should be 4 AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 4) 
開發者ID:chainer,項目名稱:chainerrl,代碼行數:25,代碼來源:test_async.py

示例7: test_gram_wc_deprecated

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_gram_wc_deprecated(self):
        A = np.array([[1., -2.], [3., -4.]])
        B = np.array([[5., 6.], [7., 8.]])
        C = np.array([[4., 5.], [6., 7.]])
        D = np.array([[13., 14.], [15., 16.]])
        sys = ss(A, B, C, D)

        # Check that default type generates a warning
        # TODO: remove this check with matrix type is deprecated
        with warnings.catch_warnings(record=True) as w:
            use_numpy_matrix(True)
            self.assertTrue(issubclass(w[-1].category, UserWarning))
            
            Wc = gram(sys, 'c')
            self.assertTrue(isinstance(Wc, np.ndarray))
            use_numpy_matrix(False) 
開發者ID:python-control,項目名稱:python-control,代碼行數:18,代碼來源:statefbk_array_test.py

示例8: test_evalfr_deprecated

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_evalfr_deprecated(self):
        sys_tf = ct.tf([1], [1, 2, 1])
        frd_tf = FRD(sys_tf, np.logspace(-1, 1, 3))

        # Deprecated version of the call (should generate warning)
        import warnings
        with warnings.catch_warnings():
            # Make warnings generate an exception
            warnings.simplefilter('error')

            # Make sure that we get a pending deprecation warning
            self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.)

        # FRD.evalfr() is being deprecated
        import warnings
        with warnings.catch_warnings():
            # Make warnings generate an exception
            warnings.simplefilter('error')

            # Make sure that we get a pending deprecation warning
            self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.) 
開發者ID:python-control,項目名稱:python-control,代碼行數:23,代碼來源:frd_test.py

示例9: test_tutorial_notebook

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_tutorial_notebook():
    pytest.importorskip('nbformat')
    pytest.importorskip('nbconvert')
    pytest.importorskip('matplotlib')

    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor

    rootdir = os.path.join(aospy.__path__[0], 'examples')
    with open(os.path.join(rootdir, 'tutorial.ipynb')) as nb_file:
        notebook = nbformat.read(nb_file, as_version=nbformat.NO_CONVERT)
    kernel_name = 'python' + str(sys.version[0])
    ep = ExecutePreprocessor(kernel_name=kernel_name)
    with warnings.catch_warnings(record=True):
        ep.preprocess(notebook, {}) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:17,代碼來源:test_tutorial.py

示例10: test_load_variable_does_not_warn

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_load_variable_does_not_warn(load_variable_data_loader,
                                     start_date, end_date):
    with warnings.catch_warnings(record=True) as warnlog:
        load_variable_data_loader.load_variable(
            condensation_rain,
            start_date, end_date,
            intvl_in='monthly')
    assert len(warnlog) == 0 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:10,代碼來源:test_data_loader.py

示例11: create

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def create(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self._legend = self._axes.legend(fontsize='small')
        if self._legend is not None:
            self._legend.get_frame().set_alpha(0.75)
            self._legend.set_visible(self._visible) 
開發者ID:EarToEarOak,項目名稱:RF-Monitor,代碼行數:9,代碼來源:legend.py

示例12: get_translate

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def get_translate(workdir=None):

    filename = os.path.join(workdir, "Vicalloy/Fe-Co-V_140922a_META_DATA.csv")
    compdata_f = pd.read_csv(filename, sep="\t").dropna()
    print compdata_f.head()
    x = compdata_f["Xnom (mm)"].values
    y = compdata_f["Ynom (mm)"].values
    Co_concentration = compdata_f["Co (at%)"].values
    Fe_concentration = compdata_f["Fe (at%)"].values
    V_concentration = compdata_f["V (at%)"].values
    method = "linear"
    # method = 'nearest'

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        Co_concI = interp2d(x, y, Co_concentration, kind=method)
        Fe_concI = interp2d(x, y, Fe_concentration, kind=method)
        V_concI = interp2d(x, y, V_concentration, kind=method)

    def translate(key):
        manip_z, manip_y = key
        sample_y = manip_z - 69.5
        sample_x = (manip_y + 8) * 2
        Co = Co_concI(sample_x, sample_y)[0] / 100.0
        Fe = Fe_concI(sample_x, sample_y)[0] / 100.0
        V = V_concI(sample_x, sample_y)[0] / 100.0
        return ("Fe{:.2f}Co{:.2f}V{:.2f}".format(Fe, Co, V), sample_x, sample_y)

    return translate 
開發者ID:materialsproject,項目名稱:MPContribs,代碼行數:31,代碼來源:translate_vicalloy.py

示例13: test_translate_message_bad_translation

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_translate_message_bad_translation(self,
                                               mock_log,
                                               mock_translation):
        message_with_params = 'A message: %s'
        es_translation = 'A message in Spanish: %s %s'
        param = 'A Message param'

        translations = {message_with_params: es_translation}
        translator = fakes.FakeTranslations.translator({'es': translations})
        mock_translation.side_effect = translator

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            msg = _message.Message(message_with_params)
            msg = msg % param
            default_translation = message_with_params % param

            self.assertEqual(default_translation, msg.translation('es'))

            self.assertEqual(1, len(w))
            # Note(gibi): in python 3.4 str.__repr__ does not put the unicode
            # marker 'u' in front of the string representations so the test
            # removes that to have the same result in python 2.7 and 3.4
            self.assertEqual("Failed to insert replacement values into "
                             "translated message A message in Spanish: %s %s "
                             "(Original: 'A message: %s'): "
                             "not enough arguments for format string",
                             str(w[0].message).replace("u'", "'"))

        mock_log.debug.assert_called_with(('Failed to insert replacement '
                                           'values into translated message '
                                           '%s (Original: %r): %s'),
                                          es_translation,
                                          message_with_params,
                                          mock.ANY) 
開發者ID:openstack,項目名稱:oslo.i18n,代碼行數:37,代碼來源:test_message.py

示例14: test_translate_message_bad_default_translation

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def test_translate_message_bad_default_translation(self,
                                                       mock_log,
                                                       mock_local,
                                                       mock_translation):
        message_with_params = 'A message: %s'
        es_translation = 'A message in Spanish: %s %s'
        param = 'A Message param'

        translations = {message_with_params: es_translation}
        translator = fakes.FakeTranslations.translator({'es': translations})
        mock_translation.side_effect = translator

        msg = _message.Message(message_with_params)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            msg = msg % param
            self.assertEqual(1, len(w))
            # Note(gibi): in python 3.4 str.__repr__ does not put the unicode
            # marker 'u' in front of the string representations so the test
            # removes that to have the same result in python 2.7 and 3.4
            self.assertEqual("Failed to insert replacement values into "
                             "translated message A message in Spanish: %s %s "
                             "(Original: 'A message: %s'): "
                             "not enough arguments for format string",
                             str(w[0].message).replace("u'", "'"))

        mock_log.debug.assert_called_with(('Failed to insert replacement '
                                           'values into translated message '
                                           '%s (Original: %r): %s'),
                                          es_translation,
                                          message_with_params,
                                          mock.ANY)
        mock_log.reset_mock()

        default_translation = message_with_params % param
        self.assertEqual(default_translation, msg)
        self.assertFalse(mock_log.warning.called) 
開發者ID:openstack,項目名稱:oslo.i18n,代碼行數:40,代碼來源:test_message.py

示例15: plot_graph

# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import catch_warnings [as 別名]
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")

            g = nx.from_numpy_matrix(am)

            if position is None:
                position=nx.drawing.circular_layout(g)

            fig = plt.figure()

            if cls is None:
                cls='r'
            else:
                # Make a user-defined colormap.
                cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])

                # Make a normalizer that will map the time values from
                # [start_time,end_time+1] -> [0,1].
                cnorm = mcol.Normalize(vmin=0, vmax=1)

                # Turn these into an object that can be used to map time values to colors and
                # can be passed to plt.colorbar().
                cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
                cpick.set_array([])
                cls = cpick.to_rgba(cls)
                plt.colorbar(cpick, ax=fig.add_subplot(111))


            nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))

            fig.savefig(os.path.join(self.plotdir, fig_name)) 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:35,代碼來源:Plotter.py


注:本文中的warnings.catch_warnings方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。