Python warnings.simplefilter() Examples

The following are code examples for showing how to use warnings.simplefilter(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_issue_8594(self):
        # XXX - this test is supposed to be removed in next major Python
        # version
        d = asyncore.dispatcher(socket.socket())
        # make sure the error message no longer refers to the socket
        # object but the dispatcher instance instead
        self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
                                getattr, d, 'foo')
        # cheap inheritance with the underlying socket is supposed
        # to still work but a DeprecationWarning is expected
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            family = d.family
            self.assertEqual(family, socket.AF_INET)
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning)) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_hmac.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_legacy_block_size_warnings(self):
        class MockCrazyHash(object):
            """Ain't no block_size attribute here."""
            def __init__(self, *args):
                self._x = hashlib.sha1(*args)
                self.digest_size = self._x.digest_size
            def update(self, v):
                self._x.update(v)
            def digest(self):
                return self._x.digest()

        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            with self.assertRaises(RuntimeWarning):
                hmac.HMAC('a', 'b', digestmod=MockCrazyHash)
                self.fail('Expected warning about missing block_size')

            MockCrazyHash.block_size = 1
            with self.assertRaises(RuntimeWarning):
                hmac.HMAC('a', 'b', digestmod=MockCrazyHash)
                self.fail('Expected warning about small block_size') 
Example 3
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def catch_warnings():
    """Catch warnings in a with block in a list"""
    # make sure deprecation warnings are active in tests
    warnings.simplefilter('default', category=DeprecationWarning)

    filters = warnings.filters
    warnings.filters = filters[:]
    old_showwarning = warnings.showwarning
    log = []
    def showwarning(message, category, filename, lineno, file=None, line=None):
        log.append(locals())
    try:
        warnings.showwarning = showwarning
        yield log
    finally:
        warnings.filters = filters
        warnings.showwarning = old_showwarning 
Example 4
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def catch_warnings():
    """Catch warnings in a with block in a list"""
    # make sure deprecation warnings are active in tests
    warnings.simplefilter('default', category=DeprecationWarning)

    filters = warnings.filters
    warnings.filters = filters[:]
    old_showwarning = warnings.showwarning
    log = []
    def showwarning(message, category, filename, lineno, file=None, line=None):
        log.append(locals())
    try:
        warnings.showwarning = showwarning
        yield log
    finally:
        warnings.filters = filters
        warnings.showwarning = old_showwarning 
Example 5
Project: DataComp   Author: Cojabi   File: test_stats.py    Apache License 2.0 6 votes vote down vote up
def test_test_cat_feats(self):
        # test if warnings are risen due to few data points
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            # Trigger a warning.
            p_vals = cat_test(self.zipper, feat_subset=self.datacol.categorical_feats)

            warns = sorted([str(m.message) for m in w])
            self.assertEqual(len(w), 4) # 4 because one warining will be a divide by zero assertion error
            self.assertTrue("cat1" in warns[0])

        # check categorical table creation
        test_data = _categorical_table(["A", "A", "C", "A", "A"])
        self.assertTrue((test_data == [4, 1]).all())

        # check categorical p-value
        cat1_p_val = chisquare([1, 3, 1],[2, 1, 3])
        self.assertEqual(p_vals["cat3"][(1, 2)], cat1_p_val.pvalue) 
Example 6
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 6 votes vote down vote up
def catch_warnings():
    """Catch warnings in a with block in a list"""
    # make sure deprecation warnings are active in tests
    warnings.simplefilter('default', category=DeprecationWarning)

    filters = warnings.filters
    warnings.filters = filters[:]
    old_showwarning = warnings.showwarning
    log = []
    def showwarning(message, category, filename, lineno, file=None, line=None):
        log.append(locals())
    try:
        warnings.showwarning = showwarning
        yield log
    finally:
        warnings.filters = filters
        warnings.showwarning = old_showwarning 
Example 7
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    Apache License 2.0 6 votes vote down vote up
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) 
Example 8
Project: sic   Author: Yanixos   File: imp.py    GNU General Public License v3.0 6 votes vote down vote up
def cache_from_source(path, debug_override=None):
    """**DEPRECATED**

    Given the path to a .py file, return the path to its .pyc file.

    The .py file does not need to exist; this simply returns the path to the
    .pyc file calculated as if the .py file were imported.

    If debug_override is not None, then it must be a boolean and is used in
    place of sys.flags.optimize.

    If sys.implementation.cache_tag is None then NotImplementedError is raised.

    """
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        return util.cache_from_source(path, debug_override) 
Example 9
Project: bigquerylayers   Author: smandaric   File: descriptor_database_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testConflictRegister(self):
    db = descriptor_database.DescriptorDatabase()
    unittest_fd = descriptor_pb2.FileDescriptorProto.FromString(
        unittest_pb2.DESCRIPTOR.serialized_pb)
    db.Add(unittest_fd)
    conflict_fd = descriptor_pb2.FileDescriptorProto.FromString(
        unittest_pb2.DESCRIPTOR.serialized_pb)
    conflict_fd.name = 'other_file2'
    with warnings.catch_warnings(record=True) as w:
      # Cause all warnings to always be triggered.
      warnings.simplefilter('always')
      db.Add(conflict_fd)
      self.assertTrue(len(w))
      self.assertIs(w[0].category, RuntimeWarning)
      self.assertIn('Conflict register for file "other_file2": ',
                    str(w[0].message))
      self.assertIn('already defined in file '
                    '"google/protobuf/unittest.proto"',
                    str(w[0].message)) 
Example 10
Project: TradzQAI   Author: kkuette   File: simple_moving_average.py    Apache License 2.0 6 votes vote down vote up
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 
Example 11
Project: FakeReviewGenerator   Author: amitabhnag   File: test_translate.py    MIT License 6 votes vote down vote up
def ignore_warnings(test_func):
    """Turn off ResourceWarnings from Python during for unit tests.

    Args:
        test_func: test function

    Returns:
        do_test module

    Code from https://stackoverflow.com/questions/26563711/disabling-python-3-2-resourcewarning.
    """
    def do_test(self, *args, **kwargs):
        """Turn off any ResourceWarnings for test_func.
        """
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ResourceWarning)
            test_func(self, *args, **kwargs)
    return do_test 
Example 12
Project: FakeReviewGenerator   Author: amitabhnag   File: test_train.py    MIT License 6 votes vote down vote up
def ignore_warnings(test_func):
    """Turn off ResourceWarnings and DeprecationWarning from Python during for unit tests.

    Args:
        test_func: test function

    Returns:
        do_test module

    Code from https://stackoverflow.com/questions/26563711/disabling-python-3-2-resourcewarning.
    """
    def do_test(self, *args, **kwargs):
        """Turn off any ResourceWarnings for test_func.
        """
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            warnings.simplefilter("ignore", ResourceWarning)
            test_func(self, *args, **kwargs)
    return do_test 
Example 13
Project: calmjs   Author: calmjs   File: test_testing.py    GNU General Public License v2.0 6 votes vote down vote up
def test_rmtree_test(self):
        path = mkdtemp(self)
        utils.rmtree(path)
        self.assertFalse(exists(path))
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path)
            self.assertFalse(w)

        utils.stub_item_attr_value(
            self, utils, 'rmtree_', utils.fake_error(IOError))
        path2 = mkdtemp(self)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path2)
            self.assertIn("rmtree failed to remove", str(w[-1].message)) 
Example 14
Project: rowgenerators   Author: Metatab   File: test_basic.py    MIT License 6 votes vote down vote up
def test_RowGenerator(self):
        import warnings
        warnings.simplefilter("ignore")

        from rowgenerators import RowGenerator

        rg = RowGenerator('http://public.source.civicknowledge.com/example.com/sources/simple-example-altnames.csv')

        self.assertEqual(10001, len(list(rg)))

        df = rg.dataframe()

        self.assertEqual(10000, len(df))

        url = 'http://public.source.civicknowledge.com/example.com/sources/simple-example.foo#&target_format=csv'

        self.assertEqual(10001, len(list(RowGenerator(url))))

        url = 'http://public.source.civicknowledge.com/example.com/sources/simple-example.foo'

        self.assertEqual(10001, len(list(RowGenerator(url, target_format='csv' )))) 
Example 15
Project: pathway-forte   Author: pathwayforte   File: cli.py    Apache License 2.0 6 votes vote down vote up
def test_stability_prediction(
        ssgsea_scores_path,
        phenotypes_path,
        outer_cv,
        inner_cv,
        max_iterations,
        turn_off_warnings,
):
    """Test stability of prediction."""
    if turn_off_warnings:
        click.echo("ssgsea_nes_to_dfWarnings are now turned off")
        warnings.simplefilter('ignore')

    do_stability_prediction(
        ssgsea_scores_path=ssgsea_scores_path,
        phenotypes_path=phenotypes_path,
        outer_cv_splits=outer_cv,
        inner_cv_splits=inner_cv,
        max_iter=max_iterations,
    ) 
Example 16
Project: sanic   Author: huge-success   File: app.py    MIT License 6 votes vote down vote up
def register_blueprint(self, *args, **kwargs):
        """
        Proxy method provided for invoking the :func:`blueprint` method

        .. note::
            To be deprecated in 1.0. Use :func:`blueprint` instead.

        :param args: Blueprint object or (list, tuple) thereof
        :param kwargs: option dictionary with blueprint defaults
        :return: None
        """

        if self.debug:
            warnings.simplefilter("default")
        warnings.warn(
            "Use of register_blueprint will be deprecated in "
            "version 1.0.  Please use the blueprint method"
            " instead",
            DeprecationWarning,
        )
        return self.blueprint(*args, **kwargs) 
Example 17
Project: jawfish   Author: war-and-code   File: test_case.py    MIT License 6 votes vote down vote up
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) 
Example 18
Project: b2ac   Author: hbldh   File: polygon.py    MIT License 5 votes vote down vote up
def get_center_point(self, use_centroid=True):
        """Returns a center of weight for the object.

        :param use_centroid: Uses a centroid finding method instead of pure mean of vertices.
        :type use_centroid: bool

        """
        if use_centroid:
            with warnings.catch_warnings(record=False) as w:
                # Cause all warnings to never be triggered.
                warnings.simplefilter("ignore")

                pnt_array = self.get_closed_polygon()

                A = self._area_help_function()
                D = (pnt_array[:-1, 0] * pnt_array[1:, 1] -
                     pnt_array[1:, 0] * pnt_array[:-1, 1])

                c_x = ((pnt_array[:-1, 0] + pnt_array[1:, 0]) * D).sum() / (6 * A)
                c_y = ((pnt_array[:-1, 1] + pnt_array[1:, 1]) * D).sum() / (6 * A)

                if np.isnan(c_x) or np.isinf(c_x) or np.isnan(c_y) or np.isinf(c_y):
                    # If centroid calculations fails (e.g. due to zero-valued area) then use the
                    # mean of the vertices as center point instead.
                    return np.mean(self.get_open_polygon(), 0)
                else:
                    return np.array([c_x, c_y])
        else:
            return np.mean(self.get_open_polygon(), 0) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_pytree.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deprecated_prefix_methods(self):
            l = pytree.Leaf(100, "foo")
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always", DeprecationWarning)
                self.assertEqual(l.get_prefix(), "")
                l.set_prefix("hi")
            self.assertEqual(l.prefix, "hi")
            self.assertEqual(len(w), 2)
            for warning in w:
                self.assertTrue(warning.category is DeprecationWarning)
            self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \
                                 "use the prefix property")
            self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \
                                 "use the prefix property") 
Example 20
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_check_metadata_deprecated(self):
        # makes sure make_metadata is deprecated
        dist, cmd = self.get_cmd()
        with check_warnings() as w:
            warnings.simplefilter("always")
            cmd.check_metadata()
            self.assertEqual(len(w.warnings), 1) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
        self.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1) 
Example 22
Project: pyblish-win   Author: pyblish   File: support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def capture_warnings(func):
    def _capture_warnings(*args, **kw):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            return func(*args, **kw)
    return _capture_warnings 
Example 23
Project: pyblish-win   Author: pyblish   File: test_register.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_check_metadata_deprecated(self):
        # makes sure make_metadata is deprecated
        cmd = self._get_cmd()
        with check_warnings() as w:
            warnings.simplefilter("always")
            cmd.check_metadata()
            self.assertEqual(len(w.warnings), 1) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_calltips.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_paramtuple_float(self):
        # 18539: (a,b) becomes '.0' in code object; change that but not 0.0
        with warnings.catch_warnings():
            # Suppess message of py3 deprecation of parameter unpacking
            warnings.simplefilter("ignore")
            exec "def f((a,b), c=0.0): pass"
        self.assertEqual(signature(f), '(<tuple>, c=0.0)') 
Example 25
Project: RF-Monitor   Author: EarToEarOak   File: legend.py    GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 26
Project: AutoDL   Author: tanguofu   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_blueprint(self, *args, **kwargs):
        # TODO: deprecate 1.0
        if self.debug:
            warnings.simplefilter('default')
        warnings.warn("Use of register_blueprint will be deprecated in "
                      "version 1.0.  Please use the blueprint method"
                      " instead",
                      DeprecationWarning)
        return self.blueprint(*args, **kwargs) 
Example 27
Project: AutoDL   Author: tanguofu   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_server(self, host=None, port=None, debug=False,
                            ssl=None, sock=None, protocol=None,
                            backlog=100, stop_event=None,
                            access_log=True):
        """Asynchronous version of `run`.

        NOTE: This does not support multiprocessing and is not the preferred
              way to run a Sanic application.
        """

        if sock is None:
            host, port = host or "127.0.0.1", port or 8000

        if protocol is None:
            protocol = (WebSocketProtocol if self.websocket_enabled
                        else HttpProtocol)
        if stop_event is not None:
            if debug:
                warnings.simplefilter('default')
            warnings.warn("stop_event will be removed from future versions.",
                          DeprecationWarning)

        server_settings = self._helper(
            host=host, port=port, debug=debug, ssl=ssl, sock=sock,
            loop=get_event_loop(), protocol=protocol,
            backlog=backlog, run_async=True,
            access_log=access_log)

        # Trigger before_start events
        await self.trigger_events(
            server_settings.get('before_start', []),
            server_settings.get('loop')
        )

        return await serve(**server_settings) 
Example 28
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def normalize(data, mean=None, sd=None):
    if mean is None:
        mean = np.mean(data, axis=0)
    if sd is None:
        sd = np.std(data, axis=0)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        normalized = np.divide(data - mean, sd)
    normalized[np.isnan(normalized)] = 0.0
    normalized[np.isinf(normalized)] = 0.0
    return normalized 
Example 29
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def ilogit(log_odds):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return 1. / (1. + np.exp(-log_odds)) 
Example 30
Project: programsynthesishunting   Author: flexgp   File: error_metric.py    GNU General Public License v3.0 5 votes vote down vote up
def f1_score(y, yhat):
    """
    The F_1 score is a metric for classification which tries to balance
    precision and recall, ie both true positives and true negatives.
    For F_1 score higher is better.

    :param y: The expected input (i.e. from dataset).
    :param yhat: The given input (i.e. from phenotype).
    :return: The f1 score.
    """

    # if phen is a constant, eg 0.001 (doesn't refer to x), then yhat
    # will be a constant. that will break f1_score. so convert to a
    # constant array.
    if not isinstance(yhat, np.ndarray) or len(yhat.shape) < 1:
        yhat = np.ones_like(y) * yhat

    # convert real values to boolean with a zero threshold
    yhat = (yhat > 0)
    with warnings.catch_warnings():
        # if we predict the same value for all samples (trivial
        # individuals will do so as described above) then f-score is
        # undefined, and sklearn will give a runtime warning and
        # return 0. We can ignore that warning and happily return 0.
        warnings.simplefilter("ignore")
        return sklearn_f1_score(y, yhat, average="weighted")
# Set maximise attribute for f1_score error metric. 
Example 31
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter('ignore', category) 
Example 32
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: deprecation.py    MIT License 5 votes vote down vote up
def install_warning_logger():
    # Enable our Deprecation Warnings
    warnings.simplefilter("default", PipDeprecationWarning, append=True)

    global _warnings_showwarning

    if _warnings_showwarning is None:
        _warnings_showwarning = warnings.showwarning
        warnings.showwarning = _showwarning 
Example 33
Project: flasky   Author: RoseOu   File: test_egg_info.py    MIT License 5 votes vote down vote up
def test_version_10_format_legacy_parser(self):
        """
        """
        path_variable = None
        for env in os.environ:
            if env.lower() == 'path':
                path_variable = env

        if path_variable:
            old_path = os.environ[path_variable]
            os.environ[path_variable] = ''
        #catch_warnings not available until py26
        warning_filters = warnings.filters
        warnings.filters = warning_filters[:]
        try:
            warnings.simplefilter("ignore", DeprecationWarning)
            self._write_entries(ENTRIES_V10)
            rev = egg_info.egg_info.get_svn_revision()
        finally:
            #restore the warning filters
            warnings.filters = warning_filters
            #restore the os path
            if path_variable:
                os.environ[path_variable] = old_path

        self.assertEqual(rev, '89000') 
Example 34
Project: elsbot   Author: Praisebetoscience   File: elsbot.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    import warnings

    warnings.simplefilter('ignore', ResourceWarning)
    warnings.simplefilter('ignore', UserWarning)

    logging.basicConfig(format='%(asctime)s (%(levelname)s): %(message)s',
                        datefmt='%m-%d-%Y %I:%M:%S %p', level=logging.INFO)
    logging.info("ELSbot starting...")

    parser = argparse.ArgumentParser(description="Snap Shot Bot with Quotes.")
    parser.add_argument('--run-once', '-r', action='store_true', help='run scan once then quit')
    parser.add_argument('--config-file', '-f', default='elsbot.cfg', help="specify a configuration file.")
    args = parser.parse_args()

    if not os.path.isfile(args.config_file):
        logging.error("Config file {} does not exist.".format(args.config_file))
        exit()

    elsbot = ELSBot(args.config_file)

    while True:
        try:
            elsbot.scan_posts()
            if args.run_once:
                break

            elsbot.db_maintenance()
            elsbot.load_quote_list()
            time.sleep(10)
        except KeyboardInterrupt:
            elsbot.close()
            exit()
        except Exception as e:
            logging.error("Error running bot.")
            logging.error(str(e))
            if args.run_once:
                exit()
            time.sleep(10) 
Example 35
Project: parasweep   Author: eviatarbach   File: test_parasweep.py    MIT License 5 votes vote down vote up
def setUp(self):
        warnings.simplefilter("ignore", ResourceWarning)
        warnings.simplefilter('ignore', ImportWarning) 
Example 36
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    Apache License 2.0 5 votes vote down vote up
def test_sequential_warning():
    with warnings.catch_warnings(record=True) as w:
        # The following line permits the test to pass if run multiple times
        warnings.simplefilter('always')
        b = gluon.nn.Sequential()
        b.add(gluon.nn.Dense(20))
        b.hybridize()
        assert len(w) == 1 
Example 37
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: test_model_zoo.py    Apache License 2.0 5 votes vote down vote up
def _test_model_list(model_list, ctx, x, pretrained=True, **kwargs):
    pretrained_models = gcv.model_zoo.pretrained_model_list()
    for model in model_list:
        if model in pretrained_models:
            net = gcv.model_zoo.get_model(model, pretrained=True, **kwargs)
        else:
            net = gcv.model_zoo.get_model(model, **kwargs)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                net.initialize()
        net.collect_params().reset_ctx(ctx)
        net(x)
        mx.nd.waitall() 
Example 38
Project: DOTA_models   Author: ringringyi   File: render_spec_with_graphviz.py    Apache License 2.0 5 votes vote down vote up
def master_spec_graph(master_spec):
  """Constructs a master spec graph.

  Args:
    master_spec: MasterSpec proto.

  Raises:
    TypeError, if master_spec is not the right type. N.B. that this may be
    raised if you import proto classes in non-standard ways (e.g. dynamically).

  Returns:
    SVG graph contents as a string.
  """
  if not isinstance(master_spec, spec_pb2.MasterSpec):
    raise TypeError("master_spec_graph() expects a MasterSpec input.")

  graph = pygraphviz.AGraph(directed=True)

  graph.node_attr.update(
      shape="box",
      style="filled",
      fillcolor="white",
      fontname="roboto, helvetica, arial",
      fontsize=11)
  graph.edge_attr.update(fontname="roboto, helvetica, arial", fontsize=11)

  for component in master_spec.component:
    graph.add_node(component.name, label=_component_contents(component))

  for component in master_spec.component:
    for linked_feature in component.linked_feature:
      graph.add_edge(
          linked_feature.source_component,
          component.name,
          label=_linked_feature_label(linked_feature))

  with warnings.catch_warnings():
    # Fontconfig spews some warnings, suppress them for now. (Especially because
    # they can clutter IPython notebooks).
    warnings.simplefilter("ignore")
    return graph.draw(format="svg", prog="dot") 
Example 39
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: fixtures.py    Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(WarningsFixture, self).setUp()
        # NOTE(sdague): Make deprecation warnings only happen once. Otherwise
        # this gets kind of crazy given the way that upstream python libs use
        # this.
        warnings.simplefilter("once", DeprecationWarning)
        warnings.filterwarnings('ignore',
                                message='With-statements now directly support'
                                        ' multiple context managers')

        self.addCleanup(warnings.resetwarnings) 
Example 40
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter('ignore', category) 
Example 41
Project: sic   Author: Yanixos   File: deprecation.py    GNU General Public License v3.0 5 votes vote down vote up
def install_warning_logger():
    # Enable our Deprecation Warnings
    warnings.simplefilter("default", PipDeprecationWarning, append=True)

    global _warnings_showwarning

    if _warnings_showwarning is None:
        _warnings_showwarning = warnings.showwarning
        warnings.showwarning = _showwarning 
Example 42
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter("ignore", category) 
Example 43
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None

    # capture warnings due to #1111
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        loader = importer.find_module(packageName)

    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 44
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter('ignore', category) 
Example 45
Project: AshsSDK   Author: thehappydinoa   File: deprecation.py    MIT License 5 votes vote down vote up
def install_warning_logger():
    # Enable our Deprecation Warnings
    warnings.simplefilter("default", PipDeprecationWarning, append=True)

    global _warnings_showwarning

    if _warnings_showwarning is None:
        _warnings_showwarning = warnings.showwarning
        warnings.showwarning = _showwarning 
Example 46
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter('ignore', category) 
Example 47
Project: Kitsu.Bundle   Author: AeonLucid   File: __init__.py    MIT License 5 votes vote down vote up
def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter('ignore', category) 
Example 48
Project: securityheaders   Author: koenbuyens   File: findingformatterfactory.py    Apache License 2.0 5 votes vote down vote up
def populate(self):
        #path = securityheaders.formatters.__path__[0]
        #with warnings.catch_warnings():
        #    warnings.simplefilter("ignore")
        #    Util.load_all_modules_from_dir(path)
        clazzes = list(Util.inheritors(FindingFormatter))
        all_my_base_classes = {cls: cls for cls in clazzes}
        for clazz in all_my_base_classes:
            self.clazzes[clazz.__name__] = clazz 
Example 49
Project: securityheaders   Author: koenbuyens   File: modelfactory.py    Apache License 2.0 5 votes vote down vote up
def populate(self):
#        path = securityheaders.models.__path__[0]
#        with warnings.catch_warnings():
#            warnings.simplefilter("ignore")
#            Util.load_all_modules_from_dir(path)
        clazzes = list(Util.inheritors(Header))
        clazzes.extend(Util.inheritors(Directive))
        clazzes.extend(Util.inheritors(Keyword))
        for header in list(Util.inheritors(Header)):
            if hasattr(header,'headerkey'):
                self.headers[header.headerkey] = header
    
        all_my_base_classes = {cls: cls for cls in clazzes}
        for clazz in all_my_base_classes:
            self.clazzes[clazz.__name__] = clazz 
Example 50
Project: calmjs   Author: calmjs   File: test_runtime.py    GNU General Public License v2.0 5 votes vote down vote up
def test_runtime_error_deprecation(self):
        stub_stdouts(self)
        working_set = mocks.WorkingSet({'calmjs.runtime': [
            'deprecated = calmjs.tests.test_runtime:deprecated',
        ]})
        rt = runtime.Runtime(working_set=working_set, prog='dummy')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with self.assertRaises(SystemExit):
                rt.error(rt.argparser, 'deprecated', 'simulated')
        self.assertIn('Runtime.error is deprecated', str(w[-1].message)) 
Example 51
Project: calmjs   Author: calmjs   File: test_cli.py    GNU General Public License v2.0 5 votes vote down vote up
def test_create_for_module_vars_and_warning(self):
        stub_os_environ(self)
        tmpdir = mkdtemp(self)
        values = {}

        class MgrDriver(cli.PackageManagerDriver):
            def __init__(self, *a, **kw):
                kw['pkg_manager_bin'] = 'mgr'
                kw['working_dir'] = tmpdir
                super(MgrDriver, self).__init__(*a, **kw)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            driver = MgrDriver.create_for_module_vars(values)
            self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
            self.assertIn(
                "Unable to locate the 'mgr' binary or runtime",
                str(w[-1].message))

        self.assertTrue(isinstance(driver, MgrDriver))
        # Normally, these will be global names.
        self.assertIn('mgr_install', values)
        self.assertIn('mgr_init', values)
        self.assertIn('get_mgr_version', values)

    # Should really put more tests of these kind in here, but the more
    # concrete implementations have done so.  This weird version here
    # is mostly just for laughs. 
Example 52
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def test_construction(self):
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                Spec(test_targets='/')

        self.assertIn(
            "Spec key 'test_targets' has been remapped to 'test_targetpaths' "
            "in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_targets' has been remapped to 'test_targetpaths' "
            "in calmjs-3.0.0;", s.getvalue()
        ) 
Example 53
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def test_set(self):
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                spec = Spec()
                spec['test_source_map'] = '/'

        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", s.getvalue()
        ) 
Example 54
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def test_getitem(self):
        spec = Spec(test_sourcepath='/')
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                self.assertEqual(spec['test_source_map'], '/')

        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", s.getvalue()
        ) 
Example 55
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def test_generate_source_map(self):
        # this is an actual attribute
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                spec = Spec(generate_source_map=True)
                self.assertTrue(spec['generate_source_map'], '/')

        self.assertEqual(len(w), 0)
        self.assertEqual(s.getvalue(), '') 
Example 56
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def test_toolchain_attributes(self):
        # should really be read/write, but in generate these are not
        # set so...
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                toolchain = NullToolchain()
                # assert existing via old property, then set using old
                # property, to see it reflected in new.
                self.assertEqual(toolchain.sourcemap_suffix, '_sourcepath')
                toolchain.sourcemap_suffix = 'foo'
                self.assertEqual(toolchain.sourcepath_suffix, 'foo')

                self.assertEqual(toolchain.target_suffix, '_targetpaths')
                toolchain.target_suffix = 'foo'
                self.assertEqual(toolchain.targetpath_suffix, 'foo')

        self.assertIn(
            "sourcemap_suffix has been renamed to sourcepath_suffix",
            str(w[0].message)
        )
        self.assertEqual(len(w), 4)
        self.assertIn(
            "sourcemap_suffix has been renamed to sourcepath_suffix",
            s.getvalue()
        )
        self.assertIn(
            "target_suffix has been renamed to targetpath_suffix",
            s.getvalue()
        ) 
Example 57
Project: calmjs   Author: calmjs   File: test_argparse.py    GNU General Public License v2.0 5 votes vote down vote up
def test_deprecation(self):
        import warnings
        argparser = ArgumentParser(prog='prog', add_help=False)
        argparser.add_argument('-n', '--normal', action='store')
        argparser.add_argument(
            '-d', '--deprecated', action='store', deprecation=True)
        argparser.add_argument(
            '--bye', action=StoreDelimitedListBase, deprecation='bye')

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # test that they store stuff
            args = argparser.parse_args(['-n', 'hello'])
            self.assertEqual(args.normal, 'hello')
            args = argparser.parse_args(['-d', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--deprecated', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--bye', 'hello,goodbye'])
            self.assertEqual(args.bye, ['hello', 'goodbye'])

        # and the warnings are triggered
        self.assertEqual(
            "option '-d' is deprecated", str(w[0].message))
        self.assertEqual(
            "option '--deprecated' is deprecated", str(w[1].message))
        self.assertEqual(
            "option '--bye' is deprecated: bye", str(w[2].message))

        stream = StringIO()
        argparser.print_help(file=stream)
        # deprecated options are not visible on help
        self.assertNotIn("--deprecated", stream.getvalue())
        self.assertNotIn("--bye", stream.getvalue())
        self.assertIn("--normal", stream.getvalue()) 
Example 58
Project: calmjs   Author: calmjs   File: runtime.py    GNU General Public License v2.0 5 votes vote down vote up
def main(args=None, runtime_cls=CalmJSRuntime):
    bootstrap = BootstrapRuntime()
    # None to distinguish args from unspecified or specified as [], but
    # ultimately the value must be a list.
    args = norm_args(args)
    # Use the bootstrap runtime to set the global runtime attributes
    # (i.e. for logging and such).
    bootstrap(args)

    # all the minimum arguments acquired, bootstrap the execution.
    with warnings.catch_warnings(record=True) as records:
        # Note that this is a workaround for some versions of Python.
        # The full details as to why is documented in the
        # BaseRuntime.__call__ implementation.
        warnings.simplefilter('always')
        # log down the construction of the bootstrap class.
        with pretty_logging(
                logger='', level=bootstrap.bootstrap_log_level,
                stream=sys.stderr):
            runtime = runtime_cls()
            # access the argparser property to trigger its construction
            # inside this logger context, so that any messages passed to
            # the logger will be correctly handled.
            runtime.argparser

            # finally, ensure all captured records (thus far) are logged
            for record in records:
                logger.warning(record.message)
                logger.debug(
                    '%s triggered at %s:%s', record.category.__name__,
                    record.filename, record.lineno,
                )

        # Running this outside of the logger, as the BaseRuntime will do
        # its logging.
        if runtime(args):
            sys.exit(0)
        else:
            sys.exit(1) 
Example 59
Project: rowgenerators   Author: Metatab   File: test_basic.py    MIT License 5 votes vote down vote up
def setUp(self):
        import warnings
        super().setUp()

        warnings.simplefilter('ignore') 
Example 60
Project: rowgenerators   Author: Metatab   File: test_basic.py    MIT License 5 votes vote down vote up
def setUp(self):
        import warnings
        warnings.simplefilter('ignore') 
Example 61
Project: rowgenerators   Author: Metatab   File: __init__.py    MIT License 5 votes vote down vote up
def setUp(self):
        import warnings
        warnings.simplefilter('ignore') 
Example 62
Project: rowgenerators   Author: Metatab   File: test_geo.py    MIT License 5 votes vote down vote up
def setUp(self):
        import warnings
        warnings.simplefilter('ignore') 
Example 63
Project: wrangle   Author: autonomio   File: df_corr_ols.py    MIT License 5 votes vote down vote up
def df_corr_ols(data, y, destructive=False):

    '''1-by-1 correlation with OLS for categorical values as strings.

    Takes in a single column DataFrame where some columns are string
    values of categories. Then performs an OLS test individually on
    values of column returning an ordinal category representation (the greater
    the value, the higher the correlation coefficient.)

    data : dataframe
        A Pandas dataframe with the data
    y : str
        The prediction variable.
    destructive : bool
        If set to True, will make changes directly to the dataframe which
        may be useful with very large dataframes instead of making a copy.

    '''

    import wrangle as wr
    import warnings

    warnings.simplefilter('ignore')

    if destructive is False:
        data = data.copy(deep=True)

    for col in data.columns:
        try:
            wr.col_corr_ols(data, col, y, destructive=True)
        except ValueError:
            pass

    return data 
Example 64
Project: pytorch-mri-segmentation-3D   Author: Achilleas   File: augmentations.py    MIT License 5 votes vote down vote up
def applyScale(images, zoom_val, spline_orders):
	new_imgs = []
	for i, img in enumerate(images):
		with warnings.catch_warnings():
			warnings.simplefilter("ignore")
			try:
				new_img = scipy.ndimage.zoom(img.squeeze(), zoom_val, order = spline_orders[i])
				new_img = new_img[np.newaxis,np.newaxis,:]
				new_imgs.append(new_img)
			except:
				pass
	return new_imgs 
Example 65
Project: openhatch   Author: campbe13   File: testpatch.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testPatchObjectDeprecation(self):
        # needed to enable the deprecation warnings
        warnings.simplefilter('default')

        @apply
        @examine_warnings
        def _examine_warnings(ws):
            patch_object(SomeClass, 'class_attribute', spec=SomeClass)
            warning = ws[0]
            self.assertIs(warning.category, DeprecationWarning) 
Example 66
Project: openhatch   Author: campbe13   File: test_spider.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        warnings.simplefilter("always") 
Example 67
Project: pybdm   Author: sztal   File: test_bdm.py    MIT License 5 votes vote down vote up
def test_bdm_d1_b9(self, bdm_d1_b9, X, expected):
        X = np.array(X)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            output = bdm_d1_b9.bdm(X)
            if w:
                assert issubclass(w[-1].category, BDMRuntimeWarning)
                assert str(w[-1].message) \
                    .startswith("CTM dataset does not contain object")
        assert output == approx(expected) 
Example 68
Project: deb-python-cassandra-driver   Author: openstack   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def setup_package():
    warnings.simplefilter('always')  # for testing warnings, make sure all are let through
    os.environ[CQLENG_ALLOW_SCHEMA_MANAGEMENT] = '1'

    set_default_cass_ip()
    use_single_node()

    setup_connection(DEFAULT_KEYSPACE)
    create_keyspace_simple(DEFAULT_KEYSPACE, 1) 
Example 69
Project: pathway-forte   Author: pathwayforte   File: cli.py    Apache License 2.0 5 votes vote down vote up
def binary(data, outer_cv, inner_cv, max_iterations, turn_off_warnings):
    """Train elastic net for binary prediction."""
    if turn_off_warnings:
        click.echo("Warnings are now turned off")
        warnings.simplefilter('ignore')

    do_binary_prediction(
        data=data,
        outer_cv_splits=outer_cv,
        inner_cv_splits=inner_cv,
        max_iter=max_iterations,
    ) 
Example 70
Project: pathway-forte   Author: pathwayforte   File: cli.py    Apache License 2.0 5 votes vote down vote up
def survival(data, outer_cv, inner_cv, turn_off_warnings):
    """Train survival model."""
    if turn_off_warnings:
        click.echo("Warnings are now turned off")
        warnings.simplefilter('ignore')

    click.echo(f'Running survival analysis for {data} with: {outer_cv} outer CVs and {inner_cv} inner CVs')
    do_survival_prediction(data=data, outer_cv_splits=outer_cv, inner_cv_splits=inner_cv) 
Example 71
Project: pathway-forte   Author: pathwayforte   File: cli.py    Apache License 2.0 5 votes vote down vote up
def subtype(
        ssgsea,
        subtypes,
        outer_cv: int,
        inner_cv: int,
        explained_variance: float,
        chain_pca: bool,
        turn_off_warnings: bool,
):
    """Train subtype analysis."""
    if turn_off_warnings:
        click.echo("Warnings are now turned off")
        warnings.simplefilter('ignore')

    click.echo(f'Running subtype analysis for {ssgsea} with: {outer_cv} outer CVs and {inner_cv} inner CVs')
    results = do_subtype_prediction(
        ssgsea,
        subtypes,
        outer_cv_splits=outer_cv,
        inner_cv_splits=inner_cv,
        chain_pca=chain_pca,
        explained_variance=explained_variance,
    )
    for i, result in enumerate(results, start=1):
        click.echo(json.dumps(result['evaluation'], indent=2))
        click.echo(metrics.classification_report(
            result['data']['y_test'],
            result['data']['y_pred'],
            target_names=['Class 0', 'Class 1', 'Class 2', 'Class 3'],
        )) 
Example 72
Project: Anamoly-Detection   Author: msmsk05   File: base.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_params(self, deep=True):
        """Get parameters for this estimator.

        See http://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html
        and sklearn/base.py for more information.

        Parameters
        ----------
        deep : boolean, optional
            If True, will return the parameters for this estimator and
            contained subobjects that are estimators.

        Returns
        -------
        params : mapping of string to any
            Parameter names mapped to their values.
        """

        out = dict()
        for key in self._get_param_names():
            # We need deprecation warnings to always be on in order to
            # catch deprecated param values.
            # This is set in utils/__init__.py but it gets overwritten
            # when running under python3 somehow.
            warnings.simplefilter("always", DeprecationWarning)
            try:
                with warnings.catch_warnings(record=True) as w:
                    value = getattr(self, key, None)
                if len(w) and w[0].category == DeprecationWarning:
                    # if the parameter is deprecated, don't show it
                    continue
            finally:
                warnings.filters.pop(0)

            # XXX: should we rather test if instance of estimator?
            if deep and hasattr(value, 'get_params'):
                deep_items = value.get_params().items()
                out.update((key + '__' + k, val) for k, val in deep_items)
            out[key] = value
        return out 
Example 73
Project: sanic   Author: huge-success   File: request.py    MIT License 5 votes vote down vote up
def raw_args(self) -> dict:
        if self.app.debug:  # pragma: no cover
            warnings.simplefilter("default")
        warnings.warn(
            "Use of raw_args will be deprecated in "
            "the future versions. Please use args or query_args "
            "properties instead",
            DeprecationWarning,
        )
        return {k: v[0] for k, v in self.args.items()} 
Example 74
Project: jawfish   Author: war-and-code   File: case.py    MIT License 5 votes vote down vote up
def __enter__(self):
        # The __warningregistry__'s need to be in a pristine state for tests
        # to work properly.
        for v in sys.modules.values():
            if getattr(v, '__warningregistry__', None):
                v.__warningregistry__ = {}
        self.warnings_manager = warnings.catch_warnings(record=True)
        self.warnings = self.warnings_manager.__enter__()
        warnings.simplefilter("always", self.expected)
        return self 
Example 75
Project: jawfish   Author: war-and-code   File: test_case.py    MIT License 5 votes vote down vote up
def testAssertDictContainsSubset(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)

            self.assertDictContainsSubset({}, {})
            self.assertDictContainsSubset({}, {'a': 1})
            self.assertDictContainsSubset({'a': 1}, {'a': 1})
            self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
            self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})

            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({1: "one"}, {})

            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({'a': 2}, {'a': 1})

            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({'c': 1}, {'a': 1})

            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})

            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})

            one = ''.join(chr(i) for i in range(255))
            # this used to cause a UnicodeDecodeError constructing the failure msg
            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) 
Example 76
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    Apache License 2.0 4 votes vote down vote up
def test_block_attr_list_of_block():
    class Model1(gluon.Block):
        def __init__(self, **kwargs):
            super(Model1, self).__init__(**kwargs)
            with self.name_scope():
                self.layers = [nn.Dense(i * 10) for i in range(6)]

    class Model2(gluon.Block):
        def __init__(self, **kwargs):
            super(Model2, self).__init__(**kwargs)
            with self.name_scope():
                self.layers = dict()
                self.layers['a'] = [nn.Dense(10), nn.Dense(10)]

    class Model3(gluon.Block):
        def __init__(self, **kwargs):
            super(Model3, self).__init__(**kwargs)
            with self.name_scope():
                self.layers = nn.Sequential()
                self.layers.add(*[nn.Dense(i * 10) for i in range(6)])

    class Model4(gluon.Block):
        def __init__(self, **kwargs):
            super(Model4, self).__init__(**kwargs)
            with self.name_scope():
                self.data = {'a': '4', 'b': 123}

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        model = Model1()
        model.collect_params()
        assert len(w) > 0
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        model = Model2()
        model.collect_params()
        assert len(w) > 0
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        model = Model3()
        model.collect_params()
        assert len(w) == 0
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        model = Model4()
        model.collect_params()
        assert len(w) == 0 
Example 77
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: quantized.py    Apache License 2.0 4 votes vote down vote up
def _create_quantized_models(name, sym_prefix):
    def func(pretrained=False, tag=None, root='~/.mxnet/models', ctx=cpu(0), **kwargs):
        r"""Quantized model.

        Parameters
        ----------
        pretrained : bool or str
            Boolean value controls whether to load the default pretrained weights for model.
            String value represents the hashtag for a certain version of pretrained weights.
        tag : str, default is None
            Optional length-8 sha1sum of parameter file. If `None`, best parameter file
            will be used.
        ctx : Context, default CPU
            The context in which to load the pretrained weights.
        root : str, default $MXNET_HOME/models
            Location for keeping the model parameters.
        """
        from ..model_zoo import get_model
        from ..model_store import get_model_file
        curr_dir = os.path.abspath(os.path.dirname(__file__))
        model_name = name.replace('mobilenet1_', 'mobilenet1.')
        model_name = model_name.replace('mobilenet0_', 'mobilenet0.')
        json_file = os.path.join(curr_dir, '{}-symbol.json'.format(model_name))
        base_name = '_'.join(model_name.split('_')[:-1])
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            param_file = get_model_file(base_name, tag=tag, root=root) if pretrained else None
            net = get_model('_'.join(model_name.split('_')[:-1]), prefix=sym_prefix)
            classes = getattr(net, 'classes', [])
            sym_net = SymbolBlock.imports(json_file, ['data'], None, ctx=ctx)
            if param_file:
                # directly imports weights saved by save_parameters is not applicable
                # so we hack it by load and export once to a temporary params file
                import tempfile
                net.load_params(param_file)
                net.hybridize()
                if '512' in base_name:
                    net(mx.nd.zeros((1, 3, 512, 512)))
                elif '300' in base_name:
                    net(mx.nd.zeros((1, 3, 300, 300)))
                else:
                    net(mx.nd.zeros((1, 3, 224, 224)))
                with tempfile.TemporaryDirectory() as tmpdirname:
                    prefix = os.path.join(tmpdirname, 'tmp')
                    net.export(prefix, epoch=0)
                    param_prefix = prefix + '-0000.params'
                    sym_net.collect_params().load(param_prefix)
        sym_net.classes = classes
        sym_net.reset_class = _not_impl
        sym_net.set_nms = _not_impl
        return sym_net
    func.__name__ = name
    globals()[name] = func 
Example 78
Project: DOTA_models   Author: ringringyi   File: render_parse_tree_graphviz.py    Apache License 2.0 4 votes vote down vote up
def parse_tree_graph(sentence):
  """Constructs a parse tree graph.

  Args:
    sentence: syntaxnet.Sentence instance.

  Returns:
    HTML graph contents, as a string.
  """
  graph = pygraphviz.AGraph(directed=True, strict=False, rankdir="TB")

  for i, token in enumerate(sentence.token):
    node_id = "tok_{}".format(i)
    graph.add_node(node_id, label=token.word)
    if token.head >= 0:
      src_id = "tok_{}".format(token.head)
      graph.add_edge(
          src_id,
          node_id,
          label=token.label,
          key="parse_{}_{}".format(node_id, src_id))

  with warnings.catch_warnings():
    # Fontconfig spews some warnings, suppress them for now. (Especially because
    # they can clutter IPython notebooks).
    warnings.simplefilter("ignore")
    svg = graph.draw(format="svg", prog="dot")

  svg = unicode(svg, "utf-8")

  # For both inline and "new window" displays, we show the tokens with the
  # graph. (The sentence order of nodes is sometimes difficult to read.)
  image_and_text = u"<p><em>Text:</em> {}</p>{}".format(" ".join(
      token.word for token in sentence.token), svg)

  # We generate a base64 URI. This is not too big, but older browsers may not
  # handle it well.
  new_window_html = (u"<style type='text/css'>svg { max-width: 100%; }</style>"
                     + image_and_text).encode("utf-8")
  as_uri = "data:text/html;charset=utf-8;base64,{}".format(
      base64.b64encode(new_window_html))

  return u"{}<p><a target='_blank' href='{}'>Open in new window</a></p>".format(
      image_and_text, as_uri) 
Example 79
Project: sic   Author: Yanixos   File: os.py    GNU General Public License v3.0 4 votes vote down vote up
def get_exec_path(env=None):
    """Returns the sequence of directories that will be searched for the
    named executable (similar to a shell) when launching a process.

    *env* must be an environment variable dict or None.  If *env* is None,
    os.environ will be used.
    """
    # Use a local import instead of a global import to limit the number of
    # modules loaded at startup: the os module is always loaded at startup by
    # Python. It may also avoid a bootstrap issue.
    import warnings

    if env is None:
        env = environ

    # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
    # BytesWarning when using python -b or python -bb: ignore the warning
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", BytesWarning)

        try:
            path_list = env.get('PATH')
        except TypeError:
            path_list = None

        if supports_bytes_environ:
            try:
                path_listb = env[b'PATH']
            except (KeyError, TypeError):
                pass
            else:
                if path_list is not None:
                    raise ValueError(
                        "env cannot contain 'PATH' and b'PATH' keys")
                path_list = path_listb

            if path_list is not None and isinstance(path_list, bytes):
                path_list = fsdecode(path_list)

    if path_list is None:
        path_list = defpath
    return path_list.split(pathsep)


# Change environ to automatically call putenv(), unsetenv if they exist. 
Example 80
Project: calmjs   Author: calmjs   File: test_artifact.py    GNU General Public License v2.0 4 votes vote down vote up
def test_iter_builders_verify_export_target_legacy(self):
        mod = ModuleType('calmjs_testing_dummy')
        mod.complete = generic_builder
        self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
        sys.modules['calmjs_testing_dummy'] = mod

        working_dir = utils.mkdtemp(self)
        utils.make_dummy_dist(self, (
            ('entry_points.txt', '\n'.join([
                '[calmjs.artifacts]',
                'artifact.js = calmjs_testing_dummy:complete',
            ])),
        ), 'app', '1.0', working_dir=working_dir)
        mock_ws = WorkingSet([working_dir])
        root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
        targets = []

        def check_target(export_target):
            # manually create the root here, to allow the completion
            # of the build process by doing what an existing
            # implementation that reuse existing code might have done.
            targets.append(export_target)
            prepare_export_location(export_target)

        # ensure that the build directory exists, because the default

        class FakeArtifactRegistry(ArtifactRegistry):
            def verify_export_target(self, export_target):
                return check_target

        registry = FakeArtifactRegistry(
            'calmjs.artifacts', _working_set=mock_ws)

        # the invalid.js should be filtered out
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            self.assertEqual(1, len(list(registry.iter_builders_for('app'))))

        self.assertIn(
            "FakeArtifactRegistry.verify_export_target returned a callable",
            str(w[-1].message))

        # ensure no early execution of check_target
        self.assertFalse(targets)
        self.assertFalse(exists(root))
        with warnings.catch_warnings(record=True):
            with pretty_logging(stream=mocks.StringIO()):
                registry.process_package('app')
        # ensure no early execution of check_target
        self.assertTrue(targets)
        self.assertTrue(exists(root))