Parse the arguments and return a tuple of types to implement for.

        Raises:
            ValueError or TypeError as appropriate.
423737
def __get_type_args(for_type=None, for_types=None):
        
        if for_type:
            if for_types:
                raise ValueError("Cannot pass both for_type and for_types.")
            for_types = (for_type,)
        elif for_types:
            if not isinstance(for_types, tuple):
                raise TypeError("for_types must be passed as a tuple of "
                                "types (classes).")
        else:
            raise ValueError("Must pass either for_type or for_types.")

        return for_types
531162
def parse(self, value):
        
        if self.required and value is None:
            raise ValueError("%s is required!" % self.name)
        elif self.ignored and value is not None:
            warn("%s is ignored for this class!" % self.name)
        elif not self.multi and isinstance(value, (list, tuple)):
            if len(value) > 1:
                raise ValueError(
                    "%s does not accept multiple values!" % self.name
                )
            return value[0]
        elif self.multi and value is not None:
            if not isinstance(value, (list, tuple)):
                return [value]
        return value
945141
def _get_args_to_parse(args, sys_argv):
    
    arguments = args if args is not None else sys_argv[1:]
    _LOG.debug("Parsing arguments: %s", arguments)
    return arguments
266443
def params(**kwargs):
    

    # Types that we'll all for as 'tuple' params
    TUPLE_TYPES = tuple, set, frozenset, list
    if (sys.version_info > (3, 0)):
        VALID_TYPES = int, float, str, bool
    else:
        VALID_TYPES = int, float, str, unicode, bool

    class ParamValidator(object):
        # name
        param_name = None  # the name of the param in the request, e.g. 'user_id' (even if we pass 'user' to the Fn)

        # type
        param_type = None

        # method - explicitly allow a certain method. If both are false we'll use defaults
        allow_GET = False
        allow_POST = False

        # value validators
        gt = None
        gte = None
        lt = None
        lte = None
        eq = None

        # optional
        optional = False
        default = None

        # multiple vals
        many = False

        # django models only
        deferred = True
        field = 'id'

        def __init__(self, arg_name, **kwargs):
            self.param_name = arg_name
            for k, v in kwargs.items():
                setattr(self, k, v)

        def check_type(self, param):
            """ Check that the type of param is valid, or raise an Exception. This doesn't take self.many into account. """
            valid_type = True
            if isinstance(self.param_type, TUPLE_TYPES):
                if not param in self.param_type:
                    raise Exception('invalid option "%s": Must be one of: %s' % (param, self.param_type))
            else:
                if self.param_type == int:
                    param = int(param)
                elif self.param_type == float:
                    param = float(param)
                elif self.param_type == str:
                    assert(isinstance(param, (str, unicode)))
                    param = unicode(param)
                elif self.param_type == bool:
                    param = str(param).lower()  # bool isn't case sensitive
                    if param in TRUE_VALUES:
                        param = True
                    elif param in FALSE_VALUES:
                        param = False
                    else:
                        raise Exception('%s is not a valid bool: must be one of: %s', param, TRUE_VALUES + FALSE_VALUES)
                elif hasattr(self.param_type, '_default_manager'):  # isinstance(django.models.Model) doesn't seem to work, but this is a good tell
                    query_set = self.param_type.objects
                    if self.deferred:
                        query_set = query_set.only('id')
                    param = query_set.get(**{self.field: param})
                else:
                    valid_type = False
            if not valid_type:
                raise Exception("Invalid param type: %s" % self.param_type.____name__)
            return param

        def check_value(self, param):
            """ Check that a single value is lt/gt/etc. Doesn't take self.many into account. """
            val = None
            if self.param_type == int or self.param_type == float:
                val = param
            elif self.param_type == str:
                val = len(param)
            if val:
                try:
                    if self.eq and val != self.eq:
                        raise Exception("must be less than %s!" % self.eq)
                    else:
                        if self.lt and val >= self.lt:
                            raise Exception("must be less than %s!" % self.lt)
                        if self.lte and val > self.lte:
                            raise Exception("must be less than or equal to %s!" % self.lte)
                        if self.gt and val <= self.gt:
                            raise Exception("must be greater than %s!" % self.gt)
                        if self.gte and val < self.gte:
                            raise Exception("must be greater than or equal to %s!" % self.gte)
                except Exception as e:
                    msg = str(e)
                    msg = ("Length " if self.param_type == str else 'Value ') + msg
                    raise Exception(msg)

    validators = {}

    for k, v in kwargs.items():
        parts = k.split('__')
        param_key = parts[0]

        if not param_key in validators:
            validators[param_key] = ParamValidator(param_key)
        obj = validators[param_key]

        if (len(parts) == 1):
            # set type
            if not hasattr(v, '_default_manager'):  # django model
                if not isinstance(v, TUPLE_TYPES) and not v in VALID_TYPES:
                    raise Exception("Invalid type for %s: %s is not a valid type" % (k, v))
            obj.param_type = v
        else:
            # we only are interested in the last part, since the only thing that can be multipart is __length__eq (etc) and 'length' is not important
            last_part = parts[-1]

            if last_part == 'method':
                if isinstance(v, TUPLE_TYPES):
                    for method in v:
                        if method == 'GET':
                            obj.allow_GET = True
                        elif method == 'POST':
                            obj.allow_POST = True
                        else:
                            raise Exception('Invalid value for __method: "%s"' % method)
                else:
                    if v == 'GET':
                        obj.allow_GET = True
                    elif v == 'POST':
                        obj.allow_POST = True
                    else:
                        raise Exception('Invalid value for __method: "%s"' % v)
                continue

            if last_part == 'name':
                obj.param_name = v
                continue

            BOOL_PARTS = 'deferred', 'optional', 'many'
            if last_part in BOOL_PARTS:
                assert(isinstance(v, bool))
                setattr(obj, last_part, v)
                continue

            NUM_PARTS = 'gt', 'gte', 'lt', 'lte', 'eq'
            if last_part in NUM_PARTS:
                assert(isinstance(v, int) or isinstance(v, float))
                setattr(obj, last_part, v)
                continue

            if last_part == 'default':
                obj.optional = True
                obj.default = v
                continue

            if last_part == 'field':
                assert(isinstance(last_part, str))
                obj.field = v
                continue

            raise Exception("Invalid option: '__%s' in param '%s'" % (last_part, k))

    def _params(fn):

        @wraps(fn)
        def wrapped_request_fn(first_arg, *args, **kwargs):

            if len(args) == 0:
                request = first_arg  # request function is a top-level function
            else:
                request = args[0]  # request fn is a method, first_arg is 'self'

            request_method = request.META['REQUEST_METHOD']
            default_param_method = 'POST' if request_method == 'POST' or request_method == 'PUT' else 'GET'
            # Validate the params
            for arg_name, validator in validators.items():
                param_name = validator.param_name

                # what methods are allowed?
                use_default_methods = not validator.allow_GET and not validator.allow_POST
                allow_GET = (default_param_method == 'GET') if use_default_methods else validator.allow_GET
                allow_POST = (default_param_method == 'POST') if use_default_methods else validator.allow_POST

                # find the param
                param = None
                if allow_POST:
                    param = request.DATA.get(param_name, None)
                    param_type = 'POST'
                if not param and allow_GET:
                    param = request.GET.get(param_name, None)
                    param_type = 'GET'

                try:
                    # optional/default
                    if param is None:  # but not False, because that's a valid boolean param
                        if not validator.optional:
                            raise Exception('Param is missing')
                        else:
                            kwargs[arg_name] = validator.default
                            continue

                    # check type, value
                    if validator.many:
                        if param_type == 'GET':
                            params = str(param).split(',')
                        else:
                            params = param if isinstance(param, list) else (param,)
                        params = [validator.check_type(p) for p in params]
                        [validator.check_value(p) for p in params]
                    else:
                        param = validator.check_type(param)
                        validator.check_value(param)

                except Exception as e:
                    return Response({'error': 'Invalid param "%s": %s' % (param_name, str(e))}, status=status.HTTP_400_BAD_REQUEST)

                kwargs[arg_name] = params if validator.many else param

            return fn(first_arg, *args, **kwargs)
        return wrapped_request_fn
    return _params
211612
def parse(self, *args):
        

        if isinstance(self.dictionary, dict):
            return self.dictionary

        raise self.subparserException("Argument passed to Dictionary SubParser is not a dict: %s" % type(self.dictionary))
1113530
def get_input(params: Union[dict, list]) -> Tuple[list, dict]:
    
    # Backwards compatibility for old clients that send params as a list
    if isinstance(params, list):
        args = params
        kwargs = {}
    elif isinstance(params, dict):
        args = params.pop('*args', [])
        kwargs = params
    else:  # pragma no coverage
        raise TypeError(
            'Unknown type {} of params, must be list or dict'.format(type(params)))

    return args, kwargs
1347078
def parse_input_args(input_args):
        
        input_args = input_args if input_args else {}
        for task, args in input_args.items():
            if not isinstance(task, EOTask):
                raise ValueError('Invalid input argument {}, should be an instance of EOTask'.format(task))

            if not isinstance(args, (tuple, dict)):
                raise ValueError('Execution input arguments of each task should be a dictionary or a tuple, for task '
                                 '{} got arguments of type {}'.format(task.__class__.__name__, type(args)))

        return input_args
1335175
def _parse_parameters(val_type, val):
    
    if val_type == "logical":
        return val == "T"
    elif val_type == "int":
        return int(val)
    elif val_type == "string":
        return val.strip()
    else:
        return float(val)
1353577
def parse_arguments(self, conf):
    
    parsed_arguments_dict = {}
    arguments = self._arguments.arguments

    for arg_name in arguments:
      arg_meta = arguments[arg_name]
      """:type arg_meta ModuleArgumentItem"""
      try:
        if arg_meta.value_type is not None:
          arg = self.__convert_value_to_type(conf.get(arg_name), arg_meta.value_type)
        else:
          arg = conf.get(arg_name)
      except KeyError:
        if arg_meta.default is None:
          raise ArgumentException("Command require \"{}\" argument to be set".format(arg_name))

        # ToDo: check default value passed from user?
        arg = arg_meta.default

      parsed_arguments_dict[arg_name] = arg
    return parsed_arguments_dict
23428
def parseParams(string):
    
    all = params_re.findall(string)
    allParameters = []
    for tup in all:
        paramList = [tup[0]]  # tup looks like (name, valuesString)
        for pair in param_values_re.findall(tup[1]):
            # pair looks like ('', value) or (value, '')
            if pair[0] != '':
                paramList.append(pair[0])
            else:
                paramList.append(pair[1])
        allParameters.append(paramList)
    return allParameters
450592
def __get_types(for_type=None, for_types=None):
        
        if for_type:
            if for_types:
                raise ValueError("Cannot pass both for_type and for_types.")
            for_types = (for_type,)
        elif for_types:
            if not isinstance(for_types, tuple):
                raise TypeError("for_types must be passed as a tuple of "
                                "types (classes).")
        else:
            raise ValueError("Must pass either for_type or for_types.")

        return for_types
1187805
def _parse_args(self, args=None, values=None):
        """"""
        options, arguments = self._parser.parse_args(args, values)
        return self._fix_set_options(options), arguments
406217
def maybe_cast_list(value, types):
    
    if not isinstance(value, list):
        return value

    if type(types) not in (list, tuple):
        types = (types,)

    for list_type in types:
        if issubclass(list_type, list):
            try:
                return list_type(value)
            except (TypeError, ValueError):
                pass
    return value
39424
def parse(self):
        
        standard_formatters = re.compile(r'\((.+?)\)', re.IGNORECASE)
        return standard_formatters.findall(self._fmt)
905809
def types(self):
        
        out = []
        if self._transform_bytes:
            out.append(bytes)
        if self._transform_str:
            out.append(str)
        return tuple(out)
425467
def parse(self, value):
        
        result = {}
        rest = {}
        for k, v in value.iteritems():
            if k in self.fields:
                if (isinstance(v, dict)
                        and not self.fields[k].supports_multiple):
                    if len(v) == 1:
                        # We support "foo.1" as "foo" as long as there is only
                        # one "foo.#" parameter provided.... -_-
                        v = v.values()[0]
                    else:
                        raise InvalidParameterCombinationError(k)
                result[k] = self.fields[k].coerce(v)
            else:
                rest[k] = v
        for k, v in self.fields.iteritems():
            if k not in result:
                result[k] = v.coerce(None)
        if rest:
            raise UnknownParametersError(result, rest)
        return result
1179229
def convert_type(ty, default=None):
    
    if isinstance(ty, tuple):
        return Tuple(ty)
    if isinstance(ty, ParamType):
        return ty
    guessed_type = False
    if ty is None and default is not None:
        ty = type(default)
        guessed_type = True
    if ty is text_type or ty is str or ty is None:
        return STRING
    if ty is int:
        return INT
    # Booleans are only okay if not guessed.  This is done because for
    # flags the default value is actually a bit of a lie in that it
    # indicates which of the flags is the one we want.  See get_default()
    # for more information.
    if ty is bool and not guessed_type:
        return BOOL
    if ty is float:
        return FLOAT
    if guessed_type:
        return STRING

    # Catch a common mistake
    if __debug__:
        try:
            if issubclass(ty, ParamType):
                raise AssertionError('Attempted to use an uninstantiated '
                                     'parameter type (%s).' % ty)
        except TypeError:
            pass
    return FuncParamType(ty)