Print data in GitHub-flavoured Markdown format for issues etc.

    data (dict or list of tuples): Label/value pairs.
    title (unicode or None): Title, will be rendered as headline 2.
426231
def print_markdown(data, title=None):
    
    markdown = []
    for key, value in data.items():
        if isinstance(value, basestring_) and Path(value).exists():
            continue
        markdown.append("* **{}:** {}".format(key, unicode_(value)))
    if title:
        print("\n## {}".format(title))
    print("\n{}\n".format("\n".join(markdown)))
1238714
def _textOutput(self, gaObjects):
        
        for gaObject in gaObjects:
            if hasattr(gaObject, 'name'):
                print(gaObject.id, gaObject.name, sep="\t")
            else:
                print(gaObject.id, sep="\t")
996006
def _format_data(data):
        # type: (Union[str, IO]) -> Union[Tuple[None, str], Tuple[Optional[str], IO, str]]
        
        if hasattr(data, 'read'):
            data = cast(IO, data)
            data_name = None
            try:
                if data.name[0] != '<' and data.name[-1] != '>':
                    data_name = os.path.basename(data.name)
            except (AttributeError, TypeError):
                pass
            return (data_name, data, "application/octet-stream")
        return (None, cast(str, data))
1152456
def format(self):
        

        values = {}
        title = "Description"
        description = self.command.description + "\n\n" + self.get_ending_note() if not self.is_cog() else inspect.getdoc(self.command)
        sections = []

        if isinstance(self.command, Command):
                description = self.command.short_doc
                sections = [{"name": "Usage", "value": self.get_command_signature()},
                            {"name": "More Info", "value": self.command.help.replace(self.command.short_doc, "").format(prefix=self.clean_prefix),
                             "inline": False}]

        def category(tup):
            cog = tup[1].cog_name
            return cog + ':' if cog is not None else '\u200bNo Category:'

        if self.is_bot():
            title = self.bot.user.display_name + " Help"
            data = sorted(self.filter_command_list(), key=category)
            for category, commands in itertools.groupby(data, key=category):
                section = {}
                commands = list(commands)
                if len(commands) > 0:
                    section['name'] = category
                section['value'] = self.add_commands(commands)
                section['inline'] = False
                sections.append(section)
        elif not sections or self.has_subcommands():
            section = {"name": "Commands:", "inline": False, "value": self.add_commands(self.filter_command_list())}
            sections.append(section)

        values['title'] = title
        values['description'] = description
        values['sections'] = sections
        return values
490352
def render_title(options={})
      result = ::Liquid::Template.parse(title).render(optional_data(options))
    rescue => e
      log_error(e)
    ensure
      return result.to_s
    end
1068696
def fields(self):
        
        process_markdown = ("fields" in self._raw.get("mrkdwn_in", []))
        fields = self._raw.get("fields", [])
        if fields:
            logging.debug("Rendering with markdown markdown %s for %s", process_markdown, fields)
        return [
            {"title": e["title"], "short": e["short"], "value": self._formatter.render_text(e["value"], process_markdown)}
            for e in fields
        ]
1173247
def title(self, value):
        

        if value is not None:
            assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
                "title", value)
        self.__title = value
1145047
def text(self, tag, textdata, step=None):
    
    if step is None:
      step = self._step
    else:
      self._step = step
    smd = SummaryMetadata(
        plugin_data=SummaryMetadata.PluginData(plugin_name='text'))
    if isinstance(textdata, (str, bytes)):
      tensor = tf.make_tensor_proto(
          values=[textdata.encode(encoding='utf_8')], shape=(1,))
    else:
      textdata = onp.array(textdata)  # convert lists, jax arrays, etc.
      datashape = onp.shape(textdata)
      if len(datashape) == 1:
        tensor = tf.make_tensor_proto(
            values=[td.encode(encoding='utf_8') for td in textdata],
            shape=(datashape[0],))
      elif len(datashape) == 2:
        tensor = tf.make_tensor_proto(
            values=[
                td.encode(encoding='utf_8') for td in onp.reshape(textdata, -1)
            ],
            shape=(datashape[0], datashape[1]))
    summary = Summary(
        value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)])
    self.add_summary(summary, step)
238520
def markdown_dict_string(d):
    
    # sort experimental data from simulated data
    from collections import OrderedDict
    types = OrderedDict()
    for key, value in sorted(d.items()):
        if 'type' in value:
            if value['type'] not in types:
                types[value['type']] = []
            types[value['type']].append(key)
        else:
            print(key, 'does not define data type!')
    # format output
    s = ''
    for type in ['scRNAseq', 'scqPCR', 'bulk', 'simulated']:
        s += '\nExamples using ' + type + ' data.\n'
        for key in types[type]:
            value = d[key]
            s += '* [' + key + '](#' + key + ')'
            if 'ref' in value:
                if 'doi' in value:
                    link = 'http://dx.doi.org/' + value['doi']
                elif 'url' in value:
                    link = value['url']
                s += (' - [' +  value['ref'].replace('et al.','*et al.*')
                             + '](' + link +  ')')
            if 'title' in value:
                s += '   \n*' + value['title'] + '*'
            s += '\n'
    return s
332470
def info(model=None, markdown=False, silent=False):
    
    msg = Printer()
    if model:
        if util.is_package(model):
            model_path = util.get_package_path(model)
        else:
            model_path = util.get_data_path() / model
        meta_path = model_path / "meta.json"
        if not meta_path.is_file():
            msg.fail("Can't find model meta.json", meta_path, exits=1)
        meta = srsly.read_json(meta_path)
        if model_path.resolve() != model_path:
            meta["link"] = path2str(model_path)
            meta["source"] = path2str(model_path.resolve())
        else:
            meta["source"] = path2str(model_path)
        if not silent:
            title = "Info about model '{}'".format(model)
            model_meta = {
                k: v for k, v in meta.items() if k not in ("accuracy", "speed")
            }
            if markdown:
                print_markdown(model_meta, title=title)
            else:
                msg.table(model_meta, title=title)
        return meta
    data = {
        "spaCy version": about.__version__,
        "Location": path2str(Path(__file__).parent.parent),
        "Platform": platform.platform(),
        "Python version": platform.python_version(),
        "Models": list_models(),
    }
    if not silent:
        title = "Info about spaCy"
        if markdown:
            print_markdown(data, title=title)
        else:
            msg.table(data, title=title)
    return data
64827
def markdown_to_text(body):
    
    # Turn our input into HTML
    md = markdown.markdown(body, extensions=[
        'markdown.extensions.extra'
    ])

    # Safely parse HTML so that we don't have to parse it ourselves
    soup = BeautifulSoup(md, 'html.parser')

    # Return just the text of the parsed HTML
    return soup.get_text()
1293365
def render_markdown(text, context=None):
    
    if context is None or not isinstance(context, dict):
        context = {}
    markdown_html = _transform_markdown_into_html(text)
    sanitised_markdown_html = _sanitise_markdown_html(markdown_html)
    return mark_safe(sanitised_markdown_html)
416346
def to_markdown(self):
        
        json = self.to_report_json()
        # summary = json['summary']

        s = "# Group: {group} - Dataset: {dataset}\n".format(group=json["group"], dataset=json["dataset"])
        s += "\n## SUMMARY\n\n"
        s += "This report generated on {}\n\n".format(datetime.date.today())
        s += "  * Associations: {}\n" . format(json["associations"])
        s += "  * Lines in file (incl headers): {}\n" . format(json["lines"])
        s += "  * Lines skipped: {}\n" . format(json["skipped_lines"])
        # Header from GAF
        s += "## Header From Original Association File\n\n"
        s += "\n".join(["> {}  ".format(head) for head in self.header])
        ## Table of Contents
        s += "\n\n## Contents\n\n"
        for rule, messages in sorted(json["messages"].items(), key=lambda t: t[0]):
            any_suppress_tag_in_rule_metadata = any([tag in self.config.rule_metadata.get(rule, {}).get("tags", []) for tag in self.config.suppress_rule_reporting_tags])
            # For each tag we say to suppress output for, check if it matches any tag in the rule. If any matches
            if self.config.rule_metadata and any_suppress_tag_in_rule_metadata:
                print("Skipping {rule_num} because the tag(s) '{tag}' are suppressed".format(rule_num=rule, tag=", ".join(self.config.suppress_rule_reporting_tags)))
                continue

            s += "[{rule}](#{rule})\n\n".format(rule=rule)

        s += "\n## MESSAGES\n\n"
        for (rule, messages) in sorted(json["messages"].items(), key=lambda t: t[0]):
            any_suppress_tag_in_rule_metadata = any([tag in self.config.rule_metadata.get(rule, {}).get("tags", []) for tag in self.config.suppress_rule_reporting_tags])

            # Skip if the rule metadata has "silent" as a tag
            if self.config.rule_metadata and any_suppress_tag_in_rule_metadata:
                # If there is a rule metadata, and the rule ID is in the config,
                # get the list of tags if present and check for existence of "silent".
                # If contained, continue to the next rule.
                continue


            s += "### {rule}\n\n".format(rule=rule)
            if rule != "other" and self.config.rule_metadata:
                s += "{title}\n\n".format(title=self.config.rule_metadata.get(rule, {}).get("title", ""))
            s += "* total: {amount}\n".format(amount=len(messages))
            if len(messages) > 0:
                s += "#### Messages\n"
            for message in messages:
                obj = " ({})".format(message["obj"]) if message["obj"] else ""
                s += "* {level} - {type}: {message}{obj} -- `{line}`\n".format(level=message["level"], type=message["type"], message=message["message"], line=message["line"], obj=obj)

        # for g in json['groups']:
        #     s += " * {}: {}\n".format(g['level'], g['count'])
        # s += "\n\n"
        # for g in json['groups']:
        #     level = g['level']
        #     msgs = g['messages']
        #     if len(msgs) > 0:
        #         s += "### {}\n\n".format(level)
        #         for m in msgs:
        #             s += " * {}: obj:'{}' \"{}\" `{}`\n".format(m['type'],m['obj'],m['message'],m['line'])
        return s
80524
def rst2markdown_github(path_to_rst, path_to_md, pandoc="pandoc"):
    
    _proc = subprocess.Popen([pandoc, "-f", "rst",
                              "-t", "markdown_github",
                              #"-o", path_to_md,
                              path_to_rst],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    print("Converting README.rst to markdown_github, "
          "using 'pandoc' ...")
    _stdout, _stderr = _proc.communicate()
    with _open(path_to_md, "w", encoding="utf-8") as _md:
        _skip_newline = False
        for line in _stdout.decode('utf-8').split(os.linesep):
            line = re.sub("``` sourceCode", "``` python", line)
            if line.startswith("[!["):
                _md.write(line)
                _md.write("\n")
                if not line.startswith(("[![LICENSE")):
                    _skip_newline = True
            elif _skip_newline and line == "":
                _skip_newline = False
                continue
            else:
                _md.write(line)
                _md.write("\n")

    if _stderr:
        print("pandoc.exe STDERR: ", _stderr)
    if os.path.isfile(path_to_md) and os.stat(path_to_md).st_size > 0:
        print("README.rst converted and saved as: {}".format(path_to_md))
48148
def cli_info(data, title='Info'):
    '''
    
    '''

    wrapper = textwrap.TextWrapper()
    wrapper.initial_indent = ' ' * 4
    wrapper.subsequent_indent = wrapper.initial_indent

    return '{title}:\n\n{text}'.format(title=title, text=wrapper.fill(data))
215886
def render_title(text, markup=True, no_smartquotes=False):
    

    # HACK: If the title starts with something that looks like a list, save it
    # for later
    pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
    text = pfx + misaka.Markdown(TitleRenderer(),
                                 extensions=TITLE_EXTENSIONS)(text)

    if not markup:
        strip = HTMLStripper()
        strip.feed(text)
        text = strip.get_data()

    if not no_smartquotes:
        text = misaka.smartypants(text)

    return flask.Markup(text)
363768
def to_text(self, omit_final_dot = False):
        

        if len(self.labels) == 0:
            return '@'
        if len(self.labels) == 1 and self.labels[0] == '':
            return '.'
        if omit_final_dot and self.is_absolute():
            l = self.labels[:-1]
        else:
            l = self.labels
        s = '.'.join(map(_escapify, l))
        return s