def index(): try: templates_path = str( os.path.join(os.path.dirname(__file__), 'templates')) file = open(templates_path + '/index.html') db = MySQLdb.connect(host='localhost', user='******', passwd='asdqwe34', db='of_site09') template = Template(renderIndex, str(file.read())) groups = docs_group.list_all(db, "core", 0) html = str(template.render(groups)) except Exception as inst: exc_type, exc_value, exc_traceback = sys.exc_info() error = str(inst) # __str__ allows args to printed directly error += "<br/>" error += str( traceback.format_exception(exc_type, exc_value, exc_traceback)) error.replace('\n', "<br/>") return "Unexpected error:<br/>", error return [html]
def class_detail(): try: templates_path = str( os.path.join(os.path.dirname(__file__), 'templates')) file = open(templates_path + '/class.html') db = MySQLdb.connect(host='localhost', user='******', passwd='asdqwe34', db='of_site09') template = Template(renderClassDetail, str(file.read())) clazz = getClass(db, 1) html = str(template.render(clazz)) except Exception as inst: exc_type, exc_value, exc_traceback = sys.exc_info() error = str(inst) # __str__ allows args to printed directly error += "<br/>" error += str( traceback.format_exception(exc_type, exc_value, exc_traceback)) error.replace('\n', "<br/>") return "Unexpected error:<br/>", error return [html]
def __init__(self, monthCalendar): """ monthCalendar : MonthCal -- an instance of MonthCal (or any other object that returns a one-month HTML calendar table when its render(year, month) method is called) """ self._template = Template(self._renderTemplate, self._html) self._monthCalendar = monthCalendar
def main(): usage = "usage: %prog -f FASTA -p OUT_PAGE -o OUT_DIR -w PROG_WORK_DIR -d" parser = OptionParser(usage=usage) parser.add_option("-f", "--fasta", dest="fasta_file", help="File with FASTA sequences.") parser.add_option("-p", "--out_page", dest="out_page", help="HTML output page with links to FASTA sequences.") parser.add_option("-o", "--out", dest="out_dir", help="Output directory containing the FASTA sequences.") (options, args) = parser.parse_args() if not options.fasta_file: print "Please specify the file with FASTA sequences (-f FASTA)" return -1 if not options.out_page: print "Please specify HTML output page (-p OUT_PAGE)" return -2 if not options.out_dir: print "Please specify the output directory (-o OUT_DIR)" return -3 if (len(args) > 0): print "Too many input arguments" return -4 fasta_file = os.path.abspath(options.fasta_file) out_page = os.path.abspath(options.out_page) out_dir = os.path.abspath(options.out_dir) if not os.path.isdir(out_dir): os.system("mkdir " + out_dir) else: os.system("rm -rf " + out_dir) os.system("mkdir " + out_dir) split_fasta(fasta_file, out_dir) os.chdir(out_dir) files = os.listdir('.') html_fastas = [] for file in files: print file html_fasta = HTMLFasta(file,file) html_fastas.append(html_fasta) # Generate output page html_page_with_fastas = HTMLPageWithFastas("HTML FASTA report", html_fastas) html_page_with_fastas_template_str = get_html_with_fastas_template() html_page_with_fastas_template = Template(render_html_with_fastas_template, html_page_with_fastas_template_str) html_page_with_fastas_html = html_page_with_fastas_template.render(html_page_with_fastas) fd_out = open(out_page,"w") fd_out.write(html_page_with_fastas_html) fd_out.close() # Done print "Done." return 0
def __init__(self, isSundayFirst=True): """ isSundayFirst : boolean -- if True, week begins on Sunday (the default); otherwise Monday """ self._template = Template(self._renderTemplate, self._html) self._isSundayFirst = isSundayFirst if isSundayFirst: self._firstWeekday = 6 columnLabels = self._weekdaysFromSun else: self._firstWeekday = 0 columnLabels = self._weekdaysFromMon self._template.labels.repeat( self._renderLabels, columnLabels) # pre-render column labels for efficiency
class HTMLdict2(dict): def __init__(self, fname=None, content=None, html_escape=0): dict.__init__(self) if fname: f = open(fname, "r") content = f.read() f.close() codecs = (defaultEncoder, defaultDecoder) if html_escape == 0: blankcodec = lambda x:x codecs = (blankcodec, blankcodec) self.t = Template(self.render, content, codecs=codecs) def render(self, node, kvs): for (k, val) in kvs.items(): a = getattr(node, k) if isinstance(val, type([])): a.repeat(self.render, val) else: if val != None: val = str(val) a.content = val def __str__(self): return self.t.render(self)
class YearCal: """Twelve-month HTML calendar renderer.""" _html = '''<!-- begin twelve-month table --> <table class="yeartable" summary="Year calendar from January to December." width="100%"> <tr node="rep:row"> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> </tr> <tr node="rep:row"> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> </tr> <tr node="rep:row"> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> <td node="rep:col" align="center">MONTH</td> </tr> </table> <!-- end twelve-month table -->''' def __init__(self, monthCalendar): """ monthCalendar : MonthCal -- an instance of MonthCal (or any other object that returns a one-month HTML calendar table when its render(year, month) method is called) """ self._template = Template(self._renderTemplate, self._html) self._monthCalendar = monthCalendar def _renderTemplate(self, node, year, dayrenderer): node.row.repeat(self._renderRow, [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], int(year), dayrenderer) # render twelve-month table (4x3) def _renderRow(self, node, monthsRow, year, dayrenderer): node.col.repeat(self._renderCol, monthsRow, year, dayrenderer) def _renderCol(self, node, month, year, dayrenderer): # a single month cell node.raw = self._monthCalendar.render(year, month, {}, dayrenderer) def render(self, year=None, dayrenderer=None): """Render a twelve-month calendar as a 4x3 table year : integer -- e.g. 2004; default is current year dayrenderer : function -- optional dayrenderer function to pass to each month template Result : string -- HTML table """ if year is None: year = time.gmtime()[0] return self._template.render(year, dayrenderer)
def index(): try: templates_path = str(os.path.join(os.path.dirname(__file__), 'templates')) file = open(templates_path + '/index.html') db=MySQLdb.connect(host='localhost',user='******',passwd='asdqwe34',db='of_site09') template = Template(renderIndex, str(file.read())) groups = docs_group.list_all(db,"core", 0) html = str(template.render(groups)) except Exception as inst: exc_type, exc_value, exc_traceback = sys.exc_info() error = str(inst) # __str__ allows args to printed directly error += "<br/>" error += str(traceback.format_exception(exc_type, exc_value, exc_traceback)) error.replace('\n',"<br/>") return "Unexpected error:<br/>", error return [html]
def renderdictionary(terms, style='py-appscript', options=[], template=None): """Render a Dictionary object's classes and commands as an XHTML string. terms : osaterminology.dom.osadictionary.Dictionary -- pre-parsed dictionary object style : str -- keyword formatting style ('appscript' or 'applescript') options : list of str -- formatting options (zero or more of: 'collapse', 'showall') template : str -- custom HTML template to use Result : str -- HTML data, or empty string if no terminology was found """ if 'showall' in options: oldvis = terms.setvisibility(osadictionary.kAll) if terms.suites(): if template: tpl = Template(renderTemplate, template) else: tpl = _template html = encodeNonASCII(tpl.render(terms, gettyperenderer(style), options)) else: html = '' if 'showall' in options: terms.setvisibility(oldvis) return html
def class_detail(): try: templates_path = str(os.path.join(os.path.dirname(__file__), 'templates')) file = open(templates_path + '/class.html') db=MySQLdb.connect(host='localhost',user='******',passwd='asdqwe34',db='of_site09') template = Template(renderClassDetail, str(file.read())) clazz = getClass(db, 1) html = str(template.render(clazz)) except Exception as inst: exc_type, exc_value, exc_traceback = sys.exc_info() error = str(inst) # __str__ allows args to printed directly error += "<br/>" error += str(traceback.format_exception(exc_type, exc_value, exc_traceback)) error.replace('\n',"<br/>") return "Unexpected error:<br/>", error return [html]
def __init__(self, isSundayFirst=True): """ isSundayFirst : boolean -- if True, week begins on Sunday (the default); otherwise Monday """ self._template = Template(self._renderTemplate, self._html) self._isSundayFirst = isSundayFirst if isSundayFirst: self._firstWeekday = 6 columnLabels = self._weekdaysFromSun else: self._firstWeekday = 0 columnLabels = self._weekdaysFromMon self._template.labels.repeat(self._renderLabels, columnLabels) # pre-render column labels for efficiency
def renderdictionary(terms, style='py-appscript', options=[], template=None): """Render a Dictionary object's classes and commands as an XHTML string. terms : osaterminology.dom.osadictionary.Dictionary -- pre-parsed dictionary object style : str -- keyword formatting style ('appscript' or 'applescript') options : list of str -- formatting options (zero or more of: 'collapse', 'showall') template : str -- custom HTML template to use Result : str -- HTML data, or empty string if no terminology was found """ if 'showall' in options: oldvis = terms.setvisibility(osadictionary.kAll) if terms.suites(): if template: tpl = Template(renderTemplate, template) else: tpl = _template html = encodeNonASCII( tpl.render(terms, gettyperenderer(style), options)) else: html = '' if 'showall' in options: terms.setvisibility(oldvis) return html
def __init__(self, fname=None, content=None, html_escape=0): dict.__init__(self) if fname: f = open(fname, "r") content = f.read() f.close() codecs = (defaultEncoder, defaultDecoder) if html_escape == 0: blankcodec = lambda x:x codecs = (blankcodec, blankcodec) self.t = Template(self.render, content, codecs=codecs)
def doc(path, file, style='appscript', options=[], template=None): """Render an XHTML file listing a scriptable application's classes and commands. path : str -- name or path to application file : str -- HTML file's destination. style : str -- keyword formatting style ('appscript' or 'applescript') options : list of str -- formatting options ([] or ['collapse']) template : str -- custom HTML template to use """ if path.endswith('.sdef'): terms = sdefparser.parsefile(path, style) elif path.endswith('.aete'): terms = aeteparser.parsefile(path, style) else: terms = aeteparser.parseapp(findapp.byname(path), style) if terms.suites(): if template: tpl = Template(renderTemplate, template) else: tpl = _template result = encodeNonASCII(tpl.render(terms, typerenderers[style](), options)) f = open(expanduser(file), 'w') f.write(str(result)) f.close()
def doc(path, file, style='appscript', options=[], template=None): """Render an XHTML file listing a scriptable application's classes and commands. path : str -- name or path to application file : str -- HTML file's destination. style : str -- keyword formatting style ('appscript' or 'applescript') options : list of str -- formatting options ([] or ['collapse']) template : str -- custom HTML template to use """ if path.endswith('.sdef'): terms = sdefparser.parsefile(path, style) elif path.endswith('.aete'): terms = aeteparser.parsefile(path, style) else: terms = aeteparser.parseapp(findapp.byname(path), style) if terms.suites(): if template: tpl = Template(renderTemplate, template) else: tpl = _template result = encodeNonASCII( tpl.render(terms, typerenderers[style](), options)) f = open(expanduser(file), 'w') f.write(str(result)) f.close()
node.row.repeat(render_row, people, [False]) def render_row(node, person, isevenrow): if isevenrow[0]: node.atts['bgcolor'] = '#CCF' isevenrow[0] = not isevenrow[0] node.name.content = person[0] node.phone.repeat(render_phone, person[1]) def render_phone(node, tel): node.content = node.content % tel template = Template(render_template, html) ####### def write(path, txt): f = open(path, 'w') f.write(txt) f.close() def listpeoplewithphones(): p = app('Address Book').people[its.phones != []] people = zip(p.last_name.get(), p.first_name.get(), p.phones.label.get(), p.phones.value.get()) result = []
class MonthCal: """One-month HTML calendar renderer.""" _months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] _weekdaysFromSun = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] _weekdaysFromMon = _weekdaysFromSun[1:] + [_weekdaysFromSun[0]] _html = '''<!-- begin one-month calendar --> <table class="calendar" summary="Monthly calendar."> <caption node="con:caption"><b>January</b></caption> <thead> <tr> <th node="rep:labels" scope="col" abbr="Sunday">S</th> <th node="del:" scope="col" abbr="Monday">M</th><th node="del:" scope="col" abbr="Tuesday">T</th><th node="del:" scope="col" abbr="Wednesday">W</th><th node="del:" scope="col" abbr="Thursday">T</th><th node="del:" scope="col" abbr="Friday">F</th><th node="del:" scope="col" abbr="Saturday">S</th> </tr> </thead><tbody> <tr node="rep:week"> <td node="del:"> </td><td node="del:"> </td> <td node="rep:day" class="wkday"><a node="con:link" href="archives/2002-01-01.html">1</a></td> <td class="wkday" node="del:">2</td><td class="wkday" node="del:">3</td><td class="wkday" node="del:">4</td><td class="wkend" node="del:">5</td> </tr><tr node="del:"> <td class="wkend">6</td> <td class="wkday">7</td> <td class="wkday">8</td> <td class="wkday">9</td> <td class="wkday">10</td> <td class="wkday">11</td> <td class="wkend">12</td> </tr><tr node="del:"> <td class="wkend">13</td> <td class="wkday">14</td> <td class="wkday">15</td> <td class="wkday">16</td> <td class="wkday">17</td> <td class="wkday">18</td> <td class="wkend">19</td> </tr><tr node="del:"> <td class="wkend">20</td> <td class="wkday">21</td> <td class="wkday">22</td> <td class="wkday">23</td> <td class="wkday">24</td> <td class="wkday">25</td> <td class="wkend">26</td> </tr><tr node="del:"> <td class="wkend">27</td> <td class="wkday">28</td> <td class="wkday">29</td> <td class="wkday">30</td> <td class="wkday">31</td> <td> </td> <td> </td> </tr><tr node="del:"> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table> <!-- end one-month calendar -->''' def __init__(self, isSundayFirst=True): """ isSundayFirst : boolean -- if True, week begins on Sunday (the default); otherwise Monday """ self._template = Template(self._renderTemplate, self._html) self._isSundayFirst = isSundayFirst if isSundayFirst: self._firstWeekday = 6 columnLabels = self._weekdaysFromSun else: self._firstWeekday = 0 columnLabels = self._weekdaysFromMon self._template.labels.repeat( self._renderLabels, columnLabels) # pre-render column labels for efficiency def _WeekendTrackerGen(isSundayFirst=True): while 1: days = [ bool(isSundayFirst), False, False, False, False, not isSundayFirst, True ] while days: yield days.pop(0) _WeekendTrackerGen = staticmethod(_WeekendTrackerGen) def _renderLabels(self, node, weekday): node.atts['abbr'] = weekday node.content = weekday[0] def _renderTemplate(self, node, year, month, ifo, links, dayrenderer): fd = calendar.firstweekday() calendar.setfirstweekday(self._firstWeekday) weeks = calendar.monthcalendar(year, month) # a list of seven-item lists calendar.setfirstweekday(fd) if len(weeks) == 5: weeks.append([0, 0, 0, 0, 0, 0, 0]) node.caption.content = "%s %s %s" % (ifo, self._months[month - 1], year ) # set table caption node.week.repeat(self._renderWeek, weeks, links, self._WeekendTrackerGen(self._isSundayFirst), year, month, dayrenderer) # render weekly rows def _renderWeek(self, node, days, links, weekendTracker, year, month, dayrenderer): node.day.repeat(self._renderDay, days, links, weekendTracker, year, month, dayrenderer) def _renderDay(self, node, day, links, weekendTracker, year, month, dayrenderer): isWeekend = weekendTracker.next() if day == 0: node.link.raw = ' ' del node.atts['class'] node.link.omittags() else: if dayrenderer: node.raw = dayrenderer(year, month, day) else: node.link.content = str(day) if isWeekend: node.atts['class'] = 'wkend' if links.has_key(day): node.link.atts['href'] = links[day] else: node.link.omittags() def render(self, year, month, ifo, links={}, dayrenderer=None): # note: the dayrenderer parameter is kinda kludged in; it'd be better if links arg was eliminated and some default day renderers were provided instead, but it's kept for backwards-compatibility's sake """Render a one-month calendar. year : integer -- e.g. 2004 month : integer -- 1-12 links : dict -- a dict of form {DAY [integer]: URI [string],...} used to add links to selected days; ignored if dayrenderer argument is given; optional dayrenderer : function -- a function/closure/callable class instance that takes year, month and day integers as arguments and returns HTML markup for each 'day' table cell; optional Result : string -- HTML table """ return self._template.render(year, month, ifo, links, dayrenderer)
def renderSideCommand(node, (name, suiteName)): node.link.atts['href'] = '#command_' + stripNonChars(name + '__' + suiteName) node.link.content = name def renderSideClass(node, (name, suiteName)): node.link.atts['href'] = '#class_' + stripNonChars(name + '__' + suiteName) node.link.content = name ###################################################################### # PRIVATE - Compiled Template ###################################################################### _template = Template(renderTemplate, _html) ###################################################################### # PUBLIC ###################################################################### def renderdictionary(terms, style='py-appscript', options=[], template=None): """Render a Dictionary object's classes and commands as an XHTML string. terms : osaterminology.dom.osadictionary.Dictionary -- pre-parsed dictionary object style : str -- keyword formatting style ('appscript' or 'applescript') options : list of str -- formatting options (zero or more of: 'collapse', 'showall') template : str -- custom HTML template to use Result : str -- HTML data, or empty string if no terminology was found """ if 'showall' in options:
</html>''' def render_template(node, people): node.row.repeat(render_row, people, [False]) def render_row(node, person, isevenrow): if isevenrow[0]: node.atts['bgcolor'] = '#CCF' isevenrow[0] = not isevenrow[0] node.name.content = person[0] node.phone.repeat(render_phone, person[1]) def render_phone(node, tel): node.content = node.content % tel template = Template(render_template, html) ####### def write(path, txt): f = open(path, 'w') f.write(txt) f.close() def listpeoplewithphones(): p = app('Address Book').people[its.phones != []] people = zip(p.last_name.get(), p.first_name.get(), p.phones.label.get(), p.phones.value.get()) result = [] for person in people:
####### # Support def encodeNonASCII(txt): """Convert non-ASCII characters to HTML entities""" res = [] for char in txt: if ord(char) < 128: res.append(char) else: res.append("&#%i;" % ord(char)) return "".join(res) def write(path, txt): f = open(path, "w") f.write(txt) f.close() ####### # Render thumbnails page template = Template(render_template, html) # get the properties of every photo of current album photos = app("iPhoto").current_album.photos.properties.get() page = template.render(photos) write(dest, encodeNonASCII(page))
def main(): usage = "usage: %prog -j JOB_ID -p JOB_HTML_PAGE -o OUT_DIR -w PROG_WORK_DIR -d" parser = OptionParser(usage=usage) parser.add_option("-j", "--job_id", dest="job_id", help="JobId of the InterProScan run.") parser.add_option("-p", "--job_html_page", dest="job_html_page", help="InterProScan job html output page.") parser.add_option("-o", "--out", dest="out_dir", help="Output directory with single html IterProScan result.") parser.add_option("-w", "--prog_work", dest="prog_work_dir", help="Program working directory, contains all processed files.") parser.add_option("-d", "--delete_program_work", action="store_true", dest="delete_program_work", default=False, help="Delete program working directory after program has completed.") (options, args) = parser.parse_args() if not options.job_id: print "Please specify the InterProScan JobId (-j JOB_ID)" return -1 if not options.job_html_page: print "Please specify InterProScan job html output page (-p JOB_HTML_PAGE)" return -2 if not options.out_dir: print "Please specify the output directory (-o OUT_DIR)" return -4 if not options.prog_work_dir: print "Please specify the program working directory (-w PROG_WORK_DIR)" return -4 if (len(args) > 0): print "Too many input arguments" return -5 iprscan_output_dir = os.environ.get("IPRSCAN_OUTPUT_DIR") iprscan_images_dir = os.environ.get("IPRSCAN_IMAGES_DIR") out_dir = os.path.abspath(options.out_dir) job_html_page = os.path.abspath(options.job_html_page) date = options.job_id.split("-")[1] iprscan_output_dir = iprscan_output_dir + "/" + date + "/" + options.job_id nr_chunks = len(glob.glob(iprscan_output_dir + "/chunk*")) prog_work_dir = os.path.abspath(options.prog_work_dir) timestamp = commands.getoutput("date +%Y-%m-%d_%H_%M_%S_%N") base_dir = prog_work_dir + "/generate_interproscan_html_report_" + timestamp if not os.path.isdir(prog_work_dir): os.system("mkdir " + prog_work_dir) if os.path.isdir(prog_work_dir): if os.path.isdir(base_dir): os.system("rm -rf " + base_dir) os.system("mkdir " + base_dir) else: os.system("mkdir " + base_dir); else: print "Program working directory does not exist." return -5 if not os.path.isdir(out_dir): os.system("mkdir " + out_dir) else: os.system("rm -rf " + out_dir) os.system("mkdir " + out_dir) iprscan_raw_html_file = os.path.abspath(base_dir + "/iprscan_raw.html") for i in range(1,int(nr_chunks) + 1): # create picture output os.system("iprscan tool=iprscan jobid=" + options.job_id + " cnk=" + str(i) + " view=picture >> " + iprscan_raw_html_file) # create table output os.system("iprscan tool=iprscan jobid=" + options.job_id + " cnk=" + str(i) + " view=Table >> " + iprscan_raw_html_file) fd_in = open(iprscan_raw_html_file, "r") ips_report_start = False ips_report = "" ips_report_start_string = "<table width=\"100%\" cellSpacing=\"0\" cellPadding=\"3\" border=\"1\" bordercolor=\"#999999\" bgcolor=\"#eeeeee\" class=\"tabletop\">" ips_report_end_string = "</tr>\n</table>\n</td></tr>\n</table>\n<br>" ips_report_header = "<html><head><title>InterProScan Results - [email protected]</title></head><link rel=\"SHORTCUT ICON\" href=\"https://foobar.com/images/bookmark.gif\">\n<br>\n<span class=\"text\">" ips_report_footer = "</span>" ips_reports = {} ips_report_id = ""; for line in fd_in: if (line.find(ips_report_start_string) > -1): if(ips_report_start): # Do not save results for first round. ips_report_start = False initially if (ips_report_id in ips_reports): report = ips_reports[ips_report_id] report = report + ips_report ips_reports[ips_report_id] = report else: ips_reports[ips_report_id] = ips_report ips_report_start = True ips_report = "" if(ips_report_start): ips_report = ips_report + line if (line.find("SEQUENCE") > -1): ips_report_id = get_ips_id(line) # Get last report if (ips_report_id in ips_reports): report = ips_reports[ips_report_id] report = report + ips_report ips_reports[ips_report_id] = report else: ips_reports[ips_report_id] = ips_report # Add html header and footer for ips_report_id in ips_reports: report = ips_reports[ips_report_id] report = ips_report_header + report + ips_report_footer ips_reports[ips_report_id] = report # Clean html for ips_report_id in ips_reports: report = ips_reports[ips_report_id] report = clean_html(report, ips_report_id) ips_reports[ips_report_id] = report interproscan_reports = [] report_ids = ips_reports.keys() sorted_report_ids = sorted(report_ids) # Print all reports for ips_report_id in sorted_report_ids: fd_out = open(out_dir + "/" + ips_report_id + "_interproscan.html", "w") fd_out.write(ips_reports[ips_report_id]) fd_out.close() interproscan_report = InterProScanReport(ips_report_id, ips_report_id + "_interproscan.html") interproscan_reports.append(interproscan_report) fd_in.close() # Cannot access html pages or links in galaxy output data subfolders. Need to put all file and images in root directory. Messy! find better way. # Need to do for now! # os.system("mkdir " + out_dir + "/images") # os.system("cp " + iprscan_images_dir + "/*.gif " + out_dir + "/images") os.system("cp " + iprscan_images_dir + "/*.gif " + out_dir ) # Generate InterProScan job index page interproscan_job = InterProScanJob(options.job_id, interproscan_reports) intproscan_job_html_template_str = get_intproscan_job_html_template() intproscan_job_html_template = Template(render_interproscan_job_template, intproscan_job_html_template_str) intproscan_job_html = intproscan_job_html_template.render(interproscan_job) fd_out = open(job_html_page,"w") fd_out.write(intproscan_job_html) fd_out.close() # Delete program working directory if indicated if(options.delete_program_work): print "Delete working directory" os.system("rm -rf " + base_dir) return 0
f.write(txt.encode('utf8')) f.close() ###################################################################### # PRIVATE - Template Controllers ###################################################################### # Frame def render_frame(node, terms, info): node.title.content = '%s terminology for %s' % (stripappsuffix( terms.name), terms.style) frametpl = Template(render_frame, framehtml) ###################################################################### # Index def render_index(node, terms, info): now = datetime.now() generated = now.strftime("%a %b %d %Y %H:%M:%S") node.title.content = node.title2.content = stripappsuffix(terms.name) node.location.content = "Generated on %s for %s" % (generated, terms.path) generatorname = info.get('generator-name', "") generatorversion = info.get('generator-version', "") if (generatorname != ""): node.build.content = "by %s %s" % (generatorname, generatorversion) else:
res = [] for char in txt: if ord(char) < 128: res.append(char) else: res.append('&#%i;' % ord(char)) return ''.join(res) def write(path, txt): f = open(path, 'w') f.write(txt) f.close() ####### # Main # Prompt user to specify HTML file to save to: sa = ScriptingAddition() sa.activate() outfile = sa.choose_file_name(default_name='iTunes_albums.html') # Render current playlist to HTML file: template = Template(render_template, html) playlist = app('iTunes').browser_windows[1].view.get() page = template.render(playlist) write(outfile.path, encodeNonASCII(page)) # Preview HTML file in user's default browser: sa.open_location(outfile.url)
class MonthCal: """One-month HTML calendar renderer.""" _months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] _weekdaysFromSun = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] _weekdaysFromMon = _weekdaysFromSun[1:] + [_weekdaysFromSun[0]] _html = '''<!-- begin one-month calendar --> <table class="calendar" summary="Monthly calendar."> <caption node="con:caption">January</caption> <thead> <tr> <th node="rep:labels" scope="col" abbr="Sunday">S</th> <th node="del:" scope="col" abbr="Monday">M</th><th node="del:" scope="col" abbr="Tuesday">T</th><th node="del:" scope="col" abbr="Wednesday">W</th><th node="del:" scope="col" abbr="Thursday">T</th><th node="del:" scope="col" abbr="Friday">F</th><th node="del:" scope="col" abbr="Saturday">S</th> </tr> </thead><tbody> <tr node="rep:week"> <td node="del:"> </td><td node="del:"> </td> <td node="rep:day" class="wkday"><a node="con:link" href="archives/2002-01-01.html">1</a></td> <td class="wkday" node="del:">2</td><td class="wkday" node="del:">3</td><td class="wkday" node="del:">4</td><td class="wkend" node="del:">5</td> </tr><tr node="del:"> <td class="wkend">6</td> <td class="wkday">7</td> <td class="wkday">8</td> <td class="wkday">9</td> <td class="wkday">10</td> <td class="wkday">11</td> <td class="wkend">12</td> </tr><tr node="del:"> <td class="wkend">13</td> <td class="wkday">14</td> <td class="wkday">15</td> <td class="wkday">16</td> <td class="wkday">17</td> <td class="wkday">18</td> <td class="wkend">19</td> </tr><tr node="del:"> <td class="wkend">20</td> <td class="wkday">21</td> <td class="wkday">22</td> <td class="wkday">23</td> <td class="wkday">24</td> <td class="wkday">25</td> <td class="wkend">26</td> </tr><tr node="del:"> <td class="wkend">27</td> <td class="wkday">28</td> <td class="wkday">29</td> <td class="wkday">30</td> <td class="wkday">31</td> <td> </td> <td> </td> </tr><tr node="del:"> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table> <!-- end one-month calendar -->''' def __init__(self, isSundayFirst=True): """ isSundayFirst : boolean -- if True, week begins on Sunday (the default); otherwise Monday """ self._template = Template(self._renderTemplate, self._html) self._isSundayFirst = isSundayFirst if isSundayFirst: self._firstWeekday = 6 columnLabels = self._weekdaysFromSun else: self._firstWeekday = 0 columnLabels = self._weekdaysFromMon self._template.labels.repeat(self._renderLabels, columnLabels) # pre-render column labels for efficiency def _WeekendTrackerGen(isSundayFirst=True): while 1: days = [bool(isSundayFirst), False, False, False, False, not isSundayFirst, True] while days: yield days.pop(0) _WeekendTrackerGen = staticmethod(_WeekendTrackerGen) def _renderLabels(self, node, weekday): node.atts['abbr'] = weekday node.content = weekday[0] def _renderTemplate(self, node, year, month, links, dayrenderer): fd = calendar.firstweekday() calendar.setfirstweekday(self._firstWeekday) weeks = calendar.monthcalendar(year, month) # a list of seven-item lists calendar.setfirstweekday(fd) if len(weeks) == 5: weeks.append([0, 0, 0, 0, 0, 0, 0]) node.caption.content = self._months[month - 1] # set table caption node.week.repeat(self._renderWeek, weeks, links, self._WeekendTrackerGen(self._isSundayFirst), year, month, dayrenderer) # render weekly rows def _renderWeek(self, node, days, links, weekendTracker, year, month, dayrenderer): node.day.repeat(self._renderDay, days, links, weekendTracker, year, month, dayrenderer) def _renderDay(self, node, day, links, weekendTracker, year, month, dayrenderer): isWeekend = weekendTracker.next() if day == 0: node.link.raw = ' ' del node.atts['class'] node.link.omittags() else: if dayrenderer: node.raw = dayrenderer(year, month, day) else: node.link.content = str(day) if isWeekend: node.atts['class'] = 'wkend' if links.has_key(day): node.link.atts['href'] = links[day] else: node.link.omittags() def render(self, year, month, links={}, dayrenderer=None): # note: the dayrenderer parameter is kinda kludged in; it'd be better if links arg was eliminated and some default day renderers were provided instead, but it's kept for backwards-compatibility's sake """Render a one-month calendar. year : integer -- e.g. 2004 month : integer -- 1-12 links : dict -- a dict of form {DAY [integer]: URI [string],...} used to add links to selected days; ignored if dayrenderer argument is given; optional dayrenderer : function -- a function/closure/callable class instance that takes year, month and day integers as arguments and returns HTML markup for each 'day' table cell; optional Result : string -- HTML table """ return self._template.render(year, month, links, dayrenderer)
def main(): usage = "usage: %prog -z ZIP_ARCHIVE -p OUT_PAGE -o OUT_DIR -w PROG_WORK_DIR -d" parser = OptionParser(usage=usage) parser.add_option("-z", "--zip_archive", dest="zip_archive", help="Zip archive consisting of images.") parser.add_option("-p", "--out_page", dest="out_page", help="HTML output page with images.") parser.add_option("-o", "--out", dest="out_dir", help="Output directory with images.") parser.add_option( "-w", "--prog_work", dest="prog_work_dir", help="Program working directory, contains all processed files.") parser.add_option( "-d", "--delete_program_work", action="store_true", dest="delete_program_work", default=False, help="Delete program working directory after program has completed.") (options, args) = parser.parse_args() if not options.zip_archive: print "Please specify the zip archive consisting of images (-z ZIP_ARCHIVE)" return -1 if not options.out_page: print "Please specify HTML output page (-p OUT_PAGE)" return -2 if not options.out_dir: print "Please specify the output directory (-o OUT_DIR)" return -4 if not options.prog_work_dir: print "Please specify the program working directory (-w PROG_WORK_DIR)" return -4 if (len(args) > 0): print "Too many input arguments" return -5 zip_archive = os.path.abspath(options.zip_archive) out_page = os.path.abspath(options.out_page) out_dir = os.path.abspath(options.out_dir) prog_work_dir = os.path.abspath(options.prog_work_dir) timestamp = commands.getoutput("date +%Y-%m-%d_%H_%M_%S_%N") base_dir = prog_work_dir + "/generate_html_with_images_report_" + timestamp if not os.path.isdir(prog_work_dir): os.system("mkdir " + prog_work_dir) if os.path.isdir(prog_work_dir): if os.path.isdir(base_dir): os.system("rm -rf " + base_dir) os.system("mkdir " + base_dir) else: os.system("mkdir " + base_dir) else: print "Program working directory does not exist." return -5 if not os.path.isdir(out_dir): os.system("mkdir " + out_dir) else: os.system("rm -rf " + out_dir) os.system("mkdir " + out_dir) os.chdir(base_dir) os.system("unzip " + zip_archive) # Simple test to check if the files are images. Add only the images to the HTML page to be rendered. files = os.listdir('.') html_images = [] for file in files: if (imghdr.what(file)): print file html_image = HTMLImage(file, file) html_images.append(html_image) os.system("cp " + file + " " + out_dir) else: print file + " is not an image file!" # Generate output page html_page_with_images = HTMLPageWithImages("HTML with images report", html_images) html_page_with_images_template_str = get_html_with_images_template() html_page_with_images_template = Template( render_html_with_images_template, html_page_with_images_template_str) html_page_with_images_html = html_page_with_images_template.render( html_page_with_images) fd_out = open(out_page, "w") fd_out.write(html_page_with_images_html) fd_out.close() # Delete program working directory if indicated if (options.delete_program_work): print "Delete working directory" os.system("rm -rf " + base_dir) # Done print "Done." return 0
node.row.repeat(render_row, people, [False]) def render_row(node, person, isEvenRow): if isEvenRow[0]: node.atts['bgcolor'] = '#CCF' isEvenRow[0] = not isEvenRow[0] node.name.content = person[0] node.phone.repeat(render_phone, person[1]) def render_phone(node, tel): node.content = node.content % tel template = Template(render_template, html) ####### def write(path, txt): f = open(path, 'w') f.write(txt) f.close() def listPeopleWithPhones(): p = app('Address Book').people[its.phones != []] people = zip(p.last_name.get(), p.first_name.get(), p.phones.label.get(), p.phones.value.get()) result = []
</html>''' def render_template(node, people): node.row.repeat(render_row, people, [False]) def render_row(node, person, isEvenRow): if isEvenRow[0]: node.atts['bgcolor'] = '#CCF' isEvenRow[0] = not isEvenRow[0] node.name.content = person[0] node.phone.repeat(render_phone, person[1]) def render_phone(node, tel): node.content = node.content % tel template = Template(render_template, html) ####### def write(path, txt): f = open(path, 'w') f.write(txt) f.close() def listPeopleWithPhones(): p = app('Address Book').people[its.phones != []] people = zip(p.last_name.get(), p.first_name.get(), p.phones.label.get(), p.phones.value.get()) result = [] for person in people:
####### # Support def encodeNonASCII(txt): """Convert non-ASCII characters to HTML entities""" res = [] for char in txt: if ord(char) < 128: res.append(char) else: res.append('&#%i;' % ord(char)) return ''.join(res) def write(path, txt): f = open(path, 'w') f.write(txt) f.close() ####### # Render thumbnails page template = Template(render_template, html) # get the properties of every photo of current album photos = app('iPhoto').current_album.photos.properties.get() page = template.render(photos) write(dest, encodeNonASCII(page))