Make report item texts in a specified format.
962066
def get_report_parts(self, apps, formats):
        
        for fmt in formats:
            width = 100 if fmt is not None else tui.get_terminal_size()[0]
            for sr in self.subreports:
                sr.make_format(fmt, width)

        logger.debug('Build a map for arguments and run\'s statistics ...')
        value_mapping = {
            'title': self.title,
            'patterns': ', '.join([repr(pattern) for pattern in self.args.patterns]) or None,
            'pattern_files': ', '.join(self.args.pattern_files) or None,
            'hosts': ', '.join(self.args.hosts) or None,
            'apps': u', '.join([
                u'%s(%d)' % (app.name, app.matches) for app in apps.values() if app.matches > 0
            ]),
            'version': __version__
        }

        filters = []
        for flt in self.args.filters:
            filters.append(' AND '.join(['%s=%r' % (k, v.pattern) for k, v in flt.items()]))
        if filters:
            value_mapping['filters'] = ' OR '.join(['(%s)' % item for item in filters])
        else:
            value_mapping['filters'] = filters[0] if filters else None

        value_mapping.update(self.stats)

        report = []
        for fmt in formats:
            if fmt == 'text':
                logger.info('appends a text page report')
                report.append(self.make_text_page(value_mapping))
            elif fmt == 'html':
                logger.info('appends a html page report')
                report.append(self.make_html_page(value_mapping))
            elif fmt == 'csv':
                logger.info('extends with a list of csv subreports')
                report.extend(self.make_csv_tables())
        return report
397739
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str:
    """"""
    output = []
    pattrs.sort(
        key=lambda x: (
            _FORMATTER[x.display_group].display_index,
            x.display_group,
            x.name,
        )
    )
    for display_group, grouped_pattrs in groupby(pattrs, lambda x: x.display_group):
        output.append(
            _FORMATTER[display_group].formatter(display_group, grouped_pattrs)
        )

    return '\n'.join(output)
923629
def text(self, text):
        '''
        
        '''

        if text:
            if not isinstance(text, str):
                text = _pformat(text)
            text += '\n\n'
            self.m(
                'add text to mail',
                more=dict(len=len(text))
            )
            self.__message.attach(_MIMEText(text, 'plain', 'UTF-8'))
960253
def _make_fn_text(self):
        """"""
        if not self._f:
            text = "(not loaded)"
        elif self._f.filename:
            text = os.path.relpath(self._f.filename, ".")
        else:
            text = "(filename not set)"
        return text
507378
def FormatContext(self):
    """"""
    text = ''
    if hasattr(self, 'feed_name'):
      text += "In feed '%s': " % self.feed_name
    if hasattr(self, 'file_name'):
      text += self.file_name
    if hasattr(self, 'row_num'):
      text += ":%i" % self.row_num
    if hasattr(self, 'column_name'):
      text += " column %s" % self.column_name
    return text
682882
def _fix_evidence_text(txt):
    """"""
    txt = re.sub('[ ]?\( xref \)', '', txt)
    # This is to make [ xref ] become [] to match the two readers
    txt = re.sub('\[ xref \]', '[]', txt)
    txt = re.sub('[\(]?XREF_BIBR[\)]?[,]?', '', txt)
    txt = re.sub('[\(]?XREF_FIG[\)]?[,]?', '', txt)
    txt = re.sub('[\(]?XREF_SUPPLEMENT[\)]?[,]?', '', txt)
    txt = txt.strip()
    return txt
323479
def p_text(self, text):
        ''''''
        item = text[1]
        text[0] = item if item[0] != "\n" else u""
        if len(text) > 2:
            text[0] += "\n"
674819
def set_item_data(self, item, filename, line_number):
        """"""
        set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
730001
def _generate_payload(author_icon, title, report):
    '''
    
    '''

    title = _sprinkle(title)

    unchanged = {
        'color': 'good',
        'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
    }

    changed = {
        'color': 'warning',
        'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
    }

    if report['changed'].get('tasks'):
        changed['fields'] = list(
            map(_format_task, report['changed'].get('tasks')))

    failed = {
        'color': 'danger',
        'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
    }

    if report['failed'].get('tasks'):
        failed['fields'] = list(
            map(_format_task, report['failed'].get('tasks')))

    text = 'Function: {function}\n'.format(function=report.get('function'))
    if report.get('arguments'):
        text += 'Function Args: {arguments}\n'.format(
            arguments=str(list(map(str, report.get('arguments')))))

    text += 'JID: {jid}\n'.format(jid=report.get('jid'))
    text += 'Total: {total}\n'.format(total=report.get('total'))
    text += 'Duration: {duration:.2f} secs'.format(
        duration=float(report.get('duration')))

    payload = {
        'attachments': [
            {
                'fallback': title,
                'color': "#272727",
                'author_name': _sprinkle('{id}'),
                'author_link': _sprinkle('{localhost}'),
                'author_icon': author_icon,
                'title': 'Success: {success}'.format(success=str(report.get('success'))),
                'text': text
            },
            unchanged,
            changed,
            failed
        ]
    }

    return payload
277986
def paragraphs(value):
    """"""
    result = "\n\n".join(
        "<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
        for p in _PARAGRAPH_RE.split(escape(value))
    )
    return result
1065304
def tokenize(text, format=None):
    
    text = Text(text)
    text = text.replace("\t", " ")
    tokens = re.findall(patterns, text)
    tokens = [token[0] for token in tokens]
    if format == "text":
        return " ".join(tokens)
    else:
        return tokens
1353184
def format_text(text):
    """"""
    result = ""
    for paragraph in text.split("\n\n"):
        result += " ".join(paragraph.split()) + "\n\n"

    result = result.rstrip("\n")  # Remove last newlines

    # converting links to HTML
    pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
    pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
    if re.search(pattern, result):
        html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
        result = re.sub(pattern, html, result)

    return result
822878
def get_report(self):
    """"""
    ostr = ''
    ostr += "target\tquery\tcnt\ttotal\n"
    poss = ['-','A','C','G','T']
    for target in poss:
      for query in poss:
        ostr += target+ "\t"+query+"\t"+str(self.matrix[target][query])+"\t"+str(self.alignment_length)+"\n"
    return ostr
135232
def as_text(self, max_rows=0, sep=" | "):
        """"""
        if not max_rows or max_rows > self.num_rows:
            max_rows = self.num_rows
        omitted = max(0, self.num_rows - max_rows)
        labels = self._columns.keys()
        fmts = self._get_column_formatters(max_rows, False)
        rows = [[fmt(label, label=True) for fmt, label in zip(fmts, labels)]]
        for row in itertools.islice(self.rows, max_rows):
            rows.append([f(v, label=False) for v, f in zip(row, fmts)])
        lines = [sep.join(row) for row in rows]
        if omitted:
            lines.append('... ({} rows omitted)'.format(omitted))
        return '\n'.join([line.rstrip() for line in lines])
469159
def text(self, normalize_spaces=False):
        """"""
        return super(TextContent,self).text(normalize_spaces=normalize_spaces)
414212
def srt_formatter(subtitles, padding_before=0, padding_after=0):
    
    sub_rip_file = pysrt.SubRipFile()
    for i, ((start, end), text) in enumerate(subtitles, start=1):
        item = pysrt.SubRipItem()
        item.index = i
        item.text = six.text_type(text)
        item.start.seconds = max(0, start - padding_before)
        item.end.seconds = end + padding_after
        sub_rip_file.append(item)
    return '\n'.join(six.text_type(item) for item in sub_rip_file)
1051286
def markdown(text):
    """"""
    text = gfm(text)
    text = markdown_lib.markdown(text)
    return text