Decorator for client code's main function.
  Serializes argparse data to JSON for use with the Gooey front end
775134
def Gooey(f=None,
          advanced=True,
          language='english',
          auto_start=False,  # TODO: add this to the docs. Used to be `show_config=True`
          target=None,
          program_name=None,
          program_description=None,
          default_size=(610, 530),
          use_legacy_titles=True,
          required_cols=2,
          optional_cols=2,
          dump_build_config=False,
          load_build_config=None,
          monospace_display=False,  # TODO: add this to the docs
          image_dir='::gooey/default',
          language_dir=getResourcePath('languages'),
          progress_regex=None,  # TODO: add this to the docs
          progress_expr=None,  # TODO: add this to the docs
          disable_progress_bar_animation=False,
          disable_stop_button=False,
          group_by_type=True,
          header_height=80,
          navigation='SIDEBAR', # TODO: add this to the docs
          tabbed_groups=False,
          **kwargs):
  '''
  
  '''

  params = merge(locals(), locals()['kwargs'])

  def build(payload):
    def run_gooey(self, args=None, namespace=None):
      source_path = sys.argv[0]

      build_spec = None
      if load_build_config:
        try:
          build_spec = json.load(open(load_build_config, "r"))
        except Exception as e:
          print( 'Exception loading Build Config from {0}: {1}'.format(load_build_config, e))
          sys.exit(1)

      if not build_spec:
        build_spec = config_generator.create_from_parser(
          self,
          source_path,
          payload_name=payload.__name__,
          **params)

      if dump_build_config:
        config_path = os.path.join(os.getcwd(), 'gooey_config.json')
        print('Writing Build Config to: {}'.format(config_path))
        with open(config_path, 'w') as f:
          f.write(json.dumps(build_spec, indent=2))
      application.run(build_spec)

    def inner2(*args, **kwargs):
      ArgumentParser.original_parse_args = ArgumentParser.parse_args
      ArgumentParser.parse_args = run_gooey
      return payload(*args, **kwargs)

    inner2.__name__ = payload.__name__
    return inner2

  def run_without_gooey(func):
    return lambda: func()

  if IGNORE_COMMAND in sys.argv:
    sys.argv.remove(IGNORE_COMMAND)
    if callable(f):
      return run_without_gooey(f)
    return run_without_gooey

  if callable(f):
    return build(f)
  return build
723748
def main(**kwargs):
    
    manifest = []

    print_intro(API_VERSION)

    if args.json_file is not None:
        with open(args.json_file, 'r') as json_file:
            app_json = json.loads(json_file.read())
            # Re-confirm the name
            name = get_name(default=args.name or app_json.get('name'))
            app_json['name'] = name
            version = get_version(default=app_json.get('version'))
            app_json['version'] = version
        try:
            os.mkdir(app_json['name'])
        except:
            sys.stderr.write(fill('''Unable to create a directory for %s, please check that it is a valid app name and the working directory exists and is writable.''' % app_json['name']) + '\n')
            sys.exit(1)
    else:
        ##################
        # BASIC METADATA #
        ##################

        name = get_name(default=args.name)

        try:
            os.mkdir(name)
        except:
            sys.stderr.write(fill('''Unable to create a directory for %s, please check that it is a valid app name and the working directory exists and is writable.''' % name) + '\n')
            sys.exit(1)

        title, summary = get_metadata(API_VERSION)

        version = get_version()

        app_json = OrderedDict()
        app_json["name"] = name

        app_json["title"] = title or name
        app_json['summary'] = summary or name

        app_json["dxapi"] = API_VERSION
        app_json["version"] = version

        ############
        # IO SPECS #
        ############

        class_completer = Completer(['int', 'float', 'string', 'boolean', 'hash',
                                     'array:int', 'array:float', 'array:string', 'array:boolean',
                                     'record', 'file', 'applet',
                                     'array:record', 'array:file', 'array:applet'])
        bool_completer = Completer(['true', 'false'])

        print('')
        print(BOLD() + 'Input Specification' + ENDC())
        print('')

        input_spec = True
        input_names = []
        printed_classes = False

        if input_spec:
            app_json['inputSpec'] = []
            print(fill('You will now be prompted for each input parameter to your app.  Each parameter should have a unique name that uses only the underscore "_" and alphanumeric characters, and does not start with a number.'))

            while True:
                print('')
                ordinal = get_ordinal_str(len(app_json['inputSpec']) + 1)
                input_name = prompt_for_var(ordinal + ' input name (<ENTER> to finish)', allow_empty=True)
                if input_name == '':
                    break
                if input_name in input_names:
                    print(fill('Error: Cannot use the same input parameter name twice.  Please choose again.'))
                    continue
                if not IO_NAME_PATTERN.match(input_name):
                    print(fill('Error: Parameter names may use only underscore "_", ASCII letters, and digits; and may not start with a digit.  Please choose again.'))
                    continue
                input_names.append(input_name)

                input_label = prompt_for_var('Label (optional human-readable name)', '')

                use_completer(class_completer)
                if not printed_classes:
                    print('Your input parameter must be of one of the following classes:')
                    print('''applet         array:file     array:record   file           int
array:applet   array:float    array:string   float          record
array:boolean  array:int      boolean        hash           string
''')
                    printed_classes = True

                while True:
                    input_class = prompt_for_var('Choose a class (<TAB> twice for choices)')
                    if input_class in class_completer.choices:
                        break
                    else:
                        print(fill('Not a recognized class; please choose again.'))

                use_completer()

                optional = prompt_for_yn('This is an optional parameter')

                default_val = None
                if optional and input_class in ['int', 'float', 'string', 'boolean']:
                    default_val = prompt_for_yn('A default value should be provided')
                    if default_val:
                        while True:
                            if input_class == 'boolean':
                                use_completer(bool_completer)
                                default_val = prompt_for_var('  Default value', choices=['true', 'false'])
                                use_completer()
                            elif input_class == 'string':
                                default_val = prompt_for_var('  Default value', allow_empty=True)
                            else:
                                default_val = prompt_for_var('  Default value')

                            try:
                                if input_class == 'boolean':
                                    default_val = (default_val == 'true')
                                elif input_class == 'int':
                                    default_val = int(default_val)
                                elif input_class == 'float':
                                    default_val = float(default_val)
                                break
                            except:
                                print('Not a valid default value for the given class ' + input_class)
                    else:
                        default_val = None

                # Fill in the input parameter's JSON
                parameter_json = OrderedDict()

                parameter_json["name"] = input_name
                if input_label != '':
                    parameter_json['label'] = input_label
                parameter_json["class"] = input_class
                parameter_json["optional"] = optional
                if default_val is not None:
                    parameter_json['default'] = default_val

                # Fill in patterns and blank help string
                if input_class == 'file' or input_class == 'array:file':
                    parameter_json["patterns"] = ["*"]
                parameter_json["help"] = ""

                app_json['inputSpec'].append(parameter_json)

        print('')
        print(BOLD() + 'Output Specification' + ENDC())
        print('')

        output_spec = True
        output_names = []
        if output_spec:
            app_json['outputSpec'] = []
            print(fill('You will now be prompted for each output parameter of your app.  Each parameter should have a unique name that uses only the underscore "_" and alphanumeric characters, and does not start with a number.'))

            while True:
                print('')
                ordinal = get_ordinal_str(len(app_json['outputSpec']) + 1)
                output_name = prompt_for_var(ordinal + ' output name (<ENTER> to finish)', allow_empty=True)
                if output_name == '':
                    break
                if output_name in output_names:
                    print(fill('Error: Cannot use the same output parameter name twice.  Please choose again.'))
                    continue
                if not IO_NAME_PATTERN.match(output_name):
                    print(fill('Error: Parameter names may use only underscore "_", ASCII letters, and digits; and may not start with a digit.  Please choose again.'))
                    continue
                output_names.append(output_name)

                output_label = prompt_for_var('Label (optional human-readable name)', '')

                use_completer(class_completer)
                if not printed_classes:
                    print('Your output parameter must be of one of the following classes:')
                    print('''applet         array:file     array:record   file           int
array:applet   array:float    array:string   float          record
array:boolean  array:int      boolean        hash           string''')
                    printed_classes = True
                while True:
                    output_class = prompt_for_var('Choose a class (<TAB> twice for choices)')
                    if output_class in class_completer.choices:
                        break
                    else:
                        print(fill('Not a recognized class; please choose again.'))

                use_completer()

                # Fill in the output parameter's JSON
                parameter_json = OrderedDict()
                parameter_json["name"] = output_name
                if output_label != '':
                    parameter_json['label'] = output_label
                parameter_json["class"] = output_class

                # Fill in patterns and blank help string
                if output_class == 'file' or output_class == 'array:file':
                    parameter_json["patterns"] = ["*"]
                parameter_json["help"] = ""

                app_json['outputSpec'].append(parameter_json)

    required_file_input_names = []
    optional_file_input_names = []
    required_file_array_input_names = []
    optional_file_array_input_names = []
    file_output_names = []

    if 'inputSpec' in app_json:
        for param in app_json['inputSpec']:
            may_be_missing = param['optional'] and "default" not in param
            if param['class'] == 'file':
                param_list = optional_file_input_names if may_be_missing else required_file_input_names
            elif param['class'] == 'array:file':
                param_list = optional_file_array_input_names if may_be_missing else required_file_array_input_names
            else:
                param_list = None
            if param_list is not None:
                param_list.append(param['name'])

    if 'outputSpec' in app_json:
        file_output_names = [param['name'] for param in app_json['outputSpec'] if param['class'] == 'file']

    ##################
    # TIMEOUT POLICY #
    ##################

    print('')
    print(BOLD() + 'Timeout Policy' + ENDC())
    app_json["runSpec"] = OrderedDict({})
    app_json['runSpec'].setdefault('timeoutPolicy', {})

    timeout, timeout_units = get_timeout(default=app_json['runSpec']['timeoutPolicy'].get('*'))

    app_json['runSpec']['timeoutPolicy'].setdefault('*', {})
    app_json['runSpec']['timeoutPolicy']['*'].setdefault(timeout_units, timeout)

    ########################
    # LANGUAGE AND PATTERN #
    ########################

    print('')
    print(BOLD() + 'Template Options' + ENDC())

    # Prompt for programming language if not specified

    language = args.language if args.language is not None else get_language()

    interpreter = language_options[language].get_interpreter()
    app_json["runSpec"]["interpreter"] = interpreter

    # Prompt the execution pattern iff the args.pattern is provided and invalid

    template_dir = os.path.join(os.path.dirname(dxpy.__file__), 'templating', 'templates', language_options[language].get_path())
    if not os.path.isdir(os.path.join(template_dir, args.template)):
        print(fill('The execution pattern "' + args.template + '" is not available for your programming language.'))
        pattern = get_pattern(template_dir)
    else:
        pattern = args.template
    template_dir = os.path.join(template_dir, pattern)

    with open(os.path.join(template_dir, 'dxapp.json'), 'r') as template_app_json_file:
        file_text = fill_in_name_and_ver(template_app_json_file.read(), name, version)
        template_app_json = json.loads(file_text)
        for key in template_app_json['runSpec']:
            app_json['runSpec'][key] = template_app_json['runSpec'][key]

    if (language == args.language) and (pattern == args.template):
        print('All template options are supplied in the arguments.')

    ##########################
    # APP ACCESS PERMISSIONS #
    ##########################

    print('')
    print(BOLD('Access Permissions'))
    print(fill('''If you request these extra permissions for your app, users will see this fact when launching your app, and certain other restrictions will apply. For more information, see ''' +
    BOLD('https://wiki.dnanexus.com/App-Permissions') + '.'))

    print('')
    print(fill(UNDERLINE('Access to the Internet') + ' (other than accessing the DNAnexus API).'))
    if prompt_for_yn("Will this app need access to the Internet?", default=False):
        app_json.setdefault('access', {})
        app_json['access']['network'] = ['*']
        print(fill('App has full access to the Internet. To narrow access to specific sites, edit the ' +
                   UNDERLINE('access.network') + ' field of dxapp.json once we generate the app.'))

    print('')
    print(fill(UNDERLINE('Direct access to the parent project') + '''. This is not needed if your app specifies outputs,
    which will be copied into the project after it's done running.'''))
    if prompt_for_yn("Will this app need access to the parent project?", default=False):
        app_json.setdefault('access', {})
        app_json['access']['project'] = 'CONTRIBUTE'
        print(fill('App has CONTRIBUTE access to the parent project. To change the access level or request access to ' +
                   'other projects, edit the ' + UNDERLINE('access.project') + ' and ' + UNDERLINE('access.allProjects') +
                   ' fields of dxapp.json once we generate the app.'))

    #######################
    # SYSTEM REQUIREMENTS #
    #######################

    print('')
    print(BOLD('System Requirements'))
    print('')
    print(BOLD('Common AWS instance types:'))
    print(format_table(InstanceTypesCompleter.aws_preferred_instance_types.values(),
                       column_names=list(InstanceTypesCompleter.instance_types.values())[0]._fields))
    print(BOLD('Common Azure instance types:'))
    print(format_table(InstanceTypesCompleter.azure_preferred_instance_types.values(),
                       column_names=list(InstanceTypesCompleter.instance_types.values())[0]._fields))
    print(fill(BOLD('Default instance type:') + ' The instance type you select here will apply to all entry points in ' +
               'your app unless you override it. See ' +
               BOLD('https://wiki.dnanexus.com/API-Specification-v1.0.0/Instance-Types') + ' for more information.'))
    use_completer(InstanceTypesCompleter())
    instance_type = prompt_for_var('Choose an instance type for your app',
                                   default=InstanceTypesCompleter.default_instance_type.Name,
                                   choices=list(InstanceTypesCompleter.instance_types))

    target_region = DEFAULT_REGION_AWS
    if instance_type in InstanceTypesCompleter.azure_preferred_instance_types.keys():
        target_region = DEFAULT_REGION_AZURE

    app_json['regionalOptions'] = OrderedDict({})
    app_json['regionalOptions'][target_region] = OrderedDict({})
    app_json['regionalOptions'][target_region].setdefault('systemRequirements', {})
    app_json['regionalOptions'][target_region]['systemRequirements'].setdefault('*', {})
    app_json['regionalOptions'][target_region]['systemRequirements']['*']['instanceType'] = instance_type

    ######################
    # HARDCODED DEFAULTS #
    ######################

    app_json['runSpec']['distribution'] = 'Ubuntu'
    app_json['runSpec']['release'] = '16.04'

    #################
    # WRITING FILES #
    #################

    print('')
    print(BOLD() + '*** Generating ' + DNANEXUS_LOGO() + BOLD() + ' App Template... ***' + ENDC())

    with open(os.path.join(name, 'dxapp.json'), 'w') as prog_file:
        prog_file.write(clean(json.dumps(app_json, indent=2)) + '\n')
    manifest.append(os.path.join(name, 'dxapp.json'))

    print('')
    print(fill('''Your app specification has been written to the
dxapp.json file. You can specify more app options by editing this file
directly (see https://wiki.dnanexus.com/Developer-Portal for complete
documentation).''' + ('''  Note that without an input and output specification,
your app can only be built as an APPLET on the system.  To publish it to
the DNAnexus community, you must first specify your inputs and outputs.
''' if not ('inputSpec' in app_json and 'outputSpec' in app_json) else "")))
    print('')

    for subdir in 'src', 'test', 'resources':
        try:
            os.mkdir(os.path.join(name, subdir))
            manifest.append(os.path.join(name, subdir, ''))
        except:
            sys.stderr.write("Unable to create subdirectory %s/%s" % (name, subdir))
            sys.exit(1)

    entry_points = ['main']

    if pattern == 'parallelized':
        entry_points = ['main', 'process', 'postprocess']
    elif pattern == 'scatter-process-gather':
        entry_points = ['main', 'scatter', 'map', 'process', 'postprocess']

    manifest += create_files_from_templates(template_dir, app_json, language,
                                            required_file_input_names, optional_file_input_names,
                                            required_file_array_input_names, optional_file_array_input_names,
                                            file_output_names, pattern,
                                            description='<!-- Insert a description of your app here -->',
                                            entry_points=entry_points)

    print("Created files:")
    for filename in sorted(manifest):
        print("\t", filename)
    print("\n" + fill('''App directory created!  See
https://wiki.dnanexus.com/Developer-Portal for tutorials on how to modify these files,
or run "dx build {n}" or "dx build --create-app {n}" while logged in with dx.'''.format(n=name)) + "\n")
    print(fill('''Running the DNAnexus build utility will create an executable on the DNAnexus platform.  Any files found in the ''' +
            BOLD() + 'resources' + ENDC() +
            ''' directory will be uploaded so that they will be present in the root directory when the executable is run.'''))
979928
def get_args(self, client):
        
        default_args = self.default_args(client)

        if self.method_args or self.optional_args:
            optional_args = getattr(self, 'optional_args', tuple())
            args = []
            for arg in (self.method_args + optional_args):
                if hasattr(self, arg):
                    obj = getattr(self, arg)
                    if hasattr(obj, 'struct'):
                        args.append(obj.struct)
                    else:
                        args.append(obj)
            args = list(default_args) + args
        else:
            args = default_args

        return args
433218
def _apply_args_to_func(global_args, func):
    
    global_args = vars(global_args)
    local_args = dict()
    for argument in inspect.getargspec(func).args:
        local_args[argument] = global_args[argument]
    return func(**local_args)
1246032
function serializeCallback(args) {
  var callback;

  debug('Transforming callback in ', args);

  return args.map(function(arg) {
    if (typeof arg !== 'function') return arg;

    // It shouldn't be an argument after the callback function
    invariant(!callback, 'Only one callback function is allowed.');

    callback = arg;

    return '__clientCallback__';
  });
}
929425
def json_input(f):
    

    @wraps(f)
    def json_input_decorator(*args, **kwargs):
        # If the data is already transformed, we do not transform it any
        # further.
        task_data = _get_data_from_args(args)

        if task_data is None:
            logging.error("Task data is empty during JSON decoding.")

        if task_data.payload:
            try:
                is_transformed = request.get_json()

                # We transform the data only in the case of plain POST requests.
                if not is_transformed:
                    task_data.transform_payload(json.loads)
            except (ValueError, RuntimeError):
                logging.error(
                    "Exception while processing JSON input decorator.")
                task_data.transform_payload(json.loads)
        else:
            task_data.transform_payload(lambda _: {})

        return f(*args, **kwargs)

    return json_input_decorator
1326815
def render_as_json(func):
    
    if inspect.isclass(func):
        setattr(func, "_renderer", json_renderer)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, jsonify)
        return decorated_view
1040492
def main():
    
    parser = argparse.ArgumentParser(description='Wrapper for obographs assocmodel library'
                                                 """
                                                 By default, ontologies and assocs are cached locally and synced from a remote sparql endpoint
                                                 """,
                                     formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('-r', '--resource', type=str, required=False,
                        help='Name of ontology')
    parser.add_argument('-f', '--file', type=str, required=False,
                        help='Name of input file for associations - currently GAF is assumed')
    parser.add_argument('-F', '--format', type=str, required=False,
                        help='Format of assoc file. One of GAF, GPAD or HPOA')
    parser.add_argument('-o', '--outfile', type=str, required=False,
                        help='Path to output file')
    parser.add_argument("--report-md", type=str, required=False, dest="report_md",
                        help="Path to report markdown file")
    parser.add_argument("--report-json", type=str, required=False, dest="report_json",
                        help="Path to report JSON file")
    parser.add_argument('-t', '--to', type=str, required=False,
                        help='Output to (tree, dot, ...)')
    parser.add_argument("--filter-out", nargs="+", required=False, default=[], metavar="EVIDENCE",
                        help="List of any evidence codes to filter out of the GAF. E.G. --filter-out IEA IMP")
    parser.add_argument("--filtered-file", required=False, default=None, metavar="FILTERED_FILE",
                        help="File to write the filtered out evidence GAF to")
    parser.add_argument('-T', '--taxon', nargs='*', required=False,
                        help='valid taxon (NCBITaxon ID) - validate against this')
    parser.add_argument('--subject_prefix', nargs='*', required=False,
                        help='E.g PomBase - validate against this')
    parser.add_argument('--object_prefix', nargs='*', required=False,
                        help='E.g GO - validate against this')
    parser.add_argument('-v', '--verbosity', default=0, action='count',
                        help='Increase output verbosity')


    subparsers = parser.add_subparsers(dest='subcommand', help='sub-command help')

    parser_n = subparsers.add_parser('validate', help='Validate associations')
    parser_n.set_defaults(function=validate_assocs)

    parser_n = subparsers.add_parser('filter', help='Filter associations')
    parser_n.set_defaults(function=filter_assocs)

    parser_n = subparsers.add_parser('convert', help='Convert associations')
    parser_n.set_defaults(function=convert_assocs)
    parser_n.add_argument('-t', '--to', type=str, required=True,
                          help='Format to convert to')

    parser_n = subparsers.add_parser('map2slim', help='Map to a subset/slim')
    parser_n.set_defaults(function=map2slim)
    parser_n.add_argument('-p', '--properties', nargs='*', type=str, default=['subClassOf', 'BFO:0000050'],
                          help='Properties')
    parser_n.add_argument('-s', '--subset', type=str, required=True,
                          help='subset (e.g. map2slim)')

    args = parser.parse_args()

    if args.verbosity >= 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.WARNING)

    logging.info("Welcome!")

    handle = args.resource

    # Ontology Factory
    ofactory = OntologyFactory()
    logging.info("Creating ont object from: {} {}".format(handle, ofactory))
    ont = ofactory.create(handle)
    logging.info("ont: {}".format(ont))

    func = args.function

    # Upper case all evidence codes
    args.filter_out = [code.upper() for code in args.filter_out]

    # set configuration
    filtered_evidence_file = open(args.filtered_file, "w") if args.filtered_file else None
    config = assocparser.AssocParserConfig(
        valid_taxa=args.taxon,
        ontology=ont,
        class_idspaces=args.object_prefix,
        entity_idspaces=args.subject_prefix,
        filter_out_evidence=args.filter_out,
        filtered_evidence_file=filtered_evidence_file
    )
    p = None
    fmt = None
    if args.format is None:
        fmt = 'gaf'
    else:
        fmt = args.format.lower()

    # TODO: use a factory
    if fmt == 'gaf':
        p = GafParser(dataset=args.file)
    elif fmt == 'gpad':
        p = GpadParser()
    elif fmt == 'hpoa':
        p = HpoaParser()
    elif fmt == "gpi":
        p = entityparser.GpiParser()
        func = validate_entity

    p.config = config

    outfh = None
    if args.outfile is not None:
        two_mb = 2097152
        outfh = open(args.outfile, "w", buffering=two_mb)
    func(ont, args.file, outfh, p, args)
    if filtered_evidence_file:
        filtered_evidence_file.close()

    if outfh is not None:
        outfh.close()

    if args.report_md is not None:
        report_md = open(args.report_md, "w")
        report_md.write(p.report.to_markdown())
        report_md.close()
    if args.report_json is not None:
        report_json = open(args.report_json, "w")
        report_json.write(json.dumps(p.report.to_report_json(), indent=4))
        report_json.close()
    if not (args.report_md or args.report_json):
        print(p.report.to_markdown())
768196
def main(*args, **kwargs):
    

    parser = argparse.ArgumentParser()
    parser.add_argument('package_name', type=str)
    parser.add_argument('output_filename', type=str)

    parsed_args = parser.parse_args()

    # Find all package requirements
    get_all_requires(parsed_args.package_name)

    # Write tmp results to a file to be read into main app context
    json_file = open(parsed_args.output_filename, 'w')
    json_file.write(json.dumps(all_requires))
159554
def apize_raw(url, method='GET'):
	
	def decorator(func):
		def wrapper(*args, **kwargs):
			elem = func(*args, **kwargs)

			if type(elem) is not dict:
				raise BadReturnVarType(func.__name__)

			response = send_request(url, method, 
				elem.get('data', {}),
				elem.get('args', {}),
				elem.get('params', {}),
				elem.get('headers', {}),
				elem.get('cookies', {}),
				elem.get('timeout', 8),
				elem.get('is_json', False),
				elem.get('verify_cert', True)
			)

			return response
		return wrapper

	return decorator
197957
function Args() {
    if (argv._.length >= 1) {
        try {
            // Attempt to parse 1st argument as JSON string
            _.extend(this, JSON.parse(argv._[0]));
        } catch (err) {
            // Pass, we must be in the console so don't worry about it
        }
    }
}
1140618
def api_call(fn):
    

    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            result = fn(*args, **kwargs)
        except (DagobahError, DAGValidationError) as e:
            if request and request.endpoint == fn.__name__:
                return jsonify(error_type=type(e).__name__, message=e.message), 400
            raise e
        except Exception as e:
            logging.exception(e)
            raise e

        if request and request.endpoint == fn.__name__:
            status_code = None
            try:
                if result and '_status' in result:
                    status_code = result['_status']
                    del result['_status']
            except TypeError:
                pass

            if isinstance(result, dict):
                if 'result' in result:
                    return jsonify(status=status_code if status_code else 200,
                                   **result)
                else:
                    return jsonify(status=status_code if status_code else 200,
                                   result=result)
            else:
                return jsonify(status=status_code if status_code else 200,
                               result=result)

        else:
            return result

    return wrapper
476749
def _as_json(self, **kwargs) -> str:
        
        return json.dumps(self, default=self._default, **kwargs)
1218037
def dumps(obj, *args, **kwargs):
    '''  '''
    return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
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)
63235
def main():
    
    parser = argparse.ArgumentParser(description=__description__)
    parser.add_argument(
        '-V', '--version', dest='version', action='store_true',
        help="show version")
    parser.add_argument(
        '--log-level', default='INFO',
        help="Specify logging level, default is INFO.")
    parser.add_argument('har_source_file', nargs='?',
        help="Specify HAR source file")
    parser.add_argument(
        '-2y', '--to-yml', '--to-yaml',
        dest='to_yaml', action='store_true',
        help="Convert to YAML format, if not specified, convert to JSON format by default.")
    parser.add_argument(
        '--filter', help="Specify filter keyword, only url include filter string will be converted.")
    parser.add_argument(
        '--exclude',
        help="Specify exclude keyword, url that includes exclude string will be ignored, multiple keywords can be joined with '|'")

    args = parser.parse_args()

    if args.version:
        print("{}".format(__version__))
        exit(0)

    log_level = getattr(logging, args.log_level.upper())
    logging.basicConfig(level=log_level)

    har_source_file = args.har_source_file
    if not har_source_file or not har_source_file.endswith(".har"):
        logging.error("HAR file not specified.")
        sys.exit(1)

    output_file_type = "YML" if args.to_yaml else "JSON"
    HarParser(
        har_source_file, args.filter, args.exclude
    ).gen_testcase(output_file_type)

    return 0
1301675
def wrap_json_params(func):
    

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "application/json":
            request.params = json.loads(request.body.decode("utf-8")) if request.body else None
        return func(request, *args, **kwargs)
    return wrapper