• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python warnings.resetwarnings函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中warnings.resetwarnings函数的典型用法代码示例。如果您正苦于以下问题:Python resetwarnings函数的具体用法?Python resetwarnings怎么用?Python resetwarnings使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了resetwarnings函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: validate

def validate(file_or_object):
    """
    Validate a given SEIS-PROV file.

    :param file_or_object: The filename or file-like object to validate.
    """
    errors = []
    warns = []

    with warnings.catch_warnings(record=True) as w:
        warnings.resetwarnings()
        warnings.simplefilter("always")

        try:
            _validate(file_or_object)
        except SeisProvValidationException as e:
            errors.append(e.message)

    for warn in w:
        warn = warn.message
        if not isinstance(warn, SeisProvValidationWarning):
            continue
        warns.append(warn.args[0])

    return SeisProvValidationResult(errors=errors,
                                    warnings=warns)
开发者ID:gitter-badger,项目名称:SEIS-PROV,代码行数:26,代码来源:validator.py


示例2: setUp

 def setUp(self):
     warnings.resetwarnings()
     self.tmpfp = NamedTemporaryFile(prefix='mmap')
     self.shape = (3,4)
     self.dtype = 'float32'
     self.data = arange(12, dtype=self.dtype)
     self.data.resize(self.shape)
开发者ID:258073127,项目名称:MissionPlanner,代码行数:7,代码来源:test_memmap.py


示例3: alert

    def alert(self, matches):
        body = self.create_alert_body(matches)

        # HipChat sends 400 bad request on messages longer than 10000 characters
        if (len(body) > 9999):
            body = body[:9980] + '..(truncated)'

        # Use appropriate line ending for text/html
        if self.hipchat_message_format == 'html':
            body = body.replace('\n', '<br />')

        # Post to HipChat
        headers = {'content-type': 'application/json'}
        # set https proxy, if it was provided
        proxies = {'https': self.hipchat_proxy} if self.hipchat_proxy else None
        payload = {
            'color': self.hipchat_msg_color,
            'message': body,
            'message_format': self.hipchat_message_format,
            'notify': self.hipchat_notify,
            'from': self.hipchat_from
        }

        try:
            if self.hipchat_ignore_ssl_errors:
                requests.packages.urllib3.disable_warnings()
            response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers,
                                     verify=not self.hipchat_ignore_ssl_errors,
                                     proxies=proxies)
            warnings.resetwarnings()
            response.raise_for_status()
        except RequestException as e:
            raise EAException("Error posting to HipChat: %s" % e)
        elastalert_logger.info("Alert sent to HipChat room %s" % self.hipchat_room_id)
开发者ID:kenshin17,项目名称:elastalert,代码行数:34,代码来源:alerts.py


示例4: test_misspecifications

def test_misspecifications():
    # Tests for model specification and misspecification exceptions
    endog = np.arange(20).reshape(10,2)

    # Bad trend specification
    assert_raises(ValueError, varmax.VARMAX, endog, order=(1,0), trend='')

    # Bad error_cov_type specification
    assert_raises(ValueError, varmax.VARMAX, endog, order=(1,0), error_cov_type='')

    # Bad order specification
    assert_raises(ValueError, varmax.VARMAX, endog, order=(0,0))

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        varmax.VARMAX(endog, order=(1,1))

    # Warning with VARMA specification
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')

        varmax.VARMAX(endog, order=(1,1))

        message = ('Estimation of VARMA(p,q) models is not generically robust,'
                   ' due especially to identification issues.')
        assert_equal(str(w[0].message), message)
    warnings.resetwarnings()
开发者ID:Bonfils-ebu,项目名称:statsmodels,代码行数:27,代码来源:test_varmax.py


示例5: open_data

def open_data(gdfilename, tracknames, verbose=False):
    warnings.simplefilter("ignore")
    with Genome(gdfilename, "r+") as genome:
        for trackname in tracknames:
            genome.add_track_continuous(trackname)

    warnings.resetwarnings()
开发者ID:weallen,项目名称:Seqwill,代码行数:7,代码来源:_open_data.py


示例6: main

def main():
    infilename = ''
    outfilename = ''

    #Get the command-line arguments
    args = sys.argv[1:]
    
    if len(args) < 4:
        usage()
        sys.exit(1)
        
    for i in range(0,len(args)):
        if args[i] == '-i':
            infilename = args[i+1]
        elif args[i] == '-o':
            outfilename = args[i+1]
    if os.path.isfile(infilename): 
        try:
            # Perform the translation using the methods from the OpenIOC to CybOX Script
            openioc_indicators = openioc.parse(infilename)
            observables_obj = openioc_to_cybox.generate_cybox(openioc_indicators, infilename, True)
            observables_cls = Observables.from_obj(observables_obj)

            # Set the namespace to be used in the STIX Package
            stix.utils.set_id_namespace({"https://github.com/STIXProject/openioc-to-stix":"openiocToSTIX"})

            # Wrap the created Observables in a STIX Package/Indicator
            stix_package = STIXPackage()
            # Add the OpenIOC namespace
            input_namespaces = {"http://openioc.org/":"openioc"}
            stix_package.__input_namespaces__ = input_namespaces

            for observable in observables_cls.observables:
                indicator_dict = {}
                producer_dict = {}
                producer_dict['tools'] = [{'name':'OpenIOC to STIX Utility', 'version':str(__VERSION__)}]
                indicator_dict['producer'] = producer_dict
                indicator_dict['title'] = "CybOX-represented Indicator Created from OpenIOC File"
                indicator = Indicator.from_dict(indicator_dict)
                indicator.add_observable(observables_cls.observables[0])
                stix_package.add_indicator(indicator)

            # Create and write the STIX Header
            stix_header = STIXHeader()
            stix_header.package_intent = "Indicators - Malware Artifacts"
            stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File"
            stix_package.stix_header = stix_header

            # Write the generated STIX Package as XML to the output file
            outfile = open(outfilename, 'w')
            # Ignore any warnings - temporary fix for no schemaLocation w/ namespace
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                outfile.write(stix_package.to_xml())
                warnings.resetwarnings()
            outfile.flush()
            outfile.close()
        except Exception, err:
            print('\nError: %s\n' % str(err))
            traceback.print_exc()
开发者ID:jhemp,项目名称:openioc-to-stix,代码行数:60,代码来源:openioc_to_stix.py


示例7: test_called_twice_from_class

 def test_called_twice_from_class(self):
     import warnings
     from guillotina.component._declaration import adapts
     from zope.interface import Interface
     from zope.interface._compat import PYTHON3
     class IFoo(Interface):
         pass
     class IBar(Interface):
         pass
     globs = {'adapts': adapts, 'IFoo': IFoo, 'IBar': IBar}
     locs = {}
     CODE = "\n".join([
         'class Foo(object):',
         '    adapts(IFoo)',
         '    adapts(IBar)',
         ])
     with warnings.catch_warnings(record=True) as log:
         warnings.resetwarnings()
         try:
             exec(CODE, globs, locs)
         except TypeError:
             if not PYTHON3:
                 self.assertEqual(len(log), 0) # no longer warn
         else:
             self.fail("Didn't raise TypeError")
开发者ID:nazrulworld,项目名称:guillotina,代码行数:25,代码来源:test__declaration.py


示例8: test_errcheck

 def test_errcheck(self):
     py.test.skip('fixme')
     def errcheck(result, func, args):
         assert result == -42
         assert type(result) is int
         arg, = args
         assert arg == -126
         assert type(arg) is int
         return result
     #
     tf_b = dll.tf_b
     tf_b.restype = c_byte
     tf_b.argtypes = (c_byte,)
     tf_b.errcheck = errcheck
     assert tf_b(-126) == -42
     del tf_b.errcheck
     with warnings.catch_warnings(record=True) as w:
         dll.get_an_integer.argtypes = []
         dll.get_an_integer()
         assert len(w) == 1
         assert issubclass(w[0].category, RuntimeWarning)
         assert "C function without declared return type called" in str(w[0].message)
         
     with warnings.catch_warnings(record=True) as w:
         dll.get_an_integer.restype = None
         dll.get_an_integer()
         assert len(w) == 0
         
     warnings.resetwarnings()
开发者ID:ParitoshThapliyal59,项目名称:pypy,代码行数:29,代码来源:test_functions.py


示例9: set_fcntl_constants

    def set_fcntl_constants(self):
        if fcntl is None: return 0
        self.F_GETFL = fcntl.F_GETFL
        self.F_SETFL = fcntl.F_SETFL
        self.F_GETFD = fcntl.F_GETFD
        self.F_SETFD = fcntl.F_SETFD
        ok = 0
        if fcntl.__dict__.has_key("FD_CLOEXEC"):
            self.FD_CLOEXEC = fcntl.FD_CLOEXEC
            ok = 1
        if ok == 0:
            try:
                FCNTL_ok = 0
                import warnings
                warnings.filterwarnings("ignore", "", DeprecationWarning)
                import FCNTL
                FCNTL_ok = 1
                warnings.resetwarnings()
            except ImportError:
                pass
            if FCNTL_ok and FCNTL.__dict__.has_key("FD_CLOEXEC"):
                self.FD_CLOEXEC = FCNTL.FD_CLOEXEC
                ok = 1
        if ok == 0:
            # assume FD_CLOEXEC = 1. see 
            # http://mail.python.org/pipermail/python-bugs-list/2001-December/009360.html
            self.FD_CLOEXEC = 1
            ok = 1

        if ok == 0:
            Es("This platform provides no ways to set "
               "close-on-exec flag. abort\n")
            os._exit(1)
开发者ID:PayasR,项目名称:paralite,代码行数:33,代码来源:portability.py


示例10: bestFit

def bestFit(indices, trace):
    """
    Function extrapolating noise from trace containing sequence
    
    :type indices: numpy.array
    :param indices: indices of noise, as retrurned by extractNoise
    :type trace: trace object from obspy.core
    :param trace: trace whose noise has to be fitted
    :returns: array of extrapolated noise
    
    """
    deg=1
    warnings.filterwarnings('error')
    #Initiate loop to choose best degree of polynomial extrapolation
    #Increment degree whille error occurs
    while True:
        try:
            best_fit = np.poly1d(np.polyfit(indices, trace.data[indices], deg))
            deg+=1
        except:
            break;
    warnings.resetwarnings()

    #Make extrapolation at optimal degree
    x=range(0, trace.stats.npts)
    fit=best_fit(x)

    return fit
开发者ID:eost,项目名称:pyCTEW1,代码行数:28,代码来源:_util.py


示例11: write

 def write(self, data):
     # get all warnings
     warnFilters = list(warnings.filters)
     # reset warnings
     warnings.resetwarnings()
     # ignore all warnings
     # we dont want warnings while pusing text to the textview
     warnings.filterwarnings("ignore")
     if PY2 and isinstance(data, str):
         try:
             data = unicode(data, "utf-8", "replace")
         except UnicodeDecodeError:
             data = "XXX " + repr(data)
     if self.outputView is not None:
         # Better not get SIGINT/KeyboardInterrupt exceptions while we're updating the output view
         with cancelLock:
             self.outputView.append(data, self.isError)
             t = time.time()
             if t - self._previousFlush > 0.2:
                 self.outputView.scrollToEnd()
                 if osVersionCurrent >= osVersion10_10:
                     AppKit.NSRunLoop.mainRunLoop().runUntilDate_(AppKit.NSDate.dateWithTimeIntervalSinceNow_(0.0001))
                 self._previousFlush = t
     else:
         self.data.append((data, self.isError))
     # reset the new warnings
     warnings.resetwarnings()
     # update with the old warnings filters
     warnings.filters.extend(warnFilters)
开发者ID:typemytype,项目名称:drawBotRoboFontExtension,代码行数:29,代码来源:scriptTools.py


示例12: deprecation

def deprecation(trac_number, message):
    r"""
    Issue a deprecation warning.

    INPUT:

    - ``trac_number`` -- integer. The trac ticket number where the
      deprecation is introduced.

    - ``message`` -- string. an explanation why things are deprecated
      and by what it should be replaced.

    EXAMPLES::

        sage: def foo():
        ....:  sage.misc.superseded.deprecation(13109, 'the function foo is replaced by bar')
        sage: foo()
        doctest:...: DeprecationWarning: the function foo is replaced by bar
        See http://trac.sagemath.org/13109 for details.
    """
    _check_trac_number(trac_number)
    message += '\n'
    message += 'See http://trac.sagemath.org/'+ str(trac_number) + ' for details.'
    resetwarnings()
    # Stack level 3 to get the line number of the code which called
    # the deprecated function which called this function.
    warn(message, DeprecationWarning, stacklevel=3)
开发者ID:chiragsinghal283,项目名称:sage,代码行数:27,代码来源:superseded.py


示例13: _run_generated_code

 def _run_generated_code(self, code, globs, locs):
     import warnings
     with warnings.catch_warnings(record=True) as log:
         warnings.resetwarnings()
         exec(code, globs, locs)
         self.assertEqual(len(log), 0) # no longer warn
         return True
开发者ID:zopefoundation,项目名称:zope.component,代码行数:7,代码来源:test__declaration.py


示例14: runTreewalkerTest

def runTreewalkerTest(innerHTML, input, expected, errors, treeClass):
    warnings.resetwarnings()
    warnings.simplefilter("error")
    try:
        p = html5parser.HTMLParser(tree = treeClass["builder"])
        if innerHTML:
            document = p.parseFragment(input, innerHTML)
        else:
            document = p.parse(input)
    except constants.DataLossWarning:
        #Ignore testcases we know we don't pass
        return

    document = treeClass.get("adapter", lambda x: x)(document)
    try:
        output = convertTokens(treeClass["walker"](document))
        output = attrlist.sub(sortattrs, output)
        expected = attrlist.sub(sortattrs, convertExpected(expected))
        diff = "".join(unified_diff([line + "\n" for line in expected.splitlines()],
                                    [line + "\n" for line in output.splitlines()],
                                    "Expected", "Received"))
        assert expected == output, "\n".join([
                "", "Input:", input,
                "", "Expected:", expected,
                "", "Received:", output,
                "", "Diff:", diff,
                ])
    except NotImplementedError:
        pass # Amnesty for those that confess...
开发者ID:mfa,项目名称:html5lib-python,代码行数:29,代码来源:test_treewalkers.py


示例15: install_config

    def install_config(self, node):
        if not self.ns.WaitForNodeToComeUp(node):
            self.log("Node %s is not up." % node)
            return None

        if not self.CIBsync.has_key(node) and self.Env["ClobberCIB"] == 1:
            self.CIBsync[node] = 1
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.sig")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.last")
            self.rsh.remote_py(node, "os", "system", "rm -f /var/lib/heartbeat/crm/cib.xml.sig.last")

            # Only install the CIB on the first node, all the other ones will pick it up from there
            if self.cib_installed == 1:
                return None

            self.cib_installed = 1
            if self.Env["CIBfilename"] == None:
                self.debug("Installing Generated CIB on node %s" %(node))
                warnings.filterwarnings("ignore")
                cib_file=os.tmpnam()
                warnings.resetwarnings()
                os.system("rm -f "+cib_file)
                self.debug("Creating new CIB for " + node + " in: " + cib_file)
                os.system("echo \'" + self.default_cts_cib + "\' > " + cib_file)
                if 0!=self.rsh.echo_cp(None, cib_file, node, "/var/lib/heartbeat/crm/cib.xml"):
                    raise ValueError("Can not create CIB on %s "%node)

                os.system("rm -f "+cib_file)
            else:
                self.debug("Installing CIB (%s) on node %s" %(self.Env["CIBfilename"], node))
                if 0!=self.rsh.cp(self.Env["CIBfilename"], "[email protected]" + (self["CIBfile"]%node)):
                    raise ValueError("Can not scp file to %s "%node)
        
            self.rsh.remote_py(node, "os", "system", "chown hacluster /var/lib/heartbeat/crm/cib.xml")
开发者ID:sipwise,项目名称:heartbeat,代码行数:35,代码来源:CM_LinuxHAv2.py


示例16: test_removed_deprecated_runas

    def test_removed_deprecated_runas(self):
        # We *always* want *all* warnings thrown on this module
        warnings.resetwarnings()
        warnings.filterwarnings('always', '', DeprecationWarning, __name__)

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        pip_list = MagicMock(return_value=['pep8'])
        pip_uninstall = MagicMock(return_value=True)
        with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                             'pip.list': pip_list,
                                             'pip.uninstall': pip_uninstall}):
            with warnings.catch_warnings(record=True) as w:
                ret = pip_state.removed('pep8', runas='me!')
                self.assertEqual(
                    'The \'runas\' argument to pip.installed is deprecated, '
                    'and will be removed in Salt Hydrogen (Unreleased). '
                    'Please use \'user\' instead.', str(w[-1].message)
                )
                self.assertSaltTrueReturn({'testsuite': ret})
                # Is the state returning a warnings key with the deprecation
                # message?
                self.assertInSalStatetWarning(
                    'The \'runas\' argument to pip.installed is deprecated, '
                    'and will be removed in Salt Hydrogen (Unreleased). '
                    'Please use \'user\' instead.', {'testsuite': ret}
                )
开发者ID:bemehow,项目名称:salt,代码行数:26,代码来源:pip_test.py


示例17: Configuration

    def Configuration(self):
        if self.config:
            return self.config.getElementsByTagName('configuration')[0]

        warnings.filterwarnings("ignore")
        cib_file=os.tmpnam()
        warnings.resetwarnings()
        
        os.system("rm -f "+cib_file)

        if self.Env["ClobberCIB"] == 1:
            if self.Env["CIBfilename"] == None:
                self.debug("Creating new CIB in: " + cib_file)
                os.system("echo \'"+ self.default_cts_cib +"\' > "+ cib_file)
            else:
                os.system("cp "+self.Env["CIBfilename"]+" "+cib_file)
        else:            
            if 0 != self.rsh.echo_cp(
                self.Env["nodes"][0], "/var/lib/heartbeat/crm/cib.xml", None, cib_file):
                raise ValueError("Can not copy file to %s, maybe permission denied"%cib_file)

        self.config = parse(cib_file)
        os.remove(cib_file)

        return self.config.getElementsByTagName('configuration')[0]
开发者ID:sipwise,项目名称:heartbeat,代码行数:25,代码来源:CM_LinuxHAv2.py


示例18: _create_trigger

    def _create_trigger(self, field):
        # import MySQLdb as Database
        from warnings import filterwarnings, resetwarnings

        filterwarnings('ignore', message='Trigger does not exist',
                       category=Warning)

        opts = field.model._meta
        trigger_name = get_trigger_name(field, opts)

        stm = self.sql.format(trigger_name=trigger_name,
                              opts=opts, field=field)
        cursor = self.connection._clone().cursor()
        try:
            cursor.execute(stm)
            self._triggers[field] = trigger_name

        except (BaseException, _mysql_exceptions.ProgrammingError) as exc:
            errno, message = exc.args
            if errno != 2014:
                import traceback
                traceback.print_exc(exc)
                raise
        resetwarnings()
        return trigger_name
开发者ID:domdinicola,项目名称:django-concurrency,代码行数:25,代码来源:creation.py


示例19: expect_deprecations

 def expect_deprecations(self):
     """Call this if the test expects to call deprecated function."""
     warnings.resetwarnings()
     warnings.filterwarnings('ignore', category=DeprecationWarning,
                             module='^keystoneclient\\.')
     warnings.filterwarnings('ignore', category=DeprecationWarning,
                             module='^debtcollector\\.')
开发者ID:npustchi,项目名称:python-keystoneclient,代码行数:7,代码来源:client_fixtures.py


示例20: clean_warning_registry

def clean_warning_registry():
    """Safe way to reset warniings """
    warnings.resetwarnings()
    reg = "__warningregistry__"
    for mod in sys.modules.values():
        if hasattr(mod, reg):
            getattr(mod, reg).clear()
开发者ID:hwwh1999,项目名称:scikit-learn,代码行数:7,代码来源:testing.py



注:本文中的warnings.resetwarnings函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python warnings.showwarning函数代码示例发布时间:2022-05-26
下一篇:
Python warnings.formatwarning函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap