• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python misc._abort函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中misc._abort函数的典型用法代码示例。如果您正苦于以下问题:Python _abort函数的具体用法?Python _abort怎么用?Python _abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了_abort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: cwiki_figure

def cwiki_figure(m):
    filename = m.group('filename')
    link = filename if filename.startswith('http') else None
    if not link and not os.path.isfile(filename):
        raise IOError('no figure file %s' % filename)

    basename  = os.path.basename(filename)
    stem, ext = os.path.splitext(basename)
    root, ext = os.path.splitext(filename)

    if link is None:
        if not ext in '.png .gif .jpg .jpeg'.split():
            # try to convert image file to PNG, using
            # convert from ImageMagick:
            cmd = 'convert %s png:%s' % (filename, root+'.png')
            failure, output = commands.getstatusoutput(cmd)
            if failure:
                print '\n**** Warning: could not run', cmd
                print 'Convert %s to PNG format manually' % filename
                _abort()
            filename = root + '.png'
    caption = m.group('caption')
    # keep label if it's there:
    caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption)

    result = r"""{{%s|%s}}""" % (filename, caption)
    return result
开发者ID:wolf9s,项目名称:doconce,代码行数:27,代码来源:cwiki.py


示例2: begin_end_consistency_checks

def begin_end_consistency_checks(filestr, envirs):
    """Perform consistency checks: no of !bc must equal no of !ec, etc."""
    for envir in envirs:
        begin = '!b' + envir
        end = '!e' + envir

        nb = len(re.findall(r'^%s' % begin, filestr, flags=re.MULTILINE))
        ne = len(re.findall(r'^%s' % end, filestr, flags=re.MULTILINE))

        lines = []
        if nb != ne:
            print 'ERROR: %d %s do not match %d %s directives' % \
                  (nb, begin, ne, end)
            if not lines:
                lines = filestr.splitlines()
            begin_ends = []
            for i, line in enumerate(lines):
                if line.startswith(begin):
                    begin_ends.append((begin, i))
                if line.startswith(end):
                    begin_ends.append((end, i))
            for k in range(1, len(begin_ends)):
                pattern, i = begin_ends[k]
                if pattern == begin_ends[k-1][0]:
                    print '\n\nTwo', pattern, 'after each other!\n'
                    for j in range(begin_ends[k-1][1], begin_ends[k][1]+1):
                        print lines[j]
                    _abort()
            if begin_ends[-1][0].startswith('!b'):
                print 'Missing %s after final %s' % \
                      (begin_ends[-1][0].replace('!b', '!e'),
                       begin_ends[-1][0])
                _abort()
开发者ID:sakhan007,项目名称:doconce,代码行数:33,代码来源:common.py


示例3: cwiki_figure

def cwiki_figure(m):
    filename = m.group('filename')
    link = filename if filename.startswith('http') else None
    if not link and not os.path.isfile(filename):
        raise IOError('no figure file %s' % filename)

    basename  = os.path.basename(filename)
    stem, ext = os.path.splitext(basename)
    root, ext = os.path.splitext(filename)

    if link is None:
        if not ext in '.png .gif .jpg .jpeg'.split():
            # try to convert image file to PNG, using
            # convert from ImageMagick:
            cmd = 'convert %s png:%s' % (filename, root+'.png')
            try:
                output = subprocess.check_output(cmd, shell=True,
                                                 stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                errwarn('\n**** Warning: could not run ' + cmd)
                errwarn('Convert %s to PNG format manually' % filename)
                _abort()
            filename = root + '.png'
    caption = m.group('caption')
    # keep label if it's there:
    caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption)

    result = r"""{{%s|%s}}""" % (filename, caption)
    return result
开发者ID:dragly,项目名称:doconce,代码行数:29,代码来源:cwiki.py


示例4: subst_footnote

 def subst_footnote(m):
     name = m.group('name').strip()
     if name in name2index:
         i = name2index[m.group('name')]
     else:
         print '*** error: found footnote with name "%s", but this one is not defined' % name
         _abort()
     xml = r'<footnote id="%s">%s<footnote>' % (i, name)
     return xml
开发者ID:apetcho,项目名称:doconce,代码行数:9,代码来源:xml.py


示例5: safe_join

def safe_join(lines, delimiter):
    try:
        filestr = delimiter.join(lines) + '\n' # will fail if ord(char) > 127
        return filestr
    except UnicodeDecodeError, e:
        if "'ascii' codec can't decode":
            print '*** error: non-ascii character - rerun with --encoding=utf-8'
            _abort()
        else:
            print e
            _abort()
开发者ID:sakhan007,项目名称:doconce,代码行数:11,代码来源:common.py


示例6: gwiki_figure

def gwiki_figure(m):
    filename = m.group("filename")
    link = filename if filename.startswith("http") else None
    if not link and not os.path.isfile(filename):
        raise IOError("no figure file %s" % filename)

    basename = os.path.basename(filename)
    stem, ext = os.path.splitext(basename)
    root, ext = os.path.splitext(filename)

    if link is None:
        if not ext in ".png .gif .jpg .jpeg".split():
            # try to convert image file to PNG, using
            # convert from ImageMagick:
            cmd = "convert %s png:%s" % (filename, root + ".png")
            failure, output = commands.getstatusoutput(cmd)
            if failure:
                print "\n**** Warning: could not run", cmd
                print "Convert %s to PNG format manually" % filename
                _abort()
            filename = root + ".png"
    caption = m.group("caption")
    # keep label if it's there:
    caption = re.sub(r"label\{(.+?)\}", "(\g<1>)", caption)

    print """
NOTE: Place %s at some place on the web and edit the
      .gwiki page, either manually (seach for 'Figure: ')
      or use the doconce script:
      doconce gwiki_figsubst.py mydoc.gwiki URL
""" % filename

    result = r"""

---------------------------------------------------------------

Figure: %s

(the URL of the image file %s must be inserted here)

<wiki:comment>
Put the figure file %s on the web (e.g., as part of the
googlecode repository) and substitute the line above with the URL.
</wiki:comment>
---------------------------------------------------------------

""" % (
        caption,
        filename,
        filename,
    )
    return result
开发者ID:apetcho,项目名称:doconce,代码行数:52,代码来源:gwiki.py


示例7: YouTubeVideo

    def YouTubeVideo(filename):
        # Use YouTubeVideo object
        if 'watch?v=' in filename:
            name = filename.split('watch?v=')[1]
        elif 'youtu.be/' in filename:
            name = filename.split('youtu.be/')[1]
        else:
            errwarn('*** error: youtube movie name "%s" could not be interpreted' % filename)
            _abort()

        text = ''
        global movie_encountered
        if not movie_encountered:
            text += 'from IPython.display import YouTubeVideo\n'
            movie_encountered = True
        text += 'YouTubeVideo("%s")\n' % name
        return text
开发者ID:KGHustad,项目名称:doconce,代码行数:17,代码来源:ipynb.py


示例8: align2equations

def align2equations(filestr, format):
    """Turn align environments into separate equation environments."""
    if not '{align}' in filestr:
        return filestr

    # sphinx: just replace align, pandoc/ipynb: replace align and align*
    # technique: add } if sphinx
    postfixes = ['}'] if format == 'sphinx' else ['}', '*}']

    lines = filestr.splitlines()
    inside_align = False
    inside_code = False
    for postfix in postfixes:
        for i in range(len(lines)):
            if lines[i].startswith('!bc'):
                inside_code = True
            if lines[i].startswith('!ec'):
                inside_code = False
            if inside_code:
                continue

            if r'\begin{align%s' % postfix in lines[i]:
                inside_align = True
                lines[i] = lines[i].replace(
                r'\begin{align%s' % postfix, r'\begin{equation%s' % postfix)
            if inside_align and '\\\\' in lines[i]:
                lines[i] = lines[i].replace(
                '\\\\', '\n' + r'\end{equation%s' % postfix + '\n!et\n\n!bt\n' + r'\begin{equation%s ' % postfix)
            if inside_align and ('begin{array}' in lines[i] or
                                 'begin{bmatrix}' in lines[i]):
                print '*** error: with %s output, align environments' % format
                print '    cannot have arrays/matrices with & and \\\\'
                print '    rewrite with single equations!'
                print '\n'.join(lines[i-4:i+5]).replace('{equation', '{align')
                _abort()
            if inside_align and '&' in lines[i]:
                lines[i] = lines[i].replace('&', '')
            if r'\end{align%s' % postfix in lines[i]:
                inside_align = False
                lines[i] = lines[i].replace(
                r'\end{align%s' % postfix, r'\end{equation%s' % postfix)
    filestr = '\n'.join(lines)
    return filestr
开发者ID:apetcho,项目名称:doconce,代码行数:43,代码来源:common.py


示例9: sphinx_inline_comment

def sphinx_inline_comment(m):
    # Explicit HTML typesetting does not work, we just use bold
    name = m.group('name').strip()
    comment = m.group('comment').strip()

    global edit_markup_warning
    if (not edit_markup_warning) and \
           (name[:3] in ('add', 'del', 'edi') or '->' in comment):
        print '*** warning: sphinx/rst is a suboptimal format for'
        print '    typesetting edit markup such as'
        print '   ', m.group()
        print '    Use HTML or LaTeX output instead, implement the'
        print '    edits (doconce apply_edit_comments) and then use sphinx.'
        edit_markup_warning = True

    chars = {',': 'comma', ';': 'semicolon', '.': 'period'}
    if name[:4] == 'del ':
        for char in chars:
            if comment == char:
                return r' (**edit %s**: delete %s)' % (name[4:], chars[char])
        return r'(**edit %s**: **delete** %s)' % (name[4:], comment)
    elif name[:4] == 'add ':
        for char in chars:
            if comment == char:
                return r'%s (**edit %s: add %s**)' % (comment, name[4:], chars[char])
        return r' (**edit %s: add**) %s (**end add**)' % (name[4:], comment)
    else:
        # Ordinary name
        comment = ' '.join(comment.splitlines()) # '\s->\s' -> ' -> '
        if ' -> ' in comment:
            # Replacement
            if comment.count(' -> ') != 1:
                print '*** wrong syntax in inline comment:'
                print comment
                print '(more than two ->)'
                _abort()
            orig, new = comment.split(' -> ')
            return r'(**%s: remove** %s) (**insert:**)%s (**end insert**)' % (name, orig, new)
        else:
            # Ordinary comment
            return r'[**%s**: %s]' % (name, comment)
开发者ID:apetcho,项目名称:doconce,代码行数:41,代码来源:sphinx.py


示例10: sphinx_inline_comment

def sphinx_inline_comment(m):
    # Explicit HTML typesetting does not work, we just use bold
    name = m.group("name").strip()
    comment = m.group("comment").strip()

    global edit_markup_warning
    if (not edit_markup_warning) and (name[:3] in ("add", "del", "edi") or "->" in comment):
        errwarn("*** warning: sphinx/rst is a suboptimal format for")
        errwarn("    typesetting edit markup such as")
        errwarn("    " + m.group())
        errwarn("    Use HTML or LaTeX output instead, implement the")
        errwarn("    edits (doconce apply_edit_comments) and then use sphinx.")
        edit_markup_warning = True

    chars = {",": "comma", ";": "semicolon", ".": "period"}
    if name[:4] == "del ":
        for char in chars:
            if comment == char:
                return r" (**edit %s**: delete %s)" % (name[4:], chars[char])
        return r"(**edit %s**: **delete** %s)" % (name[4:], comment)
    elif name[:4] == "add ":
        for char in chars:
            if comment == char:
                return r"%s (**edit %s: add %s**)" % (comment, name[4:], chars[char])
        return r" (**edit %s: add**) %s (**end add**)" % (name[4:], comment)
    else:
        # Ordinary name
        comment = " ".join(comment.splitlines())  # '\s->\s' -> ' -> '
        if " -> " in comment:
            # Replacement
            if comment.count(" -> ") != 1:
                errwarn("*** wrong syntax in inline comment:")
                errwarn(comment)
                errwarn("(more than two ->)")
                _abort()
            orig, new = comment.split(" -> ")
            return r"(**%s: remove** %s) (**insert:**)%s (**end insert**)" % (name, orig, new)
        else:
            # Ordinary comment
            return r"[**%s**: %s]" % (name, comment)
开发者ID:dragly,项目名称:doconce,代码行数:40,代码来源:sphinx.py


示例11: ipynb_movie

def ipynb_movie(m):
    # m.group() must be called before m.group('name')
    text = '<!-- dom:%s -->' % m.group()

    global html_encountered, movie_encountered, movie_files
    filename = m.group('filename')
    caption = m.group('caption').strip()
    youtube = False

    if 'youtu.be' in filename or 'youtube.com' in filename:
        youtube = True
    if '*' in filename or '->' in filename:
        errwarn('*** warning: * or -> in movie filenames is not supported in ipynb')
        return text

    def YouTubeVideo(filename):
        # Use YouTubeVideo object
        if 'watch?v=' in filename:
            name = filename.split('watch?v=')[1]
        elif 'youtu.be/' in filename:
            name = filename.split('youtu.be/')[1]
        else:
            errwarn('*** error: youtube movie name "%s" could not be interpreted' % filename)
            _abort()

        text = ''
        global movie_encountered
        if not movie_encountered:
            text += 'from IPython.display import YouTubeVideo\n'
            movie_encountered = True
        text += 'YouTubeVideo("%s")\n' % name
        return text

    text += '\n<!-- begin movie -->\n'
    display_method = option('ipynb_movie=', 'HTML')
    if display_method == 'md':
        text += html_movie(m)
    elif display_method.startswith('HTML'):
        text += '\n!bc pycod\n'
        if youtube and 'YouTube' in display_method:
            text += YouTubeVideo(filename)
            if caption:
                text += '\nprint "%s"' % caption
        else:
            # Use HTML formatting
            if not html_encountered:
                text += 'from IPython.display import HTML\n'
                html_encountered = True
            text += '_s = """' + html_movie(m) + '"""\n'
            text += 'HTML(_s)\n'
            if not filename.startswith('http'):
                movie_files.append(filename)
        text += '!ec\n'
    elif display_method == 'ipynb':
        text += '!bc pycod\n'
        if youtube:
            text += YouTubeVideo(filename)
            if caption:
                text += '\nprint "%s"' % caption
        else:
            # see http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb
            # http://stackoverflow.com/questions/18019477/how-can-i-play-a-local-video-in-my-ipython-notebook
            # http://python.6.x6.nabble.com/IPython-User-embedding-non-YouTube-movies-in-the-IPython-notebook-td5024035.html
            # Just support .mp4, .ogg, and.webm
            stem, ext = os.path.splitext(filename)
            if ext not in ('.mp4', '.ogg', '.webm'):
                errwarn('*** error: movie "%s" in format %s is not supported for --ipynb_movie=%s' % (filename, ext, display_method))
                errwarn('    use --ipynb_movie=HTML instead')
                _abort()
            height = 365
            width = 640
            if filename.startswith('http'):
                file_open = 'import urllib\nvideo = urllib.urlopen("%s").read()' % filename
            else:
                file_open = 'video = open("%s", "rb").read()' % filename
            text += """
%s
from base64 import b64encode
video_encoded = b64encode(video)
video_tag = '<video controls loop alt="%s" height="%s" width="%s" src="data:video/%s;base64,{0}">'.format(video_encoded)
""" % (file_open, filename, height, width, ext[1:])
            if not filename.startswith('http'):
                movie_files.append(filename)
            if not html_encountered:
                text += 'from IPython.display import HTML\n'
                html_encountered = True
            text += 'HTML(data=video_tag)\n'
            if caption:
                text += '\nprint "%s"' % caption
        text += '!ec\n'
    else:
        errwarn('*** error: --ipynb_movie=%s is not supported' % display_method)
        _abort()
    text += '<!-- end movie -->\n'
    return text
开发者ID:KGHustad,项目名称:doconce,代码行数:95,代码来源:ipynb.py


示例12: insert_code_and_tex

def insert_code_and_tex(filestr, code_blocks, tex_blocks, format):
    # Consistency check: find no of distinct code and math blocks
    # (can be duplicates when solutions are copied at the end)
    import sets
    pattern = r'^\d+ ' + _CODE_BLOCK
    n = len(sets.Set(re.findall(pattern, filestr, flags=re.MULTILINE)))
    if len(code_blocks) != n:
        print '*** error: found %d code block markers for %d initial code blocks' % (n, len(code_blocks))
        print """    Possible causes:
           - mismatch of !bt and !et within one file, such that a !bt
             swallows code
           - mismatch of !bt and !et across files in multi-file documents
           - !bc and !ec inside code blocks - replace by |bc and |ec
    (run doconce on each file to locate the problem, then on
     smaller and smaller parts of each file)"""
        _abort()
    pattern = r'^\d+ ' + _MATH_BLOCK
    n = len(sets.Set(re.findall(pattern, filestr, flags=re.MULTILINE)))
    if len(tex_blocks) != n:
        print '*** error: found %d tex block markers for %d initial tex blocks\nAbort!' % (n, len(tex_blocks))
        print """    Possible causes:
           - mismatch of !bc and !ec within one file, such that a !bc
             swallows tex blocks
           - mismatch of !bc and !ec across files in multi-file documents
           - !bt and !et inside code blocks - replace by |bt and |et
    (run doconce on each file to locate the problem, then on
     smaller and smaller parts of each file)"""
        _abort()

    from misc import option
    max_linelength = option('max_bc_linelength=', None)
    if max_linelength is not None:
        max_linelength = int(max_linelength)

        for i in range(len(code_blocks)):
            lines = code_blocks[i].splitlines()
            truncated = False
            for j in range(len(lines)):
                if len(lines[j]) > max_linelength:
                    lines[j] = lines[j][:max_linelength] + '...'
                    truncated = True
            if truncated:
                code_blocks[i] = '\n'.join(lines) + '\n'


    lines = filestr.splitlines()

    # Note: re.sub cannot be used because newlines, \nabla, etc
    # are not handled correctly. Need str.replace.

    for i in range(len(lines)):
        if _CODE_BLOCK in lines[i] or _MATH_BLOCK in lines[i]:
            words = lines[i].split()
            # on a line: number block-indicator code-type
            n = int(words[0])
            if _CODE_BLOCK in lines[i]:
                words[1] = '!bc'
                code = code_blocks[n]
                lines[i] = ' '.join(words[1:]) + '\n' + code + '!ec'
            if _MATH_BLOCK in lines[i]:
                words[1] = '!bc'
                math = tex_blocks[n]
                lines[i] = '!bt\n' + math + '!et'

    filestr = safe_join(lines, '\n')

    # All formats except sphinx and ipynb must remove !bc *hid blocks
    # (maybe html will get the possibility to run hidden blocks)
    if format not in ('sphinx', 'ipynb'):
        filestr = remove_hidden_code_blocks(filestr, format)

    return filestr
开发者ID:sakhan007,项目名称:doconce,代码行数:72,代码来源:common.py


示例13: remove_code_and_tex

def remove_code_and_tex(filestr, format):
    """
    Remove verbatim and latex (math) code blocks from the file and
    store separately in lists (code_blocks and tex_blocks).
    The function insert_code_and_tex will insert these blocks again.
    """
    # Method:
    # store code and tex blocks in lists and substitute these blocks
    # by the contents of _CODE_BLOCK and _MATH_BLOCK (arguments after
    # !bc must be copied after _CODE_BLOCK).
    # later we replace _CODE_BLOCK by !bc and !ec and the code block again
    # (similarly for the tex/math block).

    # ipynb (and future interactive executable documents) needs to
    # see if a code is to be executed or just displayed as text.
    # !bc *cod-t and !bc *pro-t is used to indicate pure text.
    if format not in ('ipynb',):
        filestr = re.sub(r'^!bc +([a-z0-9]+)-t', r'!bc \g<1>',
                         filestr, flags=re.MULTILINE)

    # (recall that !bc can be followed by extra information that we must keep:)
    code = re.compile(r'^!bc(.*?)\n(.*?)^!ec *\n', re.DOTALL|re.MULTILINE)

    # Note: final \n is required and may be missing if there is a block
    # at the end of the file, so let us ensure that a blank final
    # line is appended to the text:
    if filestr[-1] != '\n':
        filestr = filestr + '\n'

    result = code.findall(filestr)
    code_blocks = [c for opt, c in result]
    code_block_types = [opt.strip() for opt, c in result]

    tex = re.compile(r'^!bt *\n(.*?)^!et *\n', re.DOTALL|re.MULTILINE)
    tex_blocks = tex.findall(filestr)

    # Remove blocks and substitute by a one-line sign
    filestr = code.sub('%s \g<1>\n' % _CODE_BLOCK, filestr)
    filestr = tex.sub('%s\n' % _MATH_BLOCK, filestr)

    # Number the blocks
    lines = filestr.splitlines()
    code_block_counter = 0
    math_block_counter = 0
    for i in range(len(lines)):
        if lines[i].startswith(_CODE_BLOCK):
            lines[i] = '%d ' % code_block_counter + lines[i]
            code_block_counter += 1
        if lines[i].startswith(_MATH_BLOCK):
            lines[i] = '%d ' % math_block_counter + lines[i]
            math_block_counter += 1
    filestr = safe_join(lines, '\n')

    # Number all equations?
    if option('number_all_equations'):
        subst = [('\\begin{equation*}', '\\begin{equation}'),
                 ('\\end{equation*}', '\\end{equation}'),
                 ('\\[', '\\begin{equation} '),
                 ('\\]', '\\end{equation} '),
                 ('\\begin{align*}', '\\begin{align}'),
                 ('\\end{align*}', '\\end{align}'),
                 ]
    if option('denumber_all_equations'):
        # Remove equation numbers and also labels in those equations
        subst = [('\\begin{equation}', '\\begin{equation*}'),
                 ('\\end{equation}', '\\end{equation*}'),
                 ('\\begin{align}', '\\begin{align*}'),
                 ('\\end{align}', '\\end{align*}'),
                 ]
        removed_labels = []
        for i in range(len(tex_blocks)):
            found = False
            for construction, dummy in subst:
                if construction in tex_blocks[i]:
                    found = True
                    break
            if found:
                for from_, to_ in subst:
                    tex_blocks[i] = tex_blocks[i].replace(from_, to_)
                removed_labels += re.findall(r'label\{(.+?)\}', tex_blocks[i])
                tex_blocks[i] = re.sub(r'label\{.+?\}\n', '', tex_blocks[i])
                tex_blocks[i] = re.sub(r'label\{.+?\}', '', tex_blocks[i])
        all_refs = re.findall(r'ref\{(.+?)\}', filestr)
        problematic_refs = []
        for ref in all_refs:
            if ref in removed_labels:
                problematic_refs.append(ref)
        if problematic_refs:
            print '*** error: removed all equation labels from the DocOnce source,'
            print '    but there are still references (ref{...}) to equation labels:'
            print '\n   ', ', '.join(problematic_refs)
            print '\n    remove all these references!'
            _abort()

    # Give error if blocks contain !bt
    for i in range(len(tex_blocks)):
        if '!bt' in tex_blocks[i] or '!et' in tex_blocks[i]:
            print '*** error: double !bt or !et in latex block:'
            print tex_blocks[i]
            _abort()
#.........这里部分代码省略.........
开发者ID:sakhan007,项目名称:doconce,代码行数:101,代码来源:common.py


示例14: mwiki_figure

def mwiki_figure(m):
    filename = m.group('filename')
    link = filename if filename.startswith('http') else None
    if not link and not os.path.isfile(filename):
        raise IOError('no figure file %s' % filename)

    basename  = os.path.basename(filename)
    stem, ext = os.path.splitext(basename)
    root, ext = os.path.splitext(filename)
    if link is None:
        if not ext in '.png .gif .jpg .jpeg'.split():
            # try to convert image file to PNG, using
            # convert from ImageMagick:
            cmd = 'convert %s png:%s' % (filename, root+'.png')
            failure, output = commands.getstatusoutput(cmd)
            if failure:
                print '\n**** warning: could not run ', cmd
                print '       convert %s to PNG format manually' % filename
                _abort()
            filename = root + '.png'

    caption = m.group('caption').strip()
    if caption != '':
        caption = '|' + caption  # add | for non-empty caption
    else:
        # Avoid filename as caption when caption is empty
        # see http://www.mediawiki.org/wiki/Help:Images
        caption = '|<span title=""></span>'
    # keep label if it's there:
    caption = re.sub(r'label\{(.+?)\}', '(\g<1>)', caption)

    size = ''
    opts = m.group('options').strip()
    if opts:
        info = dict([s.split('=') for s in opts.split()])
        if 'width' in info and 'height' in info:
            size = '|%sx%spx' % (info['width'], info['height'])
        elif 'width' in info:
            size = '|%spx' % info['width']
        elif 'height' in info:
            size = '|x%spx' % info['height']

    if link:
        # We link to some image on the web
        filename = os.path.basename(filename)
        link = os.path.dirname(link)
        result = r"""
[[File:%s|frame%s|link=%s|alt=%s%s]]
""" % (filename, size, link, filename, caption)
    else:
        # We try to link to a file at wikimedia.org.
        found_wikimedia = False
        orig_filename = filename
        # Check if the file exists and find the appropriate wikimedia name.
        # http://en.wikipedia.org/w/api.php?action=query&titles=Image:filename&prop=imageinfo&format=xml

        # Skip directories - get the basename
        filename = os.path.basename(filename)
        import urllib
        prms = urllib.urlencode({
            'action': 'query', 'titles': 'Image:' + filename,
            'prop': 'imageinfo', 'format': 'xml'})
        url = 'http://en.wikipedia.org/w/api.php?' + prms
        try:
            print ' ...checking if %s is stored at en.wikipedia.org/w/api.php...' % filename
            f = urllib.urlopen(url)

            imageinfo = f.read()
            f.close()
            def get_data(name, text):
                pattern = '%s="(.*?)"' % name
                m = re.search(pattern, text)
                if m:
                    match = m.group(1)
                    if 'Image:' in match:
                        return match.split('Image:')[1]
                    if 'File:' in match:
                        return match.split('File:')[1]
                    else:
                        return match
                else:
                    return None

            data = ['from', 'to', 'title', 'missing', 'imagerepository',
                    'timestamp', 'user']
            orig_filename = filename
            filename = get_data('title', imageinfo)
            user = get_data('user', imageinfo)
            timestamp = get_data('timestamp', imageinfo)
            if user:
                found_wikimedia = True
                print ' ...found %s at wikimedia' % filename
                result = r"""
    [[File:%s|frame%s|alt=%s%s]] <!-- user: %s, filename: %s, timestamp: %s -->
    """ % (filename, size, filename, caption, user, orig_filename, timestamp)
        except IOError:
            print ' ...no Internet connection...'

        if not found_wikimedia:
            print ' ...for wikipedia/wikibooks you must upload image file %s to\n    common.wikimedia.org' % orig_filename
#.........这里部分代码省略.........
开发者ID:sakhan007,项目名称:doconce,代码行数:101,代码来源:mwiki.py


示例15: sphinx_code


#.........这里部分代码省略.........
            if option("runestone"):
                filestr = re.sub(
                    r"^!bc\s+%s\s*\n" % key,
                    """
.. activecode:: activecode_
   :language: python

""",
                    filestr,
                    flags=re.MULTILINE,
                )
            else:
                filestr = re.sub(r"^!bc\s+%s\s*\n" % key, "\n.. sagecellserver::\n\n", filestr, flags=re.MULTILINE)
        elif key == "pysccod":
            if option("runestone"):
                # Include (i.e., run) all previous code segments...
                # NOTE: this is most likely not what we want
                include = ", ".join([i for i in range(1, activecode_counter)])
                filestr = re.sub(
                    r"^!bc\s+%s\s*\n" % key,
                    """
.. activecode:: activecode_
   :language: python
   "include: %s
"""
                    % include,
                    filestr,
                    flags=re.MULTILINE,
                )
            else:
                errwarn(
                    "*** error: pysccod for sphinx is not supported without the --runestone flag\n    (but pyscpro is via Sage Cell Server)"
                )
                _abort()

        elif key == "":
            # any !bc with/without argument becomes a text block:
            filestr = re.sub(r"^!bc$", "\n.. code-block:: text\n\n", filestr, flags=re.MULTILINE)
        elif key.endswith("hid"):
            if key in ("pyhid", "jshid", "htmlhid") and option("runestone"):
                # Allow runestone books to run hidden code blocks
                # (replace pyhid by pycod, then remove all !bc *hid)
                for i in range(len(code_block_types)):
                    if code_block_types[i] == key:
                        code_block_types[i] = key.replace("hid", "cod")

                key2language = dict(py="python", js="javascript", html="html")
                language = key2language[key.replace("hid", "")]
                include = ", ".join([i for i in range(1, activecode_counter)])
                filestr = re.sub(
                    r"^!bc +%s\s*\n" % key,
                    """
.. activecode:: activecode_
   :language: %s
   :include: %s
   :hidecode:

"""
                    % (language, include),
                    filestr,
                    flags=re.MULTILINE,
                )
            else:
                # Remove hidden code block
                pattern = r"^!bc +%s\n.+?^!ec" % key
                filestr = re.sub(pattern, "", filestr, flags=re.MULTILINE | re.DOTALL)
开发者ID:dragly,项目名称:doconce,代码行数:67,代码来源:sphinx.py


示例16: ipynb_code


#.........这里部分代码省略.........
        # Add labels for the eqs above the block (for reference)
        if labels:
            #label_tp = '<a name="%s"></a>'
            label_tp = '<div id="%s"></div>'
            tex_blocks[i] = '<!-- Equation labels as ordinary links -->\n' + \
                            ' '.join([label_tp % label
                                      for label in labels]) + '\n\n' + \
                                      tex_blocks[i]

    # blocks is now a list of text chunks in markdown and math/code line
    # instructions. Insert code and tex blocks
    for i in range(len(notebook_blocks)):
        if _CODE_BLOCK in notebook_blocks[i][1] or _MATH_BLOCK in notebook_blocks[i][1]:
            words = notebook_blocks[i][1].split()
            # start of notebook_blocks[i]: number block-indicator code-type
            n = int(words[0])
            if _CODE_BLOCK in notebook_blocks[i][1]:
                notebook_blocks[i][1] = code_blocks[n]  # can be list!
            if _MATH_BLOCK in notebook_blocks[i][1]:
                notebook_blocks[i][1] = tex_blocks[n]

    # Make IPython structures

    nb_version = int(option('ipynb_version=', '4'))
    if nb_version == 3:
        try:
            from IPython.nbformat.v3 import (
                new_code_cell, new_text_cell, new_worksheet,
                new_notebook, new_metadata, new_author)
            nb = new_worksheet()
        except ImportError:
            errwarn('*** error: could not import IPython.nbformat.v3!')
            errwarn('    set --ipynb_version=4 or leave out --ipynb_version=3')
            _abort()
    elif nb_version == 4:
        try:
            from nbformat.v4 import (
                new_code_cell, new_markdown_cell, new_notebook)
        except ImportError:
            # Try old style
            try:
                from IPython.nbformat.v4 import (
                    new_code_cell, new_markdown_cell, new_notebook)
            except ImportError:
                errwarn('*** error: cannot do import nbformat.v4 or IPython.nbformat.v4')
                errwarn('    make sure IPython notebook or Jupyter is installed correctly')
                _abort()
        cells = []

    mdstr = []  # plain md format of the notebook
    prompt_number = 1
    for block_tp, block in notebook_blocks:
        if (block_tp == 'text' or block_tp == 'math') and block != '':
            # Pure comments between math/code and math/code come
            # out as empty blocks, should detect that situation
            # (challenging - can have multiple lines of comments,
            # or begin and end comment lines with important things between)
            if nb_version == 3:
                nb.cells.append(new_text_cell(u'markdown', source=block))
            elif nb_version == 4:
                cells.append(new_markdown_cell(source=block))
            mdstr.append(('markdown', block))
        elif block_tp == 'cell' and block != '' and block != []:
            if isinstance(block, list):
                for block_ in block:
                    block_ = block_.rstrip()
开发者ID:KGHustad,项目名称:doconce,代码行数:67,代码来源:ipynb.py


示例17: sphinx_quiz_runestone

def sphinx_quiz_runestone(quiz):
    quiz_feedback = option('quiz_explanations=', 'on')

    text = ''
    if 'new page' in quiz:
        text += '.. !split\n%s\n%s' % (quiz['new page'], '-'*len(quiz['new page']))

    text += '.. begin quiz\n\n'
    global question_counter
    question_counter += 1
    # Multiple correct answers?
    if sum([1 for choice in quiz['choices'] if choice[0] == 'right']) > 1:
        text += '.. mchoicema:: question_%d' % question_counter + '\n'
    else:
        text += '.. mchoicemf:: question_%d' % question_counter + '\n'

    def fix_text(s, tp='answer'):
        """
        Answers and feedback in RunestoneInteractive book quizzes
        cannot contain math, figure and rst markup. Perform fixes.
        """
        drop = False
        if 'math::' in s:
            print '\n*** warning: quiz %s with math block not supported:' % tp
            print s
            drop = True
        if '.. code-block::' in s:
            print '\n*** warning: quiz %s with code block not supported:' % tp
            print s
            drop = True
        if '.. figure::' in s:
            print '\n*** warning: quiz %s with figure not supported:' % tp
            print s
            drop = True
        if drop:
            return ''
        # Make multi-line paragraph a one-liner
        s = ' '.join(s.splitlines()).rstrip()
        # Fixes
        pattern = r'`(.+?) (<https?.+?)>`__'  # URL
        s = re.sub(pattern, '<a href="\g<2>"> \g<1> </a>', s)
        pattern = r'``(.+?)``'  # verbatim
        s = re.sub(pattern, '<tt>\g<1></tt>', s)
        pattern = r':math:`(.+?)`'  # inline math
        s = re.sub(pattern, '<em>\g<1></em>', s)  # mimic italic....
        pattern = r':\*(.+?)\*'  # emphasize
        s = re.sub(pattern, '\g<1>', s, flags=re.DOTALL)
        return s

    import string
    correct = []
    for i, choice in enumerate(quiz['choices']):
        if i > 4:  # not supported
            print '*** warning: quiz with %d choices gets truncated (first 5)' % len(quiz['choices'])
            break
        letter = string.ascii_lowercase[i]
        text += '   :answer_%s: ' % letter
        answer = fix_text(choice[1], tp='answer')
        if not answer:
            answer = 'Too advanced typesetting prevents the text from being rendered'
        text += answer + '\n'
        if choice[0] == 'right':
            correct.append(letter)
    if correct:
        text += '   :correct: ' + ', '.join(correct) + '\n'
    else:
        print '*** error: correct choice in quiz has index > 5 (max 5 allowed for RunestoneInteractive books)'
        print quiz['question']
        _abort()
    for i, choice in enumerate(quiz['choices']):
        if i > 4:  # not supported
            break
        letter = string.ascii_lowercase[i]
        text += '   :feedback_%s: ' % letter  # must be present
        if len(choice) == 3 and quiz_feedback == 'on':
            feedback = fix_text(choice[2], tp='explanation')
            if not feedback:
                feedback = '(Too advanced typesetting prevents the text from being rendered)'
            text += feedback
        text += '\n'

    text += '\n' + indent_lines(quiz['question'], 'sphinx', ' '*3) + '\n\n\n'
    return text
开发者ID:apetcho,项目名称:doconce,代码行数:83,代码来源:sphinx.py


示例18: sphinx_code


#.........这里部分代码省略.........
            if option('runestone'):
                filestr = re.sub(r'^!bc\s+%s\s*\n' % key,
                    '\n.. codelens:: codelens_\n   :showoutput:\n\n',
                    filestr, flags=re.MULTILINE)
            else:
                filestr = re.sub(r'^!bc\s+%s\s*\n' % key,
                                 '\n.. raw:: html\n\n',
                                 filestr, flags=re.MULTILINE)
        elif key == 'pyscpro':
            if option('runestone'):
                filestr = re.sub(r'^!bc\s+%s\s*\n' % key,
                                 """
.. activecode:: activecode_
   :language: python

""", filestr, flags=re.MULTILINE)
            else:
                filestr = re.sub(r'^!bc\s+%s\s*\n' % key,
                                 '\n.. sagecellserver::\n\n',
                                 filestr, flags=re.MULTILINE)
        elif key == 'pysccod':
            if option('runestone'):
                # Include (i.e., run) all previous code segments...
                # NOTE: this is most likely not what we want
                include = ', '.join([i for i in ra 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python misc._datacopied函数代码示例发布时间:2022-05-27
下一篇:
Python misc._函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap