You can customize the automated documentation by altering
        the code directly in this script or the associated jinja2 template
326275
def create_html_file(config):
    
    logging.debug("Starting create_html_file")
    logging.debug(
        "\tjinja2_template_file = {}"
        .format(config['jinja2_template_filename']))
    logging.debug(
        "\ttrendered_filename = {}"
        .format(config['rendered_filename']))

    ts = time.time()
    timestamp = datetime.datetime.utcfromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')
    script_path = os.path.dirname(os.path.abspath(__file__))
    rendered_file_path = os.path.join(
        script_path, config['rendered_filename'])
    environment = jinja2.Environment(
        loader=jinja2.FileSystemLoader(script_path))

    environment_column = True if config['environment_tags'] else False

    render_vars = {
        "timestamp": timestamp,
        "c7n_data": c7n_data,
        "environment_column": environment_column,
        "environment_tags": config['environment_tags']
    }

    with open(rendered_file_path, "w") as result_file:
        result_file.write(
            environment.get_template(config['jinja2_template_filename'])
            .render(render_vars))

    logging.debug("File created: %s", rendered_file_path)

    return rendered_file_path
1147253
def _generate_html(self):
        
        logger.debug('Generating templated HTML')
        env = Environment(
            loader=PackageLoader('pypi_download_stats', 'templates'),
            extensions=['jinja2.ext.loopcontrols'])
        env.filters['format_date_long'] = filter_format_date_long
        env.filters['format_date_ymd'] = filter_format_date_ymd
        env.filters['data_columns'] = filter_data_columns
        template = env.get_template('base.html')

        logger.debug('Rendering template')
        html = template.render(
            project=self.project_name,
            cache_date=self._stats.as_of_datetime,
            user=getuser(),
            host=platform_node(),
            version=VERSION,
            proj_url=PROJECT_URL,
            graphs=self._graphs,
            graph_keys=self.GRAPH_KEYS,
            resources=Resources(mode='inline').render(),
            badges=self._badges
        )
        logger.debug('Template rendered')
        return html
1329803
def gen_text(env: TextIOBase, package: str, tmpl: str):
    """"""
    if env:
        env_args = json_datetime.load(env)
    else:
        env_args = {}
    jinja_env = template.setup(package)
    echo(jinja_env.get_template(tmpl).render(**env_args))
263283
def _render_html(self, libraries):
        """"""

        title = self.options.get("title", "Keyword Documentation")
        date = time.strftime("%A %B %d, %I:%M %p")
        cci_version = cumulusci.__version__

        stylesheet_path = os.path.join(os.path.dirname(__file__), "stylesheet.css")
        with open(stylesheet_path) as f:
            stylesheet = f.read()

        jinjaenv = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=False
        )
        jinjaenv.filters["robot_html"] = robot.utils.html_format
        template = jinjaenv.get_template("template.html")
        return template.render(
            libraries=libraries,
            title=title,
            cci_version=cci_version,
            stylesheet=stylesheet,
            date=date,
        )
1007633
def generate_documentation(schema):
    

    documentation_title = "Configuration documentation"
    documentation = documentation_title + "\n"
    documentation += "=" * len(documentation_title) + '\n'

    for section_name in schema:
        section_created = False

        for option_name in schema[section_name]:

            option = schema[section_name][option_name]

            if not section_created:
                documentation += '\n'
                documentation += section_name + '\n'
                documentation += '-' * len(section_name) + '\n'
                section_created = True

            documentation += '\n'
            documentation += option_name + '\n'
            documentation += '~' * len(option_name) + '\n'

            if option.get('required'):

                documentation += "** This option is required! **\n"

            if option.get('type'):

                documentation += '*Type : %s.*\n' % option.get('type')

            if option.get('description'):

                documentation += option.get('description') + '\n'

            if option.get('default'):

                documentation += 'The default value is %s.\n' % option.get('default')

            if option.get('deprecated'):

                documentation += "** This option is deprecated! **\n"

    return documentation
1317096
def update_docs(self, iface, module):
        """"""        
        #We need to look in the parent module docstrings for this types decorating tags.
        key = "{}.{}".format(module.name, iface.name)
        if key in module.predocs:
            iface.docstring = self.docparser.to_doc(module.predocs[key][0], iface.name)
            iface.docstart, iface.docend = (module.predocs[key][1], module.predocs[key][2])
445371
def customize(self, customize):
        
        for k, v in list(customize.items()):
            if k in TABLE_R:
                continue
            op = k[ :k.rfind('_') ]

            if k.startswith('CALL_METHOD'):
                # This happens in PyPy only
                TABLE_R[k] = ('%c(%P)', 0, (1, -1, ', ', 100))
            elif self.version >= 3.6 and k.startswith('CALL_FUNCTION_KW'):
                TABLE_R[k] = ('%c(%P)', 0, (1, -1, ', ', 100))
            elif op == 'CALL_FUNCTION':
                TABLE_R[k] = ('%c(%P)', 0, (1, -1, ', ', 100))
            elif op in ('CALL_FUNCTION_VAR',
                        'CALL_FUNCTION_VAR_KW', 'CALL_FUNCTION_KW'):

                # FIXME: handle everything in customize.
                # Right now, some of this is here, and some in that.

                if v == 0:
                    str = '%c(%C' # '%C' is a dummy here ...
                    p2 = (0, 0, None) # .. because of the None in this
                else:
                    str = '%c(%C, '
                    p2 = (1, -2, ', ')
                if op == 'CALL_FUNCTION_VAR':
                    # Python 3.5 only puts optional args (the VAR part)
                    # lowest down the stack
                    if self.version == 3.5:
                        if str == '%c(%C, ':
                            entry = ('%c(*%C, %c)', 0, p2, -2)
                        elif str == '%c(%C':
                            entry = ('%c(*%C)', 0, (1, 100, ''))
                    elif self.version == 3.4:
                        # CALL_FUNCTION_VAR's top element of the stack contains
                        # the variable argument list
                        if v == 0:
                            str = '%c(*%c)'
                            entry = (str, 0, -2)
                        else:
                            str = '%c(%C, *%c)'
                            entry = (str, 0, p2, -2)
                    else:
                        str += '*%c)'
                        entry = (str, 0, p2, -2)
                elif op == 'CALL_FUNCTION_KW':
                    str += '**%c)'
                    entry = (str, 0, p2, -2)
                elif op == 'CALL_FUNCTION_VAR_KW':
                    str += '*%c, **%c)'
                    # Python 3.5 only puts optional args (the VAR part)
                    # lowest down the stack
                    na = (v & 0xff)  # positional parameters
                    if self.version == 3.5 and na == 0:
                        if p2[2]: p2 = (2, -2, ', ')
                        entry = (str, 0, p2, 1, -2)
                    else:
                        if p2[2]: p2 = (1, -3, ', ')
                        entry = (str, 0, p2, -3, -2)
                    pass
                else:
                    assert False, "Unhandled CALL_FUNCTION %s" % op

                TABLE_R[k] = entry
                pass
            # handled by n_dict:
            # if op == 'BUILD_SLICE':	TABLE_R[k] = ('%C'    ,    (0,-1,':'))
            # handled by n_list:
            # if   op == 'BUILD_LIST':	TABLE_R[k] = ('[%C]'  ,    (0,-1,', '))
            # elif op == 'BUILD_TUPLE':	TABLE_R[k] = ('(%C%,)',    (0,-1,', '))
            pass
        return
1182454
function(code)
        {
            var html = '',
                classes = [ 'syntaxhighlighter' ],
                tabSize,
                matches,
                lineNumbers
                ;

            // process light mode
            if (this.getParam('light') == true)
                this.params.toolbar = this.params.gutter = false;

            className = 'syntaxhighlighter';

            if (this.getParam('collapse') == true)
                classes.push('collapsed');

            if ((gutter = this.getParam('gutter')) == false)
                classes.push('nogutter');

            // add custom user style name
            classes.push(this.getParam('class-name'));

            // add brush alias to the class name for custom CSS
            classes.push(this.getParam('brush'));

            code = trimFirstAndLastLines(code)
                .replace(/\r/g, ' ') // IE lets these buggers through
            ;

            tabSize = this.getParam('tab-size');

            // replace tabs with spaces
            code = this.getParam('smart-tabs') == true
                ? processSmartTabs(code, tabSize)
                : processTabs(code, tabSize)
            ;

            // unindent code by the common indentation
            if (this.getParam('unindent'))
                code = unindent(code);

            if (gutter)
                lineNumbers = this.figureOutLineNumbers(code);

            // find matches in the code using brushes regex list
            matches = this.findMatches(this.regexList, code);
            // processes found matches into the html
            html = this.getMatchesHtml(code, matches);
            // finally, split all lines so that they wrap well
            html = this.getCodeLinesHtml(html, lineNumbers);

            // finally, process the links
            if (this.getParam('auto-links'))
                html = processUrls(html);

            if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
                classes.push('ie');

            html =
                '<div id="' + getHighlighterId(this.id) + '" class="' + classes.join(' ') + '">'
                    + (this.getParam('toolbar') ? sh.toolbar.getHtml(this) : '')
                    + '<table border="0" cellpadding="0" cellspacing="0">'
                    + this.getTitleHtml(this.getParam('title'))
                    + '<tbody>'
                    + '<tr>'
                    + (gutter ? '<td class="gutter">' + this.getLineNumbersHtml(code) + '</td>' : '')
                    + '<td class="code">'
                    + '<div class="container">'
                    + html
                    + '</div>'
                    + '</td>'
                    + '</tr>'
                    + '</tbody>'
                    + '</table>'
                    + '</div>'
            ;

            return html;
        }
1060439
def update_context(app, pagename, templatename, context, doctree):
    
    if doctree is None:
        return
    visitor = _FindTabsDirectiveVisitor(doctree)
    doctree.walk(visitor)
    if not visitor.found_tabs_directive:
        paths = [posixpath.join('_static', 'sphinx_tabs/' + f) for f in FILES]
        if 'css_files' in context:
            context['css_files'] = context['css_files'][:]
            for path in paths:
                if path.endswith('.css'):
                    context['css_files'].remove(path)
        if 'script_files' in context:
            context['script_files'] = context['script_files'][:]
            for path in paths:
                if path.endswith('.js'):
                    context['script_files'].remove(path)
407868
def _jinja_sub(self, st):
        """"""

        if isinstance(st, string_types):
            from jinja2 import Template

            try:
                for i in range(5):  # Only do 5 recursive substitutions.
                    st = Template(st).render(**(self._top.dict))
                    if '{{' not in st:
                        break
                return st
            except Exception as e:
                return st
                #raise ValueError(
                #    "Failed to render jinja template for metadata value '{}': {}".format(st, e))

        return st
1285218
def render(filename, obj):
    """"""
    template_path = abspath(filename)
    env = jinja_env(template_path)
    template_base = os.path.basename(template_path)
    try:
        parsed_content = env.parse(env
                                   .loader
                                   .get_source(env, template_base))
        template_vars = meta.find_undeclared_variables(parsed_content)
        if template_vars:
            missing_vars(template_vars, parsed_content, obj)

        LOG.debug("rendering %s with %s vars",
                  template_path, len(template_vars))
        return env \
            .get_template(template_base) \
            .render(**obj)
    except jinja2.exceptions.TemplateSyntaxError as exception:
        template_trace = traceback.format_tb(sys.exc_info()[2])
        # Different error context depending on whether it is the
        # pre-render variable scan or not
        if exception.filename:
            template_line = template_trace[len(template_trace) - 1]
            raise aomi_excep.Validation("Bad template %s %s" %
                                        (template_line,
                                         str(exception)))

        template_str = ''
        if isinstance(exception.source, tuple):
            # PyLint seems confused about whether or not this is a tuple
            # pylint: disable=locally-disabled, unsubscriptable-object
            template_str = "Embedded Template\n%s" % exception.source[0]

        raise aomi_excep.Validation("Bad template %s" % str(exception),
                                    source=template_str)

    except jinja2.exceptions.UndefinedError as exception:
        template_traces = [x.strip()
                           for x in traceback.format_tb(sys.exc_info()[2])
                           if 'template code' in x]
        raise aomi_excep.Validation("Missing template variable %s" %
                                    ' '.join(template_traces))
556017
def gen_input_edit(sig_dic):
    '''
    
    '''
    if sig_dic['en'] == 'tag_file_download':
        html_str = HTML_TPL_DICT['input_edit_download'].format(
            sig_en=sig_dic['en'],
            sig_zh=sig_dic['zh'],
            sig_dic=sig_dic['dic'][1],
            sig_type=sig_dic['type']
        )
    else:
        html_str = HTML_TPL_DICT['input_edit'].format(
            sig_en=sig_dic['en'],
            sig_zh=sig_dic['zh'],
            sig_dic=sig_dic['dic'][1],
            sig_type=sig_dic['type']
        )
    return html_str
566135
def __write_edit_tmpl(tag_key, tag_list):
    '''
    
    '''
    edit_file = os.path.join(OUT_DIR, 'edit', 'edit_' + tag_key.split('_')[1] + '.html')
    edit_widget_arr = []
    for sig in tag_list:
        html_sig = '_'.join(['html', sig])
        # var_html = eval('html_vars.' + html_sig)
        var_html = HTML_DICS[html_sig]

        if var_html['type'] in INPUT_ARR:
            tmpl = func_gen_html.gen_input_edit(var_html)
        elif var_html['type'] == 'select':
            tmpl = func_gen_html.gen_select_edit(var_html)
        elif var_html['type'] == 'radio':
            tmpl = func_gen_html.gen_radio_edit(var_html)
        elif var_html['type'] == 'checkbox':
            tmpl = func_gen_html.gen_checkbox_edit(var_html)
        elif var_html['type'] == 'file':
            tmpl = func_gen_html.gen_file_edit(var_html)
        else:
            tmpl = ''
        edit_widget_arr.append(tmpl)
    with open(edit_file, 'w') as fileout2:
        outstr = minify(
            TPL_EDIT.replace(
                'xxxxxx',
                ''.join(edit_widget_arr)
            ).replace(
                'yyyyyy',
                tag_key.split('_')[1][:2]
            ).replace(
                'kkkk',
                KIND_DICS['kind_' + tag_key.split('_')[-1]]
            )
        )
        fileout2.write(outstr)
599452
function() {
  // Start docs section with DOCS_START_MARKER
  var docs = [
    DOCS_START_MARKER
  ];

  // Generate documentation for methods
  // Sort by api name: http://bugzil.la/1200519
  docs = docs.concat(_.keys(apis).sort().filter(function(name) {
      // Find component that hold functions
      return apis[name].reference.entries.some(function(entry) {
        return entry.type === 'function';
      });
    }).map(function(name) {
    var api = apis[name];
    return [
      "",
      "### Methods in `taskcluster." + name + "`",
      "```js",
      "// Create " + name + " client instance:",
      "//  - " + api.reference.baseUrl,
      "var " + instanceName(name) + " = new taskcluster." + name + "(options);",
      "```"
    ].concat(api.reference.entries.filter(function(entry) {
      return entry.type === 'function';
    }).map(function(entry) {
      var args = entry.args.slice();
      if (entry.input) {
        args.push('payload');
      }
      if ((entry.query || []).length > 0) {
        args.push('[options]');
      }
      var retval = 'void';
      if (entry.output) {
        retval = 'result';
      }
      return " * `" + instanceName(name) + "." + entry.name +
             "(" + args.join(', ') + ") : " + retval + "`";
    })).join('\n');
  }));


  // Generate documentation for exchanges
  // Sort by exchange name: http://bugzil.la/1200519
  docs = docs.concat(_.keys(apis).sort().filter(function(name) {
      // Find component that hold functions
      return apis[name].reference.entries.some(function(entry) {
        return entry.type === 'topic-exchange';
      });
    }).map(function(name) {
    var api = apis[name];
    return [
      "",
      "### Exchanges in `taskcluster." + name + "`",
      "```js",
      "// Create " + name + " client instance:",
      "//  - " + api.reference.exchangePrefix,
      "var " + instanceName(name) + " = new taskcluster." + name + "(options);",
      "```"
    ].concat(api.reference.entries.filter(function(entry) {
      return entry.type === 'topic-exchange';
    }).map(function(entry) {
      return " * `" + instanceName(name) + "." + entry.name +
             "(routingKeyPattern) : binding-info`";
    })).join('\n');
  }));

  // End the docs section with DOCS_END_MARKER
  docs = docs.concat([
    "",
    DOCS_END_MARKER
  ]).join('\n');

  // Load README.md
  var readmePath  = path.join(__dirname, '..', 'README.md');
  var readme      = fs.readFileSync(readmePath, {encoding: 'utf-8'});

  // Split out docs and get text before and after docs, and write to readmeMD
  var before  = readme.split(DOCS_START_MARKER)[0]
  var after   = readme.split(DOCS_END_MARKER)[1];
  fs.writeFileSync(readmePath, before + docs + after, {encoding: 'utf-8'});
}
735182
def generate_html(self, jdoc, schema, schemas):
        ''''''

        params = {'functions': sorted([j for j in jdoc \
                   if (j.schema_name == schema.object_name and j.object_type \
                       in ['function', 'procedure', 'trigger'])], \
                                      key=lambda x: x.object_name),
                   'tables': sorted([j for j in jdoc \
                   if (j.schema_name == schema.object_name and j.object_type \
                       in ['table', 'view', 'materialized view', 'foreign table'])], \
                                    key=lambda x: x.object_name),
                   'schema_name': schema.object_name,
                   'schemas': sorted(schemas, key=lambda x: x.object_name),
                   'project': self.project_name,
                   'title': '{}: schema {}'.format(self.project_name,
                                                   schema.object_name)}
        template = self.lookup.get_template('schema.mako')
        html = template.render_unicode(**params)

        return html
140645
def generate_docs(self, clspath, more_content):
        """"""
        obj = import_class(clspath)
        sourcename = 'docstring of %s' % clspath
        all_options = []
        indent = '    '
        config = obj.get_required_config()

        if config.options:
            # Go through options and figure out relevant information
            for option in config:
                if 'namespace' in self.options:
                    namespaced_key = self.options['namespace'] + '_' + option.key
                else:
                    namespaced_key = option.key

                if 'case' in self.options:
                    if self.options['case'] == 'upper':
                        namespaced_key = namespaced_key.upper()
                    elif self.options['case'] == 'lower':
                        namespaced_key = namespaced_key.lower()

                all_options.append({
                    'key': namespaced_key,
                    'parser': qualname(option.parser),
                    'doc': option.doc,
                    'default': option.default,
                })

        if 'hide-classname' not in self.options:
            modname, clsname = split_clspath(clspath)
            component_name = clspath
            component_index = clsname
        else:
            component_name = 'Configuration'
            component_index = 'Configuration'

        if all_options:
            # Add index entries for options first so they link to the right
            # place; we do it this way so that we don't have to make options a
            # real object type and then we don't get to use TypedField
            # formatting
            self.add_line('.. index::', sourcename)
            for option in all_options:
                self.add_line('   single: %s; (%s)' % (option['key'], component_index), sourcename)
            self.add_line('', '')

        # Add the classname or 'Configuration'
        self.add_line('.. everett:component:: %s' % component_name, sourcename)
        self.add_line('', sourcename)

        # Add the docstring if there is one and if show-docstring
        if 'show-docstring' in self.options:
            docstring_attr = self.options['show-docstring'] or '__doc__'
            docstring = getattr(obj, docstring_attr, None)
            if docstring:
                docstringlines = prepare_docstring(docstring, ignore=1)
                for i, line in enumerate(docstringlines):
                    self.add_line(indent + line, sourcename, i)
                self.add_line('', '')

        # Add content from the directive if there was any
        if more_content:
            for line, src in zip(more_content.data, more_content.items):
                self.add_line(indent + line, src[0], src[1])
            self.add_line('', '')

        if all_options:
            # Now list the options
            sourcename = 'class definition'

            for option in all_options:
                self.add_line(
                    '%s:option %s %s:' % (indent, option['parser'], option['key']),
                    sourcename
                )
                self.add_line('%s    %s' % (indent, option['doc']), sourcename)
                if option['default'] is not NO_VALUE:
                    self.add_line('', '')
                    self.add_line(
                        '%s    Defaults to ``%r``.' % (indent, option['default']),
                        sourcename
                    )
                self.add_line('', '')
562182
def jinja_template(template_name, name='data', mimetype="text/html"):
    
    def jinja_renderer(result, errors):
        template = get_jinja_template(template_name)
        context = {name: result or Mock(), 'errors': errors, 'enumerate': enumerate}
        rendered = template.render(**context)
        return {'body': rendered, 'mimetype': mimetype}
    return jinja_renderer