Map boto-specific exceptions to the simplekv-API.
330212
def map_boto_exceptions(key=None, exc_pass=()):
    """"""
    from boto.exception import BotoClientError, BotoServerError, \
        StorageResponseError
    try:
        yield
    except StorageResponseError as e:
        if e.code == 'NoSuchKey':
            raise KeyError(key)
        raise IOError(str(e))
    except (BotoClientError, BotoServerError) as e:
        if e.__class__.__name__ not in exc_pass:
            raise IOError(str(e))
766719
def on_exception_report_input(func_=None, force=False, keys=None):
    
    def _closure_onexceptreport(func):
        if not ONEX_REPORT_INPUT and not force:
            return func
        @ignores_exc_tb(outer_wrapper=False)
        #@wraps(func)
        def wrp_onexceptreport(*args, **kwargs):
            try:
                #import utool
                #if utool.DEBUG:
                #    print('[IN EXCPRPT] args=%r' % (args,))
                #    print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
                return func(*args, **kwargs)
            except Exception as ex:
                from utool import util_str
                print('ERROR occured! Reporting input to function')
                if keys is not None:
                    from utool import util_inspect
                    from utool import util_list
                    from utool import util_dict
                    argspec = util_inspect.get_func_argspec(func)
                    in_kwargs_flags = [key in kwargs for key in keys]
                    kwarg_keys = util_list.compress(keys, in_kwargs_flags)
                    kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
                    flags = util_list.not_list(in_kwargs_flags)
                    arg_keys = util_list.compress(keys, flags)
                    arg_idxs = [argspec.args.index(key) for key in arg_keys]
                    num_nodefault = len(argspec.args) - len(argspec.defaults)
                    default_vals = (([None] * (num_nodefault)) +
                                    list(argspec.defaults))
                    args_ = list(args) + default_vals[len(args) + 1:]
                    arg_vals = util_list.take(args_, arg_idxs)
                    requested_dict = dict(util_list.flatten(
                        [zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
                    print('input dict = ' + util_str.repr4(
                        util_dict.dict_subset(requested_dict, keys)))
                    # (print out specific keys only)
                    pass
                arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
                                      for arg in args])
                kwarg_strs = ', '.join([
                    util_str.truncate_str('%s=%r' % (key, val))
                    for key, val in six.iteritems(kwargs)])
                msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
                    meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
                msg += ' * len(args) = %r\n' % len(args)
                msg += ' * len(kwargs) = %r\n' % len(kwargs)
                util_dbg.printex(ex, msg, pad_stdout=True)
                raise
        wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func)
        return wrp_onexceptreport
    if func_ is None:
        return _closure_onexceptreport
    else:
        return _closure_onexceptreport(func_)
427300
def exception_handler(exctype, value, traceback):
    
    if exctype == KeyboardInterrupt:
        pypro.console.out('')  # Adds a new line after Ctrl+C character
        pypro.console.err('Canceled')
    elif exctype == PyproException:
        pypro.console.err('[Error] ', value.message)
        exit()
    else:
        sys.__excepthook__(exctype, value, traceback)
332271
def _map_arguments(self, input_dict):
        
        data = input_dict.get('data')
        comp = input_dict.get('comp')
        library = input_dict.get('library')
        models = input_dict.get('models')
        hpx_order = input_dict.get('hpx_order_fitting')
        dry_run = input_dict.get('dry_run', False)

        self._set_link('init-model', InitModel,
                       comp=comp, data=data,
                       library=library,
                       models=models,
                       hpx_order=hpx_order,
                       dry_run=dry_run)

        self._set_link('assemble-model', AssembleModel_SG,
                       comp=comp, data=data,
                       models=models)
806565
def py_to_couch_validate(key, val):
    
    if key not in RESULT_ARG_TYPES:
        raise CloudantArgumentError(116, key)
    # pylint: disable=unidiomatic-typecheck
    # Validate argument values and ensure that a boolean is not passed in
    # if an integer is expected
    if (not isinstance(val, RESULT_ARG_TYPES[key]) or
            (type(val) is bool and int in RESULT_ARG_TYPES[key])):
        raise CloudantArgumentError(117, key, RESULT_ARG_TYPES[key])
    if key == 'keys':
        for key_list_val in val:
            if (not isinstance(key_list_val, RESULT_ARG_TYPES['key']) or
                    type(key_list_val) is bool):
                raise CloudantArgumentError(134, RESULT_ARG_TYPES['key'])
    if key == 'stale':
        if val not in ('ok', 'update_after'):
            raise CloudantArgumentError(135, val)
308892
def translate_exception(exc, kwargs):
    
    error = exc.response['Error']
    error.setdefault('Message', '')
    err_class = EXC.get(error['Code'], DynamoDBError)
    return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'],
                     exc_info=sys.exc_info(), args=pformat(kwargs), **error)
737653
def exception(cls, method, uri, response, message):
        
        # noinspection PyBroadException
        try:
            error_payload = json.loads(response.text)
            if 'message' in error_payload:
                message = '{}: {}'.format(message, error_payload['message'])
            code = error_payload.get('code', response.status_code)
            return TwilioRestException(response.status_code, uri, message, code, method)
        except Exception:
            return TwilioRestException(response.status_code, uri, message, response.status_code, method)
673307
def exception(message):
    """"""

    def decorator(method):
        """Inner decorator so we can accept arguments."""

        @wraps(method)
        def wrapper(self, *args, **kwargs):
            """Innermost decorator wrapper - this is confusing."""
            if self.messages:
                kwargs['message'] = args[0] if args else kwargs.get('message', message)
            else:
                kwargs['message'] = None
            kwargs['prefix'] = self.prefix
            kwargs['statsd'] = self.statsd

            return method(self, **kwargs)

        return wrapper

    return decorator
107601
def catch_boto_400(message, **info):
    """"""
    try:
        yield
    except ClientError as error:
        if str(error.response["ResponseMetadata"]["HTTPStatusCode"]).startswith("4"):
            error_message = error.response["Error"]["Message"]
            raise BadAmazon(message, error_message=error_message, error_code=error.response["ResponseMetadata"]["HTTPStatusCode"], **info)
        else:
            raise
1256871
function simpleMap(map, lvls, opts, type, ext, callback) {
    opts = utils.clone(opts);
    lvls--;
    if(lvls < 1) {
        opts.simple = false;
        opts.recursive = true;
        opts.type = type;
        opts.ext = ext;
    }
    var folders = map.__filter({type:'directory'}, true);
    var count = folders.length;
    var errs = [];

    function end(err) {
        if(err) {
            errs.push(err);
        }
        if(--count !== 0) {
            return;
        }
        if(errs.length) {
            callback(errs);
            return;
        }
        callback(null, map);
    }
    folders.forEach(function (folder) {
        folder.__map(opts, function (err, fMap) {
            if(err) {
                end(err);
                return;
            }
            if(lvls < 1) {
                end();
            } else {
                simpleMap(fMap, lvls, opts, type, ext, end);
            }
        });
    });
}
349487
def raise_api_exceptions(function, *args, **kwargs):
    
    try:
        return_value = function(*args, **kwargs)
    except errors.HTTPException as exc:
        if exc._raw.status_code != 400:  # pylint: disable=W0212
            raise  # Unhandled HTTPErrors
        try:  # Attempt to convert v1 errors into older format (for now)
            data = exc._raw.json()  # pylint: disable=W0212
            assert len(data) == 2
            return_value = {'errors': [(data['reason'],
                                        data['explanation'], '')]}
        except Exception:
            raise exc
    if isinstance(return_value, dict):
        if return_value.get('error') == 304:  # Not modified exception
            raise errors.NotModified(return_value)
        elif return_value.get('errors'):
            error_list = []
            for error_type, msg, value in return_value['errors']:
                if error_type in errors.ERROR_MAPPING:
                    if error_type == 'RATELIMIT':
                        args[0].evict(args[1])
                    error_class = errors.ERROR_MAPPING[error_type]
                else:
                    error_class = errors.APIException
                error_list.append(error_class(error_type, msg, value,
                                              return_value))
            if len(error_list) == 1:
                raise error_list[0]
            else:
                raise errors.ExceptionList(error_list)
    return return_value
262440
def openstack_exception(func):
        '''
            
        '''
        async def wrap(*args, **kwargs):
            try:
                return await func(*args, **kwargs)
            except Exception as e:
                logging.error(e)
                raise IaasException
        return wrap
337674
def clean_fail(func):
    '''
    
    '''
    def func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except botocore.exceptions.ClientError as e:
            print(str(e), file=sys.stderr)
            sys.exit(1)
    return func_wrapper
217238
function _mapError(err) {
        if (!err) {
            return null;
        }

        switch (err) {
        case appshell.fs.ERR_INVALID_PARAMS:
            return FileSystemError.INVALID_PARAMS;
        case appshell.fs.ERR_NOT_FOUND:
            return FileSystemError.NOT_FOUND;
        case appshell.fs.ERR_CANT_READ:
            return FileSystemError.NOT_READABLE;
        case appshell.fs.ERR_CANT_WRITE:
            return FileSystemError.NOT_WRITABLE;
        case appshell.fs.ERR_UNSUPPORTED_ENCODING:
            return FileSystemError.UNSUPPORTED_ENCODING;
        case appshell.fs.ERR_OUT_OF_SPACE:
            return FileSystemError.OUT_OF_SPACE;
        case appshell.fs.ERR_FILE_EXISTS:
            return FileSystemError.ALREADY_EXISTS;
        case appshell.fs.ERR_ENCODE_FILE_FAILED:
            return FileSystemError.ENCODE_FILE_FAILED;
        case appshell.fs.ERR_DECODE_FILE_FAILED:
            return FileSystemError.DECODE_FILE_FAILED;
        case appshell.fs.ERR_UNSUPPORTED_UTF16_ENCODING:
            return FileSystemError.UNSUPPORTED_UTF16_ENCODING;
        }
        return FileSystemError.UNKNOWN;
    }
707739
def _client_wrapper(attr, *args, **kwargs):
    '''
    
    '''
    catch_api_errors = kwargs.pop('catch_api_errors', True)
    func = getattr(__context__['docker.client'], attr, None)
    if func is None or not hasattr(func, '__call__'):
        raise SaltInvocationError('Invalid client action \'{0}\''.format(attr))
    if attr in ('push', 'pull'):
        try:
            # Refresh auth config from config.json
            __context__['docker.client'].reload_config()
        except AttributeError:
            pass
    err = ''
    try:
        log.debug(
            'Attempting to run docker-py\'s "%s" function '
            'with args=%s and kwargs=%s', attr, args, kwargs
        )
        ret = func(*args, **kwargs)
    except docker.errors.APIError as exc:
        if catch_api_errors:
            # Generic handling of Docker API errors
            raise CommandExecutionError(
                'Error {0}: {1}'.format(exc.response.status_code,
                                        exc.explanation)
            )
        else:
            # Allow API errors to be caught further up the stack
            raise
    except docker.errors.DockerException as exc:
        # More general docker exception (catches InvalidVersion, etc.)
        raise CommandExecutionError(exc.__str__())
    except Exception as exc:
        err = exc.__str__()
    else:
        return ret

    # If we're here, it's because an exception was caught earlier, and the
    # API command failed.
    msg = 'Unable to perform {0}'.format(attr)
    if err:
        msg += ': {0}'.format(err)
    raise CommandExecutionError(msg)
1061214
def ExceptionHookPDB(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
    pdb.pm()
1146693
def formatTextException(*args):
        

        format = lambda x: re.sub(r"^(\s+)", lambda y: "{0} ".format("." * len(y.group(0))), x.rstrip().expandtabs(4))

        verbose = 10
        cls, instance, trcback = args
        stack = foundations.exceptions.extract_stack(foundations.exceptions.get_inner_most_frame(trcback), verbose)

        text = []
        text.append(foundations.strings.to_string(cls))
        text.append("")

        for line in foundations.exceptions.format_exception(cls, instance, trcback):
            text.append(format("{0}".format(format(line))))
        text.append("")

        text.append("An unhandled exception occured in {0} {1}!".format(Constants.application_name,
                                                                        Constants.version))
        text.append("Sequence of calls leading up to the exception, in their occurring order:")
        text.append("")

        for frame, file_name, line_number, name, context, index in stack:
            location = "{0}{1}".format(name if name != "<module>" else "",
                                       inspect.formatargvalues(*inspect.getargvalues(frame)))
            text.append("File \"{0}\", line {1}, in {2}".format(file_name, line_number, location))
            for i, line in enumerate(context):
                if i == index:
                    text.append(format("\t{0} {1} <===".format(line_number - index + i, format(format(line)))))
                else:
                    text.append(format("\t{0} {1}".format(line_number - index + i, format(format(line)))))
            text.append("")
        for line in traceback.format_exception_only(cls, instance):
            text.append("{0}".format(format(line)))
        text.append("")

        text.append("Frames locals by stack ordering, innermost last:")
        text.append("")
        for frame, locals in foundations.exceptions.extract_locals(trcback):
            name, file_name, line_number = frame
            text.append("Frame \"{0}\" in \"{1}\" file, line {2}:".format(name, file_name, line_number))
            arguments, nameless_args, keyword_args, locals = locals
            has_arguments, has_locals = any((arguments, nameless_args, keyword_args)), any(locals)
            has_arguments and text.append(format("\tArguments:"))
            for key, value in arguments.iteritems():
                text.append(format("\t\t{0} = {1}".format(key, value)))
            for value in nameless_args:
                text.append(format("\t\t{0}".format(value)))
            for key, value in sorted(keyword_args.iteritems()):
                text.append(format("\\tt{0} = {1}".format(key, value)))
            has_locals and text.append(format("\tLocals:"))
            for key, value in sorted(locals.iteritems()):
                text.append(format("\t\t{0} = {1}".format(key, value)))
            text.append("")

        return text