def initialize(self, paramnames, width): """Set up and display widget. Parameters ---------- paramnames: list of str Parameter names width: int number of html table columns. """ from ipywidgets import HTML, VBox, GridBox, Layout, GridspecLayout from IPython.display import display grid = GridspecLayout(len(paramnames), width + 3) self.laststatus = [] for a, paramname in enumerate(paramnames): self.laststatus.append('*' * width) htmlcode = "<div style='background-color:#6E6BF4;'> </div>" for b in range(width): grid[a, b + 2] = HTML(htmlcode, layout=Layout(margin="0")) htmlcode = "<div style='background-color:#FFB858; font-weight:bold; padding-right: 2em;'>%s</div>" grid[a, 0] = HTML(htmlcode % html_escape(paramname), layout=Layout(margin="0")) grid[a, 1] = HTML("...", layout=Layout(margin="0")) grid[a,-1] = HTML("...", layout=Layout(margin="0")) self.grid = grid self.label = HTML() box = VBox(children=[self.label, grid]) display(box)
def _save_annotation_body(self, cython_code, generated_code): outlist = [u'<div class="cython">'] pos_comment_marker = u'/* \N{HORIZONTAL ELLIPSIS} */\n' new_calls_map = dict( (name, 0) for name in 'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto' .split()).copy self.mark_pos(None) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return ur"<span class='%s'>%s</span>" % (group_name, match.group(group_name)) lines = self._htmlify_code(cython_code).splitlines() lineno_width = len(str(len(lines))) for k, line in enumerate(lines, 1): try: c_code = generated_code[k] except KeyError: c_code = '' else: c_code = _replace_pos_comment(pos_comment_marker, c_code) if c_code.startswith(pos_comment_marker): c_code = c_code[len(pos_comment_marker):] c_code = html_escape(c_code) calls = new_calls_map() c_code = _parse_code(annotate, c_code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) if c_code: onclick = " onclick='toggleDiv(this)'" expandsymbol = '+' else: onclick = '' expandsymbol = ' ' outlist.append( u"<pre class='cython line score-{score}'{onclick}>" # generate line number with expand symbol in front, # and the right number of digit u"{expandsymbol}{line:0{lineno_width}d}: {code}</pre>\n". format( score=score, expandsymbol=expandsymbol, lineno_width=lineno_width, line=k, code=line.rstrip(), onclick=onclick, )) if c_code: outlist.append(u"<pre class='cython code score-%s'>%s</pre>" % (score, c_code)) outlist.append(u"</div>") return outlist
def _insert_link(self): ref = self.tpl.docx._part.relate_to( self.url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) return '</w:t></w:r><w:hyperlink r:id="%s"><w:r><w:rPr><w:rStyle w:val="InternetLink"/></w:rPr><w:t>%s</w:t></w:r></w:hyperlink><w:r><w:rPr></w:rPr><w:t xml:space="preserve">' % ( ref, html_escape(self.anchor_text))
def update_p(self, p): fields = ("status", "priority", "support", "author", "depends") extras = ["{}: <b>{}</b>".format(n, html_escape(p[n])) for n in fields if p.get(n)] p["extras"] = " ".join(["💁"] + extras) p["file"] = p["$file"].replace("/cat/", "/doc/tip/") for field in ("version", "title", "description", "type", "category"): p.setdefault(field, "-") return p
def _save_annotation_body(self, cython_code, generated_code): outlist = ['<div class="cython">'] pos_comment_marker = '/* \N{HORIZONTAL ELLIPSIS} */\n' new_calls_map = dict( (name, 0) for name in 'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto'.split() ).copy self.mark_pos(None) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return r"<span class='%s'>%s</span>" % ( group_name, match.group(group_name)) lines = self._htmlify_code(cython_code).splitlines() lineno_width = len(str(len(lines))) for k, line in enumerate(lines, 1): try: c_code = generated_code[k] except KeyError: c_code = '' else: c_code = _replace_pos_comment(pos_comment_marker, c_code) if c_code.startswith(pos_comment_marker): c_code = c_code[len(pos_comment_marker):] c_code = html_escape(c_code) calls = new_calls_map() c_code = _parse_code(annotate, c_code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) if c_code: onclick = " onclick='toggleDiv(this)'" expandsymbol = '+' else: onclick = '' expandsymbol = ' ' outlist.append( "<pre class='cython line score-{score}'{onclick}>" # generate line number with expand symbol in front, # and the right number of digit "{expandsymbol}{line:0{lineno_width}d}: {code}</pre>\n".format( score=score, expandsymbol=expandsymbol, lineno_width=lineno_width, line=k, code=line.rstrip(), onclick=onclick, )) if c_code: outlist.append("<pre class='cython code score-%s'>%s</pre>" % (score, c_code)) outlist.append("</div>") return outlist
def _htmlify_code(self, code, language): try: from pygments import highlight from pygments.lexers import CythonLexer, CppLexer from pygments.formatters import HtmlFormatter except ImportError: # no Pygments, just escape the code return html_escape(code) if language == "cython": lexer = CythonLexer(stripnl=False, stripall=False) elif language == "c/cpp": lexer = CppLexer(stripnl=False, stripall=False) else: # unknown language, use fallback return html_escape(code) html_code = highlight(code, lexer, HtmlFormatter(nowrap=True)) return html_code
def _htmlify_code(self, code): try: from pygments import highlight from pygments.lexers import CythonLexer from pygments.formatters import HtmlFormatter except ImportError: # no Pygments, just escape the code return html_escape(code) html_code = highlight(code, CythonLexer(stripnl=False, stripall=False), HtmlFormatter(nowrap=True)) return html_code
def _error_as_json_cargo__Error(self, error): std_cargo = error.as_json_cargo result = {} anr = self.attr_name_replacer for k in error._mf3_json_attributes: v = std_cargo.get(k) if v is not None: if isinstance(v, pyk.string_types): v = anr(html_escape(v)) result[k] = v return result
def _error_as_json_cargo__Error (self, error) : std_cargo = error.as_json_cargo result = {} anr = self.attr_name_replacer for k in error._mf3_json_attributes : v = std_cargo.get (k) if v is not None : if isinstance (v, pyk.string_types) : v = anr (html_escape (v)) result [k] = v return result
def _replace(self, match): result = match.group("name") try: f = self.field_map[result] except KeyError: pass else: head = match.group("head") tail = match.group("tail") result = """%s<a data-id="%s">%s</a>%s""" % \ (head, f.id, html_escape (_T (f.label)), tail) return result
def RClansiconv(inputtext, escape=True): """ Uses Krounz/ansi2html (MIT) renamed to produce a reasonably minimal html.""" if _debugging: logging.debug('Received ' + inputtext) txt = html_escape(inputtext) if escape else inputtext txt = re.sub("\n", "<br>\n", txt) txt = re.sub(" ", r" ", txt) try: rettxt = unicode(txt, 'utf-8') # we get unicode characters from IPython sometimes except: rettxt = txt # if it is already unicode htmlFragment = ansi2html(rettxt).encode('ascii', 'xmlcharrefreplace') return _textFormatStr.format(htmlFragment)
def _replace (self, match) : result = match.group ("name") try : f = self.field_map [result] except KeyError : pass else : head = match.group ("head") tail = match.group ("tail") result = """%s<a data-id="%s">%s</a>%s""" % \ (head, f.id, html_escape (_T (f.label)), tail) return result
def RClansiconv(inputtext, escape=True): """ Uses Krounz/ansi2html (MIT) renamed to produce a reasonably minimal html.""" if _debugging: logging.debug('Received ' + inputtext) txt = html_escape(inputtext) if escape else inputtext txt = re.sub("\n", "<br>\n", txt) txt = re.sub(" ", r" ", txt) try: rettxt = unicode( txt, 'utf-8') # we get unicode characters from IPython sometimes except: rettxt = txt # if it is already unicode htmlFragment = ansi2html(rettxt).encode('ascii', 'xmlcharrefreplace') return _textFormatStr.format(htmlFragment)
def _preprocess(self, s_html): to_tag = lambda t: lambda m: '<%s>%s</%s>' % (t, html_escape(m), t) s_html = self._preprocess_inline_javadoc_replace('code', to_tag('code'), s_html) s_html = self._preprocess_inline_javadoc_replace('literal', to_tag('span'), s_html) s_html = self._preprocess_inline_javadoc_replace('docRoot', lambda m: '', s_html) s_html = self._preprocess_inline_javadoc_replace('linkplain', self._preprocess_replace_javadoc_link, s_html) s_html = self._preprocess_inline_javadoc_replace('link', self._preprocess_replace_javadoc_link, s_html) # Make sure all anchor tags are closed s_html = self._preprocess_close_anchor_tags(s_html) # Fix up some entitities without closing ; s_html = self._preprocess_fix_entities(s_html) return s_html
def _preprocess(self, s_html): to_tag = lambda t: lambda m: "<%s>%s</%s>" % (t, html_escape(m), t) s_html = self._preprocess_inline_javadoc_replace("code", to_tag("code"), s_html) s_html = self._preprocess_inline_javadoc_replace("literal", to_tag("span"), s_html) s_html = self._preprocess_inline_javadoc_replace("docRoot", lambda m: "", s_html) s_html = self._preprocess_inline_javadoc_replace("linkplain", self._preprocess_replace_javadoc_link, s_html) s_html = self._preprocess_inline_javadoc_replace("link", self._preprocess_replace_javadoc_link, s_html) # Make sure all anchor tags are closed s_html = self._preprocess_close_anchor_tags(s_html) # Fix up some entitities without closing ; s_html = self._preprocess_fix_entities(s_html) return s_html
def get_rows(servers, types): """Generate the HTML code for the table rows (without the <tr> element!) Use singleton to generate them only once""" global ROWS if ROWS is not None: return ROWS ROWS = {} component_jid = lambda component: component.get("jid") for server_key, server in servers.iteritems(): jid = server["jid"] if SHRINK_SERVERNAMES and len(jid) > SHRINK_SERVERNAMES_TO: server_name = jid[: SHRINK_SERVERNAMES_TO - 3] + "..." else: server_name = jid tooltip = jid if "about" in server and "homepage" in server["about"]: server_name = "<a href='%s' name='%s' >%s</a>" % (server["about"]["homepage"], jid, server_name) tooltip = u"<a href='%s'>%s</a>" % (server["about"]["homepage"], tooltip) else: server_name = "<a name='%s' >%s</a>" % (jid, server_name) tooltip = u"<strong>%s</strong><ul>" % tooltip if "about" in server: if "latitude" in server["about"] and "longitude" in server["about"]: if "city" in server["about"] and "country" in server["about"]: tooltip = ( u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s, %s</a></li>" % ( tooltip, server["about"]["latitude"], server["about"]["longitude"], jid, server["about"]["city"], server["about"]["country"], ) ) elif "country" in server["about"]: tooltip = ( u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s</a></li>" % ( tooltip, server["about"]["latitude"], server["about"]["longitude"], jid, server["about"]["country"], ) ) else: tooltip = ( u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location</a></li>" % (tooltip, server["about"]["latitude"], server["about"]["longitude"], jid) ) elif "city" in server["about"] and "country" in server["about"]: tooltip = ( u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s, %s</a></li>" % ( tooltip, server["about"]["city"], server["about"]["country"], jid, server["about"]["city"], server["about"]["country"], ) ) elif "country" in server["about"]: tooltip = u"%s<li>Location: %s</li>" % (tooltip, server["about"]["country"]) if "ipv6_ready" in server and server["ipv6_ready"]: tooltip = u"%s<li>IPv6 Ready</li>" % tooltip tooltip = u"%s</ul>" % tooltip if "about" in server and "description" in server["about"]: assert server["about"]["description"] is not None tooltip = u"%s<p>%s</p>" % (tooltip, html_escape(server["about"]["description"])) server_text = u"<div class='tooltip_container'>%s<div class='tooltip'><span>%s</span></div></div>" % ( server_name, tooltip, ) if "version" in server: (impl_name, impl_web, impl_logo) = _get_server_implementation_info(server["version"]) version_info = u"%s - %s" % (server["version"]["name"], server["version"]["version"]) else: (impl_name, impl_web, impl_logo) = _get_server_implementation_info(None) version_info = "" impl_text = "<img src='%s' width='16' height='16' alt='%s' title='%s'/>" % ( impl_logo, version_info, version_info, ) if impl_web: impl_text = "<a href='%s'>%s</a>" % (impl_web, impl_text) row = u"""<td class='server'>%s %s</td>""" % (impl_text, server_text) for service_type in types: if service_type not in server["available_services"] and service_type not in server["unavailable_services"]: row += """<td class='feature no %s_%s'></td>""" % (service_type[0], service_type[1]) else: if service_type in server["available_services"]: service_available = True else: service_available = False row += """<td class='feature yes %s %s_%s'>""" % ( "available" if service_available else "unavailable", service_type[0], service_type[1], ) row += "<div class='tooltip_container'>" row += """<img src='%s' width='16' height='16' alt='Yes' />""" % _get_image_filename( service_type, service_available ) row += "<div class='tooltip'>" if service_type in server["available_services"]: for component in sorted(server["available_services"][service_type], key=component_jid): row += """<span class='available'>%s</span>""" % ( "%s (%s)" % (component[u"jid"], component[u"node"]) if "node" in component else component[u"jid"] ) if service_type in server["unavailable_services"]: for component in sorted(server["unavailable_services"][service_type], key=component_jid): row += """<span class='unavailable'>%s</span>""" % ( "%s (%s)" % (component[u"jid"], component[u"node"]) if "node" in component else component[u"jid"] ) row += "</div></div></td>" if server["offline_since"] is None: if "uptime" in server: uptime = timedelta(seconds=server["uptime"]) # uptime_text = "%dd, %dh, %dm, %ds" % ( # uptime.days, uptime.seconds / 3600, # uptime.seconds % 3600 / 60, uptime.seconds % 60 ) uptime_text = str(uptime) else: uptime_text = "" else: uptime_text = "Offline since %s" % server["offline_since"].strftime("%d %b %Y %H:%M UTC") row += "<td class='uptime'>%s</td>" % uptime_text row += "<td class='times_online'>%d%% (%d/%d)</td>" % ( int(100 * server["times_queried_online"] / server["times_queried"]), server["times_queried_online"], server["times_queried"], ) ROWS[server_key] = row return ROWS
def _save_annotation_body(self, cython_code, generated_code, annotation_items, scopes, covered_lines=None): outlist = [u'<div class="cython">'] pos_comment_marker = u'/* \N{HORIZONTAL ELLIPSIS} */\n' new_calls_map = dict( (name, 0) for name in 'refnanny trace py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto' .split()).copy self.mark_pos(None) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return u"<span class='%s'>%s</span>" % (group_name, match.group(group_name)) lines = self._htmlify_code(cython_code, "cython").splitlines() lineno_width = len(str(len(lines))) if not covered_lines: covered_lines = None for k, line in enumerate(lines, 1): try: c_code = generated_code[k] except KeyError: c_code = '' else: c_code = _replace_pos_comment(pos_comment_marker, c_code) if c_code.startswith(pos_comment_marker): c_code = c_code[len(pos_comment_marker):] c_code = html_escape(c_code) calls = new_calls_map() c_code = _parse_code(annotate, c_code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) if c_code: onclick = self._onclick_attr expandsymbol = '+' else: onclick = '' expandsymbol = ' ' covered = '' if covered_lines is not None and k in covered_lines: hits = covered_lines[k] if hits is not None: covered = 'run' if hits else 'mis' outlist.append( u'<pre class="cython line score-{score}"{onclick}>' # generate line number with expand symbol in front, # and the right number of digit u'{expandsymbol}<span class="{covered}">{line:0{lineno_width}d}</span>: {code}</pre>\n' .format( score=score, expandsymbol=expandsymbol, covered=covered, lineno_width=lineno_width, line=k, code=line.rstrip(), onclick=onclick, )) if c_code: outlist.append( u"<pre class='cython code score-{score} {covered}'>{code}</pre>" .format(score=score, covered=covered, code=c_code)) outlist.append(u"</div>") # now the whole c-code if needed: if self.show_entire_c_code: outlist.append(u'<p><div class="cython">') onclick_title = u"<pre class='cython line'{onclick}>+ {title}</pre>\n" outlist.append( onclick_title.format( onclick=self._onclick_attr, title=AnnotationCCodeWriter.COMPLETE_CODE_TITLE, )) complete_code_as_html = self._htmlify_code(self.buffer.getvalue(), "c/cpp") outlist.append(u"<pre class='cython code'>{code}</pre>".format( code=complete_code_as_html)) outlist.append(u"</div></p>") return outlist
def RClTextFormat(s, escape=True): newtext = html_escape(s) if escape else s return _textFormatStr.format(newtext)
def _insert_link(self): ref = self.tpl.docx._part.relate_to(self.url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) return '</w:t></w:r><w:hyperlink r:id="%s"><w:r><w:rPr><w:rStyle w:val="InternetLink"/></w:rPr><w:t>%s</w:t></w:r></w:hyperlink><w:r><w:rPr></w:rPr><w:t xml:space="preserve">' % (ref, html_escape(self.anchor_text))
def escape(s): if not isinstance(s, basestring): s = repr(s).decode('unicode_escape') return html_escape(s).encode('utf-8')
def get_rows(servers, types): """Generate the HTML code for the table rows (without the <tr> element!) Use singleton to generate them only once""" global ROWS if ROWS is not None: return ROWS ROWS = {} component_jid = lambda component: component.get('jid') for server_key, server in servers.iteritems(): jid = server['jid'] if SHRINK_SERVERNAMES and len(jid) > SHRINK_SERVERNAMES_TO: server_name = (jid[:SHRINK_SERVERNAMES_TO - 3] + '...') else: server_name = jid tooltip = jid if 'about' in server and 'homepage' in server['about']: server_name = "<a href='%s' name='%s' >%s</a>" % ( server['about']['homepage'], jid, server_name) tooltip = u"<a href='%s'>%s</a>" % (server['about']['homepage'], tooltip) else: server_name = "<a name='%s' >%s</a>" % (jid, server_name) tooltip = u"<strong>%s</strong><ul>" % tooltip if 'about' in server: if 'latitude' in server['about'] and 'longitude' in server['about']: if 'city' in server['about'] and 'country' in server['about']: tooltip = u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s, %s</a></li>" % ( tooltip, server['about']['latitude'], server['about']['longitude'], jid, server['about']['city'], server['about']['country']) elif 'country' in server['about']: tooltip = u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s</a></li>" % ( tooltip, server['about']['latitude'], server['about']['longitude'], jid, server['about']['country']) else: tooltip = u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location</a></li>" % ( tooltip, server['about']['latitude'], server['about']['longitude'], jid) elif 'city' in server['about'] and 'country' in server['about']: tooltip = u"%s<li><a href='http://maps.google.com/maps?q=%s,+%s+(%s)&iwloc=A&hl=en'>Location: %s, %s</a></li>" % ( tooltip, server['about']['city'], server['about']['country'], jid, server['about']['city'], server['about']['country']) elif 'country' in server['about']: tooltip = u"%s<li>Location: %s</li>" % ( tooltip, server['about']['country']) if 'ipv6_ready' in server and server['ipv6_ready']: tooltip = u"%s<li>IPv6 Ready</li>" % tooltip tooltip = u"%s</ul>" % tooltip if 'about' in server and 'description' in server['about']: assert server['about']['description'] is not None tooltip = u"%s<p>%s</p>" % ( tooltip, html_escape(server['about']['description'])) server_text = u"<div class='tooltip_container'>%s<div class='tooltip'><span>%s</span></div></div>" % ( server_name, tooltip) if 'version' in server: (impl_name, impl_web, impl_logo) = _get_server_implementation_info(server['version']) version_info = u"%s - %s" % (server['version']['name'], server['version']['version']) else: (impl_name, impl_web, impl_logo) = _get_server_implementation_info(None) version_info = '' impl_text = "<img src='%s' width='16' height='16' alt='%s' title='%s'/>" % ( impl_logo, version_info, version_info) if impl_web: impl_text = "<a href='%s'>%s</a>" % (impl_web, impl_text) row = (u"""<td class='server'>%s %s</td>""" % (impl_text, server_text)) for service_type in types: if (service_type not in server['available_services'] and service_type not in server['unavailable_services']): row += """<td class='feature no %s_%s'></td>""" % ( service_type[0], service_type[1]) else: if service_type in server['available_services']: service_available = True else: service_available = False row += """<td class='feature yes %s %s_%s'>""" % ( 'available' if service_available else 'unavailable', service_type[0], service_type[1]) row += "<div class='tooltip_container'>" row += ( """<img src='%s' width='16' height='16' alt='Yes' />""" % _get_image_filename(service_type, service_available)) row += "<div class='tooltip'>" if service_type in server['available_services']: for component in sorted( server['available_services'][service_type], key=component_jid): row += """<span class='available'>%s</span>""" % ( "%s (%s)" % (component[u'jid'], component[u'node']) if 'node' in component else component[u'jid']) if service_type in server['unavailable_services']: for component in sorted( server['unavailable_services'][service_type], key=component_jid): row += """<span class='unavailable'>%s</span>""" % ( "%s (%s)" % (component[u'jid'], component[u'node']) if 'node' in component else component[u'jid']) row += "</div></div></td>" if server['offline_since'] is None: if 'uptime' in server: uptime = timedelta(seconds=server['uptime']) #uptime_text = "%dd, %dh, %dm, %ds" % ( #uptime.days, uptime.seconds / 3600, #uptime.seconds % 3600 / 60, uptime.seconds % 60 ) uptime_text = str(uptime) else: uptime_text = '' else: uptime_text = "Offline since %s" % server[ 'offline_since'].strftime('%d %b %Y %H:%M UTC') row += "<td class='uptime'>%s</td>" % uptime_text row += "<td class='times_online'>%d%% (%d/%d)</td>" % (int( 100 * server['times_queried_online'] / server['times_queried'] ), server['times_queried_online'], server['times_queried']) ROWS[server_key] = row return ROWS
def save_annotation(self, source_filename, target_filename): self.mark_pos(None) f = Utils.open_source_file(source_filename) lines = f.readlines() for k, line in enumerate(lines): for c, cc, html in special_chars: line = line.replace(c, cc) lines[k] = line f.close() all = [] if False: for pos, item in self.annotations: if pos[0].filename == source_filename: start = item.start() size, end = item.end() if size: all.append((pos, start)) all.append(((source_filename, pos[1], pos[2]+size), end)) else: all.append((pos, start+end)) all.sort(reverse=True) for pos, item in all: _, line_no, col = pos line_no -= 1 col += 1 line = lines[line_no] lines[line_no] = line[:col] + item + line[col:] html_filename = os.path.splitext(target_filename)[0] + ".html" f = codecs.open(html_filename, "w", encoding="UTF-8") f.write('<!DOCTYPE html>\n') f.write('<!-- Generated by Cython %s -->\n' % Version.watermark) f.write('<html>\n') f.write(""" <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-family: courier; font-size: 12; } .code { font-size: 9; color: #444444; display: none; margin-left: 20px; } .py_c_api { color: red; } .py_macro_api { color: #FF7000; } .pyx_c_api { color: #FF3000; } .pyx_macro_api { color: #FF7000; } .refnanny { color: #FFA000; } .error_goto { color: #FFA000; } .tag { } .coerce { color: #008000; border: 1px dotted #008000 } .py_attr { color: #FF0000; font-weight: bold; } .c_attr { color: #0000FF; } .py_call { color: #FF0000; font-weight: bold; } .c_call { color: #0000FF; } .line { margin: 0em } </style> <script> function toggleDiv(id) { theDiv = document.getElementById(id); if (theDiv.style.display != 'block') theDiv.style.display = 'block'; else theDiv.style.display = 'none'; } </script> </head> """) f.write('<body>\n') f.write('<p>Generated by Cython %s\n' % Version.watermark) c_file = Utils.decode_filename(os.path.basename(target_filename)) f.write('<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file)) zero_calls = dict((name, 0) for name in 'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto'.split()) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return r"<span class='%s'>%s</span>" % ( group_name, match.group(group_name)) pos_comment_marker = '/* \N{HORIZONTAL ELLIPSIS} */\n' k = 0 code_source_file = self.code.get(source_filename, {}) for line in lines: k += 1 try: code = code_source_file[k] except KeyError: code = '' else: code = _replace_pos_comment(pos_comment_marker, code) if code.startswith(pos_comment_marker): code = code[len(pos_comment_marker):] code = html_escape(code) calls = zero_calls.copy() code = _parse_code(annotate, code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) color = "FFFF%02x" % int(255/(1+score/10.0)) f.write("<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k)) f.write(" %d: " % k) for c, cc, html in special_chars: line = line.replace(cc, html) f.write(line.rstrip()) f.write('</pre>\n') f.write("<pre id='line%s' class='code' style='background-color: #%s'>%s</pre>" % (k, color, code)) f.write('</body></html>\n') f.close()
def _save_annotation_body(self, cython_code, generated_code, annotation_items, scopes, covered_lines=None): outlist = [u'<div class="cython">'] pos_comment_marker = u'/* \N{HORIZONTAL ELLIPSIS} */\n' new_calls_map = dict( (name, 0) for name in 'refnanny trace py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto'.split() ).copy self.mark_pos(None) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return u"<span class='%s'>%s</span>" % ( group_name, match.group(group_name)) lines = self._htmlify_code(cython_code).splitlines() lineno_width = len(str(len(lines))) if not covered_lines: covered_lines = None for k, line in enumerate(lines, 1): try: c_code = generated_code[k] except KeyError: c_code = '' else: c_code = _replace_pos_comment(pos_comment_marker, c_code) if c_code.startswith(pos_comment_marker): c_code = c_code[len(pos_comment_marker):] c_code = html_escape(c_code) calls = new_calls_map() c_code = _parse_code(annotate, c_code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) if c_code: onclick = textwrap.dedent(''' onclick=" this.nextElementSibling.style.display != 'block' ? this.nextElementSibling.style.display = 'block' : this.nextElementSibling.style.display = 'none' "''').replace('\n', '') expandsymbol = '+' else: onclick = '' expandsymbol = ' ' covered = '' if covered_lines is not None and k in covered_lines: hits = covered_lines[k] if hits is not None: covered = 'run' if hits else 'mis' outlist.append( u'<pre class="cython line score-{score}"{onclick}>' # generate line number with expand symbol in front, # and the right number of digit u'{expandsymbol}<span class="{covered}">{line:0{lineno_width}d}</span>: {code}</pre>\n'.format( score=score, expandsymbol=expandsymbol, covered=covered, lineno_width=lineno_width, line=k, code=line.rstrip(), onclick=onclick, )) if c_code: outlist.append(u"<pre class='cython code score-{score} {covered}'>{code}</pre>".format( score=score, covered=covered, code=c_code)) outlist.append(u"</div>") return outlist
def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" html_escape_table = {'"': """, "'": "'"} return html_escape(html, html_escape_table)
def _save_annotation_body(self, cython_code, generated_code, annotation_items, scopes, covered_lines=None): outlist = [u'<div class="cython">'] pos_comment_marker = u"/* \N{HORIZONTAL ELLIPSIS} */\n" new_calls_map = dict( (name, 0) for name in "refnanny trace py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto".split() ).copy self.mark_pos(None) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return u"<span class='%s'>%s</span>" % (group_name, match.group(group_name)) lines = self._htmlify_code(cython_code).splitlines() lineno_width = len(str(len(lines))) if not covered_lines: covered_lines = None for k, line in enumerate(lines, 1): try: c_code = generated_code[k] except KeyError: c_code = "" else: c_code = _replace_pos_comment(pos_comment_marker, c_code) if c_code.startswith(pos_comment_marker): c_code = c_code[len(pos_comment_marker) :] c_code = html_escape(c_code) calls = new_calls_map() c_code = _parse_code(annotate, c_code) score = 5 * calls["py_c_api"] + 2 * calls["pyx_c_api"] + calls["py_macro_api"] + calls["pyx_macro_api"] if c_code: onclick = " onclick='toggleDiv(this)'" expandsymbol = "+" else: onclick = "" expandsymbol = " " covered = "" if covered_lines is not None and k in covered_lines: hits = covered_lines[k] if hits is not None: covered = "run" if hits else "mis" outlist.append( u'<pre class="cython line score-{score}"{onclick}>' # generate line number with expand symbol in front, # and the right number of digit u'{expandsymbol}<span class="{covered}">{line:0{lineno_width}d}</span>: {code}</pre>\n'.format( score=score, expandsymbol=expandsymbol, covered=covered, lineno_width=lineno_width, line=k, code=line.rstrip(), onclick=onclick, ) ) if c_code: outlist.append( u"<pre class='cython code score-{score} {covered}'>{code}</pre>".format( score=score, covered=covered, code=c_code ) ) outlist.append(u"</div>") return outlist
def save_annotation(self, source_filename, target_filename): self.mark_pos(None) f = Utils.open_source_file(source_filename) lines = f.readlines() for k, line in enumerate(lines): for c, cc, html in special_chars: line = line.replace(c, cc) lines[k] = line f.close() all = [] if False: for pos, item in self.annotations: if pos[0].filename == source_filename: start = item.start() size, end = item.end() if size: all.append((pos, start)) all.append( ((source_filename, pos[1], pos[2] + size), end)) else: all.append((pos, start + end)) all.sort(reverse=True) for pos, item in all: _, line_no, col = pos line_no -= 1 col += 1 line = lines[line_no] lines[line_no] = line[:col] + item + line[col:] html_filename = os.path.splitext(target_filename)[0] + ".html" f = codecs.open(html_filename, "w", encoding="UTF-8") f.write(u'<!DOCTYPE html>\n') f.write(u'<!-- Generated by Cython %s -->\n' % Version.watermark) f.write(u'<html>\n') f.write(u""" <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-family: courier; font-size: 12; } .code { font-size: 9; color: #444444; display: none; margin-left: 20px; } .py_c_api { color: red; } .py_macro_api { color: #FF7000; } .pyx_c_api { color: #FF3000; } .pyx_macro_api { color: #FF7000; } .refnanny { color: #FFA000; } .error_goto { color: #FFA000; } .tag { } .coerce { color: #008000; border: 1px dotted #008000 } .py_attr { color: #FF0000; font-weight: bold; } .c_attr { color: #0000FF; } .py_call { color: #FF0000; font-weight: bold; } .c_call { color: #0000FF; } .line { margin: 0em } </style> <script> function toggleDiv(id) { theDiv = document.getElementById(id); if (theDiv.style.display != 'block') theDiv.style.display = 'block'; else theDiv.style.display = 'none'; } </script> </head> """) f.write(u'<body>\n') f.write(u'<p>Generated by Cython %s\n' % Version.watermark) c_file = Utils.decode_filename(os.path.basename(target_filename)) f.write(u'<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file)) zero_calls = dict( (name, 0) for name in 'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto' .split()) def annotate(match): group_name = match.lastgroup calls[group_name] += 1 return ur"<span class='%s'>%s</span>" % (group_name, match.group(group_name)) pos_comment_marker = u'/* \N{HORIZONTAL ELLIPSIS} */\n' k = 0 code_source_file = self.code.get(source_filename, {}) for line in lines: k += 1 try: code = code_source_file[k] except KeyError: code = '' else: code = _replace_pos_comment(pos_comment_marker, code) if code.startswith(pos_comment_marker): code = code[len(pos_comment_marker):] code = html_escape(code) calls = zero_calls.copy() code = _parse_code(annotate, code) score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] + calls['py_macro_api'] + calls['pyx_macro_api']) color = u"FFFF%02x" % int(255 / (1 + score / 10.0)) f.write( u"<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k)) f.write(u" %d: " % k) for c, cc, html in special_chars: line = line.replace(cc, html) f.write(line.rstrip()) f.write(u'</pre>\n') f.write( u"<pre id='line%s' class='code' style='background-color: #%s'>%s</pre>" % (k, color, code)) f.write(u'</body></html>\n') f.close()