Pass in the required arguments for a payload, the enc type and the cmd,
    then a list of keyword args to generate the body of the load dict.
425346
def format_payload(enc, **kwargs):
    '''
    
    '''
    payload = {'enc': enc}
    load = {}
    for key in kwargs:
        load[key] = kwargs[key]
    payload['load'] = load
    return package(payload)
87228
def add_command_line_options_argparse(cls, argparser):
        """"""
        import argparse

        class SetParameter(argparse.Action):
            """callback object for ArgumentParser"""

            def __call__(self, parser, namespace, value, option_string=None):
                cls.config[option_string] = value
                if option_string == "--stomp-conf":
                    cls.load_configuration_file(value)

        argparser.add_argument(
            "--stomp-host",
            metavar="HOST",
            default=cls.defaults.get("--stomp-host"),
            help="Stomp broker address, default '%(default)s'",
            type=str,
            action=SetParameter,
        )
        argparser.add_argument(
            "--stomp-port",
            metavar="PORT",
            default=cls.defaults.get("--stomp-port"),
            help="Stomp broker port, default '%(default)s'",
            type=int,
            action=SetParameter,
        )
        argparser.add_argument(
            "--stomp-user",
            metavar="USER",
            default=cls.defaults.get("--stomp-user"),
            help="Stomp user, default '%(default)s'",
            type=str,
            action=SetParameter,
        )
        argparser.add_argument(
            "--stomp-pass",
            metavar="PASS",
            default=cls.defaults.get("--stomp-pass"),
            help="Stomp password",
            type=str,
            action=SetParameter,
        )
        argparser.add_argument(
            "--stomp-prfx",
            metavar="PRE",
            default=cls.defaults.get("--stomp-prfx"),
            help="Stomp namespace prefix, default '%(default)s'",
            type=str,
            action=SetParameter,
        )
        argparser.add_argument(
            "--stomp-conf",
            metavar="CNF",
            default=cls.defaults.get("--stomp-conf"),
            help="Stomp configuration file containing connection information, disables default values",
            type=str,
            action=SetParameter,
        )
335393
def argv(self, module, argv=sys.argv[1:]):
        '''
        
        '''
        kwargs = {'enabled': False}
        last_priority = {}
        parser = argparse.ArgumentParser(add_help=False)
        # Hack: This allows the ListActionParser class to correllate short options to long options.
        # There is probably a built-in way to do this in the
        # argparse.ArgumentParser class?
        parser.short_to_long = {}

        # Must build arguments from all modules so that:
        #
        #    1) Any conflicting arguments will raise an exception
        #    2) The only unknown arguments will be the target files, making them
        #       easy to identify
        for m in self.list(attribute="CLI"):

            for module_option in m.CLI:

                parser_args = []
                parser_kwargs = {}

                if not module_option.long:
                    continue

                if module_option.short:
                    parser_args.append('-' + module_option.short)
                parser_args.append('--' + module_option.long)
                parser_kwargs['dest'] = module_option.long

                if module_option.type is None:
                    parser_kwargs['action'] = 'store_true'
                elif module_option.type is list:
                    parser_kwargs['action'] = 'append'
                    parser.short_to_long[
                        module_option.short] = module_option.long

                parser.add_argument(*parser_args, **parser_kwargs)

        args, unknown = parser.parse_known_args(argv)
        args = args.__dict__

        # Only add parsed options pertinent to the requested module
        for module_option in module.CLI:

            if module_option.type == binwalk.core.common.BlockFile:

                for k in get_keys(module_option.kwargs):
                    kwargs[k] = []
                    for unk in unknown:
                        kwargs[k].append(unk)

            elif has_key(args, module_option.long) and args[module_option.long] not in [None, False]:

                # Loop through all the kwargs for this command line option
                for (name, default_value) in iterator(module_option.kwargs):

                    # If this kwarg has not been previously processed, or if its priority is equal to or
                    # greater than the previously processed kwarg's priority,
                    # then let's process it.
                    if not has_key(last_priority, name) or last_priority[name] <= module_option.priority:

                        # Track the priority for future iterations that may
                        # process the same kwarg name
                        last_priority[name] = module_option.priority

                        try:
                            kwargs[name] = module_option.convert(args[module_option.long], default_value)
                        except KeyboardInterrupt as e:
                            raise e
                        except Exception as e:
                            raise ModuleException("Invalid usage: %s" % str(e))

        binwalk.core.common.debug("%s :: %s => %s" % (module.TITLE, str(argv), str(kwargs)))
        return kwargs
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
1017336
def get_args(cls, dist, header=None):
        
        if header is None:
            header = cls.get_header()
        spec = str(dist.as_requirement())
        for type_ in 'console', 'gui':
            group = type_ + '_scripts'
            for name, ep in dist.get_entry_map(group).items():
                cls._ensure_safe_name(name)
                script_text = cls.template % locals()
                args = cls._get_script_args(type_, name, header, script_text)
                for res in args:
                    yield res
1001418
def shell(_parser, cmd, args):  # pragma: no cover
    

    parser = argparse.ArgumentParser(
        prog=_parser.prog,
        description=_parser.description,
    )

    group = parser.add_mutually_exclusive_group()
    group.set_defaults(shell=have_bpython and 'bpython' or (have_IPython and 'ipython' or 'python'))
    if have_bpython:
        group.add_argument(
            '--bpython',
            action='store_const',
            dest='shell',
            const='bpython',
            help='Use the bpython interpreter'
        )
    if have_IPython:
        group.add_argument(
            '--ipython',
            action='store_const',
            dest='shell',
            const='ipython',
            help='Use the IPython interpreter'
        )
    group.add_argument(
        '--python',
        action='store_const',
        dest='shell',
        const='python',
        help='Use the default python interpreter'
    )

    args = parser.parse_args(args)

    import pwny
    pwny_locals = dict(
        (key, getattr(pwny, key))
        for key in dir(pwny)
        if not key.startswith('__') and not key == 'shell'
    )

    if args.shell == 'bpython':
        from bpython import embed
        embed(pwny_locals, banner=BANNER)
    elif args.shell == 'ipython':
        from IPython import start_ipython
        start_ipython(
            argv=['--ext=pwnypack.ipython_ext'],
        )
    else:
        import code
        code.interact(BANNER, local=pwny_locals)
318341
def build_payload(cls, method, args):
        
        ref = str(uuid.uuid4())
        return (method, args, ref)
325500
def parse_cmdline_args(args, classes):
    
    if args is None:
        raise ValueError("args must not be None")
    parsed_args = {}
    for kls in classes:
        prefix = kls.configuration_key_prefix()
        name = kls.configuration_key
        if getattr(args, "%s_%s" % (prefix, name), False):
            logging.debug(
                "Gathering initargs for '%s.%s'", prefix, name)
            initargs = {}
            for arg_name in kls.init_argnames():
                val = getattr(args, "%s_%s_%s" %
                              (prefix, name, arg_name))
                if val is not None:
                    initargs[arg_name] = val
            if prefix not in parsed_args:
                parsed_args[prefix] = []
            parsed_args[prefix].append((name, initargs))
    return parsed_args
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)
994793
def generate_payload(self):
        
        events = []
        transformation_task = self._get_alias_transformation_properties()
        transformation_task.update(self._get_based_properties())
        events.append(transformation_task)

        for exception in self.exceptions:
            properties = {
                'Reserved.DataModel.Fault.TypeString': exception.__class__.__name__,
                'Reserved.DataModel.Fault.Exception.Message': self.get_exception_message(exception),
                'Reserved.DataModel.Fault.Exception.StackTrace': _get_stack_trace(),
            }
            self.set_custom_properties(properties, 'ActionType', 'Exception')
            self.set_custom_properties(properties, 'Version', VERSION)
            events.append(properties)

        return events
380767
def load_cli_args(self):
        
        parser = argparse.ArgumentParser(description='QTPyLib Reporting',
                                         formatter_class=argparse.ArgumentDefaultsHelpFormatter)

        parser.add_argument('--port', default=self.args["port"],
                            help='HTTP port to use', type=int)
        parser.add_argument('--host', default=self.args["host"],
                            help='Host to bind the http process to')
        parser.add_argument('--blotter',
                            help='Use this Blotter\'s MySQL server settings')
        parser.add_argument('--nopass',
                            help='Skip password for web app (flag)',
                            action='store_true')

        # only return non-default cmd line args
        # (meaning only those actually given)
        cmd_args, _ = parser.parse_known_args()
        args = {arg: val for arg, val in vars(
            cmd_args).items() if val != parser.get_default(arg)}
        return args
25823
def use_args(
        self,
        argmap: ArgMap,
        req: typing.Optional[Request] = None,
        locations: typing.Iterable = None,
        as_kwargs: bool = False,
        validate: Validate = None,
        error_status_code: typing.Optional[int] = None,
        error_headers: typing.Union[typing.Mapping[str, str], None] = None,
    ) -> typing.Callable[..., typing.Callable]:
        
        locations = locations or self.locations
        request_obj = req
        # Optimization: If argmap is passed as a dictionary, we only need
        # to generate a Schema once
        if isinstance(argmap, Mapping):
            argmap = core.dict2schema(argmap, self.schema_class)()

        def decorator(func: typing.Callable) -> typing.Callable:
            req_ = request_obj

            if inspect.iscoroutinefunction(func):

                @functools.wraps(func)
                async def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = await self.parse(
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args or {})
                        return await func(*args, **kwargs)
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return await func(*new_args, **kwargs)

            else:

                @functools.wraps(func)  # type: ignore
                def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = yield from self.parse(  # type: ignore
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args)
                        return func(*args, **kwargs)  # noqa: B901
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return func(*new_args, **kwargs)

            return wrapper

        return decorator
336706
def params(self):
        
        payload = self.payload
        d = {}
        for i, p in enumerate(payload["currentConfiguration"]):
            type_name = p["typeName"]
            cp = payload["configurationParameters"][i]["message"]
            name = cp["parameterName"]
            if type_name == "BTMParameterQuantity":
                try:
                    v = q(p["message"]["expression"])
                except:
                    v = q(p["message"]["value"], p["message"]["units"])
            elif type_name == "BTMParameterBoolean":
                v = p["message"]["value"]
            elif type_name == "BTMParameterEnum":
                enum = p["message"]["value"]
                enum_map = {d['message']['option']: i for i, d in enumerate(cp['options'])}
                v = cp['options'][enum_map[enum]]['message']['optionName']
            d[name] = v
        return d
278092
def generate_payload(self, config, context):
        
        from flask import current_app, session, request as _request

        current_view = current_app.view_functions[_request.endpoint]
        if hasattr(current_view, 'view_class'):
            component = '.'.join((current_view.__module__, current_view.view_class.__name__))
        else:
            component = current_view.__module__
        cgi_data = {
            k: v
            for k, v in iteritems(_request.headers)
        }
        cgi_data.update({
            'REQUEST_METHOD': _request.method
        })
        payload = {
            'url': _request.base_url,
            'component': component,
            'action': _request.endpoint,
            'params': {},
            'session': filter_dict(dict(session), config.params_filters),
            'cgi_data': cgi_data,
            'context': context
        }

        # Add query params
        params = filter_dict(dict(_request.args), config.params_filters)
        params.update(filter_dict(dict(_request.form), config.params_filters))

        payload['params'] = params

        return payload
649857
def make_argparser():
    """"""

    if PY2:
        def unicode_arg(val):
            return val.decode(sys.getfilesystemencoding() or 'utf8')
    else:
        unicode_arg = str

    # Generic options
    p_main = ArgumentParser()
    generic = p_main.add_argument_group("generic arguments")
    generic.add_argument("-q", "--quiet",
                         action='store_true', dest='quiet', default=False,
                         help="silence information messages")
    generic.add_argument("-f", "--force",
                         action='store_true', dest='force', default=False,
                         help="Kill connections automatically if they prevent a command from executing. "
                              "Rename existing databases that are in the way.")
    generic.add_argument("--traceback", action='store_true', default=False,
                         help="print traceback when an error occurs")
    generic.add_argument("--host", metavar="HOST",
                         help="hostname of database server")
    generic.add_argument("-p", "--port", metavar="PORT", type=int,
                         help="port number of database server")

    sub = p_main.add_subparsers(metavar="COMMAND", dest='cmd')

    p_cp = sub.add_parser('cp', description=cmd_copy.__doc__,
                          help="Create a copy of a database within a server")
    p_mv = sub.add_parser('mv', description=cmd_move.__doc__,
                          help="Rename a database within a server")

    for p_cmd in (p_cp, p_mv):
        p_cmd.add_argument('src', metavar="SOURCE", type=unicode_arg,
                           help="source database name")
        p_cmd.add_argument('dest', metavar="DEST", type=unicode_arg,
                           help="destination database name")
        p_cmd.add_argument("--no-backup",
                           action='store_true', dest='no_backup', default=False,
                           help="drop existing DEST database if it exists")

    p_kill = sub.add_parser('kill', description=cmd_kill.__doc__,
                            help="Terminate active connections to a database")
    p_kill.add_argument('databases', metavar="DBNAME", type=unicode_arg, nargs='+',
                        help="kill connections on this database")

    p_reindex = sub.add_parser('reindex', description=cmd_reindex.__doc__,
                               help="Gracefully recreate an index")
    p_reindex.add_argument('-d', '--database', metavar="DB", type=unicode_arg,
                           help="apply reindex in this database")
    p_reindex.add_argument('indexes', metavar="IDXNAME", type=unicode_arg, nargs='+',
                           help="reindex these indexes")

    return p_main
979266
def _body_builder(self, kwargs):
        
        p = {
            'action_name': self.name,
            'service_type': self.service_type,
            'arguments': '',
            }
        if kwargs:
            arguments = [
                self.argument_template % {'name': k, 'value': v}
                for k, v in kwargs.items()
            ]
            p['arguments'] = ''.join(arguments)
        body = self.body_template.strip() % p
        return body
1316136
def add_arguments(cls, subparsers, dirs):
        
        parser = subparsers.add_parser(
            'packet',
            help='Packet Bare Metal',
            formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120))

        m = parser.add_argument_group('Mandatory Packet Parameters') # pylint: disable=invalid-name

        g = m.add_mutually_exclusive_group(required=False) # pylint: disable=invalid-name
        g.add_argument('-create-demand',
                       action='store_true',
                       help='Create an on demand based bare metal device instance.')

        g.add_argument('-create-spot',
                       action='store_true',
                       help='Create a spot price based bare metal device instance.')

        g.add_argument('-reboot',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Reboot active instances.')

        g.add_argument('-stop',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Stop active instances.')

        g.add_argument('-terminate',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Terminate active instances.')

        o = parser.add_argument_group('Optional Parameters') # pylint: disable=invalid-name
        o.add_argument('-create-volume',
                       nargs='+',
                       type=str,
                       metavar='s',
                       help='Create storage: <plan> <size> <region> <description>')

        o.add_argument('-conf',
                       metavar='path',
                       type=argparse.FileType(),
                       default=os.path.join(dirs.user_config_dir, 'examples', 'packet', 'packet.json'),
                       help='Packet configuration')

        o.add_argument('-list-projects',
                       action='store_true',
                       help='List available projects.')

        o.add_argument('-list-plans',
                       action='store_true',
                       help='List available plans.')

        o.add_argument('-list-operating-systems',
                       action='store_true',
                       help='List available operating systems.')

        o.add_argument('-list-spot-prices',
                       action='store_true',
                       help='List spot prices.')

        o.add_argument('-list-facilities',
                       action='store_true',
                       help='List available facilities.')

        o.add_argument('-list-devices',
                       action='store_true',
                       help='List devices under given project name.')

        o.add_argument('-project',
                       metavar='project',
                       type=str,
                       default='fuzzing',
                       help='The project to perform operations on.')
        o.add_argument('-tags',
                       metavar='seq',
                       nargs='+',
                       type=str,
                       help='Tags associated with the instance.')
        o.add_argument('-region',
                       metavar='region',
                       type=str,
                       default='nrt1',
                       help='The facility in which the instance is going to run.')
        o.add_argument('-os',
                       metavar='name',
                       type=str,
                       default='ubuntu_18_04',
                       help='The operating system for the created instance.')
        o.add_argument('-plan',
                       metavar='name',
                       type=str,
                       default='baremetal_0',
                       help='The instance type to run.')
        o.add_argument('-max-spot-price',
                       metavar='#',
                       type=float,
                       default='0.05',
                       help='Max price for spot instances.')
        o.add_argument('-count',
                       metavar='#',
                       type=int,
                       default='1',
                       help='The amount of devices to be spawned.')
        o.add_argument('-only',
                       metavar='k=v',
                       nargs='+',
                       type=str,
                       help='Filter instances by criterias.')
        o.add_argument('-version',
                       action='version',
                       version='%(prog)s {}'.format(cls.VERSION),
                       help=argparse.SUPPRESS)