def generateYANGPageMainHTML(self, file_name: str, stats: dict): """ Create YANGPageMain HTML with compilation results statistics and generate a HTML file. Arguments: :param file_name (str) Prefix of the YANGPageMain html file name to be created :param stats (dict) Dictionary containing number of passed, failed and total number of modules """ generated_message = 'Generated on {} by the YANG Catalog.'.format(time.strftime('%d/%m/%Y')) content = [ '{} YANG MODELS'.format(file_name), 'Number of YANG data models from {} that passed compilation: {}/{}'.format(file_name, stats['passed'], stats['total']), 'Number of YANG data models from {} that passed compilation with warnings: {}/{}'.format(file_name, stats['warnings'], stats['total']), 'Number of YANG data models from {} that failed compilation: {}/{}'.format(file_name, stats['failed'], stats['total']) ] message_html = HTML.list([generated_message]) content_html = HTML.list(content) HTML_filename = '{}{}YANGPageMain.html'.format(self.__htmlpath, file_name) with open(HTML_filename, 'w', encoding='utf-8') as f: f.write(message_html) f.write(content_html) os.chmod(HTML_filename, 0o664) print('{}{}YANGPageMain.html HTML page generated in directory {}' .format(self.__get_timestamp_with_pid(), file_name, self.__htmlpath), flush=True)
def main(): # part1: #------------------------------------------------------------------- Part1.Part1() #------------------------------------------------------------------- # part2: #------------------------------------------------------------------- # set last parameter to true to enable export of shots stitched_shots, all_shots, outstitched_shots = Part2.Part2(False) #------------------------------------------------------------------- #html stuff: #------------------------------------------------------------------- HTML.html_stuff(stitched_shots, all_shots, outstitched_shots, 'Oberstdorf16-shots.csv', './html_input/index_part1.txt', './html_input/index_part2.txt', './html_output/index.html') #------------------------------------------------------------------- #xml stuff: #------------------------------------------------------------------- XML.create_XML('caffe_output.txt')
def retrieveData (self,event): socials=self.intxt.GetLineText(1).split(' ') self.doScreen() #fix the screens coming back with old data self.htmlList=[] #clear out html pages cnxn=accP2() cursor=cnxn.cursor() for social in socials: if len(social) < 11: social=social[0:3]+'-'+social[3:5]+'-'+social[5:] # get all socsecs if just the number entered htmlText=htmlString() # set up an instance of the html string EEData = xyz99(None,'ssn',None,None,social) for i,j in zip(EEData.Fields, EEData.Types): pass # print i,j EEHTML = HTML.table([['No employee found'],['No data returned']]) if len(EEData.OutData) > 0: self.EEDataXL = [(field,data) for field,data in zip(EEData.Fields , EEData.OutData[0])] self.EETypes = [(field,data) for field,data in zip(EEData.Fields , EEData.Types)] EEHTML = HTML.table(EEData.outStringTable()) #then get the IB data self.ibRecs = getibData(social,cursor) IBHTML = HTML.table([['No record in IBControl table'],['No data returned']]) if max([len(i) for i in self.ibRecs]) > 1: # getibData returns a list of tuples, which only have the column name in each if they are empty columnAlign = ['top' ]* len(self.ibRecs[0]) IBHTML = HTML.table(self.ibRecs,col_valign=columnAlign) OutputTable = [['Employee Data','IB Control Data'],[EEHTML, IBHTML]] htmlText.v+= HTML.table(OutputTable,col_valign=('top','top')) htmlText.v+='</td>' htmlText.vend() htmlText.vreduceFont() self.Addapanel(htmlText) cnxn.close() self.bigPanel.SetSizerAndFit(self.subPans) self.bigPanel.Layout()
def formated(self, tablefmt="pipe"): '''tablefmt must be a format accepted by the tabular packagesee plain,simple,grid,pipe,orgtbl,rst,mediawiki,latex''' table = [] for i, row in enumerate(self.probabilities): conditioned = [['False', 'True'][r] for r in self.conditioned_config(i)] table.append([str(r) for r in conditioned + row]) if tablefmt == 'html': import HTML fillers = [HTML.TableCell()] * len(self.parents) title = HTML.TableCell(self.node, style='font-weight:bold;', attribs={'colspan': 2}) htmlcode = HTML.table([self.parents + ['False', "True"]] + table, header_row=fillers + [title], style='', border='') from IPython.display import display_html from IPython.display import HTML as IPHTML return IPHTML(htmlcode) else: return '\n' + '\t' * (len(self.parents) + 1) + '' + str( self.node) + '' + '\n' + tabulate( table, headers=self.parents + ['False', "True"], tablefmt=tablefmt) + '\n'
class Document: generator = HTML.META(name="generator", content="HyperText package (Python)") DOCTYPE = HTML.DOCTYPE body_element = HTML.BODY def __init__(self, *content, **attrs): from HTML import HEAD, HTML self.doctype = self.DOCTYPE self.body = apply(self.body_element, content, attrs) self.head = HEAD(self.generator) if hasattr(self, 'style'): self.head.append(self.style) if hasattr(self, 'title'): self.head.append(self.title) self.html = HTML(self.head, self.body) self.setup() def setup(self): pass def append(self, *items): map(self.body.content.append, items) def __str__(self, indent=0, perlevel=2): return join([self.doctype.__str__(indent, perlevel), self.html.__str__(indent, perlevel)], '') def writeto(self, fp=sys.stdout, indent=0, perlevel=2): self.doctype.writeto(fp, indent, perlevel) self.html.writeto(fp, indent, perlevel)
def premailer(): my_test_list = {} result_colors = { 'SUCCESS': 'lime', 'FAIL': 'red', 'ERROR': 'yellow', 'SKIPPED': 'silver', } myTable = HTML.Table(header_row=['Sequence', 'Test Executed', 'Results']) for title, val_dict in test_table.iteritems(): my_test_list[val_dict['id']] = title for test_id in sorted(my_test_list.keys()): my_status = test_table[my_test_list[test_id]]['status'] my_title = my_test_list[test_id] color = result_colors[my_status] colored_result = HTML.TableCell(my_status, bgcolor=color) myTable.rows.append([test_id, my_title, colored_result]) mySummary = HTML.Table( header_row=['Total', 'Skipped', 'Success', 'Failed', 'Error']) mySummary.rows.append([ stats_values(), get_skipped(), get_success(), get_failure(), get_error() ]) return str(myTable) + str(mySummary)
def do_GET(self): """ Respond to a GET request. """ self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() html_head = """<html><head><title>Website Monitor Status</title> <meta http-equiv="refresh" content="5"> <script type="text/javascript"> </script> </head> """ body_text = "" data = dict() with open(settings.storage_db_file, 'rb') as handle: data = pickle.load(handle) resultColors = {'UP': 'lime', 'DOWN': 'red'} string = '' t = HTML.Table(header_row=[ 'TIME', 'Web Page URL', 'STATUS', 'CONTENT FOUND', 'URL RESPONSE TIME' ]) for url_key, infos in data.iteritems(): color = resultColors[infos[0]] status = HTML.TableCell(infos[0], bgcolor=color) content_found = HTML.TableCell(infos[1], bgcolor=color) elapsed_time = HTML.TableCell(infos[2], bgcolor=color) at_time = HTML.TableCell(infos[3]) t.rows.append( [at_time, url_key, status, content_found, elapsed_time]) self.wfile.write(html_head) self.wfile.write(t)
def create_testbeam_html_pages(self): testbeams = [self.results[x].getint('RunInfo', 'runno') / 100 for x in self.results] testbeams = sorted(list(set(testbeams))) testbeamDate = utilities.get_dict_from_file('%s/testBeamDates.cfg' % self.config_dir) for testbeam in testbeams: key = '%s' % testbeam if not key in testbeamDate: testbeamDate[key] = 'unkown' irr = utilities.get_dict_from_file('%s/irradiationType.cfg' % self.config_dir) allDiamonds = self.get_list_of_diamonds(self.results) allDiamonds = sorted(allDiamonds, key=lambda z: '%s-%s' % (irr.get(z, 'unkown'), z)) allDiamondLinks = map(lambda z: HTML.link('%s (%s)' % (z, irr.get(z, 'unknown')), 'results_%s.html' % z), allDiamonds) testBeamLinkTable = [] header = [HTML.link('Test Beam', 'results.html')] + allDiamondLinks for testbeam in testbeams: results = filter(lambda z: self.results[z].getint('RunInfo', 'runno') / 100 == testbeam, self.results) results = {key: self.results[key] for key in results} diamonds = self.get_list_of_diamonds(results) # results = sorted(results,key=itemgetter(mapping['RunNo'],mapping['dia'],mapping['corrected'])) print testbeam, len(results), diamonds fileName = '%s/results_%sXX.html' % (self.config.get('HTML', 'outputDir'), testbeam) fileName = fileName.replace('//', '/') # raw_input(fileName) self.create_html_overview_table(results, fileName) fileName = 'results_%sXX.html' % testbeam row = [HTML.link('%sXX - %s ' % (testbeam, testbeamDate['%s' % testbeam]), fileName)] + map( lambda z: z in diamonds, allDiamonds) testBeamLinkTable.append(row) htmlcode = HTML.table(testBeamLinkTable, header_row=header) fileName = '%s/results_testBeams.html' % self.config.get('HTML', 'outputDir') utilities.save_html_code(fileName, htmlcode)
def skelet_html(l_database, sel, title): cgitb.enable() # l_database = 'PNPR1' con = cx_Oracle.connect('/@'+l_database) cur = con.cursor() cur.execute(sel) results = [] col_names = [row[0] for row in cur.description] noprint='NOPRINT' if noprint in col_names: i = col_names.index(noprint) col_names = col_names[:i] + col_names[i+1:] for result in cur: results.append(result[:i] + result[i+1:]) else: for result in cur: results.append(result) cur.close con.close start = f""" <html> <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="/table.css"> <title> {title} </title>""" start += """ <script> function reset_addr() {window.history.replaceState("", "", "/");} </script> """ start += f""" </head> <body alink="#00c6c9" link="#0060ff" vlink="#6e00ce"> <script> reset_addr(); </script> <h1>{title}.</h1><br/> """ eind = """ </body> </html> """ print(start) t=HTML.Table(header_row=col_names,cellpadding=2) for x in results: y = list(map(lambda i: HTML.TableCell(i,align='right') if type(i) is int else i, x)) t.rows.append(y) print(t) print('<br/>') print(eind)
def generateIETFYANGPageMainHTML(self, drafts_stats: dict): """ Create IETFYANGPageMain HTML with compilation results statistics of IETF YANG draft modules and generate a HTML file. Argument: :param drafts_stats (dict) Dictionary containing number of passed, failed and total number of draft modules """ generated_message = 'Generated on {} by the YANG Catalog.'.format(time.strftime('%d/%m/%Y')) content = ['<h3>IETF YANG MODELS</h3>', 'Number of correctly extracted YANG models from IETF drafts: {}'.format(drafts_stats.get('total-drafts')), 'Number of YANG models in IETF drafts that passed compilation: {}/{}'.format( drafts_stats.get('draft-passed'), drafts_stats.get('total-drafts')), 'Number of YANG models in IETF drafts that passed compilation with warnings: {}/{}'.format( drafts_stats.get('draft-warnings'), drafts_stats.get('total-drafts')), 'Number of all YANG models in IETF drafts (examples, badly formatted, etc. ): {}'.format( drafts_stats.get('all-ietf-drafts')), 'Number of correctly extracted example YANG models from IETF drafts: {}'.format( drafts_stats.get('example-drafts')) ] message_html = HTML.list([generated_message]) content_html = HTML.list(content) HTML_filename = '{}IETFYANGPageMain.html'.format(self.__htmlpath) with open(HTML_filename, 'w', encoding='utf-8') as f: f.write(message_html) f.write(content_html) os.chmod(HTML_filename, 0o664) print('{}IETFYANGPageMain.html HTML page generated in directory {}' .format(self.__get_timestamp_with_pid(), self.__htmlpath), flush=True)
def main(): cgitb.enable() l_database = 'OPVDB' sel1 = """select t.regeling,to_char(t.datum_bericht,'IW') weeknr, t.npr_status, count(1) aantal from COMP_WOT.WOT_WOKP_INKOMEND t where to_char(t.datum_bericht,'YYYYIW') >= to_char(sysdate - 7 * 10,'YYYYIW') group by t.regeling,to_char(t.datum_bericht,'IW'), t.npr_status order by to_char(t.datum_bericht,'IW') desc, t.regeling, t.npr_status""" sel = """select to_char(t.datum_bericht,'YYYYIW') jaarweek, t.regeling,to_char(t.datum_bericht,'IW') weeknr, t.npr_status, count(1) aantal from COMP_WOT.WOT_WOKP_INKOMEND t where to_char(t.datum_bericht,'YYYYIW') >= to_char(sysdate - 7 * 10,'YYYYIW') group by t.regeling,to_char(t.datum_bericht,'YYYYIW'), to_char(t.datum_bericht,'IW'), t.npr_status order by to_char(t.datum_bericht,'YYYYIW') desc, t.regeling, t.npr_status""" con = cx_Oracle.connect('/@' + l_database) cur = con.cursor() cur.execute(sel) results = [] for result in cur: results.append(result[1:]) col_names = [row[0] for row in cur.description[1:]] cur.close con.close start = """ <html> <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="/table.css"> <title> Overzicht Deelnemerstatus Opvraging </title> </head> <body alink="#00c6c9" link="#0060ff" vlink="#6e00ce"> <h1>Overzicht van opvragen deelnemerstatus voor WOKP inkomend.</h1><br/> """ eind = """ </body> </html> """ print(start) t = HTML.Table(header_row=col_names, cellpadding=2) for x in results: y = list( map( lambda i: HTML.TableCell(i, align='right') if type(i) is int else i, x)) t.rows.append(y) print(t) print('<br/>') print(eind)
def link(tmp_list): """ generate links to Tapper """ if len(tmp_list) > 1: link_html = HTML.link("results+", "https://tapper/tapper/reports/idlist/" + ",".join(str(l) for l in tmp_list)) elif len(tmp_list) == 1: link_html = HTML.link("results", "https://tapper/tapper/reports/id/" + ",".join(str(l) for l in tmp_list)) return link_html
def feed2html(self, feed): table_data = [] entrylist = [] for entry in feed.entry: entrylist = [ HTML.link(entry.media.title.text,entry.media.player.url), entry.published.text[:10], entry.media.category[0].text, self.sec2time(entry.media.duration.seconds), self.formatViewCount(entry.statistics.view_count), '%.2f'%float(entry.rating.average)] table_data.append(entrylist) html_string = HTML.table(table_data, header_row=['Video title','Video published on','Video category','Video duration','Video view count','Video rating']) return html_string
def __init__(self, *content, **attrs): from HTML import HEAD, HTML self.doctype = self.DOCTYPE self.body = apply(self.body_element, content, attrs) self.head = HEAD(self.generator) if hasattr(self, 'style'): self.head.append(self.style) if hasattr(self, 'title'): self.head.append(self.title) self.html = HTML(self.head, self.body) self.setup()
def main(): ''' Application to manage all the most used packages using apt-get. Unfinished. ''' form = cgi.FieldStorage() sm=serviceManagerBuilder() config=Configuration() view = View(config.system.actions) table_data = [ ['Smith', 'John', 30], ['Carpenter', 'Jack', 47], ['Johnson', 'Paul', 62], ] htmlcode = HTML.table(table_data, header_row=['Last name', 'First name', 'Age']) ins = open( "recommendationsList.txt", "r" ) packages = [] for line in ins: packages.append( line ) installedPackages = [[]] toInstallPackages = [[]] i = -1 j = -1 for a in packages: a = a.rstrip() # strip the new line bashCommand = "dpkg-query -l | grep '" + a + " '" output = execute( bashCommand ) if output == "" : i += 1 toInstallPackages.append( [a, 'w8'] ) else : j += 1 installedPackages.append( [ a, 'w8'] ) if i != -1 : htmlcode += HTML.table( toInstallPackages, header_row=['Package Name', 'p'] ) if j != -1 : htmlcode += HTML.table( installedPackages, header_row=['Package Name', 'p'] ) #if installed add it in the installedPackages array #else in the restPackages #subprocess.call("./checkIfInstalled.sh", shell=True)\ -> maybe generate xml file to get response so it is then compatible with the android view.setContent('Arxidi2 App', htmlcode ) view.output()
def insertTable(table_data, report, hasheader=False, tabclass="table table-rep"): if hasheader: htmlcode = HTML.table(table_data[1:], attribs={'class': tabclass}, header_row=table_data[0]) else: htmlcode = HTML.table(table_data, attribs={'class': tabclass}) report.write(htmlcode)
def make_debian_links(pkg, version): """Return a string containing debian links for a package""" pts_base = "http://packages.qa.debian.org/" bts_base = "http://bugs.debian.org/cgi-bin/pkgreport.cgi?src=" deb_buildd_base = "https://buildd.debian.org/status/logs.php?arch=&pkg=" pts = HTML.link('PTS', pts_base + pkg) bts = HTML.link('BTS', bts_base + pkg) deb_buildd = HTML.link('Buildd', deb_buildd_base + pkg) return " ".join((pts, bts, deb_buildd))
def process_bc_person(person): res = [HTML.Table(header_row=['info for {}'.format(person['name']),''])] k = person.keys() for itm in k: if type(person[itm]) == dict: res.append(HTML.Table(header_row=[itm,''])) for x in person[itm]: res[len(res)-1].rows.append((x,person[itm][x])) else: res[0].rows.append((itm,person[itm])) return '\n<br />'.join(map(str,res))
def process_data(data): rtn = [] tmp = [] tbls = [HTML.Table(header_row=['basecamp data',''])] for itm in data: if type(data[itm]) == dict: tbls.append(HTML.Table(header_row=[itm,''])) for x in data[itm]: tbls[len(tbls)-1].rows.append(x,data[itm[x]]) else: tbls[0].append((itm,data[data.index(itm)])) return tbls
def html_write(info,data,oligo,inputfile,linklist): tabinfo=HTML.table(info) tab=HTML.table(data) linkhome=HTML.link('Home','../report.html') htmlcode=('<haed><link rel="stylesheet" type="text/css" href="http://matrix.petoukhov.com/css/default.css"' + 'media="screen" /></haed>'+linkhome+'<hr><br>'+ tabinfo+'<hr><br>'+tab ) fname=inputfile.path+str(oligo)+'-plet_'+inputfile.get_level()+'.html' fres=open(fname,'w') fres.write(htmlcode) fres.close() form_linklist(linklist,inputfile,oligo)
def createHTMLFromResultFiles(self, resultsFolder, casSystems): if resultsFolder is None: return None resultFiles = os.path.join(resultsFolder, "resultFiles") if resultFiles is None: return None output = "" for cas in casSystems: table = [['Problem Instance \\ Property']] propRow = table[0] problemInstances = next(os.walk(resultFiles))[1] for problemInstance in problemInstances: table.append([problemInstance]) curRow = table[len(table) - 1] solutionPath = os.path.join(resultFiles, problemInstance, cas) if 'solutionInXML.xml' in next(os.walk(solutionPath))[2]: solutionFile = os.path.join(solutionPath, "solutionInXML.xml") root = etree.parse(solutionFile).getroot() for prop in root: propName = prop.tag if len(prop.getchildren()) > 0: propPath = os.path.join(solutionPath, "solutionInXMLSplit") if not os.path.exists(propPath): os.mkdir(propPath) propFile = os.path.join(propPath, propName + ".xml") propXML = mdom.parseString(etree.tostring(prop))\ .toprettyxml(" ") open(propFile, 'w').write(propXML) propVal = HTML.link( "xml", os.path.relpath(propFile, resultsFolder)) else: propVal = prop.text if propName not in propRow: propRow.append(propName) propIndex = propRow.index(propName) while len(curRow) < propIndex: curRow.append('') if len(curRow) == propIndex: curRow.append(propVal) else: curRow[propIndex] = propVal output += "<h1>" + cas + "</h1>\n" + HTML.table(table) + "\n" return output
def link(tmp_list): ''' generate links to Tapper ''' if len(tmp_list) > 1: link_html = HTML.link('results+', 'https://tapper/tapper/reports/idlist/' + ','.join(str(l) for l in tmp_list)) elif len(tmp_list) == 1: link_html = HTML.link('results', 'https://tapper/tapper/reports/id/' + ','.join(str(l) for l in tmp_list)) return link_html
def html_data_conversion(self): resultant_colors = {'Success': '#3CB371', 'Failure': '#FFA07A'} htmlcode = HTML.Table( header_row=['Time', 'Job', 'Table', 'Status'], style="border: 3px solid #000000; border-collapse: collapse;", cellpadding="8") for i in self.vacuum_status: for j in resultant_colors: if i[3].find(j) > -1: coloured_row = HTML.TableRow(i, attribs={'bgcolor': j}) htmlcode.rows.append(coloured_row) return self.text_data, htmlcode
def make_ubuntu_links(pkg, version): """Return a string containing ubuntu links for a package""" puc_base = "http://packages.ubuntu.com/search?searchon=sourcenames&keywords=" lp_base = "https://launchpad.net/ubuntu/+source/" ubu_bugs_base = "https://launchpad.net/ubuntu/+source/%s/+bugs" ubu_buildd_base = "https://launchpad.net/ubuntu/+source/%s/%s" puc = HTML.link('packages.u.c.', puc_base + pkg) lp = HTML.link('LP', lp_base + pkg) ubu_bugs = HTML.link('Bugs', ubu_bugs_base % pkg) ubu_buildd = HTML.link('Buildd', ubu_buildd_base % (pkg, version)) return " ".join((puc, lp, ubu_bugs, ubu_buildd))
def form_linklist(linklist,fname,oligo=0): if oligo==0: linklist.append( {'linktype':'data','deep':fname.compdeep,'type':fname.comptype, 'link':HTML.link(fname.get_level(),fname.get_name()) } ) else: linklist.append( {'linktype':'table','deep':fname.compdeep,'type':fname.comptype, 'link':HTML.link(fname.get_level(),fname.path+str(oligo)+'-plet_'+fname.get_level()+'.html'), 'oligo':oligo } )
def generate_table(self): t = HTML.Table(header_row=['ID', 'LOGIN', 'POINTS', 'COLOR']) for pl in sorted(self.players, key=lambda x: -x.points): t.rows.append([ pl.id, pl.login, pl.points, HTML.TableCell(" ", bgcolor="#{}".format(pl.color)) ]) buf = "<html><head>" buf += '<meta http-equiv="refresh" content="5">' buf += '<title>TheGame - Day %d </title>' % ( datetime.date.today().day - 17) buf += '</head>' buf += str(t).replace(' ', '0') buf += '</html>' self.dump_html(buf)
def getFollowers(): """ Retrieves list of followers and writes to HTML file """ print "[+] Attempting to create list of followers..." print "[*] Warning: May take up to 15 minutes per 180 followers" try: ids = [] for page in tweepy.Cursor(api.followers_ids, screen_name=user.screen_name).pages(): ids.extend(page) time.sleep(60) table = HTML.Table(header_row=["Name", 'Handle', 'Web Link']) file = user.screen_name + "_followers_" + datetime.now().strftime( '%Y-%m-%d_%H%M') + ".html" i = 0 for user_id in ids: if i % 180 == 0: time.sleep(900) i += 1 follower = api.get_user(user_id) webUrl = HTML.link('View Profile', "http://twitter.com/" + follower.screen_name) newRow = [ follower.name.encode('utf-8'), "@" + follower.screen_name, webUrl ] table.rows.append(newRow) print "[+] Found %d follower(s)" % len(ids) name = user.screen_name + "_followers_" + datetime.now().strftime( '%Y-%m-%d_%H%M%S') + ".html" localFile = open(name, 'w') localFile.writelines(str(table)) localFile.close() print "[+] Results written to " + file return except Exception, e: print "[-] Error retrieving followers" errorLog(e, "getFollowers") return
def WriteToStaticHtmlFile(filename, content, anchor): link = 'smart-stocker/' + filename filename = WWW_ROOT + '/' + link with open(filename, 'w') as output_file: os.chmod(filename, 0o600) output_file.write(content) return HTML.link(anchor, link)
def run(run_options=None): logging.debug('Process run......') f = open('videoplayback_result.html', 'w') file_list = glob.glob('%s/*' % HOST_MEDIA_PATH) result_list = {} for file in file_list: baseFile = os.path.basename(file) result_list[baseFile] = ['N/A', 'N/A', 'N/A', 'N/A', '-1', 'N/A', 'N/A', 'N/A'] num = 1 sortedResult = [] for file in file_list: testID = 'Video-%d' % num baseFile = os.path.basename(file) runEachTest(testID, baseFile, result_list[baseFile]) sortedResult.append(result_list[baseFile]) time.sleep(2) num += 1 htmlcode = HTML.table(sortedResult, header_row=['Test ID', 'File Name', 'Codec Type', 'Video Size', 'FPS', 'Frame Drop', 'Playback Result', 'Screen Capture']) os.system('adb shell input keyevent KEYCODE_HOME') f.write(htmlcode) f.close() return True
def create_diamond_html_pages(self): diamonds = self.get_list_of_diamonds(self.results) diamondLinkList = [] for diamond in diamonds: print 'Create Page for diamond: "%s"' % diamond results = filter(lambda x: self.results[x].get('RunInfo', 'dia') == diamond, self.results) results = {key: self.results[key] for key in results} fileName = '%s/results_%s.html' % (self.config.get('HTML', 'outputDir'), diamond) diamondLinkList.append(HTML.link(diamond, 'results_%s.html' % diamond)) self.create_html_overview_table(results, fileName) htmlcode = HTML.list(diamondLinkList) fileName = '%s/results_diamonds.html' % self.config.get('HTML', 'outputDir') if self.verbosity: print 'save diamond file to: "%s"' % fileName utilities.save_html_code(fileName, htmlcode) pass
def get_link(value, string_format, haslink, result): mainLink = result.get('RunInfo', 'mainLink') if haslink != 'None': # print haslink if '%(mainLink' in haslink and haslink.endswith('>)'): divided = haslink.rsplit('%', 1) # print 'divided "%s"'%divided entries = divided[1].strip('()') entries = entries.rsplit('<') entry = entries[-1].strip('<>').split(',') # print entry link = divided[0].strip("'") % (mainLink, result.get(entry[0], entry[1])) elif '%mainLink' in haslink: links = haslink.rsplit('%', 1) # replace('%mainLink','')%mainLink link = links[0].strip("'") % mainLink elif '%diamondName' in haslink: links = haslink.rsplit('%', 1) # replace('%mainLink','')%mainLink link = links[0].strip("'") % result.get('RunInfo','dia') else: link = haslink try: website = string_format % value except: print 'ERROR could not convert "%s"' % string_format website = string_format ouput_link = HTML.link(website, link) return ouput_link try: website = string_format % value except: print 'ERROR could not convert "%s"' % string_format website = string_format return website
def main(): leftDirectionPins, rightDirectionPins = getDirections() leftValuesPins, rightValuesPins = getValues() pins = [[]] text = '' for index in range(len(leftPins)): leftDirectionText, leftValuesText = getFieldTexts(index, leftPins, leftDirectionPins, leftValuesPins) pins.append( [ leftDirectionText, leftValuesText, leftPins[index] ] ) for index in range(len(rightPins)): rightDirectionText, rightValuesText = getFieldTexts(index, rightPins, rightDirectionPins, rightValuesPins) pins[index+1]+=[rightPins[index], rightValuesText, rightDirectionText ] html_code='<div style="clear: both">'+\ '<h4 style="float: left">RPi.GPIO version: ' + str(GPIO.VERSION) + '</h4>'+\ '<h4 style="float: right">RPi Board Revision: ' + str(GPIO.RPI_REVISION) + '</h4>' +\ '</div>' +\ '<hr />' html_code += '<div id="gpio_table">\n' html_code += HTML.table( pins, header_row=[ 'DIRECTION', 'VALUE', 'LEFT', 'RIGHT', 'VALUE', 'DIRECTION' ] ) html_code += '</div>\n' html_code += ''' <div align="center"> <div id="user_space"></div> <button style="float: left;" class="btn btn-primary" onclick="gpio_clear()">Cleanup GPIO</button> <button style="float: right;" type="button" class="btn btn-info" onclick="navigate(\'/cgi-bin/toolkit/gpio_manager.py?type=js\');">Refresh</button> </div> ''' view.setContent('GPIO Manager', html_code) output(view, cgi.FieldStorage())
def login_submit(): # Get the names from the prompt and split them on commas names = request.forms.get('name').split(',') for i in range(len(names)): # Remove any extra spaces names[i] = names[i].strip() player_data = [] # Loop through the list of names and fetch the corresponding url and player data for i in range(len(names)): temp = names[i].split(' ')[0].capitalize() + ' ' + names[i].split( ' ')[1].capitalize() names[i] = temp player_url = get_player_urls(names[i]) player_data.append(get_player_data(player_url)) player_data[i].insert(0, names[i]) # Add the titles to the table player_data.insert( 0, ['Name', 'Height', 'Weight', 'Age', 'Birthdate/Birthplace']) # Turn the python list into an html text table htmlTable = HTML.table(player_data) outFile1 = open('output1.htm') outFile2 = open('output2.htm') return outFile1.read() + htmlTable + outFile2.read() outFile1.close() outFile2.close()
def print_aux(self, start, end, name, date): doc = open(os.path.join(self.path, 'documentos', name + '.html'), 'w') doc.write("""<style type="text/css"> <!-- @import url("style.css"); --> </style>""") print date.Month, date.Year sep = [10, 10, 10, 20] saldo = 0 cur_cta = '' acum = [] for cuenta, fecha, tipopol, numpol, referencia, tipomov, importe in self.get_records(start, end): saldo += importe * (-1 if tipomov == 'True' else 1) fecha = fecha + " " * (sep[0] - len(fecha)) tipopol = self.movs[tipopol] + " " * (sep[1] - len(self.movs[tipopol])) numpol = str(numpol) + " " * (sep[2] - len(str(numpol))) referencia = referencia + " " * (sep[3] - len(referencia)) importe = (" " * (7 if tipomov == 'True' else 0)) + locale.currency(importe, grouping=True) + " " * (7 if tipomov == 'True' else 12) if cur_cta != cuenta: acum.append(['Saldo','','','','','', locale.currency(saldo, grouping=True)]) acum.append(['','','','','','', '']) saldo = 0 cur_cta = cuenta acum.append([cuenta, fecha, tipopol, numpol, referencia, importe, locale.currency(saldo, grouping=True)]) htmlcode = HTML.table(acum, attribs={'id':"hor-minimalist-b"}, border=0, header_row=['Cuenta', 'Fecha', 'Tipo', '#Poliza', 'Ref', 'Importe', 'Saldo']) doc.write(htmlcode)
def errorLog(error, module): """ Writes errors to HTML log file Arguments: error Error recieved from module module Function where error was encountered """ try: log = HTML.Table(header_row=['Function', 'Time', 'Info']) entry = [ module, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), str(error) ] log.rows.append(entry) logFile = open("talon_error_log.html", 'a') logFile.writelines("<br>") logFile.writelines(str(log)) logFile.close() except Exception, e: print "ERROR\n" + str(e) return
def main(): leftDirectionPins, rightDirectionPins = getDirections() leftValuesPins, rightValuesPins = getValues() pins = [[]] text = '' for index in range(len(leftPins)): leftDirectionText, leftValuesText = getFieldTexts(index, leftPins, leftDirectionPins, leftValuesPins) pins.append( [ leftDirectionText, leftValuesText, leftPins[index] ] ) for index in range(len(rightPins)): rightDirectionText, rightValuesText = getFieldTexts(index, rightPins, rightDirectionPins, rightValuesPins) pins[index+1]+=[rightPins[index], rightValuesText, rightDirectionText ] html_code='<div style="clear: both">'+\ '<h4 style="float: left">RPi.GPIO version: ' + str(GPIO.VERSION) + '</h4>'+\ '<h4 style="float: right">RPi Board Revision: ' + str(GPIO.RPI_REVISION) + '</h4>' +\ '</div>' +\ '<hr />' html_code += '<div id="gpio_table">\n' html_code += HTML.table( pins, header_row=[ 'DIRECTION', 'VALUE', 'LEFT', 'RIGHT', 'VALUE', 'DIRECTION' ] ) html_code += '</div>\n' html_code += '<center><div id="user_space"></div><button class="btn btn-primary" onclick="gpio_clear()">Cleanup GPIO</button></center>' view.setContent('GPIO Manager', html_code) view.output()
def create_diamond_html_pages(newResults, mapping): diamonds = map(lambda x: x[mapping['dia']], newResults) diamonds = sorted(list(set(diamonds))) diamondLinkList = [] for diamond in diamonds: results = filter(lambda x: x[mapping['dia']] == diamond, newResults) fileName = 'results_%s.html' % diamond diamondLinkList.append(HTML.link(diamond, fileName)) create_html_overview_table(results, fileName, mapping) print diamond htmlcode = HTML.list(diamondLinkList) fileName = 'results_diamonds.html' with open(fileName, "w") as f: f.write('%s' % htmlcode) pass
def sendemail(): global table if table: html = HTML.table(table, header_row=[ 'Caller ID', 'Call Time', 'Source', 'Destination', 'Disposition', 'Duration (Seconds)' ]) with open('email.html', 'w') as em: em.write(html) fromaddr = "ADD FROM ADDRESS HERE" toaddr = "ADD TO ADDRESS HERE" bcc = ['ADD BCC ADDRESS HERE'] message = MIMEMultipart() message['From'] = "ADD FROM ADDRESS HERE" message['To'] = "ADD TO ADDRESS HERE" message['BCC'] = "ADD BCC ADDRESS HERE" message['Subject'] = "PBX Outbound/Inbound Call Report" email = file('email.html') attachment = MIMEText(email.read(), 'html') message.attach(attachment) server = smtplib.SMTP('ADD SMTP SERVER HERE', 587) server.ehlo() server.starttls() server.ehlo() server.login("ADD LOGIN ADDRESS HERE", "ADD PASSWORD HERE") text = message.as_string() print "sending email....\n\n" toaddrs = [toaddr] + bcc server.sendmail(fromaddr, toaddrs, text)
def sendemail(): global table if table: html = HTML.table(table,header_row=['Caller ID', 'Call Time', 'Source', 'Destination', 'Disposition', 'Duration (Seconds)']) with open('email.html', 'w') as em: em.write(html) fromaddr = "ADD FROM ADDRESS HERE" toaddr = "ADD TO ADDRESS HERE" bcc = ['ADD BCC ADDRESS HERE'] message = MIMEMultipart() message['From'] = "ADD FROM ADDRESS HERE" message['To'] = "ADD TO ADDRESS HERE" message['BCC'] = "ADD BCC ADDRESS HERE" message['Subject'] = "PBX Outbound/Inbound Call Report" email = file('email.html') attachment = MIMEText(email.read(),'html') message.attach(attachment) server = smtplib.SMTP('ADD SMTP SERVER HERE', 587) server.ehlo() server.starttls() server.ehlo() server.login("ADD LOGIN ADDRESS HERE", "ADD PASSWORD HERE") text = message.as_string() print "sending email....\n\n" toaddrs = [toaddr] + bcc server.sendmail(fromaddr, toaddrs, text)
def main(): leftDirectionPins, rightDirectionPins = getDirections() leftValuesPins, rightValuesPins = getValues() pins = [[]] text = '' for index in range(len(leftPins)): leftDirectionText, leftValuesText = getFieldTexts( index, leftPins, leftDirectionPins, leftValuesPins) pins.append([leftDirectionText, leftValuesText, leftPins[index]]) for index in range(len(rightPins)): rightDirectionText, rightValuesText = getFieldTexts( index, rightPins, rightDirectionPins, rightValuesPins) pins[index + 1] += [rightPins[index], rightValuesText, rightDirectionText] html_code='<div style="clear: both">'+\ '<h4 style="float: left">RPi.GPIO version: ' + str(GPIO.VERSION) + '</h4>'+\ '<h4 style="float: right">RPi Board Revision: ' + str(GPIO.RPI_REVISION) + '</h4>' +\ '</div>' +\ '<hr />' html_code += '<div id="gpio_table">\n' html_code += HTML.table(pins, header_row=[ 'DIRECTION', 'VALUE', 'LEFT', 'RIGHT', 'VALUE', 'DIRECTION' ]) html_code += '</div>\n' html_code += '<center><div id="user_space"></div><button class="btn btn-primary" onclick="gpio_clear()">Cleanup GPIO</button></center>' view.setContent('GPIO Manager', html_code) output(view, cgi.FieldStorage())
def main(): form = cgi.FieldStorage() config=Configuration() view = View(config.system.actions) o = export_all_pins() leftValuesPins, rightValuesPins = getValues() leftDirectionPins, rightDirectionPins = getDirections() pins = [[]] text = '' for index in range(len(leftPins)): leftDirectionText, leftValuesText = getFieldTexts(index, leftPins, leftDirectionPins, leftValuesPins) pins.append( [ leftDirectionText, leftValuesText, leftPins[index] ] ) for index in range(len(rightPins)): rightDirectionText, rightValuesText = getFieldTexts(index, rightPins, rightDirectionPins, rightValuesPins) pins[index+1]+=[rightPins[index], rightValuesText, rightDirectionText ] html_code = HTML.table( pins, header_row=[ 'DIRECTION', 'VALUE', 'LEFT', 'RIGHT', 'VALUE', 'DIRECTION' ] ) view.setContent('GPIO Manager', html_code) view.output()
def report(self, method=''): # self.set_data() sdf_ext = super(ReporterBBVAP, self).report() if self.prev_result is not None: self.prev_result['AP'] = sdf_ext else: self.prev_result = {'AP': sdf_ext} if method == '': return self.sdf_ext elif method == 'intermediate': return self.prev_result elif method == 'string': output = self.prev_result if len(output.keys()) < 2: raise Exception('output must have 2 keys') try: oneCResult = [u'Energie (Wh, 1C Entladen, Speicher Derating Aktiv) ', str( self.prev_result['OneC']['summary.energyBatteryWh'][0])] except: oneCResult = [u'Energie (Wh, 1C Entladen, Speicher Derating Aktiv) ', 'Simulation Failed!'] table_string = str(HTML.table([[u'AP1 (25 °C, 10s, EoL, RCI=10%)', "Leistung (W): " + str(self.prev_result['AP']['summary.batteryPower'][0])], [u'AP3 ( 0 °C, 10s, EoL, RCI=80%)', "Leistung (W): " + str(self.prev_result['AP']['summary.batteryPower'][1])], [u'AP6 (25 °C, 10s, BoL, RCI=80%)', "Leistung (W): " + str(self.prev_result['APBOL']['summary.batteryPower'][0])], oneCResult], set_column=True)) return table_string
def tables_html(): res=db_connection() #print(list(res)) table_data = res htmlcode = HTML.table(res) print htmlcode write_html(htmlcode)
def tables_html(): r = connection() #print(list(res)) #table_data = res htmlcode = HTML.table(r) print htmlcode htmlconnection(htmlcode)
def generateHtmlView(self): try: self.__logger.debug( "=== Test Results Folder : %s===" % self.__xunitOutFolder) """Create html table with rows 'SNo', 'TCName', 'Result','Time'""" t = HTML.table(header_row=['SNo', 'TCName', 'Result', 'RunTime']) test_suites = [] no = 1 if self.__xunitOutFolder: if os.path.isdir(self.__xunitOutFolder): for items in os.listdir(self.__xunitOutFolder): if os.path.isfile(self.__xunitOutFolder + "/" + items) and items.startswith("test") and items.endswith("xml"): test_suites.append(items) for files in test_suites: with open(self.__xunitOutFolder + "/" + files) as f: self.__ts, self.__tr = parse(self.__xunitOutFolder + "/" + files) for tc in self.__ts : t.rows.append([no, tc.classname+"_"+tc.methodname, tc.result, tc.time.total_seconds()]) no = no + 1 return t except Exception as e: self.__logger.debug( "\nParsing Xunit Test Output Failed : %s" % Codes.GetDetailExceptionInfo(e)) return Codes.FAILED
def main(): ''' Application to display the iptables of raspberry to the user ''' form = cgi.FieldStorage() f = open(os.environ['MY_HOME'] + '/html/iptables_overlay_html', 'r') html_tables= f.read() f.close() chain_els=[[]] iptables=IPTablesManager() header_list=['protocol', 'target', 'otherinfo','destination', 'source', 'option'] for chain in iptables.chains: html_tables+='<h4><a href="javascript:open_iptables_panel(\'' + chain + '\')">' + chain + '</a>'+' (Default Protocol: ' \ + iptables.chains[chain].policy + ')</h4>' if iptables.chains[chain]._isRulesEmpty(): chain_els.append(['--','--','--','--','--','--']) else: for rule in iptables.chains[chain].rules: chain_els.append(list(rule.values())) html_tables+=HTML.table(chain_els, header_row=header_list) chain_els=[[]] html_tables+='</br>' view.setContent('IPTables', html_tables) output(view, form)
def login_submit(): # Replace spaces with + signs to insert into the url search = request.forms.get('name').replace(' ','+') url = "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyDYyZCC32BnqauGRprJlB1c4fPSpx6Wym0&country=US&q="+search+"&alt=json" output = urllib2.urlopen(url).readlines() # Initialize the table table = [ ['Product Name', 'Price'] ] # parse the output # Look through each line for the data I want for index in range(len(output)): line = output[index] # Check for height data if line.count('"title":') > 0: title = getTitle(line) if line.count('"price":') > 0: price = getPrice(line) temp = [title, price] table.append(temp) # Package the data print table # Turn the python list into an html text table htmlTable = HTML.table(table) outFile1 = open('output1.htm') outFile2 = open('output2.htm') return outFile1.read() + htmlTable + outFile2.read() outFile1.close() outFile2.close()
def count_letters_and_write_to_file(seq,inputfile): '''запись 1 отчета в файл''' seq=seq.lower() ## print seq,len(seq) c=seq.count('c');g=seq.count('g');a=seq.count('a');t=seq.count('t') # подсчет букв S=float(c+g+a+t) ## print S CG=float(c+g) AT=float(a+t) outfile=inputfile.copy() outfile.ext='.html' outf=open(outfile.get_name(),'w') def p(l): 'проценты' return ' ('+str(round(l*100/S,2))+' %)' print >> outf, HTML.link('Home','../report.html'),'<br><hr>',outfile.name,'<br><hr>' print >> outf, 'conv. level:',outfile.get_level(),'<br><hr>' ## print >> outf, 'total amount of all letters:',S,'<br>' ## print >> outf, 'number of letters c:',c,p(c),'<br>' ## print >> outf, 'number of letters g:',g,p(g),'<br>' ## print >> outf, 'number of letters a:',a,p(a),'<br>' ## print >> outf, 'number of letters t:',t,p(t),'<br>' ## print >> outf, 'total number of letters (c+g):', CG, p(CG),'<br>' ## print >> outf, 'total number of letters (a+t):', AT, p(AT),'<br>' ## print >> outf, 'relevant amounts of pairs of letters: (a+t)/(c+g):', round(AT/CG,3),'<br>' ## print >> outf, 'pairwise relationship of letters: a/c:', round(a/c,3),'<br>' ## print >> outf, 'pairwise relationship of letters: a/g:', round(a/g,3),'<br>' ## print >> outf, 'pairwise relationship of letters: a/t:', round(a/t,3),'<br>' ## print >> outf, 'pairwise relationship of letters: g/c:', round(g/c,3),'<br>' ## print >> outf, '<br><hr>' return outf
def genhtmlreport(today,enDdate,Status): starttime=today endtime=enDdate TEXT ='<!doctype html public '"-//w3c//dtd html 4.0 transitional//en"'><html><head><meta http-equiv='"Content-Type"' content='"text/html; charset=utf-8"'></head><body> <style>table {width:100%;}table, th, td {border: 1px solid black;border-collapse: collapse;}th, td {padding: 5px;text-align: left;}table#t01 tr:nth-child(even) {background-color: #eee;}table#t01 tr:nth-child(odd) {background-color:#fff;}table#t01 th {background-color: green;color: white;}</style></head><body>' TEXT=TEXT+'<table id="t01">'+'Start Time: '+today+'</p>' htmlcode = HTML.table(Status, header_row=['Server Name','DB Name','Run Time','DB Size']) TEXT=TEXT+htmlcode+'</p>'+'End Time: '+enDdate+'</table></body></html>' sendmail(TEXT)
def make_cluster_table(cld, idn,idd, outfile): cli = {} clns = [] for i in os.listdir(cld): if ".fa" not in i: continue sps = set() firstdef = None num = 0 avl = 0 for j in seq.read_fasta_file_iter(cld+"/"+i): sps.add(idn[j.name]) firstdef = idd[j.name] avl += len(j.seq) num += 1 avl = avl/float(num) cli[i] = sps if len(sps) > 2: clns.append([hl.link(i,"clusters/"+i),len(sps),avl,firstdef]) clns = sorted(clns, key=lambda x: x[1], reverse=True) clns.insert(0,["<b>name</b>","<b>num_species</b>","<b>avg unaln len</b>","<b>defline</b>"]) htmlf = open(outfile,"w") links = [] if os.path.isfile(cld+"/../../info.html"): #htmlc = hl.link('back','../info.html') links.append([hl.link('back','../info.html')]) #htmlf.write(htmlc) for i in os.listdir(cld+"/../"): if os.path.isdir(cld+"/../"+i) and "clusters" not in i: #htmlc = hl.link(" "+i+" ",i+"/info.html") links.append([hl.link(" "+i+" ",i+"/info.html")]) #htmlf.write(htmlc) name = cld.split("/")[-2] htmlf.write("<h1>"+name+"</h1>") htmlf.write("<div style=\"float: left\">\n") htmlc = hl.table(links,style="border: 2px solid #000000; border-collapse: collapse;") htmlf.write(htmlc) htmlf.write("</div>\n<div style=\"float: left\">\n") htmlc = hl.table(clns,width=600,style="border: 2px solid #000000; border-collapse: collapse;") htmlf.write(htmlc) htmlf.write("</div>\n") htmlf.close()
def RunStrategies(): tipList = [] for name, strategy in STRATEGY_FUNCS.items(): logging.info('Running strategy: %s\n' % (name)) tip = strategy() if tip != '': tipList.append('<pre>\n' + tip + '\n</pre>') return HTML.list(tipList)
def RunStrategies(): tipList = [] for name, strategy in STRATEGY_FUNCS.items(): logging.info('Running strategy: %s\n'%(name)) tip = strategy() if tip != '': tipList.append('<pre>\n' + tip + '\n</pre>') return HTML.list(tipList)
def tables_html(self,r,monthname,i): #print(list(res)) #table_data = res #for k in monthname: htmlcode="<b>"+monthname[i]+"</b>" htmlcode+= HTML.table(r) print htmlcode return htmlcode
def index(): table_data = [ ['Last name', 'First name', 'Age'], ['Trocchia', 'Scott', '24'], ['Trocchia', 'Stan', '61'] ] htmlcode = HTML.table(table_data) return render_template("HTMLCODE.html", htmlcode = htmlcode)
def getTransactions(): if request.method == 'POST': result = request.form query = "SELECT *FROM TRANSACTIONS WHERE SENDER= '{}'".format(result['username']) cur.execute(query) records = cur.fetchall() html = HTML.table(records, header_row=['Transaction ID', 'Sender', 'Recipient', 'Amount', 'Transaction Date & Time']) return html
def __init__(self, html=False, header_row=None): """ @type html: bool @type header_row: list(str) @param html: C{True} for HTML, C{False} for plain text. @param header_row: Optional header row. """ self.html = html if html: if header_row: self.table = HTML.Table(header_row=header_row) else: self.table = HTML.Table() else: self.table = texttable.Texttable(max_width=140) if header_row: self.table.add_row(['*%s*' % x for x in header_row])
def form_linklist(linklist,filename): fname=filename.copy() fname.ext='.html' linklist.append( {'deep':fname.compdeep,'type':fname.comptype, 'link':HTML.link(fname.get_level(),'report/'+fname.get_name().rpartition('/')[2]) } )