Main function for prepare and render OpenAPI specification
        :return:
768634
def run(self):
        '''
        
        '''
        # Loading yaml
        self.load_yaml()

        # Print paths from schema
        section_title = '**API Paths**'
        self.write(section_title)
        self.write('=' * len(section_title))
        self.print_paths()

        # Print models
        section_title = '**Schemas Description**'
        self.write(section_title)
        self.write('=' * len(section_title))
        self.print_schemas()

        # Render by sphinx
        node = nodes.section()
        node.document = self.state.document
        nested_parse_with_titles(self.state, self.__view_list, node)
        return node.children
710794
def _prepare(self):
        
        if self.method not in http.ALLOWED_METHODS:
            raise UberIllegalState('Unsupported HTTP Method.')

        api_host = self.api_host
        headers = self._build_headers(self.method, self.auth_session)
        url = build_url(api_host, self.path)
        data, params = generate_data(self.method, self.args)

        return generate_prepared_request(
            self.method,
            url,
            headers,
            data,
            params,
            self.handlers,
        )
1055687
def render(self, get_params, module, _if=None):
        
        enough = False
        output = []
        valid = None

        if self.commands.show:
            valid = True
        if self.parent and self.commands.soft and _if is None:
            return None, self
        if _if:
            valid = True
        elif self.commands._if:
            valid = self.check_valid(get_params)
        if valid is not False:
            for item in self.content:
                if isinstance(item, Placeholder):
                    sub_valid, sub_output, enough = item.get(get_params, self)
                    output.append(sub_output)
                elif isinstance(item, Literal):
                    sub_valid = None
                    enough = True
                    output.append(item.text)
                elif isinstance(item, Block):
                    sub_valid, sub_output = item.render(get_params, module)
                    if sub_valid is None:
                        output.append(sub_output)
                    else:
                        output.extend(sub_output)
                valid = valid or sub_valid
        if not valid:
            if self.next_block:
                valid, output = self.next_block.render(
                    get_params, module, _if=self.commands._if
                )
            elif self.parent is None and (
                (not self.next_block and enough) or self.base_block
            ):
                valid = True
            else:
                output = []

        # clean
        color = self.commands.color
        if color and color[0] != "#":
            color_name = "color_%s" % color
            threshold_color_name = "color_threshold_%s" % color
            # substitute color
            color = (
                getattr(module, color_name, None)
                or getattr(module, threshold_color_name, None)
                or getattr(module.py3, color_name.upper(), None)
            )
            if color == "hidden":
                return False, []

        text = u""
        out = []
        if isinstance(output, str):
            output = [output]

        # merge as much output as we can.
        # we need to convert values to unicode for concatination.
        if python2:
            conversion = unicode  # noqa
            convertables = (str, bool, int, float, unicode)  # noqa
        else:
            conversion = str
            convertables = (str, bool, int, float, bytes)

        first = True
        last_block = None
        for index, item in enumerate(output):
            is_block = isinstance(item, Block)
            if not is_block and item:
                last_block = None
            if isinstance(item, convertables) or item is None:
                text += conversion(item)
                continue
            elif text:
                if not first and (text == "" or out and out[-1].get("color") == color):
                    out[-1]["full_text"] += text
                else:
                    part = {"full_text": text}
                    if color:
                        part["color"] = color
                    out.append(part)
                text = u""
            if isinstance(item, Composite):
                if color:
                    item.composite_update(item, {"color": color}, soft=True)
                out.extend(item.get_content())
            elif is_block:
                # if this is a block then likely it is soft.
                if not out:
                    continue
                for x in range(index + 1, len(output)):
                    if output[x] and not isinstance(output[x], Block):
                        valid, _output = item.render(get_params, module, _if=True)
                        if _output and _output != last_block:
                            last_block = _output
                            out.extend(_output)
                        break
            else:
                if item:
                    out.append(item)
            first = False

        # add any left over text
        if text:
            part = {"full_text": text}
            if color:
                part["color"] = color
            out.append(part)

        # process any min/max length commands
        max_length = self.commands.max_length
        min_length = self.commands.min_length

        if max_length or min_length:
            for item in out:
                if max_length is not None:
                    item["full_text"] = item["full_text"][:max_length]
                    max_length -= len(item["full_text"])
                if min_length:
                    min_length -= len(item["full_text"])
            if min_length > 0:
                out[0]["full_text"] = u" " * min_length + out[0]["full_text"]
                min_length = 0

        return valid, out
1111950
def render(opts, functions, states=None, proxy=None, context=None):
    '''
    
    '''
    if context is None:
        context = {}

    pack = {'__salt__': functions,
            '__grains__': opts.get('grains', {}),
            '__context__': context}

    if states:
        pack['__states__'] = states
    pack['__proxy__'] = proxy or {}
    ret = LazyLoader(
        _module_dirs(
            opts,
            'renderers',
            'render',
            ext_type_dirs='render_dirs',
        ),
        opts,
        tag='render',
        pack=pack,
    )
    rend = FilterDictWrapper(ret, '.render')

    if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']):
        err = ('The renderer {0} is unavailable, this error is often because '
               'the needed software is unavailable'.format(opts['renderer']))
        log.critical(err)
        raise LoaderError(err)
    return rend
1068823
def main():
    
    parser = make_parser()
    args = parser.parse_args()
    data_dir = Path(args.data_dir).expand()
    if not data_dir.isdir():  # pylint: disable=no-value-for-parameter
        msg = u"Data directory {dir} does not exist".format(dir=args.data_dir)
        raise ValueError(msg)
    data_filenames = [name for name in data_dir.files()  # pylint: disable=no-value-for-parameter
                      if name.endswith(".json")]
    if not data_filenames:
        msg = u"Data directory {dir} contains no JSON files".format(dir=args.data_dir)
        raise ValueError(msg)
    output_dir = Path(args.output_dir).expand()
    output_dir.makedirs_p()  # pylint: disable=no-value-for-parameter

    return render_html(data_dir, output_dir)
919273
def main():
    """"""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global Image

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    if PANDOCVERSION < '1.16':
        Image = elt('Image', 2)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    attach_attrs_image = attach_attrs_factory(Image,
                                              extract_attrs=_extract_attrs)
    detach_attrs_image = detach_attrs_factory(Image)
    insert_secnos = insert_secnos_factory(Image)
    delete_secnos = delete_secnos_factory(Image)
    filters = [insert_secnos, process_figures, delete_secnos] \
      if PANDOCVERSION >= '1.16' else \
      [attach_attrs_image, insert_secnos, process_figures,
       delete_secnos, detach_attrs_image]
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               filters, blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'figure')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt == 'latex':

        rawblocks = []

        if has_unnumbered_figures:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Figure':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()
388255
def main():
    """"""
    args = docopt(__doc__, version=__version__, options_first=True)

    # Validate args.
    s = Schema({
        six.text_type: bool,
        '--config-file': Or(None, str),
        '<args>': list,
        '<command>': Or(str, lambda _: 'help'),
    })
    try:
        args = s.validate(args)
    except SchemaError as exc:
        print('{0}\n{1}'.format(str(exc), printable_usage(__doc__)), file=sys.stderr)
        sys.exit(1)

    # Get subcommand.
    cmd = args['<command>']
    if cmd in cmd_aliases:
        cmd = cmd_aliases[cmd]

    if (cmd == 'help') or (not cmd):
        if not args['<args>']:
            sys.exit(print(__doc__.strip(), file=sys.stderr))
        else:
            ia_module = load_ia_module(args['<args>'][0])
            sys.exit(print(ia_module.__doc__.strip(), file=sys.stderr))

    if cmd != 'configure' and args['--config-file']:
        if not os.path.isfile(args['--config-file']):
            print('--config-file should be a readable file.\n{0}'.format(
                printable_usage(__doc__)), file=sys.stderr)
            sys.exit(1)

    argv = [cmd] + args['<args>']

    config = dict()
    if args['--log']:
        config['logging'] = {'level': 'INFO'}
    elif args['--debug']:
        config['logging'] = {'level': 'DEBUG'}

    if args['--insecure']:
        config['general'] = dict(secure=False)

    session = get_session(config_file=args['--config-file'],
                          config=config,
                          debug=args['--debug'])

    ia_module = load_ia_module(cmd)
    try:
        sys.exit(ia_module.main(argv, session))
    except IOError as e:
        # Handle Broken Pipe errors.
        if e.errno == errno.EPIPE:
            sys.stderr.close()
            sys.stdout.close()
            sys.exit(0)
        else:
            raise
574779
def main():
    """"""
    parser = argparse.ArgumentParser(
        description='Auto-generate a RESTful API service '
        'from an existing database.'
        )
    parser.add_argument(
        'URI',
        help='Database URI in the format '
             'postgresql+psycopg2://user:password@host/database')
    parser.add_argument(
        '-d',
        '--debug',
        help='Turn on debug logging',
        action='store_true',
        default=False)
    parser.add_argument(
        '-p',
        '--port',
        help='Port for service to listen on',
        default=5000)
    parser.add_argument(
        '-l',
        '--local-only',
        help='Only provide service on localhost (will not be accessible'
             ' from other machines)',
        action='store_true',
        default=False)
    parser.add_argument(
        '-r',
        '--read-only',
        help='Make all database resources read-only (i.e. only the HTTP GET method is supported)',
        action='store_true',
        default=False)
    parser.add_argument(
        '-s',
        '--schema',
        help='Use this named schema instead of default',
        default=None)


    args = parser.parse_args()
    app = get_app(args.URI, read_only=args.read_only, schema=args.schema)
    if args.debug:
        app.config['DEBUG'] = True
    if args.local_only:
        host = '127.0.0.1'
    else:
        host = '0.0.0.0'
    app.config['SECRET_KEY'] = '42'
    app.run(host=host, port=int(args.port))
773098
def copy_openapi_specs(output_path, component):
    """"""
    if component == 'reana-server':
        file = 'reana_server.json'
    elif component == 'reana-workflow-controller':
        file = 'reana_workflow_controller.json'
    elif component == 'reana-job-controller':
        file = 'reana_job_controller.json'
    if os.environ.get('REANA_SRCDIR'):
        reana_srcdir = os.environ.get('REANA_SRCDIR')
    else:
        reana_srcdir = os.path.join('..')
    try:
        reana_commons_specs_path = os.path.join(
            reana_srcdir,
            'reana-commons',
            'reana_commons',
            'openapi_specifications')
        if os.path.exists(reana_commons_specs_path):
            if os.path.isfile(output_path):
                shutil.copy(output_path,
                            os.path.join(reana_commons_specs_path,
                                         file))
                # copy openapi specs file as well to docs
                shutil.copy(output_path,
                            os.path.join('docs', 'openapi.json'))
    except Exception as e:
        click.echo('Something went wrong, could not copy openapi '
                   'specifications to reana-commons \n{0}'.format(e))
140163
def main():
    """"""
    parser = argparse.ArgumentParser(description='Python module name to'
                                     'package name')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--dist', help='distribution style '
                       '(default: %(default)s)',
                       default=platform.linux_distribution()[0])
    group.add_argument('--upstream', help='map to OpenStack project name',
                       action='store_true')
    parser.add_argument('--pyver', help='Python versions to return. "py" is '
                        'the unversioned name',
                        action='append', choices=['py', 'py2', 'py3'],
                        default=[])
    parser.add_argument('modulename', help='python module name')
    args = vars(parser.parse_args())

    pyversions = args['pyver'] if args['pyver'] else ['py']

    if args['upstream']:
        print(module2upstream(args['modulename']))
    else:
        pylist = module2package(args['modulename'], args['dist'],
                                py_vers=pyversions)
        # When only 1 version is requested, it will be returned as a string,
        # for backwards compatibility. Else, it will be a list.
        if type(pylist) is list:
            print(' '.join(pylist))
        else:
            print(pylist)
589733
function produceAPI(sourceArr, rsPath) {
    var apidocsPath = path.join(envPath, 'docs');
    const output = jsdoc2md.renderSync({ files: sourceArr })
    var isexist = fs.existsSync(apidocsPath);
    if (!isexist) {
        fs.mkdirSync(apidocsPath);
    }
    fs.writeFileSync(path.join(apidocsPath, rsPath), output)
}
944836
def main(global_config, **settings):
    """"""
    initialize_sentry_integration()
    config = Configurator(settings=settings)
    declare_api_routes(config)
    declare_type_info(config)

    # allowing the pyramid templates to render rss and xml
    config.include('pyramid_jinja2')
    config.add_jinja2_renderer('.rss')
    config.add_jinja2_renderer('.xml')

    mandatory_settings = ['exports-directories', 'exports-allowable-types']
    for setting in mandatory_settings:
        if not settings.get(setting, None):
            raise ValueError('Missing {} config setting.'.format(setting))

    config.scan(ignore='.tests')
    config.include('cnxarchive.events.main')

    config.add_tween('cnxarchive.tweens.conditional_http_tween_factory')

    return config.make_wsgi_app()
1101463
def render_for_api(api_template_or_options, render_options)
      if api_template_or_options.is_a?(Hash)
        api_template = []
        api_template << api_template_or_options.delete(:prefix)
        api_template << api_template_or_options.delete(:template)
        api_template << api_template_or_options.delete(:postfix)
        api_template = api_template.reject(&:blank?).join('_')
      else
        api_template = api_template_or_options
      end

      # extract the api format and model
      api_format_options = {}

      ActsAsApi::Config.accepted_api_formats.each do |item|
        if render_options.key?(item)
          api_format_options[item] = render_options[item]
          render_options.delete item
        end
      end

      meta_hash = render_options[:meta] if render_options.key?(:meta)

      api_format =  api_format_options.keys.first
      api_model  =  api_format_options.values.first

      # set the params to render
      output_params = render_options

      api_root_name = nil

      if !output_params[:root].nil?
        api_root_name = output_params[:root].to_s
      elsif api_model.class.respond_to?(:model_name)
        api_root_name = api_model.class.model_name
      elsif api_model.respond_to?(:collection_name)
        api_root_name = api_model.collection_name
      elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.class.respond_to?(:model_name)
        api_root_name = api_model.first.class.model_name
      elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.respond_to?(:model_name)
        api_root_name = api_model.first.model_name
      elsif api_model.respond_to?(:model_name)
        api_root_name = api_model.model_name
      else
        api_root_name = ActsAsApi::Config.default_root.to_s
      end
      api_root_name = api_root_name.to_s.underscore.tr('/', '_')

      if api_model.is_a?(Array) || (defined?(ActiveRecord) && api_model.is_a?(ActiveRecord::Relation))
        api_root_name = api_root_name.pluralize
      end

      api_root_name = api_root_name.dasherize if ActsAsApi::Config.dasherize_for.include? api_format.to_sym

      output_params[:root] = api_root_name

      api_response = api_model.as_api_response(api_template)

      if api_response.is_a?(Array) && api_format.to_sym == :json && ActsAsApi::Config.include_root_in_json_collections
        api_response = api_response.collect { |f| { api_root_name.singularize => f } }
      end

      if meta_hash || ActsAsApi::Config.add_root_node_for.include?(api_format)
        api_response = { api_root_name.to_sym => api_response }
      end

      api_response = meta_hash.merge api_response if meta_hash

      if ActsAsApi::Config.allow_jsonp_callback && params[:callback]
        output_params[:callback] = params[:callback]
        api_format = :acts_as_api_jsonp if ActsAsApi::Config.add_http_status_to_jsonp_response
      end

      # create the Hash as response
      output_params[api_format] = api_response

      render output_params
    end
1261197
def main():
    
    parser = argparse.ArgumentParser(
        description='A pipeline that generates analysis pipelines.')
    parser.add_argument('input', nargs='?',
                   help='A valid metapipe configuration file.')
    parser.add_argument('-o', '--output',
                   help='An output destination. If none is provided, the '
                   'results will be printed to stdout.',
                   default=sys.stdout)
    parser.add_argument('-t', '--temp',
                   help='A desired metapipe binary file. This is used to store '
                   'temp data between generation and execution. '
                   '(Default: "%(default)s")', default='.metapipe')
    parser.add_argument('-s', '--shell',
                   help='The path to the shell to be used when executing the '
                   'pipeline. (Default: "%(default)s)"',
                   default='/bin/bash')
    parser.add_argument('-r', '--run',
                   help='Run the pipeline as soon as it\'s ready.',
                   action='store_true')
    parser.add_argument('-n', '--name',
                   help='A name for the pipeline.',
                   default='')
    parser.add_argument('-j', '--job-type',
                   help='The destination for calculations (i.e. local, a PBS '
                   'queue on a cluster, etc).\nOptions: {}. '
                   '(Default: "%(default)s)"'.format(JOB_TYPES.keys()),
                   default='local')
    parser.add_argument('-p', '--max-jobs',
                   help='The maximum number of concurrent jobs allowed. '
                   'Defaults to maximum available cores.',
                   default=None)
    parser.add_argument('--report-type',
                   help='The output report type. By default metapipe will '
                   'print updates to the console. \nOptions: {}. '
                   '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()),
                   default='text')
    parser.add_argument('-v','--version',
                    help='Displays the current version of the application.',
                    action='store_true')
    args = parser.parse_args()

    if args.version:
        print('Version: {}'.format(__version__))
        sys.exit(0)

    try:
        with open(args.input) as f:
            config = f.read()
    except IOError:
        print('No valid config file found.')
        return -1

    run(config, args.max_jobs, args.output, args.job_type, args.report_type,
        args.shell, args.temp, args.run)
284708
def render(self, tmpl_name, request_env):
        
        return super(WebApplication, self).render(tmpl_name, request_env)
434602
protected function loadOpenApiFile()
	{
		if (!is_null($this->outputInterface)) {
			$this->outputInterface->writeln('<info>Loading OpenAPI file : ' . $this->openApiFilePath . '</info>');
		}

		$fileContent = file_get_contents($this->openApiFilePath);

		// Parse the file using the right parser (json or yaml)

		$jsonException = null;

		if (!is_null($this->outputInterface)) {
			$this->outputInterface->writeln('<info>Decode JSON from OpenAPI file</info>');
		}

		try {
			$this->openApiFileContent = json_decode($fileContent, true);
		} catch (Exception $e) {
			$jsonException = $e;
		}

		$jsonLastError = json_last_error();

		if ($jsonLastError != JSON_ERROR_NONE)
		{
			if (!is_null($this->outputInterface)) {
				$this->outputInterface->writeln('<info>Can not decode JSON, try YAML</info>');
			}
			$this->openApiFileContent = Yaml::parse($fileContent, Yaml::PARSE_OBJECT | Yaml::PARSE_OBJECT_FOR_MAP | Yaml::PARSE_DATETIME | Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
		}

		if (!is_null($this->outputInterface)) {
			$this->outputInterface->writeln('<info>File decoded</info>');
		}
	}
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))