def document_collection(resource, path, root_discovery, discovery, css=CSS): """Document a single collection in an API. Args: resource: Collection or service being documented. path: string, Dot separated name of the resource. root_discovery: Deserialized discovery document. discovery: Deserialized discovery document, but just the portion that describes the resource. css: string, The CSS to include in the generated file. """ collections = [] methods = [] resource_name = path.split(".")[-2] html = [ "<html><body>", css, "<h1>%s</h1>" % breadcrumbs(path[:-1], root_discovery), "<h2>Instance Methods</h2>", ] # Which methods are for collections. for name in dir(resource): if not name.startswith("_") and callable(getattr(resource, name)): if hasattr(getattr(resource, name), "__is_resource__"): collections.append(name) else: methods.append(name) # TOC if collections: for name in collections: if not name.startswith("_") and callable(getattr(resource, name)): href = path + name + ".html" html.append( string.Template(COLLECTION_LINK).substitute(href=href, name=name) ) if methods: for name in methods: if not name.startswith("_") and callable(getattr(resource, name)): doc = getattr(resource, name).__doc__ params = method_params(doc) firstline = doc.splitlines()[0] html.append( string.Template(METHOD_LINK).substitute( name=name, params=params, firstline=firstline ) ) if methods: html.append("<h3>Method Details</h3>") for name in methods: dname = name.rsplit("_")[0] html.append(method(name, getattr(resource, name).__doc__)) html.append("</body></html>") return "\n".join(html)
def html_render_page(tree): soup = bs4.BeautifulSoup() html = soup.new_tag('html') soup.append(html) head = soup.new_tag('head') html.append(head) style = soup.new_tag('style') style.append(''' .comment, .job, .poll, .pollopt, .story { padding-left: 20px; margin-top: 4px; margin-right: 4px; margin-bottom: 4px; } .job, .poll, .story { border: 2px solid blue; } body > .story + .comment, body > .comment + .comment { margin-top: 10px; } .comment, .pollopt { border: 1px solid black; } ''') head.append(style) body = soup.new_tag('body') html.append(body) item = tree.data if item['type'] == 'comment': body.append(html_render_comment_tree(soup=soup, tree=tree)) elif item['type'] == 'job': body.append(html_render_job(soup=soup, item=item)) elif item['type'] == 'poll': body.append(html_render_poll(soup=soup, item=item)) for child in tree.list_children(sort=lambda node: node.data['time']): body.append(html_render_comment_tree(soup=soup, tree=child)) elif item['type'] == 'story': body.append(html_render_story(soup=soup, item=item)) for child in tree.list_children(sort=lambda node: node.data['time']): body.append(html_render_comment_tree(soup=soup, tree=child)) return soup
async def zlist(self, bot, event, room, user): html = E.TABLE() html.append(E.TR(E.TH('id'), E.TH('name'))) for unused_id, game in sorted(self.games.items(), key=lambda x: x[1]['name']): html.append(E.TR(E.TD(game['id']), E.TD(game['name']))) html_data = lxml.html.tostring(html, pretty_print=True).decode('utf-8') await bot.send_room_html(room, html_data)
def display_retainers(retainers): html = ["<p>"] for retaining_nodes, retained_nodes in retainers.items(): for node in retaining_nodes: html.append("{}".format(render_node(node))) html.append("<ul>") for node in retained_nodes: html.append("<li>{}</li>".format(render_node(node))) html.append("</ul>") html.append("</p>") display(HTML("".join(html)))
def generate_epub(story, cover_options={}, output_filename=None, normalize=False): dates = list(story.dates()) metadata = { 'title': story.title, 'author': story.author, 'unique_id': story.url, 'started': min(dates), 'updated': max(dates), } valid_cover_options = ('fontname', 'fontsize', 'width', 'height', 'wrapat', 'bgcolor', 'textcolor', 'cover_url') cover_options = CoverOptions( **{k: v for k, v in cover_options.items() if k in valid_cover_options}) cover_options = attr.asdict(cover_options, filter=lambda k, v: v is not None, retain_collection_types=True) # The cover is static, and the only change comes from the image which we generate html = [('Cover', 'cover.html', cover_template)] if cover_options and "cover_url" in cover_options: image = make_cover_from_url(cover_options["cover_url"], story.title, story.author) elif story.cover_url: image = make_cover_from_url(story.cover_url, story.title, story.author) else: image = make_cover(story.title, story.author, **cover_options) cover_image = ('images/cover.png', image.read(), 'image/png') html.append(('Front Matter', 'frontmatter.html', frontmatter_template.format(now=datetime.datetime.now(), **metadata))) html.extend(chapter_html(story, normalize=normalize)) css = ('Styles/base.css', requests.Session().get( 'https://raw.githubusercontent.com/mattharrison/epub-css-starter-kit/master/css/base.css' ).text, 'text/css') output_filename = output_filename or story.title + '.epub' output_filename = make_epub(output_filename, html, metadata, extra_files=(css, cover_image)) return output_filename
def _render_item(item): html = ["<hr>"] title = item["title"] or "No Headline" html.append(f"<h2>{title}</h2>") date = time.strftime("%a, %d %b %Y %H:%M:%S", item["date"]) html.append(f"<p><i>{date}</i></p>") if item["link"] is not None: link = item["link"] html.append(f"<p><a href='{link}'>{link}</a></p>") else: html.append(f"<p><a>no link</a></p>") description = item["description"] or "No description" html.append(f"<p>{description}</p>") html = "".join(html) return html
def make_html(self): """Return the HTML representation of the differences between `source` and `proposal`. :param source: the original text :param proposal: the proposed text """ html = [] diff = self.diff[:] line = diff.pop(0) next = diff.pop(0) while True: html.append(self._handle_line(line, next)) line = next try: next = diff.pop(0) except IndexError: html.append(self._handle_line(line)) break return ''.join(html).rstrip()
def form(self): html = ['<!DOCTYPE html>\n<html lang="en"><head><meta charset="UTF-8"><title>{}</title></head><body>'.format( self.title), '<form><table border="0">'] this_row = None for key, value in self.items.items(): row, column = key if this_row is None: html.append('<tr>') elif this_row != row: html.append('</tr>\n <tr>') this_row = row html.append(' ' + value) html.append('</tr></table></form></body></html>') return '\n'.join(html)
def sort_by_author(bibdata, output_dir, sort_reverse=False): """ Convert BibTeX data to HTML code sorted by (reverse) author. """ publications = {} html = [] # Populate the dictionary `publications' whose keys are author names and # whose values are publications of the respective author. for bibkey in bibdata.entries: if len(list(bibdata.entries[bibkey].persons.values())) == 0: continue for author in list(bibdata.entries[bibkey].persons.values())[0]: if author_to_string(author) in publications: publications[author_to_string(author)].append(bibkey) else: publications[author_to_string(author)] = [bibkey] html.append("<ul>\n") author = None for author in sorted(list(publications.keys()), key=lambda name: name.split(' ')[-1], reverse=sort_reverse): try: for bibkey in publications[author]: html.append( format_html(bibkey, bibdata.entries[bibkey], output_dir, hilight=author)) except NotImplementedError as err: print("[+] %s" % err, file=sys.stderr) continue html.append("</ul>\n<ul>\n") html.pop(-1) html.append("</ul>\n") return "".join(html)
def sort_by_year(bibdata, output_dir, sort_reverse=False): """ Convert BibTeX data to HTML code sorted by (reverse) year. """ html = [] html.append("<ul>\n") year = None def get_year(key): try: return bibdata.entries[key].fields["year"] except KeyError: return 0 def get_venue(key): try: return bibdata.entries[key].fields["booktitle"] except KeyError: return 0 for bibkey in sorted(list(bibdata.entries.keys()), key=lambda k: (str(get_year(k)), str(get_venue(k))), reverse=sort_reverse): if not year: year = get_year(bibkey) current_year = get_year(bibkey) if current_year != year: html.append("</ul>\n<ul>\n") year = current_year try: html.append( format_html(bibkey, bibdata.entries[bibkey], output_dir, hilight=str(year))) except NotImplementedError as err: print("[+] %s" % err, file=sys.stderr) continue html.append("</ul>\n") return "".join(html)
async def zlistsaves(self, bot, event, game_id, room, user): room_id = room.room_id specific_savegame_dir = os.path.join( self.save_dir, ZGameModule.escape_room_id(room_id), game_id) os.makedirs(specific_savegame_dir, exist_ok=True) filenames = [(f, os.path.getmtime(os.path.join(specific_savegame_dir, f))) for f in os.listdir(specific_savegame_dir) if os.path.isfile(os.path.join(specific_savegame_dir, f))] print(specific_savegame_dir, filenames) filenames.sort(key=lambda x: x[1]) html = E.TABLE() if not filenames: await bot.send_room_text( room, "No savegames for '{}' in this room".format(game_id)) return for f, s in filenames: timestamp = datetime.fromtimestamp(s) html.append(E.TR(E.TD(timestamp.isoformat(' ')), E.TD(f))) html_data = lxml.html.tostring(html, pretty_print=True).decode('utf-8') await bot.send_room_html(room, html_data)
def format_html(key, bib_entry, output_dir, hilight=None): """ Convert the given BibTeX entry to HTML. """ html = [] html.append("<li>\n") # Header including paper title and links to pdf and bibtex. html.append("<span class=\"paper\"><a name=\"%s\">%s</a></span>\n" % (key, latex_to_html(bib_entry.fields["title"]))) html.append("<span class='icons'>") #html.append("<a name=\"%s\"> " % key) if "url" in bib_entry.fields: html.append(format_url(bib_entry.fields["url"])) if os.path.isfile(os.path.join(output_dir, "pdf", key + ".pdf")): html.append("<a href='pdf/%s.pdf'>" % key) html.append( '<img class="icon" title="Download cached PDF" src="img/cache-icon.svg" alt="Cached PDF download icon"/>' ) html.append("</a>") elif os.path.isfile(os.path.join(output_dir, "ps", key + ".ps")): html.append("<a href=\"ps/%s.ps\">" % key) html.append( '<img class="icon" title="Download cached file" src="img/cache-icon.svg" alt="Cached file download icon"/>' ) html.append("</a>") # BibTex link with icon. html.append("<a href='bibtex.html#%s'>" % key + "<img class='icon' title='Download BibTeX record'" + " src='img/bibtex-icon.svg' alt='BibTeX download icon' />" + "</a>") # Anchor link to paper. html.append("<a href='#%s'>" % key + "<img class='icon' title='Link to paper'" + " src='img/link-icon.svg' alt='Link to paper' />" + "</a>\n") html.append("</span><br/>") # Add author/editor list. try: html.append("<span class='author'>") html.append(format_authors(bib_entry.persons, hilight)) html.append("</span>") except IndexError as err: print("[+] %s" % err, file=sys.stderr) # Add venue/publication type. if bib_entry.type not in conversion_table: raise NotImplementedError("BibTeX type `%s' not supported. " "Skipping" % bib_entry.type) venue = (conversion_table[bib_entry.type])(bib_entry) if hilight: venue = venue.replace(hilight, "<b>%s</b>" % hilight) html.append("<span class='other'>") html.append(venue) html.append("</span>") # Append notes if they exist if "note" in bib_entry.fields: html.append("<span class=\"note\">%s</span>\n" % latex_to_html(bib_entry.fields["note"])) html.append("</li>\n") # Remove curly braces because latexcodec won't do it for us. final_html = "".join(html).replace("{", "").replace("}", "") return final_html
def _render_document(title, items, date_str): html = ["<html><head><title>"] h_title = f"{date_str}" html.append(h_title) html.append("</title></head><body>") html.append("<h1>") html.append(title) html.append("</h1>") for i in items: html.append(_render_item(i)) html = "".join(html) return html
def display_node(node, option=NodeDisplayOptions.BOTH): html = [render_node(node)] if option & NodeDisplayOptions.PREDS: html.append("<br/>Predecessors:<br/>") html.append("<ul>") for pred in node.preds: html.append("<li>{}</li>".format(render_node(pred))) html.append("</ul>") if option & NodeDisplayOptions.SUCCS: html.append("<br/>Successors:<br/>") html.append("<ul>") for succ in node.succs: html.append("<li>{}</li>".format(render_node(succ))) html.append("</ul>") display(HTML("".join(html)))
def make_standings_table(tourney, show_draws_column, show_points_column, show_spread_column, show_first_second_column=False, linkify_players=False, show_tournament_rating_column=False, show_qualified=False, which_division=None, show_finals_column=True): html = [] num_divisions = tourney.get_num_divisions() ranking_by_wins = tourney.is_ranking_by_wins() if linkify_players: linkfn = lambda x: player_to_link( x, tourney.get_name(), open_in_new_window=True) else: linkfn = lambda x: escape(x.get_name()) if which_division is None: div_list = range(num_divisions) else: div_list = [which_division] html.append("<table class=\"standingstable\">") for div_index in div_list: standings = tourney.get_standings(div_index) if num_divisions > 1: div_string = tourney.get_division_name(div_index) else: div_string = "" finals_form_exists = False for s in standings: if "W" in s.finals_form or "D" in s.finals_form or "L" in s.finals_form: finals_form_exists = True break if not finals_form_exists: show_finals_column = False if div_index > 0: html.append("<tr class=\"standingstabledivspacer\"><td></td></tr>") html.append( "<tr><th colspan=\"2\">%s</th>%s<th>Played</th><th>Wins</th>%s%s%s%s%s</tr>" % (escape(div_string), "<th>Finals</th>" if show_finals_column else "", "<th>Draws</th>" if show_draws_column else "", "<th>Points</th>" if show_points_column else "", "<th>Spread</th>" if show_spread_column else "", "<th>1st/2nd</th>" if show_first_second_column else "", "<th>Tournament Rating</th>" if show_tournament_rating_column else "")) last_wins_inc_draws = None tr_bgcolours = ["#ffdd66", "#ffff88"] bgcolour_index = 0 for s in standings: (pos, name, played, wins, points, draws, spread, num_first) = s[0:8] tournament_rating = s.tournament_rating finals_form = s.finals_form # Remove any leading dashes while finals_form and finals_form[0] == '-': finals_form = finals_form[1:] finals_points = s.finals_points player = tourney.get_player_from_name(name) if finals_form: bgcolour = "#aaffaa" elif ranking_by_wins: if last_wins_inc_draws is None: bgcolour_index = 0 elif last_wins_inc_draws != wins + 0.5 * draws: bgcolour_index = (bgcolour_index + 1) % 2 last_wins_inc_draws = wins + 0.5 * draws if player.is_withdrawn(): bgcolour = "#cccccc" elif s.qualified and show_qualified: bgcolour = "#66ff66" else: bgcolour = tr_bgcolours[bgcolour_index] else: if player.is_withdrawn(): bgcolour = "#cccccc" elif s.qualified and show_qualified: bgcolour = "#66ff66" else: bgcolour = "#ffdd66" html.append( "<tr class=\"standingsrow\" style=\"background-color: %s\">" % (bgcolour)) bold_style = "style=\"font-weight: bold;\"" if ranking_by_wins: wins_style = bold_style draws_style = bold_style else: wins_style = "" draws_style = "" if tourney.is_ranking_by_points(): points_style = bold_style else: points_style = "" if tourney.is_ranking_by_spread(): spread_style = bold_style else: spread_style = "" html.append("<td class=\"standingspos\">%d</td>" % pos) html.append("<td class=\"standingsname\">%s</td>" % (linkfn(player))) if show_finals_column: html.append("<td class=\"standingsfinals\">%s</td>" % (finals_form)) html.append("<td class=\"standingsplayed\">%d</td>" % played) html.append("<td class=\"standingswins\" %s >%d</td>" % (wins_style, wins)) if show_draws_column: html.append("<td class=\"standingsdraws\" %s >%d</td>" % (draws_style, draws)) if show_points_column: html.append("<td class=\"standingspoints\" %s >%d</td>" % (points_style, points)) if show_spread_column: html.append("<td class=\"standingsspread\" %s >%+d</td>" % (spread_style, spread)) if show_first_second_column: html.append("<td class=\"standingsfirstsecond\">%d/%d</td>" % (num_first, played - num_first)) if show_tournament_rating_column: html.append("<td class=\"standingstournamentrating\">") if tournament_rating is not None: html.append("%.2f" % (tournament_rating)) html.append("</td>") html.append("</tr>") html.append("</table>") return "\n".join(html)
def main(argv=None): # defaults update = 0 local = 0 username = '' verbose = 1 browse = 0 check_requirements() if argv is None: argv = sys.argv[1:] try: opts, args = getopt.getopt( argv, 'bilhqu:', ['browse', 'install', 'local', 'help', 'quiet', 'user='******'-h', '--help'): usage(0) elif opt in ('-i', '--install'): update = 1 elif opt in ('-l', '--local'): update = 1 local = 1 elif opt in ('-u', '--user'): username = arg elif opt in ('-q', '--quiet'): verbose = 0 elif opt in ('-b', '--browse'): browse = 1 if args: reprst = [] html = [] for rep in args: file = find_rep(rep) reprst.append(file) newfile = make_html(file, verbose=verbose) if newfile: html.append(newfile) if browse and not update: browse_file(rep) else: # do them all reprst = [] html = [] files = glob.glob("rep-*.rst") files.sort() for file in files: reprst.append(file) newfile = make_html(file, verbose=verbose) if newfile: html.append(newfile) if browse and not update: browse_file("0") if update: push_rep(html, reprst, username, verbose, local=local) if browse: if args: for rep in args: browse_remote(rep) else: browse_remote("0")
hdrtext.attrib['href'] = '#abstract-' + event['slug'] else: hdrtext = header hdrtext.text = event['title'] if event['persons']: br = ET.SubElement(td, 'br') br.tail = ', '.join(event['persons']) tmp = ET.SubElement(html, 'h3') tmp.text = 'Abstracts' for title in sorted(abstracts): html.append(abstracts[title]) tree = ET.ElementTree(html) tree.write('schedule.html', encoding='UTF-8', xml_declaration=False) #####