Utility method to print a warning message about failed import of some modules

    :param type_of_obj_support:
    :param caught:
    :return:
178517
def warn_import_error(type_of_obj_support: str, caught: ImportError):
    
    msg = StringIO()
    msg.writelines('Import Error while trying to add support for ' + type_of_obj_support + '. You may continue but '
                   'the associated parsers and converters wont be available : \n')
    traceback.print_tb(caught.__traceback__, file=msg)
    msg.writelines(str(caught.__class__.__name__) + ' : ' + str(caught) + '\n')
    warn(msg.getvalue())
1325406
def tryImportClass(self):
        
        logger.info("Importing: {}".format(self.fullClassName))
        self._triedImport = True
        self._exception = None
        self._cls = None
        try:
            for pyPath in self.pythonPath.split(':'):
                if pyPath and pyPath not in sys.path:
                    logger.debug("Appending {!r} to the PythonPath.".format(pyPath))
                    sys.path.append(pyPath)
            self._cls = import_symbol(self.fullClassName) # TODO: check class?
        except Exception as ex:
            self._exception = ex
            logger.warn("Unable to import {!r}: {}".format(self.fullClassName, ex))
            if DEBUGGING:
                raise
327627
def _scons_user_error(e):
    
    global print_stacktrace
    etype, value, tb = sys.exc_info()
    if print_stacktrace:
        traceback.print_exception(etype, value, tb)
    filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
    sys.stderr.write("\nscons: *** %s\n" % value)
    sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine))
    sys.exit(2)
375413
function notifyHandlers (stack, windowError) {
            var exception = null;
            if (windowError && !TraceKit.collectWindowErrors) {
                return;
            }
            for (var i in handlers) {
                if (_has(handlers, i)) {
                    try {
                        handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2)));
                    } catch (inner) {
                        exception = inner;
                    }
                }
            }

            if (exception) {
                throw exception;
            }
        }
1102148
def _handle_errors(errors):
  """"""
  if not errors:
    return
  log_all = True  # pylint: disable=unused-variable
  err_msg = "T2T: skipped importing {num_missing} data_generators modules."
  print(err_msg.format(num_missing=len(errors)))
  for module, err in errors:
    err_str = str(err)
    if not _is_import_err_msg(err_str, module):
      print("From module %s" % module)
      raise err
    if log_all:
      print("Did not import module: %s; Cause: %s" % (module, err_str))
779662
def capture_pywarnings(handler):
        """"""
        logger = logging.getLogger('py.warnings')
        # Check for previously installed handlers.
        for h in logger.handlers:
            if isinstance(h, handler.__class__):
                return
        logger.addHandler(handler)
        logger.setLevel(logging.WARNING)
1148720
def redirect_warnings(capture=True, logger='py.warnings'):
    
    global _warnings_showwarning
    if capture:
        assert _warnings_showwarning is None
        _warnings_showwarning = warnings.showwarning
        # `warnings.showwarning` must be a function, a generic
        # callable object is not accepted ...
        warnings.showwarning = _WarningsLogger(logger, format_warning_oneline).__call__
    else:
        assert _warnings_showwarning is not None
        warnings.showwarning = _warnings_showwarning
        _warnings_showwarning = None
708505
def _agent_import_failed(trace):
    """"""

    class _AgentImportFailed(Trainer):
        _name = "AgentImportFailed"
        _default_config = with_common_config({})

        def _setup(self, config):
            raise ImportError(trace)

    return _AgentImportFailed
239958
def withTracebackPrint(ErrorType, thrownError, _traceback):
    ''''''
    file = StringIO.StringIO()
    traceback.print_exception(ErrorType, thrownError, _traceback, file = file)
    return _loadError(ErrorType, thrownError, file.getvalue())
1277688
def exception_handler(exceptionObj):
    """"""
    try:
        if isinstance(exceptionObj, Exception) and hasattr(exceptionObj, 'args'):
            if not (hasattr(exceptionObj, 'message' or hasattr(exceptionObj, 'msg'))):
                if len(exceptionObj.args) >= 1:
                    if type(exceptionObj.args[0]) == type(b''):
                        ob = json.loads(exceptionObj.args[0].decode('utf-8'))
                        if type(ob) == type({}) and ob['message']:
                            return ob['message']
                    else:

                        try:
                            if type(exceptionObj.args[0]) == type('') and exceptionObj.args[0][0] == 'b':
                                ob = json.loads(exceptionObj.args[0][2:-1])
                            else:
                                ob = json.loads(exceptionObj.args[0])
                            if type(ob) == type({}) and ob['message']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['message']
                            elif type(ob) == type({}) and ob['msg']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['msg']
                            return str(json.loads(exceptionObj.args[0]))
                        except Exception as e:
                            return str(exceptionObj.args[0])
            elif hasattr(exceptionObj, 'msg'):
                return exceptionObj.msg
            elif hasattr(exceptionObj, 'message'):
                return exceptionObj.message
        elif type(exceptionObj) == type(''):
            try:
                ob = json.loads(exceptionObj)
                if type(ob) == type({}):
                    if ob['message']:
                        return ob['message']
                    elif ob['msg']:
                        return ob['msg']
                    else:
                        return ob
            except Exception as e:
                return exceptionObj

    except Exception as e:
        return e
339323
def printif(self, obj_print, tipo_print=None):
        """"""
        if self.verbose:
            print(obj_print)
        if tipo_print == 'ok':
            logging.info(obj_print)
        elif tipo_print == 'error':
            logging.error(obj_print)
        elif tipo_print == 'warning':
            logging.warning(obj_print)
857872
def catch_exception(exception, message=None):
    
    def decorator(f):
        @click.pass_context
        def new_func(ctx, *args, **kwargs):
            try:
                return ctx.invoke(f, *args, **kwargs)
            except exception as e:
                message1 = message if message is not None else '{}'.format(e)
                click.echo(message1)
                ctx.exit(code=exit_codes.OTHER_FAILURE)
        return update_wrapper(new_func, f)
    return decorator
1305570
def _exception_default_handler(self, e):
        
        if isinstance(e, HTTPError):
            if e.log_message:
                format = "%d %s: " + e.log_message
                args = [e.status_code, self._request_summary()] + list(e.args)
                app_log.warning(format, *args)
            if e.status_code not in httplib.responses:
                app_log.error("Bad HTTP status code: %d", e.status_code)
                self.send_error(500, exc_info=sys.exc_info())
            else:
                self.send_error(e.status_code, exc_info=sys.exc_info())
        else:
            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
                          self.request, exc_info=True)
            self.send_error(500, exc_info=sys.exc_info())
942588
function printWarnings (deps, type) {
  if (!Object.keys(deps).length) return

  var warnings = {
    E404: {title: 'Unregistered', list: []},
    ESCM: {title: 'SCM', list: []},
    EDEPTYPE: {title: 'Non-string dependency', list: []}
  }

  for (var name in deps) {
    var dep = deps[name]

    if (dep.warn) {
      warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())])
    }
  }

  Object.keys(warnings).forEach(function (warnType) {
    var warnList = warnings[warnType].list

    if (!warnList.length) return

    var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}})

    console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n')
    warnList.forEach(function (row) { table.push(row) })
    console.log(table.toString() + '\n')
  })
}
505885
def try_import(module_name, names=None, default=ImportErrorModule, warn=True):
    
    try:
        module = importlib.import_module(module_name)
    except ImportError:
        if warn:
            if warn is True:
                Config.utils_logger.warning(
                    "Module `%s` not found. Install it to remove this warning"
                    % module_name
                )
            else:
                warn(module_name, names, default)
        module = (
            ImportErrorModule(module_name) if default is ImportErrorModule else default
        )
    if not names:
        return module
    if not isinstance(names, (tuple, set, list)):
        names = [names]
    result = []
    for name in names:
        if hasattr(module, name):
            result.append(module.__getattribute__(name))
        else:
            result.append(
                ImportErrorModule("%s.%s" % (module_name, name))
                if default is ImportErrorModule
                else default
            )
    return result[0] if len(result) == 1 else result
1139755
def _new_err(self, errclass: str, *args) -> 'Err':
        
        # get the message or exception
        ex, msg = self._get_args(*args)
        # construct the error
        # handle exception
        ftb = None  # type: str
        function = None  # type: str
        errtype = None  # type: str
        file = None  # type: str
        line = None  # type: int
        code = None  # type: str
        ex_msg = None  # type: str
        caller = None  # type: str
        caller_msg = None  # type: str

        st = inspect.stack()

        if ex is not None:
            # get info from exception
            errobj, ex_msg, tb = sys.exc_info()
            tb = traceback.extract_tb(tb)
            file, line, function, code = tb[-1]
            # if called from an external lib
            if len(tb) > 1:
                file, line, caller, code = tb[0]
            else:
                call_stack = []
                for c in st:
                    call_stack.append(c[3])
                caller = self._get_caller(call_stack, function)

            internals = [
                "err",
                "_new_err",
                "fatal",
                "warning",
                "debug",
                "info",
                "<module>"]  
            if caller == function or caller in internals:
                caller = None
            # handle messages
            if msg is not None:
                caller_msg = msg
                msg = str(ex_msg)
            else:
                msg = str(ex_msg)
            ftb = traceback.format_exc()
            errtype = errobj.__name__
        if function is None:
            # for el in st:
            #   print(el)
            function = st[3][3]
            if function == "<module>":
                function = None
        # init error object
        date = datetime.now()
        error = Err(
            function,
            date,
            msg,
            errtype,
            errclass,
            line,
            file,
            code,
            ftb,
            ex,
            caller,
            caller_msg)
        return error
305537
def get_exception_message(instance):
    ''''''
    args = getattr(instance, 'args', None)

    if args:
        return str(instance)

    try:
        return type(instance).__name__
    except AttributeError:
        return str(instance)