Пример #1
0
def test_title():
  d = document()
  assert d.title == 'Dominate'

  d = document(title='foobar')
  assert d.title == 'foobar'

  d.title = 'baz'
  assert d.title == 'baz'

  d.title = title('bar')
  assert d.title == 'bar'

  assert d.render() == \
'''<!DOCTYPE html>
Пример #2
0
def makeHtml(path, fileName, sitename, authorname, usecss, usejs):
    doc = dominate.document(title=sitename)

    with doc.head:
        if (usecss.lower() == "y"):
            link(rel='stylesheet', href='style.css')
        if (usejs.lower() == "y"):
            script(type='text/javascript', src='script.js')
        with meta():
            attr(author=authorname)

    with doc:
        with div(id='header').add(ol()):
            for i in ['home', 'about', 'contact']:
                li(a(i.title(), href='/%s.html' % i))

        with div():
            attr(cls='body')
            p('Lorem ipsum..')

    if not os.path.exists("./" + path):
        os.makedirs("./" + path)

    f = open("./" + path + "/" + fileName, 'w+')
    f.write(str(doc))
    f.close()

    if (usejs.lower() == "y"):
        if not os.path.exists("./" + sitename + "/js"):
            os.makedirs("./" + sitename + "/js")
    if (usecss.lower() == "y"):
        if not os.path.exists("./" + sitename + "/css"):
            os.makedirs("./" + sitename + "/css")
Пример #3
0
def generateStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates the Stats HTML section

	firstLevel = checkFirstLevel(graph)
	softwareLabelNum = queryVersionNum(graph)
	softwareLabelNumList = addQueryToList(softwareLabelNum)
	
	stats = document(title="FSL Viewer") #Creates initial html page (stats)
	stats += h1("Sample FSL Viewer")
	stats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	stats += h2("Stats")
	stats += hr()
	stats += h3("Analysis Methods")
	
	if askSpm(graph) == True: #Checks if SPM was used
		
		stats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/)." % softwareLabelNumList[1])
		
	elif askFsl(graph) == True: #Checks if FSL was used
		
		fslFeatVersion = queryFslFeatVersion(graph)
		stats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." % (fslFeatVersion[0], softwareLabelNumList[1]))
		
	stats += hr()
	stats += h3("Design Matrix")
	
	designMatrixLocation = queryDesignMatrixLocation(graph)
	stats += a(img(src = designMatrixLocation[1], style = "border:5px solid black", border = 0), href = designMatrixLocation[0]) #Adds design matrix image (as a link) to html page
	
	statsFile = open(statsFilePath, "x")
	print(stats, file = statsFile) #Prints html page to a file
	statsFile.close()
Пример #4
0
 def __init__(self,  data=[], outdir=""):
     self.outdir = outdir
     self.file = outdir + '/report.html'
     self.data = data
     self.doc = dominate.document(title="tmtc report", doctype="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd\">")
     metastring=meta(http_equiv="Content-Type", content="text/html; charset=utf-8")
     self.doc.head.add(metastring)
Пример #5
0
def open_html_doc(name, letter=None):
    html_doc = dominate.document(title=u"מילון הראיה")
    html_doc['dir'] = 'rtl'
    with html_doc.head:
        with tags.meta():
            tags.attr(charset="utf-8")
        with tags.meta():
            tags.attr(name="viewport", content="width=device-width, initial-scale=1")

        tags.script(src="jquery/dist/jquery.min.js")
        tags.link(rel='stylesheet', href='bootstrap-3.3.6-dist/css/bootstrap.min.css')
        tags.link(rel='stylesheet', href='style.css')
        tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js")
        tags.link(rel='stylesheet', href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css")
        tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css')
        tags.script(src="milon.js")
        tags.script(src="html_demos-gh-pages/footnotes.js")
        tags.script(src="subjects_db.json")




    html_doc.footnote_ids_of_this_html_doc = []
    html_doc.name = name
    if letter:
        html_doc.letter = letter
        html_doc.section = html_docs_l[-1].section
    else:
        html_doc.section = name

    html_doc.index = len(html_docs_l) + 1
    with html_doc.body:
        with tags.div():
            tags.attr(cls="container-fluid")
            # TODO: call page_loaded to update saved URL also in other links
            tags.script("page_loaded('%s.html')" % html_doc.index)

            with tags.div():
                tags.attr(cls="fixed_top_left", id="menu_bar")
                with tags.div():
                    with tags.button(type="button"):
                        tags.attr(id="search_icon_button", type="button", cls="btn btn-default")
                        with tags.span():
                            tags.attr(cls="glyphicon glyphicon-search")
                    with tags.span():
                        tags.attr(cls="dropdown")
                        with tags.button(type="button", cls="btn btn-primary") as b:
                            tags.attr(href="#") #, cls="dropdown-toggle")
                            with tags.span():
                                tags.attr(cls="glyphicon glyphicon-menu-hamburger")
                                # b['data-toggle'] = "dropdown"
                        with tags.ul():
                            tags.attr(cls="dropdown-menu dropdown-menu-left scrollable-menu")





    return html_doc
Пример #6
0
def generateMainHTML(graph,mainFilePath = "Main.html", statsFilePath = "stats.html", postStatsFilePath = "postStats.html"): #Generates the main HTML page

	main = document(title="FSL Viewer")
	main += h1("Sample FSL Viewer")
	main += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html")))
	mainFile = open(mainFilePath, "x")
	print(main, file = mainFile)
	mainFile.close()
def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv,
      'androidpublisher',
      'v2',
      __doc__,
      __file__,
      parents=[argparser],
      scope='https://www.googleapis.com/auth/androidpublisher')

  # Process flags and read their values.
  package_name = flags.package_name

  try:

    edit_request = service.edits().insert(body={}, packageName=package_name)
    result = edit_request.execute()
    edit_id = result['id']

    apks_result = service.edits().apks().list(
        editId=edit_id, packageName=package_name).execute()

    version_codes = [apk['versionCode'] for apk in apks_result['apks']]

    doc = dominate.document(title="Build Up The Base! Changelog")
    with doc.head:
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js')
        tags.link(rel='stylesheet', href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css')
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js')
        tags.script("""
        $(function(){
            $('#change_log').accordion();
        });
        """,type='text/javascript')

    with doc:
        with tags.div(id="change_log"):
            for version in version_codes[::-1]:
                listings_result = service.edits().apklistings().list(
                        editId=edit_id, packageName=package_name, apkVersionCode=version
                    ).execute()

                tags.h3("VERSION %s" % version, id="version_%s"%version)
                with tags.div():
                    if 'listings' in listings_result:
                        for line in  listings_result['listings'][0]['recentChanges'].splitlines():
                            tags.div(line)
                    else:
                        tags.div("No listing found")

    print doc

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Пример #8
0
def pollsToHtml(title, results):
    doc = document(title=title)
    with doc:
        h1(title)
    with doc.head:
        meta(charset='utf-8')
    for p, r in results:
        with doc:
            r.htmlOutput(doc, p)
    return doc
Пример #9
0
def buildHTML(user,indexes,dicItems,itemIdSet,dataSet,values):
    print 'Building html output'
    print '==============================================\n'
    doc = dominate.document(title='Top recommendations for ' + str(user))
    sortedData = sorted(dataSet[str(user)].items(),key=lambda x: x[1],reverse=True) 
    with doc.head:
        link(rel='stylesheet', href='http://cdn.foundation5.zurb.com/foundation.css')

    with doc:
        with div(id='header', cls='small-7 large-centered columns'):
            h1('recommendations for user ' + str(user))
        with div(id='content', cls='small-7 large-centered columns'):
            h3('We recommend:')
            print ('Recomendations for user %i:')% user
            with table().add(tbody()):
                l = tr()
                l.add(th('Place'))
                l.add(th('Title'))
                l.add(th('Genre'))
                l.add(th('Recommendator value'))
                for counter, index in enumerate(indexes):
                    itemId = itemIdSet[index]
                    l = tr()
                    l.add(td(str(counter+1)))
                    l.add(td(a(dicItems[itemId]['name'],href=dicItems[itemId]['url'])))
                    print str(counter+1) + '.-' + dicItems[itemId]['name']
                    l.add(td(dicItems[itemId]['genre']))
                    l.add(td(values[counter]))

            h3('You have seen:')
            with table().add(tbody()):
                l = tr()
                l.add(th('Title'))
                l.add(th('Rating'))
                l.add(th('Genre'))
                for (movie,rating) in sortedData:
                    l = tr()
                    l.add(td(a(dicItems[movie]['name'],href=dicItems[movie]['url'])))
                    l.add(td(dataSet[str(user)][movie]))
                    l.add(td(dicItems[movie]['genre']))

    f = codecs.open('output.html','w+',encoding='utf8')
    
    print '\n=============================================='

    try:
        f.write(ensure_unicode(doc))
        new = 2 
        brow = webbrowser.get('safari')
        url = os.path.abspath("output.html")
        # open a public URL, in this case, the webbrowser docs
        brow.open(url,new=new)
    except Exception, e:
        print 'Error building HTML output:'
        print e
Пример #10
0
def index(request):
  doc = dominate.document(title='SNAKE5')
  doc.head += script(src='http://pyy.zkpq.ca/pyy.min.js')
  doc.head += link(rel='stylesheet', href='static/snake5.css')
  with doc:
    with div(id='body'):
      with div(cls='game'):
        canvas(width="800", height="480")
    script(src='static/snake5.js')

  return doc.render()
Пример #11
0
	def new(self, route = '/',
				 title = 'Classy Domination',
				 css = 'static/css', js = 'static/js'):
		page = dominate.document(title)
		with page.head:
			for  i in walk(css):
				link(rel='stylesheet', href='/%s/%s' % (css,i[2][0]))
			for i in walk(js): 
				script(type="text/javascript", src='/%s/%s' % (js,i[2][0]))
		self.paged = page
		self.route = route
		return self
Пример #12
0
def list_notices(buf):
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document:
        H.h1(title)
        with H.div(_class=u'notices-list'):
            placeholder = Placeholder()
            for id_ in sorted(notice.notices.keys()):
                _notice_to_html(notice.notices[id_], placeholder,
                                with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Пример #13
0
def sheet_of_most_population():
    sortList=sort_list('population')
    doc=document(title="most population")
    with doc.head:
        with doc.body:
            h1("most poulation")
            for k in sortList:
                a(k['name'],href='{}.html'.format(k['short_name']))
                br()

    with open('index1.html','w') as f:
        f.write(doc.render())
Пример #14
0
    def __init__(self, web_dir, title, refresh=0):
        self.title = title
        self.web_dir = web_dir
        self.img_dir = os.path.join(self.web_dir, 'images')
        if not os.path.exists(self.web_dir):
            os.makedirs(self.web_dir)
        if not os.path.exists(self.img_dir):
            os.makedirs(self.img_dir)

        self.doc = dominate.document(title=title)
        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))
Пример #15
0
def sheet_of_continents(countries):
   for k,v in countries.items():
        doc=document(title="continent")
        with doc.head:
            with doc.body:
                h1(k)
                for x in v:
                    a(x['name'],href='{}.html'.format(x['short_name']))
                    br()
                a('bake to index',href="index.html")

        with open('continent_{}.html'.format(k),'w') as f:
            f.write(doc.render())
Пример #16
0
def pdf_it():
    """
    Function for generating PDF from HTML and some options which are defined in this function. Function is taking AJAX
    POST data that represents html <table> generated in view and append it in <body> block.
    :return: name: str - name of generated PDF file
    """
    if request.is_ajax:
        # POST data
        data = request.body.read()
        # Options of PDF
        options = {'page-size': 'A4',
                   'orientation': 'Landscape'
        }
        page = dominate.document('PDF Export')
        with page.head:
            # CSS
            style("""td, th{text-align: left;}
                     table{width: 100%;}
                     tr{
                        page-break-inside: avoid;
                     }
                  """
            )
            # JS
            script(type='text/javascript', src='https://code.jquery.com/jquery-1.11.3.min.js')
            script(
                """
                $(document).ready(function(){
                  $('tr:even').css('background-color', '#cfcfcf');
                  $('tr:odd').css('background-color', '#e1e1e1');
                });

                """, type='text/javascript')

        page.body.add_raw_string(data)
        name = 'export_' + str(time()) + '.pdf'
        page = page.render()
        # Change directory to tmp for storing PDFs.
        try:
            os.mkdir('tmp')
        except OSError:
            # Passing exceptions is really bad habit, but in this case it is not necessary to process it, because it is
            # raised if folder already exists, so this doesn't mean anything, and checking for folder existing with
            # trying to make it is more important thing.
            pass
        path = 'tmp/' + name
        pdfkit.from_string(page, path, options=options)
        return name
Пример #17
0
def index_keywords(keywords, primary, path_dest):
    logger = logging.getLogger(sys._getframe().f_code.co_name)
    doc = dominate.document(title=u'AWOL Index: Resources by Keywords')
    with doc.head:
        link(rel='stylesheet', type='text/css', href='http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(rel='stylesheet', type='text/css', href='http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(rel='stylesheet', type='text/css', href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700&amp;subset=latin,cyrillic-ext,greek-ext,greek,latin-ext,cyrillic')        
        link(rel='stylesheet', type='text/css', href='./index-style.css')
    doc += h1('Index of Resources by Keywords')
    _p = p('part of ', cls='subtitle')
    _p += a('The AWOL Index', href='../index.html')
    doc += _p
    for kw in sorted(keywords.keys(), key=lambda s: s.lower()):
        these = [pri for pri in keywords[kw] if ' ' not in pri['domain'] and pri['title'] != u'' and pri in primary]
        if len(these) > 0:
            for pri in these:
                try:
                    sort_key = pri['sort_key']
                except KeyError:
                    rtitle = pri['title']
                    sort_key = rtitle.lower()
                    if sort_key != unicode(sort_key.encode('ascii', 'ignore')):
                        classification = langid.classify(sort_key)
                        if classification[1] > 0.9:
                            if classification[0] in transliterate_languages:
                                sort_key = transliterate.translit(sort_key, classification[0], reversed=True)
                                sort_key = unicodedata.normalize('NFKD', sort_key)
                        sort_key = codecs.encode(sort_key, 'translit/long')
                        sort_key = unidecode(sort_key)
                        sort_key = sort_key.encode('ascii', 'ignore')
                        if len(sort_key) == 0:
                            sort_key = rtitle.lower()
                    sort_key = RX_PUNCT.sub(u'', sort_key)
                    sort_key = u''.join(sort_key.strip().split()).lower()
                    logger.debug(u'sortkey for title "{0}": "{1}"'.format(rtitle, sort_key))
                    pri['sort_key'] = sort_key

            _div = doc.add(div(id=kw.lower().replace(u' ', u'-')))
            _div += h2(kw)
            _ul = _div.add(ul())
            for pri in sorted(these, key=lambda k: k['sort_key']):
                _li = list_entry(_ul, pri)
        else:
            logger.warning(u"suppressed keyword with no top resources: {0}".format(kw))
    html_out(doc, os.path.join(path_dest, 'index-keywords.html'))
Пример #18
0
def list_notices(buf):
    """Render the list of all notices to the file-like `buf`."""
    title = u'HTTPolice notices'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.body:
        H.attr(_class=u'notices-list')
    with document:
        H.h1(title)
        H.p(u'This is the list of all notices produced by ',
            H.a(u'HTTPolice', href=homepage, target='_self'),
            u' version ', version, u'.')
        H.p(u'See also the ',
            H.a(u'HTTPolice manual', href=u'index.html', target='_self'), u'.')
        placeholder = Placeholder()
        for id_ in sorted(notice.all_notices.keys()):
            _notice_to_html(notice.all_notices[id_], placeholder,
                            with_anchor=True)
    buf.write(document.render().encode('utf-8'))
Пример #19
0
def base_page():
    """
    Basic template for all pages.
    It includes all headers, styles, footer and other stuff.
    It will be passed to other specific views which will add to DOM, things that every of these views show.
    :return: object of <dominate.document> class
    """
    doc = dominate.document(title='Home Page')
    with doc.head:
        # CSS
        link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css')
        link(rel='stylesheet', href='jquery.pnotify.default.css')

        # JS
        script(type='text/javascript', src='https://code.jquery.com/jquery-1.11.3.min.js')
        script(type='text/javascript', src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js')
        script(type='text/javascript', src='jquery.pnotify.min.js')
        script(type='text/javascript', src='serve.js')
    return doc
Пример #20
0
def generate_rt_html(tables):
    doc = dominate.document(title='ABED Rank Tests')

    with doc.head:
        # meta tags
        tags.meta(charset='utf-8')
        tags.meta(http_equiv='X-UA-Compatible', content='IE=edge')
        tags.meta(name='viewport',
                content='width=device-width, initial-scale=1')
        tags.meta(name='description', content='Rank graphs for ABED results')
        tags.meta(name='author', content='Gertjan van den Burg')

        # JQuery & Bootstrap JS
        tags.script(type='text/javascript',
                src=copy_data_file('jquery/1.11.3/jquery.min.js'))
        tags.script(type='text/javascript',
                src=copy_data_file('bootstrap-3.3.5-dist/js/bootstrap.min.js'))
        # Bootstrap core CSS
        tags.link(rel='stylesheet', href=copy_data_file(
            'bootstrap-3.3.5-dist/css/bootstrap.min.css'))

        # ABED CSS & JS
        tags.link(rel='stylesheet', href=copy_data_file('abed/css/abed.css'))

    tables = [t for t in tables if t.is_summary and t.type ==
            AbedTableTypes.RANKS]
    labels = sorted(set([t.target for t in tables]))
    lbl_table = {}
    for lbl in labels:
        lbl_table[lbl] = [t for t in tables if t.target == lbl]

    with doc:
        with tags.div(id='header'):
            navbar(active=AbedHTMLTypes.RANK_TESTS)
        with tags.div(id='content'):
            with tags.div(_class='container'):
                for lbl in sorted(lbl_table.keys()):
                    generate_label_panel(lbl, lbl_table)
            tags.comment('./container')
        with tags.div(id='footer'):
            pass

    return str(doc)
Пример #21
0
def generate_index_html(task_dict):
    doc = dominate.document(title='ABED Main page')

    with doc.head:
        # meta tags
        tags.meta(charset='utf-8')
        tags.meta(http_equiv='X-UA-Compatible', content='IE=edge')
        tags.meta(name='viewport',
                content='width=device-width, initial-scale=1')
        tags.meta(name='description', content='')
        tags.meta(name='author', content='')
        #tags.link(rel='icon', href=copy_data_file('ABED/images/favicon.ico'))

        # JQuery & Bootstrap JS
        tags.comment('Bootstrap core JavaScript')
        tags.script(src=copy_data_file('jquery/1.11.3/jquery.min.js'))
        tags.script(
                src=copy_data_file('bootstrap-3.3.5-dist/js/bootstrap.min.js'))

        # Bootstrap core CSS
        tags.link(rel='stylesheet', href=copy_data_file(
            'bootstrap-3.3.5-dist/css/bootstrap.min.css'))

        # ABED CSS
        tags.link(rel='stylesheet', href=copy_data_file('abed/css/abed.css'))

    with doc:
        navbar(active=AbedHTMLTypes.INDEX)
        with tags.div(_class='container'):
            with tags.div(_class='abed-title'):
                tags.h1('ABED Results Overview for project %s' % 
                        settings.PROJECT_NAME)
            tags.p('Percentage of tasks completed:')
            with tags.div(_class='progress'):
                perc = str(get_status_perc(task_dict))
                tags.div('%s%%' % perc, _class='progress-bar', 
                        role='progressbar', aria_valuenow=perc, 
                        aria_minvalue='0', aria_maxvalue='100',
                        style='width: %s%%;' % perc)
        tags.comment('/.container')

    return str(doc)
Пример #22
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document:
        H.h1(title)
        _render_exchanges(exchanges)
    buf.write(document.render().encode('utf-8'))
Пример #23
0
def tree_dominate(commands, vna_list):
    doc = dominate.document(title="VNA cmd ref")
    re_url = re.compile("<(.*)>")
    doc.head += script(src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js")
    doc.head += script(src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js")
    doc.head += link(rel="stylesheet", type="text/css", href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css")

    doc.head += script(src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js")
    doc.head += link(rel="stylesheet", type="text/css", href="https://cdn.datatables.net/fixedheader/3.1.5/css/fixedHeader.dataTables.min.css")

    doc.head += script(src="cmd_tree.js")
    doc.head += link(rel="stylesheet", type="text/css", href="cmd_tree.css")

    with doc.body:
        with table(cls="cmd-table"):
            with thead().add(tr()):
                th("Command")
                for vna in vna_list:
                    th(vna, cls="vna-col")
            with tbody():
                for cmd in sorted(commands.keys()):
                    with tr():
                        td(cmd)
                        for vna in vna_list:
                            try:
                                node = commands[cmd][vna]
                            except KeyError:
                                td("N")
                            else:
                                href = re_url.search(node.__doc__)
                                if href:
                                    td(a("Y", href=href.group(1)))
                                else:
                                    td("Y")
            with tfoot().add(tr()):
                td(input(type="text", placeholder="Filter commands"))
                for vna in vna_list:
                    td(vna)
    with open("cmd_tree.html", "wb") as f:
        f.write(doc.render())
Пример #24
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
 def get_student_grades_html(self):
     import dominate
     from dominate import tags
     page = dominate.document(title='Final Grades')
     with page:
         with tags.table(border="1"):
             number_of_assignments = self.get_number_of_assignments()
             with tags.tr():
                 tags.th("First Name")
                 tags.th("Last Name")
                 tags.th("Overall Average")
                 tags.th("Letter Grade")
                 tags.th("Scores", colspan=str(number_of_assignments))
             for student in self.sorted_students():
                 with tags.tr():
                     grade_average = student.grade_average(number_of_assignments)
                     tags.td(student.name.first)
                     tags.td(student.name.last)
                     tags.td(grade_average)
                     tags.td(self._grade_tiers.letter(grade_average))
                     for score in student.sorted_scores():
                         tags.td(score)
     return str(page)
Пример #26
0
def index_primary(primary, path_dest):
    logger = logging.getLogger(sys._getframe().f_code.co_name)
    transliterate_languages = transliterate.get_available_language_codes()
    doc = dominate.document(title=u'AWOL Index: Top-Level Resources')
    with doc.head:
        link(rel='stylesheet', type='text/css', href='http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(rel='stylesheet', type='text/css', href='http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(rel='stylesheet', type='text/css', href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700&amp;subset=latin,cyrillic-ext,greek-ext,greek,latin-ext,cyrillic')
        link(rel='stylesheet', type='text/css', href='./index-style.css')
    doc += h1('Index of Top-Level Resources')
    _p = p('part of ', cls='subtitle')
    _p += a('The AWOL Index', href='../index.html')
    doc += _p
    _ul = doc.add(ul())
    for pri in primary:
        rtitle = pri['title']
        sort_key = rtitle.lower()
        if sort_key != unicode(sort_key.encode('ascii', 'ignore')):
            classification = langid.classify(sort_key)
            if classification[1] > 0.9:
                if classification[0] in transliterate_languages:
                    sort_key = transliterate.translit(sort_key, classification[0], reversed=True)
                    sort_key = unicodedata.normalize('NFKD', sort_key)
            sort_key = codecs.encode(sort_key, 'translit/long')
            sort_key = unidecode(sort_key)
            sort_key = sort_key.encode('ascii', 'ignore')
            if len(sort_key) == 0:
                sort_key = rtitle.lower()
        sort_key = RX_PUNCT.sub(u'', sort_key)
        sort_key = u''.join(sort_key.strip().split()).lower()
        logger.debug(u'sortkey for title "{0}": "{1}"'.format(rtitle, sort_key))
        pri['sort_key'] = sort_key

    for pri in sorted([pri for pri in primary if ' ' not in pri['domain'] and pri['title'] != u'' and pri['sort_key'] != u''], key=lambda k: k['sort_key']):
        _li = list_entry(_ul, pri)
    html_out(doc, os.path.join(path_dest, 'index-top.html'))
Пример #27
0
    def dash(self, **params):
        #get the current weather first...
        current = {}

        #then rest...
        dash_data = {}
        if "city" in params:
            if "country_code" in params:
                if "state" in params:
                    self.cityDash(
                        {
                            "city": params["city"],
                            "state": params["state"],
                            "country_code": params["country_code"]
                        }, dash_data)
                    c = self.parseCommandAndParams("/cityweather " +
                                                   params["city"] + "," +
                                                   params["state"] + "," +
                                                   params["country_code"])
                    #print("city parsed: {}".format(c))
                    self.prepareData(WeatherType.CITY, c["user_parameters"],
                                     current)
                else:
                    self.cityDash(
                        {
                            "city": params["city"],
                            "country_code": params["country_code"]
                        }, dash_data)
                    c = self.parseCommandAndParams("/cityweather " +
                                                   params["city"] + "," +
                                                   params["country_code"])
                    #print("city parsed: {}".format(c))
                    self.prepareData(WeatherType.CITY, c["user_parameters"],
                                     current)
            else:
                self.cityDash({"city": params["city"]}, dash_data)
                c = self.parseCommandAndParams("/cityweather " +
                                               params["city"])
                #print("city parsed: {}".format(c))
                self.prepareData(WeatherType.CITY, c["user_parameters"],
                                 current)
        else:
            return "Bad parameters - need a city name for a forecast dashboard at a minimum."

        #print(dash_data)
        #print(current)

        #set up the doc
        doc = dominate.document(title="Weather Dashboard")

        with doc.head:
            script(type='text/javascript',
                   src="https://cdn.plot.ly/plotly-latest.min.js")
            script(
                type='text/javascript',
                src=
                "https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"
            )
            script(type='text/javascript',
                   src="https://code.jquery.com/jquery-3.5.1.min.js")
            script(
                type='text/javascript',
                src=
                "https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js",
                integrity=
                "sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN",
                crossorigin="anonymous")
            script(
                type='text/javascript',
                src=
                "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js",
                integrity=
                "sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV",
                crossorigin="anonymous")
            script(
                type='text/javascript',
                src=
                "https://cdn.datatables.net/v/bs4/dt-1.10.22/datatables.min.js"
            )
            script(
                type='text/javascript',
                src="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js")
            link(
                rel='stylesheet',
                href=
                "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css",
                integrity=
                "sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z",
                crossorigin="anonymous")
            link(
                rel='stylesheet',
                href=
                "https://cdn.datatables.net/v/bs4/dt-1.10.22/datatables.min.css"
            )
            link(rel='stylesheet', href="/static/css/styles.css")
            link(
                rel='stylesheet',
                href="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css"
            )
            link(rel='stylesheet',
                 href="https://unpkg.com/[email protected]/dist/leaflet.css")
            script(type='text/javascript',
                   src="https://unpkg.com/[email protected]/dist/leaflet.js")

        #handle display under error conditions...
        if dash_data == None or dash_data == {}:
            with doc:
                wrap = div(id="content", cls="container-fluid")
                with wrap:
                    div(raw(
                        "Unable to create a dashboard from the parameters given!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>"
                    ),
                        cls=
                        "msg alert alert-danger alert-dismissible fade show",
                        role="alert")
                    div(
                        h1("Please take a closer look at your command and try again :("
                           ))

            return doc.render()

        dy = []
        dates = []
        mins = []
        maxes = []
        for i in range(0, len(dash_data["forecasts"])):
            dy.append(dash_data["forecasts"][i]["temp"])
            mins.append(dash_data["forecasts"][i]["min_temp"])
            maxes.append(dash_data["forecasts"][i]["max_temp"])
            dates.append(dash_data["forecasts"][i]["date_time"])

        miny = min(mins)
        maxy = max(maxes)

        fig = plotly.graph_objects.Figure(layout_title_text="Hourly Forecast")
        fig.add_trace(
            plotly.graph_objects.Scatter(x=dates,
                                         y=dy,
                                         fill='tozeroy',
                                         line=dict(color='#990000', width=4),
                                         mode='lines+markers+text',
                                         name='Temp',
                                         marker=dict(size=14)))
        #fig.add_trace(plotly.graph_objects.Scatter(x=dx, y=maxes, name='High', line=dict(color='firebrick', width=16)))
        #fig.add_trace(plotly.graph_objects.Scatter(x=dx, y=mins, name='Low', line=dict(color='royalblue', width=4)))

        #fig.update_layout(yaxis=dict(range=[miny, maxy]))
        fig.update_layout(xaxis_range=[dates[0], dates[7]],
                          yaxis_title="Temperature (degrees F)",
                          xaxis_title="Date and Time (24-hour clock format)",
                          template='plotly_dark',
                          paper_bgcolor='rgba(0,0,0,0)',
                          plot_bgcolor='rgba(0,0,0,0)')
        #fig.update_yaxes(nticks=5)
        #fig.update_xaxes(nticks=5)
        fig.update_xaxes(showgrid=False)
        fig.update_yaxes(showgrid=False)

        line_chart = plotly.io.to_html(fig,
                                       include_plotlyjs=False,
                                       full_html=False)

        share_url = hook_data["url"] + "/dash?" + urllib.parse.urlencode(
            params)
        #print(share_url)
        share_comment = "Forecast dashboard: " + dash_data["place"]
        #print(share_comment)
        with doc:
            wrap = div(id="content", cls="container-fluid")
            with wrap:
                div(raw(
                    "{} - Dashboard created successfully!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>"
                    .format(dash_data["place"])),
                    cls="msg alert alert-info alert-dismissible fade show",
                    role="alert")
                div(script(src="https://telegram.org/js/telegram-widget.js?11",
                           data_telegram_share_url=share_url,
                           data_comment=share_comment,
                           data_size="large"),
                    cls="row justify-content-center",
                    style="margin: 10px; width: 100%;")
                with div(cls="row justify-content-center"):
                    with div(cls="col-6"):
                        div(
                            p(dash_data["timestamp"].strftime(
                                "%I:%M%p %Z %b. %d"),
                              cls="current-date"), h1(dash_data["place"]),
                            h2(
                                raw("{}°F".format(current["temp"]) +
                                    "&nbsp;<img src=\"" +
                                    "https://openweathermap.org/img/wn/" +
                                    current["icon"] + "@2x.png\"" + ">")),
                            p("Feels like {}°F. ".format(current["feel"]) +
                              current["main"] + ". " + current["desc"]),
                            blockquote(
                                p("Air pressure - {}hPa".format(
                                    current["pressure"])),
                                p("Humidity - {}%".format(
                                    current["humidity"]))))
                    with div(cls="col-6"):
                        div(id="map")
                with div(cls="row justify-content-center"):
                    with div(cls="col-6"):
                        div(raw(line_chart), id="line-chart")
                    with div(cls="col-6"):
                        h2("5-Day Forecast")
                        dt = table(
                            id="forecast",
                            cls="table table-dark table-borderless table-hover"
                        )
                        with dt:
                            with tbody():
                                for i in range(0, len(dash_data["forecasts"])):
                                    date = dash_data["forecasts"][i][
                                        "date_time"].strftime("%a. %b %d, %Y")
                                    if i == 0 or i % 8 == 0:
                                        with tr():
                                            td(date)
                                            td("{}".format(
                                                dash_data["forecasts"][i]
                                                ["temp"]) + "°F")
                                            td(
                                                raw(dash_data["forecasts"][i]
                                                    ["main"] + "/" +
                                                    dash_data["forecasts"][i]
                                                    ["description"] +
                                                    "&nbsp;<img src=\"" +
                                                    "https://openweathermap.org/img/wn/"
                                                    + dash_data["forecasts"][i]
                                                    ["icon"] + ".png\"" + ">"))

            script().add(
                "$(document).ready(function() { $('#forecast').DataTable();} );"
            )
            script().add(
                "var mymap = L.map('map').setView([{},".format(
                    dash_data["latitude"]) +
                "{}".format(dash_data["longitude"]) + "], 13);" +
                "var marker = L.marker([{},".format(dash_data["latitude"]) +
                "{}".format(dash_data["longitude"]) + "]).addTo(mymap);")
            script().add(
                "var link = new DOMParser().parseFromString('Map data © <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>', 'text/html').documentElement.textContent;"
                +
                "L.tileLayer('https://api.mapbox.com/styles/v1/{{id}}/tiles/{{z}}/{{x}}/{{y}}?access_token={}'"
                .format(mapbox["key"]) + ", { maxZoom: 18, " +
                "attribution: link, " + "id: 'mapbox/streets-v11', " +
                "tileSize: 512, " + "zoomOffset: -1, " + "accessToken: '" +
                mapbox["key"] + "'" + "}).addTo(mymap);")
            script().add(
                "$('.msg').fadeTo(2000, 500).slideUp(500, function(){ $('.msg').slideUp(500);});"
            )

        return doc.render()
Пример #28
0
    def __init__(self, web_dir, title, refresh=0, grid_style=False, width=128):
        self.title = title
        self.web_dir = web_dir
        self.img_dir = os.path.join(self.web_dir, 'images')
        self.width = width
        if not os.path.exists(self.web_dir):
            os.makedirs(self.web_dir)
        if not os.path.exists(self.img_dir):
            os.makedirs(self.img_dir)
        # print(self.img_dir)

        self.doc = dominate.document(title=title)
        if refresh > 0:
            with self.doc.head:
                meta(http_equiv="refresh", content=str(refresh))

        if grid_style:
            with self.doc.head:
                style("""
* {
	box-sizing: border-box;
}

body {
	margin: 0;
	font-family: Arial, Helvetica, sans-serif;
}

p {
  word-wrap: break-word;
}

.header {
	text-align: center;
	padding: 32px;
}

.row {
	display: -ms-flexbox; /* IE 10 */
	display: flex;
	-ms-flex-wrap: wrap; /* IE 10 */
	flex-wrap: nowrap;
	padding: 0 4px;
}

/* Create two equal columns that sits next to each other */
.column {""" + ("""
    width: {}px;
""".format(width)) + """                
	/* -ms-flex: 50%; IE 10 */
	/* flex: 50%; */
	padding: 0 4px;
}

.column img {
	margin-top: 4px;
	vertical-align: middle;
}
""")
        with self.doc:
            self.row = div(cls="row")
Пример #29
0
def generate_html_document(trackers: List[Tracker], sequences: List[Sequence],
                           results, storage: Storage):
    def insert_figure(figure):
        buffer = io.StringIO()
        figure.save(buffer, "SVG")
        raw(buffer.getvalue())

    def insert_mplfigure(figure):
        buffer = io.StringIO()
        figure.savefig(buffer,
                       format="SVG",
                       bbox_inches='tight',
                       pad_inches=0.01,
                       dpi=200)
        raw(buffer.getvalue())

    def add_style(name, linked=False):
        if linked:
            link(rel='stylesheet',
                 href='file://' +
                 os.path.join(os.path.dirname(__file__), name))
        else:
            style(read_resource(name))

    def add_script(name, linked=False):
        if linked:
            script(type='text/javascript',
                   src='file://' +
                   os.path.join(os.path.dirname(__file__), name))
        else:
            with script(type='text/javascript'):
                raw("//<![CDATA[\n" + read_resource(name) + "\n//]]>")

    logger = logging.getLogger("vot")

    table_header, table_data, table_order = extract_measures_table(
        trackers, results)
    plots = extract_plots(trackers, results)

    legend = StyleManager.default().legend(Tracker)

    doc = dominate.document(title='VOT report')

    linked = check_debug()

    with doc.head:
        add_style("pure.css", linked)
        add_style("report.css", linked)
        add_script("jquery.js", linked)
        add_script("table.js", linked)
        add_script("report.js", linked)

    with doc:

        h1("VOT report")

        with ol(cls="metadata"):
            li('Toolkit version: ' + toolkit_version())
            li('Created: ' + datetime.datetime.now().isoformat())

        if len(table_header[2]) == 0:
            logger.debug("No measures found, skipping table")
        else:
            with table(
                    cls=
                    "overview-table pure-table pure-table-horizontal pure-table-striped"
            ):
                with thead():
                    with tr():
                        th()
                        [
                            th(c[0].identifier, colspan=c[1])
                            for c in merge_repeats(table_header[0])
                        ]
                    with tr():
                        th()
                        [
                            th(c[0].title, colspan=c[1])
                            for c in merge_repeats(table_header[1])
                        ]
                    with tr():
                        th("Trackers")
                        [
                            th(c.abbreviation,
                               data_sort="int" if order else "")
                            for c, order in zip(table_header[2], table_order)
                        ]
                with tbody():
                    for tracker, data in table_data.items():
                        with tr(data_tracker=tracker.reference):
                            with td():
                                insert_mplfigure(legend.figure(tracker))
                                span(tracker.label)
                            for value, order in zip(data, table_order):
                                insert_cell(
                                    value, order[tracker]
                                    if not order is None else None)

        for experiment, experiment_plots in plots.items():
            if len(experiment_plots) == 0:
                continue

            h2("Experiment {}".format(experiment.identifier), cls="experiment")

            with div(cls="plots"):

                for title, plot in experiment_plots:
                    with div(cls="plot"):
                        p(title)
                        insert_figure(plot)

    with storage.write("report.html") as filehandle:
        filehandle.write(doc.render())
Пример #30
0
    NameChange = TriggerIO("Change Name")
    IntWithMinMax = IntIO("Int with min max", units="int", min=15, max=225)
    FloatWithMinMax = FloatIO("Float with min max", units="float", min=-40, max=200)

test_group = TestGroup(namespace="Test")

def on_name_change(value):
    test_group.FirstName = "Steven"
    test_group.LastName = "Smith"

test_group.NameChange.write_callback=on_name_change

html_test_group =HMTLIOGroup(test_group)


doc = dominate.document(title='Test Page')
with doc.head:
    link(rel='stylesheet', href='https://www.w3schools.com/w3css/4/w3.css')
    link(rel='stylesheet', href="/static/easyio.css")
    link(rel='stylesheet', href='/static/keyboard.css')
    script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js')
    script(type='text/javascript', src='static/easyio.js')
    script(type='text/javascript', src='static/keyboard.js')
with doc.body:
    keyboard(doc)
    with div(cls="flex-container"):
        with div(cls="w3-card w3-margin w3-border w3-padding"):
            html_test_group.html_table(
                headers=["ITEM", "VALUE", "UNITS"],
                show_units=True)
    with table():
Пример #31
0
def generate_html():

    print("Py: Generating html")

    # Validate output directories
    if not (os.path.isdir(path_to_output)):
        quit("Py: Could not find output directory: " + path_to_output)

    if not os.path.isdir(path_to_movies):
        os.mkdir(path_to_movies)

    copy_assets()

    # Copy all mp4 files into the movies directory
    mp4_numbers = []
    mp4_pattern = re.compile('(\d+)\.mp4')
    for root, dirs, files in os.walk(path_to_sims):
        for f in files:
            mp4_match = mp4_pattern.match(f)
            if mp4_match:
                subprocess.call(['cp', os.path.join(root, f), os.path.join(path_to_movies, f), '-u'])
                mp4_numbers.append(int(mp4_match.group(1)))

    generate_movies_html(os.listdir(path_to_movies))

    # Read params and results into lists of lists
    with open(os.path.join(path_to_output, 'params_file.csv'), 'r') as params_file:
        combined_parameters = params_file.readlines()

    with open(os.path.join(path_to_output, 'combined_results.csv'), 'r') as combined_results_file:
        combined_results = combined_results_file.readlines()

    # Concatenate and format the headers
    header_row = combined_parameters[0].strip().split(',') + combined_results[0].strip().split(',')[1:]
    header_row = [header_row[x].replace('_', ' ').title() for x in range(len(header_row))]

    params_and_results = []
    for row_num in range(1, len(combined_parameters)):
        params_and_results.append(combined_parameters[row_num].strip().split(',') +
                                  combined_results[row_num].strip().split(',')[1:])

    # Determine which data columns are unchanging
    unchanging_cols = []
    for col_idx in range(len(params_and_results[0])):
        column = [row[col_idx] for row in params_and_results]
        first_value = column[0]
        if all(x == first_value for x in column):
            unchanging_cols.append(col_idx)

    # Create html document
    html_doc = dominate.document(title="Immersed Boundary Simulations")

    # Add html head containing css and js
    with html_doc.head:
        link(rel='stylesheet', href='css/theme.green.min.css')
        link(rel='stylesheet', href='css/default.css')
        script(src='js/jquery.min.js')
        script(src='js/jquery.tablesorter.min.js')
        script(src='js/sort_table.js')

    with html_doc:
        with div(_class='main').add(table(id='mp4_table', _class='tablesorter')):
            with thead():
                td('mp4 Name')
                for idx, cell in enumerate(header_row):
                    if idx in unchanging_cols:
                        td(cell, _class='cell_header cell_unchanging')
                    else:
                        td(cell, _class='cell_header')
            with tbody():
                for row in params_and_results:
                    idx = int(row[0])
                    with tr():
                        if idx in mp4_numbers:
                            mp4 = str(idx).zfill(2)
                            td(a(mp4 + '.mp4', href=os.path.join('html', mp4 + '.html'), target='_blank'))
                        else:
                            td('no mp4')
                        for idx, cell in enumerate(row):
                            if idx in unchanging_cols:
                                td(cell, _class='cell_right cell_unchanging')
                            elif idx == 0:
                                td(cell, _class='cell_centre')  # id column centred
                            else:
                                td(cell, _class='cell_right')   # other columns right-aligned

    with open(os.path.join(path_to_output, 'index.html'), 'w') as html_index:
        html_index.write(html_doc.render())
Пример #32
0
import dominate
from dominate.tags import *

from calendar_builder.date_utils import create_month_block
from calendar_builder.html_utils import create_html_month_block

if __name__ == "__main__":

    base_year = 1995

    doc = dominate.document(title=f'Year {base_year} +-1 calendar')

    with doc.head:
        link(rel='stylesheet', href='style.css')

    with doc:
        for year in [base_year - 1, base_year, base_year + 1]:
            h1(f'{year}', cls='year')
            with div(cls='grid') as year_div:
                for month in range(1, 13):
                    month_block = create_month_block(year, month)
                    html_month_block = create_html_month_block(
                        month, month_block)
                    year_div.add(html_month_block)

    output_file = "test.html"
    with open(output_file, "w") as f:
        f.write(str(doc))
Пример #33
0
 def __writeEventResultIndv(self):
     doc = dominate.document(title='Event Results')
     with doc.head:
         link(
             rel='stylesheet',
             href=
             'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css',
             integrity=
             'sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7',
             crossorigin='anonymous')
         link(
             rel='stylesheet',
             href=
             'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css'
         )
         meta(name='viewport',
              content='width=device-width, initial-scale=1.0')
     with doc:
         page = div(cls='container-fluid')
     with page:
         with div(cls='row').add(div(cls='col-xs-12')):
             h1('Results for {0}'.format(self.event.name))
             try:
                 eventdate = datetime.date(
                     *[int(x) for x in event.date.split('-')])
                 p('An orienteering event held at {0} on {1:%d %B %Y}'.
                   format(self.event.venue, eventdate))
             except:
                 pass
             p('Competition Classes:')
         with div(cls='row'):
             for ec in self.eventclasses:
                 self.eventclasses.sort(key=lambda x: x.shortname)
                 div((a(ec.name, href='#{0}'.format(ec.shortname))),
                     cls='col-md-3')
         for ec in self.eventclasses:
             with div(cls='row').add(div(cls='col-md-8')):
                 classresults = [
                     r for r in self.personresults if r.classid == ec.id
                 ]
                 h3(ec.name, id=ec.shortname)
                 t = table(cls='table table-striped table-condensed',
                           id='ResultsTable-{0}'.format(ec.shortname))
                 with t.add(tr(id='column-titles')):
                     if ec.scoremethod in [
                             'time', 'worldcup', '1000pts', 'score',
                             'score1000'
                     ]:
                         classresults = _sortByPosition(classresults)
                         th('Pos.')
                     th('Name')
                     if ec.scoremethod in ['alpha']:
                         classresults = _sortByName(classresults)
                     th('Club')
                     if ec.scoremethod in ['score', 'score1000']:
                         th('Points')
                         th('Penalty')
                         th('Total')
                     th('Time')
                     if ec.scoremethod in [
                             '1000pts', 'worldcup', 'score1000'
                     ]:
                         th('Score')
                 for pr in classresults:
                     with t.add(tr()):
                         if ec.scoremethod in [
                                 'time', 'worldcup', '1000pts', 'score',
                                 'score1000'
                         ]:
                             td(pr.position) if pr.position > 0 else td()
                         td(pr.name)
                         td(pr.club_shortname) if pr.club_shortname else td(
                         )
                         if ec.scoremethod in ['score', 'score1000']:
                             td(pr.ScoreO_points)
                             td(pr.ScoreO_penalty)
                             td(pr.ScoreO_net)
                         if pr.coursestatus in ['ok']:
                             td(pr.timetommmss())
                         elif pr.resultstatus in ['ok']:
                             td('{1} {0}'.format(pr.timetommmss(),
                                                 pr.coursestatus))
                         else:
                             td('{1} {2} {0}'.format(
                                 pr.timetommmss(), pr.coursestatus,
                                 pr.resultstatus))
                         if (ec.scoremethod
                                 in ['worldcup', '1000pts', 'score1000']):
                             td('{0:d}'.format(int(pr.score))
                                ) if pr.score is not None else td()
     return doc  # __writeEventResultIndv
Пример #34
0
    for pos in range(0, len(my_keys)):
        dictionary[my_keys[pos]] = ws.cell(row=row, column=pos + 1).value

    for key in dictionary:
        if key == 'Pos':
            dictionary[key] = teller
            teller += 1
        elif type(dictionary[key]) == float:
            dictionary[key] = "{:2.2f}".format(dictionary[key])
    workbook_list.append(dictionary)

# Round all the values to 2 decimals
print(workbook_list)

# Converting the list to html table
doc = dominate.document(title="Excel spread sheet")
# with doc.head:
#     link(rel="stylesheet", href="style.css")
with doc:
    with div().add(table(id="horses")):
        with thead():
            dictionary = workbook_list[0]
            for key in dictionary.keys():
                table_header = th()
                table_header.add(key)

        for dictionary in workbook_list:
            with tr():
                for key in dictionary:
                    table_data = td()
                    table_data.add(dictionary[key])
Пример #35
0
def index_keywords(keywords, primary, path_dest):
    logger = logging.getLogger(sys._getframe().f_code.co_name)
    doc = dominate.document(title=u'AWOL Index: Resources by Keywords')
    with doc.head:
        link(rel='stylesheet',
             type='text/css',
             href=
             'http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(rel='stylesheet',
             type='text/css',
             href=
             'http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css')
        link(
            rel='stylesheet',
            type='text/css',
            href=
            'http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700&amp;subset=latin,cyrillic-ext,greek-ext,greek,latin-ext,cyrillic'
        )
        link(rel='stylesheet', type='text/css', href='./index-style.css')
    doc += h1('Index of Resources by Keywords')
    _p = p('part of ', cls='subtitle')
    _p += a('The AWOL Index', href='../index.html')
    doc += _p
    for kw in sorted(keywords.keys(), key=lambda s: s.lower()):
        these = [
            pri for pri in keywords[kw] if ' ' not in pri['domain']
            and pri['title'] != u'' and pri in primary
        ]
        if len(these) > 0:
            for pri in these:
                try:
                    sort_key = pri['sort_key']
                except KeyError:
                    rtitle = pri['title']
                    sort_key = rtitle.lower()
                    if sort_key != unicode(sort_key.encode('ascii', 'ignore')):
                        classification = langid.classify(sort_key)
                        if classification[1] > 0.9:
                            if classification[0] in transliterate_languages:
                                sort_key = transliterate.translit(
                                    sort_key, classification[0], reversed=True)
                                sort_key = unicodedata.normalize(
                                    'NFKD', sort_key)
                        sort_key = codecs.encode(sort_key, 'translit/long')
                        sort_key = unidecode(sort_key)
                        sort_key = sort_key.encode('ascii', 'ignore')
                        if len(sort_key) == 0:
                            sort_key = rtitle.lower()
                    sort_key = RX_PUNCT.sub(u'', sort_key)
                    sort_key = u''.join(sort_key.strip().split()).lower()
                    logger.debug(u'sortkey for title "{0}": "{1}"'.format(
                        rtitle, sort_key))
                    pri['sort_key'] = sort_key

            _div = doc.add(div(id=kw.lower().replace(u' ', u'-')))
            _div += h2(kw)
            _ul = _div.add(ul())
            for pri in sorted(these, key=lambda k: k['sort_key']):
                _li = list_entry(_ul, pri)
        else:
            logger.warning(
                u"suppressed keyword with no top resources: {0}".format(kw))
    html_out(doc, os.path.join(path_dest, 'index-keywords.html'))
Пример #36
0
def visualization_html(header, data, metrics):
    challenges = data.keys()

    #    geometry_options = {
    #        "margin": "1.5in",
    #        "headheight": "20pt",
    #        "headsep": "10pt",
    #        "includeheadfoot": True
    #    }
    #    doc = Document(header, page_numbers=True, geometry_options=geometry_options)
    file_path = os.path.join(os.getcwd(), 'evaluation_results.html')
    if os.path.isfile(file_path):
        os.remove(file_path)
    doc1 = dominate.document(title='Tracking Evaluator')

    with doc1:
        with div():
            attr(cls='body')
            h1('Evaluation Results')
        with div():
            h2('Results table')
            tags.style(".calendar_table{width:880px;}")
            tags.style("body{font-family:Helvetica}")
            tags.style("h1{font-size:x-large}")
            tags.style("h2{font-size:large}")
            tags.style("table{border-collapse:collapse}")
            tags.style(
                "th{font-size:small;border:1px solid gray;padding:4px;background-color:#DDD}"
            )
            tags.style(
                "td{font-size:small;text-align:center;border:1px solid gray;padding:4px}"
            )

            with tags.table():
                with tags.thead():
                    tags.th("Challenge",
                            style="color:#ffffff;background-color:#6A75F2")
                    tags.th("Tracker",
                            style="color:#ffffff;background-color:#6A75F2")
                    for m in metrics:
                        tags.th(m,
                                style="color:#ffffff;background-color:#6A75F2")

                with tags.tbody():
                    for c in challenges:
                        with tags.tr():  #New row Challenges
                            tags.td(
                                c,
                                style=
                                "font-size:small;text-align:center;padding:4px"
                            )
                        for t in trackers:
                            if data[c][t]:
                                with tags.tr():  #New row Data per tracker
                                    tags.td(
                                        ' ',
                                        style=
                                        "font-size:small;text-align:center;padding:4px"
                                    )
                                    tags.td(
                                        t,
                                        style=
                                        "font-size:small;text-align:center;padding:4px"
                                    )
                                    if 'Accuracy' in metrics:
                                        tags.td(
                                            data[c][t]['tracker_acc'],
                                            style=
                                            "font-size:small;text-align:center;padding:4px"
                                        )
                                    if 'Robustness' in metrics:
                                        tags.td(
                                            data[c][t]['tracker_robust'],
                                            style=
                                            "font-size:small;text-align:center;padding:4px"
                                        )
                                    if 'Precision(Center Location Error)' in metrics:
                                        tags.td(
                                            data[c][t]['tracker_precision'],
                                            style=
                                            "font-size:small;text-align:center;padding:4px"
                                        )

        with div():
            h2('Graphs')
            for graph in plot_list:
                tags.img(src=graph, style='max-width:700px;margin-top: 50px;')
                tags.br()

        if frame_list:
            for c in challenges:
                if frame_list[c]:
                    for t in frame_list[c].keys():
                        with figure():
                            h3('Low Frames for tracker: %s' % t +
                               ' challenge: %s' % c)
                            for i in range(len(frame_list[c][t])):
                                tags.img(src=frame_list[c][t][i][0],
                                         style="width:340px;margin-top: 50px")
                                tags.i(frame_list[c][t][i][1])

    f = open(file_path, 'w')
    f.write(doc1.render())
    f.close()
Пример #37
0
def filtershtml():
	os.chdir(ROOT_DIR)
	doc = dominate.document(title='Metaforge')

	#Creates <head>
	with doc.head:
		link(rel='stylesheet', href="Template_Data/css/main.css")
		link(rel='icon', type="image/png", href="Template_Data/img/favicon.png")
		script(type='text/javascript', src="Template_Data/js/main.js")

	#Creates <body>
	with doc:
		with div(id='header'):
			img(src='Template_Data/img/title.png')
			img(id='logo',src='Template_Data/img/logo.png')
			h2("Home/Statistics")
			with div(id='metaforge-credits'):
				p("Created by Chris Morris and Collin Mockbee")
				p("https://github.com/chriswmorris/Metaforge")
			br()
		with div(id= 'wrapper'):
			with div(id='navbar').add(ul()):
				with div(id='nav-li'):
				
					img(src='Template_Data/img/home.png',width="35px", height="35px")
					a('Home/Stats' , cls='button', href='index.html' % ['index'])
					img(src='Template_Data/img/filter.png', width="35px", height="35px")
					a('Filtered Metadata',cls='button', href='filters.html' % ['filters'])
					img(src='Template_Data/img/star.png', width="35px", height="35px")
					a('All Metadata', cls='button',href='rawmeta.html' % ['rawmeta'])
					img(src='Template_Data/img/dealwithit.png', width="85px", height="25px")
					a('Hexadecimal View', cls='button', href='hexdump.html' % ['hexdump'])


			br()		
			with div(id='filtertitle'):

				p(b("This section contains a shortened view of all of the metadata from all files."))
				p("We went through the tags of each individual filetype and selected only noteworthy and important tags so you don't have to look through useless meta ;)")
				br()
			br()
			br()
			br()

			with span(id='filtered'):
				br()
				br()
				#loop through all exifoutputs


				os.chdir(ROOT_DIR +"/exifdata/filtered/")
				for file in os.listdir("."):
					filename = os.path.splitext(file)[0]
					file_read = open(file, 'r')
					with div(id='filtered-box'):
						h3(filename)
						p(file_read.readline())
						for line in file_read:
							p(file_read.readlines(1))
					br()
					br()
			os.chdir(ROOT_DIR)
						
	with open('filters.html', 'w') as filters:
		filters.write(doc.render())
Пример #38
0
def statshtml():
# This will display stats about the files
# Some stats to include will be...
# 1) Number of file types (graph too) 
# 2) Geolocations with map (maybe?)
# 3) Filtered vs. unfiltered meta
# 4) File Size Graph?
# 5) Software
# 6) Device/manufact. model
# 7) Top 5 largest files
# Then Generate the html report

	# ADD CUSTOM TAGS HERE:
	# The best way to look for tags is to run exiftool -j -G <filename> 
	# FORMAT: add "" and a comma to separate them. Example: "Composite:GPSPosition","EXIF:GPSAltitude"
	# 
	# Leave the PLACEHOLDER there




	customtags = ("PLACEHOLDER", "PLACEHOLDER")

	#################################################################################

	# FILETYPE CHART
	# Stats about the number of files in each supported filetype
	# Supported filetypes: dll, docx, exe, gif, html, jpeg, mkv, mp3, mp4, odp, odt ods, pdf, png, pptx, svg, torrent, wav, xlsx, zip
	jsonexifdir = (ROOT_DIR + "/exifdata/json/")
	statsdir = (ROOT_DIR + "/exifdata/stats/")
	jsondirs = ("dll", "docx", "exe", "gif", "html", "jpeg", "mkv", "mp3", "mp4", "odp","odt", "ods", "pdf",
	 "png", "pptx", "svg", "torrent", "wav", "xlsx", "zip")


	try: 
		filetypestxt= open(statsdir + "filetypes.txt","w+")
		os.chdir(jsonexifdir)
		for dirs in jsondirs:
			filetypestxt.write(dirs + ": " )
			os.chdir(jsonexifdir + dirs)
			listfiles = os.listdir(".")
			numberoffiles = str(len(listfiles))
			filetypestxt.write(numberoffiles + "\n")

		os.chdir(jsonexifdir)
		unkfiles = [f for f in listdir(".") if isfile(join(".", f))]
		filetypestxt.write("Unknown Files: " + str(len(unkfiles)) + "\n")
		os.chdir(ROOT_DIR + "/exifdata/html/")
		filetypestxt.write("Total Files: ")
		listtotal = os.listdir(".")
		numberoftotalfiles = str(len(listtotal))
		filetypestxt.write(numberoftotalfiles + "\n")
		filetypestxt.close()

	except:
		print("Error: Filetype chart generation failed: ", sys.exc_info() )

	#FILE SIZE CHART
	#Stats about the top 10 largest files
	mediadir = (ROOT_DIR + "/media")
	
	try:
		os.chdir(mediadir)
		subprocess.run("du -k * | sort -nr > filesizes.txt", shell=True, check=True)
		shutil.move(mediadir +"/" + "filesizes.txt", statsdir)

	except:
		print("Error: Filesize chart generation failed: ", sys.exc_info() )


	#GEOLOCATION CHARTS
	#Filters through media to find only files with geolocation data
	jsonalldir = (ROOT_DIR + "/exifdata/json/all/")
	geolocationsdir = (ROOT_DIR + "/exifdata/stats/geolocations/")
	geotags=("Composite:GPSPosition","EXIF:GPSAltitude", "EXIF:GPSLongitude", "EXIF:GPSLatitude")


	try: 
		os.chdir(jsonalldir)
		for gfile in os.listdir("."):
			with open(gfile) as ogfile:
				baseg = os.path.basename(gfile)
				with open(os.path.splitext(baseg)[0]+".txt", "w") as geolocationfile:	
					for ogline in ogfile:
						for tag in geotags:
							if tag in ogline:
								geolocationfile.write(ogline+ "\n")

		os.chdir(jsonalldir)						
		for geofile in os.listdir("."):
			if ".txt" in geofile:
				shutil.move(jsonalldir + geofile, geolocationsdir)

		os.chdir(geolocationsdir)		
		for geofile in os.listdir("."):
			if os.path.exists(geofile) and os.path.getsize(geofile) == 0:
				os.remove(geofile)

	except:
		print("Error: Geolocation chart generation failed: ", sys.exc_info() )



	# AUTHOR,ORG,COMPANY AND CREATORS CHART
	# Filters through media to find only files with above info 

	authortags=("XMP:Creator", "XML:Company","FlashPix:Author","FlashPix:Company","HTML:Author","XMP-dc:Creator","PDF:Creator",
		"PDF:Producer", "PDF:Author","EXE:LegalCopyright","EXE:CompanyName","Torrent:Creator", "FlashPix:Tag_AuthorEmail", "FlashPix:Tag_AuthorEmailDisplayName")

	authordir=(ROOT_DIR + "/exifdata/stats/authors/")

	try:
		os.chdir(jsonalldir)
		for authorfile in os.listdir("."):
			with open(authorfile) as oauthorfile:
				baseauthor = os.path.basename(authorfile)
				with open(os.path.splitext(baseauthor)[0]+".txt", "w") as authoretcfile:
					for authorline in oauthorfile:
						for authortag in authortags:
							if authortag in authorline:
								authoretcfile.write(authorline+ "\n")

		os.chdir(jsonalldir)
		for authorfile in os.listdir("."):
			if ".txt" in authorfile:
				shutil.move(jsonalldir + authorfile, authordir)

		os.chdir(authordir)
		for authorfile in os.listdir("."):
			if os.path.exists(authorfile) and os.path.getsize(authorfile) == 0:
				os.remove(authorfile)


	except:
		print("Error: Author/Creator/etc chart generation failed: ", sys.exc_info() )



	#SOFTWARE CHARTS
	#Filters through media to find only files with Software data		

	softwaredir = (ROOT_DIR + "/exifdata/stats/software/")
	softwaretags = ("EXIF:Software","PNG:Software","FlashPix:Software","XML:Application", "FlashPix:Software", "PDF:Producer",  "RIFF:Software")

	try:
		os.chdir(jsonalldir)
		for sfile in os.listdir("."):
			with open(sfile) as osfile:
				bases = os.path.basename(sfile)
				with open(os.path.splitext(bases)[0]+".txt", "w") as softwarefile:	
					for osline in osfile:
						for sotag in softwaretags:
							if sotag in osline:
								softwarefile.write(osline + "\n")

		os.chdir(jsonalldir)						
		for softfile in os.listdir("."):
			if ".txt" in softfile:
				shutil.move(jsonalldir + softfile, softwaredir)

		os.chdir(softwaredir)		
		for softfile in os.listdir("."):
			if os.path.exists(softfile) and os.path.getsize(softfile) == 0:
				os.remove(softfile)

	except:
		print("Error: Software chart generation failed: ", sys.exc_info() )

	#DEVICE/MODELS CHARTS
	#Filters through media to find only files with Device and Model data		

	devicedir = (ROOT_DIR + "/exifdata/stats/devices/")
	devicetags = ("ICC-header:DeviceAttributes", "ICC_Profile:DeviceModel", "ICC_Profile:DeviceMfgDesc", "ICC_Profile:DeviceModelDesc", 
		"ExifIFD:LensModel", "EXIF:Model", "ICC_Profile:MakeAndModel")

	try:
		os.chdir(jsonalldir)
		for devfile in os.listdir("."):
			with open(devfile) as odevfile:
				based = os.path.basename(devfile)
				with open(os.path.splitext(based)[0]+".txt", "w") as devicefile:	
					for odevline in odevfile:
						for devtag in devicetags:
							if devtag in odevline:
								devicefile.write(odevline + "\n")

		os.chdir(jsonalldir)						
		for devfile in os.listdir("."):
			if ".txt" in devfile:
				shutil.move(jsonalldir + devfile, devicedir)

		os.chdir(devicedir)		
		for devfile in os.listdir("."):
			if os.path.exists(devfile) and os.path.getsize(devfile) == 0:
				os.remove(devfile)

	except:
		print("Error: Device/Model chart generation failed: ", sys.exc_info() )

	# CUSTOM CHART
	# CUSTOM TAGS WILL BE HERE
	customdir = (ROOT_DIR + "/exifdata/stats/custom/")

	try:
		os.chdir(jsonalldir)
		for customfile in os.listdir("."):
			with open(customfile) as ocustomfile:
				basecustom = os.path.basename(customfile)
				with open(os.path.splitext(basecustom)[0]+".txt", "w") as thecustomfile:	
					for customline in ocustomfile:
						for customtag in customtags:
							if customtag in customline:
								thecustomfile.write(customline + "\n")

		os.chdir(jsonalldir)						
		for customfile in os.listdir("."):
			if ".txt" in customfile:
				shutil.move(jsonalldir + customfile, customdir)

		os.chdir(customdir)		
		for customfile in os.listdir("."):
			if os.path.exists(customfile) and os.path.getsize(customfile) == 0:
				os.remove(customfile)

	except:
		print("Error: Custom chart generation failed: ", sys.exc_info() )


	# FILTERED DATA VS RAW EXIF
	# Count the number of lines in all filtered and all raw
	# Use jsonalldir for raw metadata

	try:

		filterdir = (ROOT_DIR + "/exifdata/filtered/")
		os.chdir(jsonalldir)
		subprocess.run("cat * > all_lines.txt", shell=True, check=True)
		shutil.move(jsonalldir + "all_lines.txt", statsdir)
		os.chdir(filterdir)
		subprocess.run("cat * > all_filter.txt", shell=True, check=True)
		shutil.move(filterdir + 'all_filter.txt', statsdir)
		allnum_lines = 0
		allfilter_lines = 0
		linestatstxt= open(statsdir + "linestats.txt","w+")
		os.chdir(statsdir)
		with open("all_lines.txt", "r") as alllinestxt:
			for al_line in alllinestxt:
				allnum_lines += 1
		linestatstxt.write("Number of lines before filtering metadata: " + str(allnum_lines) + "\n")
		with open("all_filter.txt", "r") as allfiltertxt:
			for fi_line in allfiltertxt:
				allfilter_lines +=1
		linestatstxt.write("Number of lines after filtering metadata: " + str(allfilter_lines))
		linestatstxt.close()
		os.remove(statsdir + 'all_filter.txt')
		os.remove(statsdir + 'all_lines.txt')

	except:
		print("Error: Filtered vs Raw chart generation failed: ", sys.exc_info() )



	# START STAT HTML REPORT GEN----------------------------------------------------------------
	# HTML REPORT GENERATION
	# THIS MAKES THE INDEX/STATS PAGE
	os.chdir(ROOT_DIR)
	doc = dominate.document(title='Metaforge')

	#Creates <head>
	with doc.head:
		link(rel='stylesheet', href="Template_Data/css/main.css")
		link(rel='icon', type="image/png", href="Template_Data/img/favicon.png")
		script(type='text/javascript', src="Template_Data/js/main.js")

		
	#Creates <body>
	with doc:
		with div(id='header'):
			img(src='Template_Data/img/title.png')
			img(id='logo',src='Template_Data/img/logo.png')
			h2("Home/Statistics")
			with div(id='metaforge-credits'):
				p("Created by Chris Morris and Collin Mockbee")
				p("https://github.com/chriswmorris/Metaforge")
			br()
		with div(id= 'wrapper'):
			with div(id='navbar').add(ul()):
				with div(id='nav-li'):
					
					img(src='Template_Data/img/home.png',width="35px", height="35px")
					a('Home/Stats' , cls='button', href='index.html' % ['index'])
					img(src='Template_Data/img/filter.png', width="35px", height="35px")
					a('Filtered Metadata',cls='button', href='filters.html' % ['filters'])
					img(src='Template_Data/img/star.png', width="35px", height="35px")
					a('All Metadata', cls='button',href='rawmeta.html' % ['rawmeta'])
					img(src='Template_Data/img/dealwithit.png', width="85px", height="25px")
					a('Hexadecimal View', cls='button', href='hexdump.html' % ['hexdump'])

			with div(id='toprow'):
				with div(id='filetypechart'):
					h4("Number of Files in each Filetype")	
					with div(id='filetypechart-box'):
						filetype_stat = open(ROOT_DIR + "/exifdata/stats/filetypes.txt")
						filetyperead = filetype_stat.readlines()
						for fline in filetyperead:
							p(fline)
							br()
							br()

				with div(id='sizechart'):
					h4("Top 5 Largest Files")
					h5("File Size in Kilobytes")
					with div(id='size-box'):
						sizechart_stat = open(ROOT_DIR + "/exifdata/stats/filesizes.txt")
						asizechartread = sizechart_stat.readline()
						bsizechartread = sizechart_stat.readline()
						csizechartread = sizechart_stat.readline()
						dsizechartread = sizechart_stat.readline()
						esizechartread = sizechart_stat.readline()
						p(asizechartread)
						p(bsizechartread)
						p(csizechartread)
						p(dsizechartread)
						p(esizechartread)
						br()

				with div(id='comparechart'):
					h4("Raw Metadata vs Filtered Metadata")
					h5("Actual lines of metadata vs. Amount of filtered metadata")	
					with div(id='comparechart-box'):
						linestats_stat = open(ROOT_DIR + "/exifdata/stats/linestats.txt")
						linestatsread = linestats_stat.readlines()
						for lsline in linestatsread:
							p(lsline)
						br()
						br()

			br()			
			hr()		
			with div(id='secondrow'):
				with div(id='customchart'):
					h4("Custom Tags")
					with div(id='custom-box'):
						os.chdir(customdir)
						for customfile in os.listdir("."):
							customfilename = os.path.splitext(customfile)[0]
							custom_read = open(customfile, 'r')
							h4(customfilename)
							p(custom_read.readline())
							for custom_line in custom_read:
								p(custom_read.readlines(8))
							br()

					os.chdir(ROOT_DIR)
				with div(id='geolocationschart'):
					h4("Geolocations")
					with div(id='geolocation-box'):
						os.chdir(geolocationsdir)
						for geolocationfile in os.listdir("."):
							geofilename = os.path.splitext(geolocationfile)[0]
							gfile_read = open(geolocationfile, 'r')
							h4(geofilename)
							p(gfile_read.readline())
							for g_line in gfile_read:
								p(gfile_read.readlines(1))
							br()
					os.chdir(ROOT_DIR)	

				

				

			with div(id='thirdrow'):
				with div(id='devicechart'):
					h4("Devices/Models")
					with div(id='device-box'):
						os.chdir(devicedir)
						for softwfile in os.listdir("."):
							softfilename = os.path.splitext(softwfile)[0]
							sfile_read = open(softwfile, 'r')
							h4(softfilename)
							p(sfile_read.readline())
							for soft_line in sfile_read:
								p(sfile_read.readlines(8))
							br()
					os.chdir(ROOT_DIR)

				with div(id='authorchart'):
					h4("Authors/Companies/etc")
					with div (id='author-box'):
						os.chdir(authordir)
						for authorfile in os.listdir("."):
							authorfilename = os.path.splitext(authorfile)[0]
							author_read = open(authorfile, 'r')
							h4(authorfilename)
							p(author_read.readline())
							for auth_line in author_read:
								p(author_read.readlines(1))
							br()

				with div(id='softwarechart'):
					h4("Software")
					with div(id='software-box'):
						os.chdir(softwaredir)
						for softwfile in os.listdir("."):
							softfilename = os.path.splitext(softwfile)[0]
							sfile_read = open(softwfile, 'r')
							h4(softfilename)
							p(sfile_read.readline())
							for soft_line in sfile_read:
								p(sfile_read.readlines(8))
							br()
					os.chdir(ROOT_DIR)

				



	with open('index.html', 'w') as index:
		index.write(doc.render()) 
Пример #39
0
def generate_html(img_urls):
    doc = dominate.document(title='Image Thumbnails')

    with doc.head:
        style("""
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            display: flex;
            flex-wrap: wrap;
        }
        .box:after{
            content: '';
            flex-grow: 99999;
    	}
    	.imgBox{
                flex-grow: 1;
                margin: 5px;
    	}
    	.imgBox img{
    	    width: auto;
    	    height: 200px;
    	    object-fit: cover; 
    	}
        figure {
            width: -webkit-min-content;
            width: -moz-min-content;
            width: min-content;
        }
        figure.item {
            vertical-align: top;
            display: inline-block;
            text-align: center;
        }
    	.caption {
            display: block;
        }
        .zoom {
          padding: 5px;
          transition: transform .2s;
          margin: 0 auto;
        }
        .zoom:hover {
          -ms-transform: scale(1.05); /* IE 9 */
          -webkit-transform: scale(1.05); /* Safari 3-8 */
          transform: scale(1.05); 
        }
         """)

    with doc:
        with div(cls="box", id="box"):
            with div(cls="imgBox"):
                for url in img_urls:
                    with a(href=url):
                        with figure(cls="item"):
                            with div(cls="zoom"):
                                img(src=url)
                                # replace the description here
                                figcaption(
                                    "A very very very very very very long description",
                                    cls="caption")

    return doc
Пример #40
0
def generate_table(agents, items, data, file_name, data_json):
    with document(title='Algorithm Results') as doc:
        head_page = head()
        head_page += link(rel='shortcut icon', href="../images/web-logo.png")
        head_page += link(rel="stylesheet", type="text/css", href="../css/Home.css")
        head_page += link(href="https://fonts.googleapis.com/css2?family=Special+Elite&display=swap", rel="stylesheet")
        head_page += link(href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap",
                          rel="stylesheet")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css",
             integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm",
             crossorigin="anonymous")
        link(rel="stylesheet", type="text/css", href="../css/styles.css")
        content_div = div(cls='topnav')
        content_div += a('Home', cls='active', href='../Home.html')
        content_div += a('About Us', cls='active', href='../About_Us.html')
        content_div += a('Contact us', cls='active', href='../Contact_Us.html')

        h1('Results', cls='header')

        result_table = table(cls='content-table')
        link(rel='stylesheet', href='../css/table.css')
        header_thread = thead()
        header_tr = tr()
        header_tr += th('Items')
        for agent in agents:
            header_tr += th(agent)
        header_thread += header_tr

        item_index = 0

        thread_body = tbody()
        for item in items:
            item_tr = tr()
            item_tr += th(item)
            for score in [z[item_index] for z in data[0:]]:
                item_tr += td('{} %'.format(score))
            item_index += 1
            thread_body += item_tr

        result_table += header_thread
        result_table += thread_body

        if data_json['problem'] == 'EnvyFree':
            explanations = build_envy_free_output(data, data_json)
        elif data_json['problem'] == 'Proportional':
            explanations = build_proportional_output(data, data_json)

        h1('Results Explanation', cls='header')

        result_explanation_table = table(cls='content-table')
        thread_body = tbody()
        for index, explanation in enumerate(explanations):
            item_tr = tr()
            item_tr += th(agents[index])
            item_tr += td(explanation)
            thread_body += item_tr
        result_explanation_table += thread_body

    with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'w') as f:
        f.write(doc.render())

    with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'r') as f:
        file_data = f.read()

    # Replace the target string
    file_data = file_data.replace('&lt;br&gt;', '<br>')

    # Write the file out again
    with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'w') as f:
        f.write(file_data)

    print('generated url is {}'.format(file_name))
    return '{}/generated_html/{}.html'.format(URL, file_name)
Пример #41
0
def generate_tables_html(tables):
    doc = dominate.document(title="ABED Scalar Tables")

    with doc.head:
        # meta tags
        tags.meta(charset="utf-8")
        tags.meta(http_equiv="X-UA-Compatible", content="IE=edge")
        tags.meta(name="viewport",
                  content="width=device-width, initial-scale=1")
        tags.meta(name="description", content="")
        tags.meta(name="author", content="")
        # tags.link(rel='icon', href=copy_data_file('ABED/images/favicon.ico'))

        # JQuery & Bootstrap JS
        tags.script(src=copy_data_file("jquery/1.11.3/jquery.min.js"))
        tags.script(
            src=copy_data_file("bootstrap-3.3.5-dist/js/bootstrap.min.js"))
        # Bootstrap core CSS
        tags.link(
            rel="stylesheet",
            href=copy_data_file("bootstrap-3.3.5-dist/css/bootstrap.min.css"),
        )

        # Datatables CSS & JS
        tags.link(
            rel="stylesheet",
            href=copy_data_file(
                "DataTables-1.10.7/media/css/jquery.dataTables.css"),
        )
        tags.script(
            type="text/javascript",
            src=copy_data_file(
                "DataTables-1.10.7/media/js/jquery.dataTables.js"),
        )

        # ABED CSS & JS
        tags.link(rel="stylesheet", href=copy_data_file("abed/css/abed.css"))
        tags.script(
            type="text/javascript",
            src=copy_data_file("abed/js/abed_showtables.js"),
        )
        tags.script(
            type="text/javascript",
            src=copy_data_file("abed/js/abed_scalartables.js"),
        )

    with doc:
        navbar(active=AbedHTMLTypes.SCALAR_TABLES)
        with tags.div(_class="container"):
            with tags.table(
                    id="AbedButtons",
                    _class="display",
                    cellspacing="0",
                    width="100%",
            ):
                with tags.thead():
                    tr = tags.tr()
                    tr += tags.th("Target")
                    tr += tags.th("Output Type")
                with tags.tbody():
                    tr = tags.tr()
                    tr += tags.td(
                        bootstrap_radio_group(
                            generate_buttons(tables, "target")))
                    tr += tags.td(
                        bootstrap_radio_group(generate_buttons(tables,
                                                               "type")))
            for table in tables:
                tabid = get_table_id(table)
                with tags.div(id="div_" + tabid, _class="AbedTable"):
                    if "summary" in tabid:
                        tags.p("Summary Table:")
                    with tags.table(
                            id="tbl_" + tabid,
                            _class="display",
                            cellspacing="0",
                            width="100%",
                    ):
                        with tags.thead():
                            tr = tags.tr()
                            for hdr in table.headers:
                                tr += tags.th(hdr)
                        if not "summary" in tabid:
                            with tags.tfoot():
                                tr = tags.tr()
                                for hdr in table.headers:
                                    tr += tags.th(hdr)
        tags.comment("/.container")
    return str(doc)
Пример #42
0
# <codecell>

#for numz in apsize:
#    print numz[0]
#    if numz[0] > 800:
#        print ('greater than 800')
#    else:
#        print ('less than 800!')

# <codecell>


# <codecell>

doc = dominate.document(title='GetsDrawn')

with doc.head:
    link(rel='stylesheet', href='style.css')
    script(type='text/javascript', src='script.js')
    
    with div():
        attr(cls='header')
        h1('GetsDrawn')
        p(img('imgs/getsdrawn-bw.png', src='imgs/getsdrawn-bw.png'))
        h1('Updated ', strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))
        p(panz)
        p(bodycom)
    
    
Пример #43
0
def dominate_register_page():
    """
    第二頁:註冊頁面,對應到  @app.route('/jump')  及其函數   registerpage_run
    目標:利用dominate寫出registerpage的html並在templates資料夾中存成index2.html

    分為三個區塊
    doc = dominate.document()
    with doc.head   (包含css的style;meta確保中文可以運行在utf-8下)
    with doc.body   (包含 a form with 7 legends: name/ password/ student_id/
                    telephone_number/ school_bike_license/ bike_lock_number/ picture uploading and a button submit)

    最後寫入文件中(在templates資料夾中存成index2.html)
    """
    doc = dominate.document(title="registerpage")

    with doc.head:
        tags.meta(name='charset', content="utf-8")
        tags.style("""\
            body {
                background-color: #F9F8F1;
                color: #2C232A;
                font-family: sans-serif;
                font-size: 14;
                text-align: center;
            }
            
             section{
                width: 800px;
                height: 800px;
                position: absolute;
                top: 15%;
                left: 15%;
                overflow: auto;
                text-align: center;
            }

            label{
                cursor: pointer;
                display: inline-block;
                padding: 3px 6px;
                text-align: center;
                width: 500px;
                vertical-align: top;
            }

            input{
                font-size: inherit;
            }

        """)

    with doc.body:
        with tags.div(clas='headline', style='font-size: 20;'):
            tags.h1('Register Page')
        with tags.section():
            with tags.form(method='POST', action="/jump", enctype="multipart/form-data"):
                with tags.legend():
                    tags.label('請輸入姓名(中文)')
                    tags.input(type='text', name='name', size=20)
                with tags.legend():
                    tags.label('請輸入密碼')
                    tags.input(type='text', name='password', size=20)
                with tags.legend():
                    tags.label('請輸入學號(1個大寫英文字母+8個數字)')
                    tags.input(type='text', name='student_id', size=20)
                with tags.legend():
                    tags.label('請輸入電話(請輸入10位數字)')
                    tags.input(type='text', name='telephone_number', size=20)
                with tags.legend():
                    tags.label('是否有台大車證(Y/N)')
                    tags.input(type='text', name='school_bike_license', size=20)
                with tags.legend():
                    tags.label('腳踏車的密碼(選填、請輸入數字)')
                    tags.input(type='text', name='bike_lock_number', size=20)
                with tags.legend():
                    tags.label('上傳圖片')
                    tags.input(type='file', name='photo', size=20)
                with tags.div(cls='button', style="margin:0 auto; width:250px;"):
                    tags.input(type='submit', value='click me', style="width:120px; background-color:pink;")

    fn = 'templates/index2.html'
    with open(file=fn, mode='w', encoding='utf-8') as f:
        f.write(doc.render())
Пример #44
0
    def dominate_document(self, title="pywrapBokeh", bokeh_version='1.0.0rc3'):
        """ Create dominate document, see https://github.com/Knio/dominate

        Populates the required bokeh/jquery links
        Sets up common javascript

        The dominate document is returned, but if you don't need to use it, just ignore it

        :param title: title string
        :param bokeh_version: version
        :return: dominate document
        """
        d = dominate.document(title=title)
        with d.head:
            link(href="https://cdn.pydata.org/bokeh/dev/bokeh-{bokeh_version}.min.css".format(bokeh_version=bokeh_version),
                 rel="stylesheet",
                 type="text/css")
            script(src="https://cdn.pydata.org/bokeh/dev/bokeh-{bokeh_version}.min.js".format(bokeh_version=bokeh_version))
            link(href="https://cdn.pydata.org/bokeh/dev/bokeh-widgets-{bokeh_version}.min.css".format(bokeh_version=bokeh_version),
                 rel="stylesheet",
                 type="text/css")
            script(src="https://cdn.pydata.org/bokeh/dev/bokeh-widgets-{bokeh_version}.min.js".format(bokeh_version=bokeh_version))
            link(href="https://cdn.pydata.org/bokeh/dev/bokeh-tables-{bokeh_version}.min.css".format(bokeh_version=bokeh_version),
                 rel="stylesheet",
                 type="text/css")
            script(src="https://cdn.pydata.org/bokeh/dev/bokeh-tables-{bokeh_version}.min.js".format(bokeh_version=bokeh_version))

            script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js")

            meta(charset="UTF-8")

        with d.body:
            js = """
            function postAndRedirect(url, postData, callerWidget) {
                var postFormStr = "<form id='virtualForm' method='POST' action='" + url + "'>";
            
                for (var key in postData) {
                    if (postData.hasOwnProperty(key)) {
                        postFormStr += "<input type='hidden' name='" + encodeURIComponent(key) + "' value='" + unescape(encodeURIComponent(postData[key])) + "'></input>";
                    }
                }
                // add the widget that triggers the post
                postFormStr += "<input type='hidden' name='callerWidget' value='" + callerWidget + "'></input>";
                postFormStr += "<input type='hidden' name='windowWidth' value='" + window.innerWidth + "'></input>";
                postFormStr += "<input type='hidden' name='windowHeight' value='" + window.innerHeight + "'></input>";
                postFormStr += "<input type='hidden' name='windowUrl' value='" +url + "'></input>";
             
                postFormStr += "</form>";
                //alert(postFormStr);
                //alert(postAndRedirect.caller);  // probably not useful
                
                var formElement = $(postFormStr);
            
                $('body').append(formElement);
                $('#virtualForm').submit();
            }      
            
            function postAndRedirectWrapper() {
                // dummy prevents thinking that landing on URL for first time, resize 
                // is caused by user after landing on the page
                postAndRedirect(window.location.href, {'dummy': 0}, 'windowResize' )
            }
            
            window.addEventListener("resize", postAndRedirectWrapper);
               
            """
            script(raw(js))

        self.logger.info("created dominate document")
        self.logger.debug(d)
        self.dom_doc = d
        return d
Пример #45
0
for key, item in allItems.iteritems():
    zot.add_parameters(limit='None', content='bib')
    bib[key] = dict()
    # this adds the formatted citation
    bib[key]['item'] = zot.item(key)
    #pp.pprint(bib[key]['item'])
    if key in allNotes:
        # this attaches the note to the item.
        bib[key]['note'] = allNotes[key]['note']

# ----- fancy HTML part -----
import dominate
from dominate.tags import *
from dominate.util import raw

doc = dominate.document(title='Annotated Bibliography')

# make an HTML document!
with doc.head:
    link(rel='stylesheet', href='styles.css')

# in the HTML document
with doc:
    # for each entry that we created above:
    for key, entry in bib.iteritems():
        # we're going to make a div to hold the whole thing
        with div(cls='one-entry'):
            # i've been having some serious encoding problems.
            temp = entry['item'][0]
            # and then print the raw html returned from Zotero
            raw(temp)
Пример #46
0
    sys.stderr.write("\nerror of xml parser skipped\n%d items were already collected\n" % len(res_list))
  
#print(len(res_list))

res_dict = defaultdict(list)
for el in res_list:
    res_dict[el[1]].append(el)
    
gene_level_res = []
header = "Query", "Hit", "Link", "q_start", "q_end", "h_start", "h_end", "Identity [%]", "Score"
for hit, local_list in res_dict.items():
    name_ = hit.split("|")[-1]
    gene_level_res.append(( hit, len(local_list), sum([x[-1] for x in local_list]) ))
    local_list.sort(key = lambda x: x[-1], reverse = True)
    with open(os.path.join(LOCAL_GENES_PATH, '%s.html' % name_), 'w') as f:
        doc = dominate.document(title="%s: similarity blast ppredictions" % os.path.basename(args.outdir))
        with doc.head:
            style(_style)
        with doc:
            with table(id = "myTable") as _table:
                _tr = tr()
                _tr.add([td(x) for x in header])
                for query, hit, fname, q_start, q_end, h_start, h_end, identity, score in local_list:
                    _ , uniprot, name = hit.split("|")
                    with tr():
                        td(query)
                        td(raw('<a href=%s target="_blank">%s</a>' % (add_uniprot_ref(uniprot), name) ))
                        td(raw('<a href=%s target="_blank">link</a>' % os.path.join('../local', fname) ))
                        td(q_start)
                        td(q_end)
                        td(h_start)
Пример #47
0
        )

    writer.build_file(path, page)


for f in os.listdir("ru"):
    target = os.path.splitext(f)[0] + ".html"
    page_generate("ru/" + target, "ZenCad", os.path.join("ru", f), "ru/nav.md")

for f in os.listdir("en"):
    target = os.path.splitext(f)[0] + ".html"
    page_generate(
        "en/" + target, "ZenCad", os.path.join("en", f), "en/nav.md", comming=True
    )

redirect_page = dominate.document()
with redirect_page:
    dominate.tags.meta(charset=u"utf-8")
redirect_page.add(
    dominate.util.raw(
        """<meta http-equiv="refresh" content="0; url=ru/index.html" />"""
    )
)
with redirect_page:
    dominate.tags.p("Если ваш браузер не поддерживает redirect, перейдите по ссылке:")
    with dominate.tags.p():
        dominate.tags.a("ZenCad/ru", href="ru/index.html")
    with dominate.tags.p():
        dominate.tags.a("ZenCad/en", href="en/index.html")
writer.build_file("index.html", redirect_page)
Пример #48
0
import dominate
from dominate.tags import *

doc = dominate.document(title='Hello wujimaster')

with doc.head:
    link(
        rel='stylesheet',
        href='../../hello_boostrap/bootstrap-4.5.0-dist/css/bootstrap.min.css')
    script(rel='text/javascript',
           src='../../hello_boostrap/bootstrap-4.5.0-dist/js/bootstrap.min.js')
    script(rel='text/javascript',
           src='../../hello_boostrap/jquery-3.4.1/jquery-3.4.1.min.js')

with doc.body:
    h1('Hello world, wuji!')
    container = div(cls='container')
    jumbtron = div(cls='jumbotron')
    container.add(jumbtron)
    jumbtron.add(h1('you are at container'))
    jumbtron.add(p('check the demo'))
    row = div(cls='row')
    container.add(row)
for i in range(3):
    with row.add(div(cls='col-sm-4')):
        h1('Column %d' % i)

print(doc)
Пример #49
0
def main(args):
    """
    main functions
    """
    logger = logging.getLogger(sys._getframe().f_code.co_name)

    path_source = os.path.realpath(args.json[0])
    path_dest = os.path.abspath(args.html[0])
    print('path_dest: {0}'.format(path_dest))
    r = requests.get(
        'https://raw.githubusercontent.com/mattcg/language-subtag-registry/master/data/json/registry.json'
    )
    if r.status_code == 200:
        lang_registry = r.json()
    else:
        # load from file
        pass
    languages = {}
    for lang in lang_registry:
        if lang['Type'] == 'language':
            languages[lang['Subtag']] = lang['Description'][0]

    # statistics and indexes
    quality_primary = 0.0
    quality_subordinate = 0.0
    quantity_primary = 0
    quantity_subordinate = 0
    primary = []
    secondary = []
    domains = []
    keywords = {}
    primary = []

    def grade(ratio):
        if ratio >= 0.9:
            return 'A'
        elif ratio >= 0.8:
            return 'B'
        elif ratio >= 0.7:
            return 'C'
        elif ratio >= 0.6:
            return 'D'
        else:
            return 'F'

    for dir_name, sub_dir_list, file_list in os.walk(path_source):
        this_dir = os.path.basename(dir_name)
        try:
            logger.info(u'converting {0}'.format(this_dir))
        except UnicodeDecodeError:
            try:
                logger.info('converting {0}'.format(this_dir))
            except UnicodeDecodeError:
                try:
                    logger.info(u'converting {0}'.format(
                        UnicodeDammit(this_dir).unicode_markup))
                except UnicodeDecodeError:
                    logger.warning('this directory name is unspeakable evil')

        for file_name_json in file_list:
            with open(os.path.join(dir_name, file_name_json),
                      'r') as file_json:
                resource = json.load(file_json)
            this_out = os.path.splitext(file_name_json)[0]

            # stats and grades

            rtitle = resource['title']
            rdesc = resource['description']
            if rdesc is not None:
                rdescwords = sorted(
                    set(RX_PUNCT.sub(u'', rdesc).lower().split()))
                rtitlewords = sorted(
                    set(RX_PUNCT.sub(u'', rtitle).lower().split()))
                if rdescwords != rtitlewords:
                    if len(rdescwords
                           ) > 6 or resource['volume'] is not None or resource[
                               'year'] is not None:
                        quality = 1.0
                    else:
                        quality = 0.5
                else:
                    quality = 0.0
            else:
                quality = 0.0
            pkg = {
                'domain': this_dir,
                'hash': this_out,
                'title': rtitle,
                'url': resource['url']
            }
            issn = None
            isbn = None
            try:
                issn = resource['identifiers']['issn']['electronic'][0]
            except KeyError:
                try:
                    issn = resource['identifiers']['issn']['generic'][0]
                except KeyError:
                    try:
                        isbn = resource['identifiers']['isbn']['electronic'][0]
                    except KeyError:
                        try:
                            isbn = resource['identifiers']['isbn']['generic'][
                                0]
                        except KeyError:
                            pass
            if issn is not None:
                pkg['issn'] = issn
            if isbn is not None:
                pkg['isbn'] = isbn
            if resource['is_part_of'] is not None and len(
                    resource['is_part_of']) > 0:
                quantity_subordinate += 1
                quality_subordinate += quality
            else:
                primary.append(pkg)
                quantity_primary += 1
                quality_primary += quality
            for k in resource['keywords']:
                try:
                    kwlist = keywords[k]
                except KeyError:
                    kwlist = keywords[k] = []
                kwlist.append(pkg)
            # make html
            doc = dominate.document(
                title=u'AWOL Index: {0}'.format(resource['title']))
            with doc.head:
                link(
                    rel='stylesheet',
                    type='text/css',
                    href=
                    'http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css'
                )
                link(
                    rel='stylesheet',
                    type='text/css',
                    href=
                    'http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css'
                )
                link(rel='stylesheet',
                     type='text/css',
                     href='../item-style.css')
            doc += h1(
                a(resource['title'], href=resource['url'], target="_blank"))
            _p = p('this record is part of ', cls='subtitle')
            _p += a('The AWOL Index', href='../../index.html')
            doc += _p
            _p = p()
            _p += a('JSON version',
                    href='../../json/{0}/{1}'.format(
                        dir_name.split('/')[-1], file_name_json),
                    target="_blank")
            doc += _p
            _dl = doc.add(dl())
            for k in sorted(resource.keys()):
                if k != 'title' and k != 'provenance' and resource[
                        k] is not None:
                    field = resource[k]
                    if type(field) in [list, dict]:
                        if len(field) > 0:
                            if k == 'identifiers':
                                for ident_type in field.keys():
                                    if type(field[ident_type]) == dict:
                                        for ident_subtype in field[
                                                ident_type].keys():
                                            if ident_subtype == 'generic':
                                                _dl += dt(u'{0}: '.format(
                                                    ident_type))
                                            else:
                                                _dl += dt(
                                                    u'{0} ({1}): '.format(
                                                        ident_type,
                                                        ident_subtype))
                                            _dl += dd(field[ident_type]
                                                      [ident_subtype])
                                    elif type(field[ident_type]) == list:
                                        _dl += dt(u'{0}: '.format(ident_type))
                                        for v in field[ident_type]:
                                            _dl += dt(u'{0}: '.format(v))
                                    else:
                                        raise ValueError('heckito')
                            else:
                                _dl += dt(k.replace(u'_', u' '))
                                if type(field) == list:
                                    if k == 'language':
                                        _dl += dd(languages[resource[k][0]])
                                    elif k in [
                                            'subordinate_resources',
                                            'related_resources'
                                    ]:
                                        _ul = _dl.add(ul())
                                        for rr in field:
                                            _ul += li(
                                                a(rr['title_full'],
                                                  href=rr['url']))
                                    else:
                                        _dl += dd(u', '.join(
                                            sorted([
                                                unicode(thing)
                                                for thing in resource[k]
                                            ])))
                                else:
                                    _ul = ul()
                                    for kk in sorted(field.keys()):
                                        if type(field[kk]) in [
                                                unicode, str
                                        ] and field[kk][0:4] == 'http':
                                            _li = _ul.add(
                                                li(u'{0}: '.format(kk)))
                                            _li += a(field[kk],
                                                     href=field[kk],
                                                     target="_blank")
                                        else:
                                            _ul += li(u'{0}: {1}'.format(
                                                kk, field[kk]))
                                    _dl += dd(_ul)
                    else:
                        _dl += dt(k)
                        if resource[k][0:4] == 'http':
                            _dl += dd(
                                a(resource[k],
                                  href=resource[k],
                                  target="_blank"))
                        else:
                            _dl += dd(resource[k])

            if 'provenance' in resource.keys():
                _div = doc.add(div(id='provenance'))
                _div += h2('data provenance')
                _dl = _div.add(dl())
                events = sorted([prov for prov in resource['provenance']],
                                key=lambda k: k['when'])
                for event in events:
                    try:
                        _dl += dt(dateout(dateutil.parser.parse(
                            event['when'])))
                    except ValueError:
                        _dl += dt(
                            dateout(
                                LOCAL.localize(
                                    dateutil.parser.parse(event['when']))))
                    _dd = _dl.add(
                        dd(u'{0}: '.format(
                            un_camel(event['term'].split(u'/')[-1]).replace(
                                u'cites as ', u''))))
                    rid = event['resource']
                    if rid[0:4] == 'http':
                        _dd += (a(rid.split('://')[1],
                                  href=rid,
                                  target="_blank"))
                    else:
                        _dd += rid
                    try:
                        _dd += u' (last updated: {0})'.format(
                            dateout(
                                dateutil.parser.parse(event['resource_date'])))
                    except KeyError:
                        _dd += u' (last updated not indicated)'

            #print (unicode(doc))
            file_name_html = '.'.join((this_out, 'html'))
            out_path = os.path.join(path_dest, this_dir)
            file_path_html = os.path.join(out_path, file_name_html)
            #print file_path_html
            try:
                os.makedirs(out_path)
            except OSError as exc:  # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(out_path):
                    pass
                else:
                    raise
            with open(file_path_html, 'w') as file_html:
                file_html.write(unicode(doc).encode('utf-8'))

        for ignore_dir in ['.git', '.svn', '.hg']:
            if ignore_dir in sub_dir_list:
                sub_dir_list.remove(ignore_dir)

    index_primary(primary, path_dest)
    index_keywords(keywords, primary, path_dest)
    quantity = quantity_primary + quantity_subordinate
    print "quantity: {0}".format(quantity)
    print "   top-level: {0}".format(quantity_primary)
    print "   subordinate: {0}".format(quantity_subordinate)
    qratio = (quality_primary + quality_subordinate) / float(quantity)
    qratio_primary = quality_primary / float(quantity_primary)
    qratio_subordinate = quality_subordinate / float(quantity_subordinate)
    print "quality ratio: {0:.2f}".format(qratio)
    print "   top-level: {0:.2f}".format(qratio_primary)
    print "   subordinate: {0:.2f}".format(qratio_subordinate)
    print "grade: {0}".format(grade(qratio))
    print "   top-level: {0}".format(grade(qratio_primary))
    print "   subordinate: {0}".format(grade(qratio_subordinate))
Пример #50
0
    "Score Threshold", "Mean Coverage", "Coverage Threshold", "Total Peaks",
    "Filtered by Score", "Filtered by Coverage", "num of re-centered peaks"
]
for l in (section2text['filter_peaks']):
    if (l):
        filter_list.append(float(l.split("\t")[1]))

filter_list = [
    filter_list[0], filter_list[3], filter_list[4], filter_list[5],
    detection_list[1], filter_list[10], filter_list[6], filter_list[7],
    filter_list[12], filter_list[13]
]
filter_total = filter_list[6]

########### HTML SECTION ###########
doc = dominate.document(title="CHAP analyses overview for the sample \"%s\"" %
                        name)
with open(args.css) as f:
    _style = f.read()
with doc.head:
    style(_style)

with doc:
    p(strong("Mapping Results", style='font-size: 16pt'))
    with table(style='font-size: 14pt') as _table:
        for label, value in zip(bowtie_labels, bowtie_list):
            with tr():
                td(label)
                td('{:,}'.format(value))
                td("%1.2f%%" % (value / bowtie_total * 100))

    with div(cls="row", style="display: flex"):
Пример #51
0
def generate_tables_html(tables):
    doc = dominate.document(title='ABED Scalar Tables')

    with doc.head:
        # meta tags
        tags.meta(charset='utf-8')
        tags.meta(http_equiv='X-UA-Compatible', content='IE=edge')
        tags.meta(name='viewport',
                content='width=device-width, initial-scale=1')
        tags.meta(name='description', content='')
        tags.meta(name='author', content='')
        #tags.link(rel='icon', href=copy_data_file('ABED/images/favicon.ico'))

        # JQuery & Bootstrap JS
        tags.script(src=copy_data_file('jquery/1.11.3/jquery.min.js'))
        tags.script(
                src=copy_data_file('bootstrap-3.3.5-dist/js/bootstrap.min.js'))
        # Bootstrap core CSS
        tags.link(rel='stylesheet', href=copy_data_file(
            'bootstrap-3.3.5-dist/css/bootstrap.min.css'))

        # Datatables CSS & JS
        tags.link(rel='stylesheet', href=copy_data_file(
            'DataTables-1.10.7/media/css/jquery.dataTables.css'))
        tags.script(type='text/javascript', src=copy_data_file(
            'DataTables-1.10.7/media/js/jquery.dataTables.js'))

        # ABED CSS & JS
        tags.link(rel='stylesheet', href=copy_data_file('abed/css/abed.css'))
        tags.script(type="text/javascript", 
                src=copy_data_file('abed/js/abed_showtables.js'))
        tags.script(type="text/javascript", 
                src=copy_data_file('abed/js/abed_scalartables.js'))

    with doc:
        navbar(active=AbedHTMLTypes.SCALAR_TABLES)
        with tags.div(_class='container'):
            with tags.table(id='AbedButtons', _class='display',
                    cellspacing='0', width='100%'):
                with tags.thead():
                    tr = tags.tr()
                    tr += tags.th('Target')
                    tr += tags.th('Output Type')
                with tags.tbody():
                    tr = tags.tr()
                    tr += tags.td(bootstrap_radio_group(generate_buttons(
                        tables, 'target')))
                    tr += tags.td(bootstrap_radio_group(generate_buttons(
                        tables, 'type')))
            for table in tables:
                tabid = get_table_id(table)
                with tags.div(id='div_'+tabid, _class='AbedTable'):
                    if 'summary' in tabid:
                        tags.p("Summary Table:")
                    with tags.table(id='tbl_'+tabid, _class='display', 
                            cellspacing='0', width='100%'):
                        with tags.thead():
                            tr = tags.tr()
                            for hdr in table.headers:
                                tr += tags.th(hdr)
                        if not 'summary' in tabid:
                            with tags.tfoot():
                                tr = tags.tr()
                                for hdr in table.headers:
                                    tr += tags.th(hdr)
        tags.comment('/.container')
    return str(doc)
Пример #52
0
_title = "Binding peaks for the sample: %s" % name
peaks = list(
    sorted(BedTool(args.path), key=lambda x: float(x.score),
           reverse=True))[:args.top]

header_main = ["ucsc", 'chrom', 'start', 'end', 'top', 'strand']
dtypes_main = [0, 0, 1, 1, 1, 0]
header_attrs = [
    'geneID', 'genesymbol', 'gtype', 'tss', 'atg', 'annotation', 'function',
    'fold_change', 'topcoverage', 'other_topcoverage', 'cg'
]
dtypes_attrs = [0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0]
header = header_main + header_attrs
dtypes = dtypes_main + dtypes_attrs

doc = dominate.document(title=_title)

with open(args.css) as f:
    _style = f.read()

with open(args.js) as f:
    plain_script = f.read()

with doc.head:
    style(_style)

with doc:
    p(strong(_title))
    input(type="text",
          id="inp1",
          onkeyup='my_search(7, "inp1", "myTable")',
Пример #53
0
def main(args):
    lists = pd.read_csv(args.infile, header=None, delimiter='\t')
    categories = utils.io.load_categories(args.categories)
    C = len(categories)
    x_min, x_max = lists[2].min(), lists[2].max()
    y_min, y_max = lists[3].min(), lists[3].max()

    doc = dominate.document(title='t-SNE browser ' + args.infile)

    with doc.head:
        #link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.css')
        link(rel='stylesheet', href='c3.css')
        script(type='text/javascript', src='https://d3js.org/d3.v3.min.js')
        script(type='text/javascript', src='https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.js')
        script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js')
        _css = style(type='text/css')
        _css += '''
        #images{
            overflow-x: auto;
            white-space: nowrap;
        }
        #images figure{
            display: inline-block;
            margin: 1px;
            border: 2px solid white;
            text-align: center;
            background-color: gray;
        }
        #images figure span{
            display:inline-block;
            width:10px;
            height:10px;
            margin-right:6px;
        }
        #images figure:hover{
            border: 2px solid black;
        }
        '''
    with doc:
        '''with div(id='categorylist').add(ul(style="list-style:none;")):
            for i, c in enumerate(categories):
                _li = li()
                _label = _li.add(label())
                _label += dominate.tags.input(
                    type="checkbox", id='check_'+c, cls='category_checklist',
                    name="categories[]", value=str(i), checked="checked")
                _label += c'''
        with div(id="chart"):
            _script = script(type='text/javascript')
            xs_str = ",\n".join([c+": '"+c+"_x'" for c in categories])
            color_list = ", ".join([colorfloat2hex(plt.cm.jet(float(i)/(C-1))) for i in range(C)])
            #print(color_list)
            #print(xs_str)
            columns_str_list=[]
            image_path_list=[]
            for i, c in enumerate(categories):
                c_list = lists[lists[1] == i]
                columns_str_list.append(
                "['"+c+"_x', " + ",".join([str(v) for v in c_list[2]]) + "]"
                )
                columns_str_list.append(
                "['"+c+"', " + ",".join([str(v) for v in c_list[3]]) + "]"
                )
                image_path_list.append(
                "imagepath['"+c+"'] = [" + ",".join(["'" + os.path.join(args.root, v) + "'" for v in c_list[0]]) + "];"
                )

            columns_str = ",\n".join(columns_str_list)
            #print(columns_str_list)
            #print(image_path_list)
            append_imagepath_code = "\n".join(image_path_list)
            _script.add_raw_string('var abc = 0;')
            _script.add_raw_string( # += \
'''
<!--
var imagepath = {};\n''' + append_imagepath_code + '''

function printProperties(obj) {
    var properties = '';
    for (var prop in obj){
        properties += prop + '=' + obj[prop] + '\\n';
    }
    console.log(properties);
}

$(function() {
    $('#clearbutton').click(function(e){
        $('#images figure').remove();
    });
    $('#images').on("mouseup", "figure", function(e){
        if (e.ctrlKey || e.which == 2) {
            console.log(this);
            $(this).remove();
            names = $(this).attr('name').split('-');
            id = names[0];
            index = parseInt(names[1]);
            //console.log(id, index);
            chart.unselect([id], [index]);
        }
    });
    $('#images').on("mouseover", "figure", function(e){
        names = $(this).attr('name').split('-');
        id = names[0];
        index = parseInt(names[1]);
        //console.log(id, index);
        chart.select([id], [index], true);
    });
    $('#images').on("mouseout", "figure", function(e){
        names = $(this).attr('name').split('-');
        id = names[0];
        index = parseInt(names[1]);
        chart.unselect([id], [index], true);
    });
});

var chart = c3.generate({
    size: {
        height: 600,
        width: 800
    },
    data: {
        xs: {''' + xs_str + '''},
        columns: [''' + columns_str + '''],
        type: 'scatter',
        selection: {
            enabled: true
        },
        onclick: function (d, element) {
            console.log(d, element);
            chart.unselect([d.id], [d.index]);
            var fig = $('<figure name="'+ d.id + '-' + d.index +'">');
            var img = $('<img src="' + imagepath[d.id][d.index] + '" width="200px", height="200px">');
            var cap = $('<figcaption>' + d.id + '</figcaption>');
            $('#images').append(fig);
            fig.append(img);
            fig.append(cap);
            cap.css('color', chart.color(d.id));
        }
    },
    color: {
        pattern: [''' + color_list + ''']
    },
    tooltip: {
        contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
        var $$ = this, config = $$.config,
            titleFormat = config.tooltip_format_title || defaultTitleFormat,
            nameFormat = config.tooltip_format_name || function (name) { return name; },
            valueFormat = config.tooltip_format_value || defaultValueFormat,
            text, i, title, value, name, bgcolor;
            text = "<table class='c3-tooltip c3-tooltip-container'>";
            for (i = 0; i < d.length; i++) {
                if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
                value = d[i].x.toFixed(4) + ', ' + d[i].value.toFixed(4);
                name = nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index);
                bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);

                text += "<tr class='" + d[i].id + "'>";
                text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
                text += "<td class='value'>" + value + "</td>";
                text += "</tr>";
                text += "<tr style=><th colspan='2'><img border=0px src=" + imagepath[d[i].id][d[i].index] + "></th></tr>";
            }
            return text + "</table>";
        }
    },
    axis: {
        x: {
            label: 'tsne1',
            min: ''' +str(math.floor(x_min))+ ''',
            max: ''' +str(math.ceil(x_max))+ ''',
            tick: {
                fit: false
            }
        },
        y: {
            label: 'tsne2',
            min: ''' +str(math.floor(y_min))+ ''',
            max: ''' +str(math.ceil(y_max))+ ''',
            tick: {
                fit: false
            }
        }
    },
    legend: {
        item: {
            onclick: function (d) {
                if (event.ctrlKey) {
                    chart.toggle();
                }
                chart.toggle(d);
            }
        }
    }
});
-->
''')
        clearbutton = button(id="clearbutton")
        clearbutton += "clear"
        div(id="images")

    #print(doc)
    with open(args.out, 'w') as fo:
        fo.write(doc.render())
Пример #54
0
import dominate
from dominate.tags import *


def writefile(content='', path=''):
    with open(path, 'w') as f:
        f.write(content)


# Main example below.
# Basic var to contain html content.
doc = dominate.document(title='My tag')

# Manage a <head> block.
with doc.head:
    link(rel='stylesheet', href='style.css')
    script(type='text/javascript', src='srcipt.js')

# Manage a <body> block.
with doc:
    # Create an ordered list
    with div(id='header').add(ol()):
        for i in ['first', 'second', 'third']:
            li(a(i.title(), href='/%s.html' % i))

    with div():
        # Add attributes inside of [with] manager
        attr(cls='body')
        # [<] or [>] or other characters are safe.
        p('My own <p> tag, crazy')
Пример #55
0
    def html(self, imdbid):

        data = self.sql.get_movie_details('imdbid', imdbid)
        if data:
            poster_path = core.URL_BASE + '/static/images/posters/{}.jpg'.format(
                data['imdbid'])
            title_date = data['title'] + " " + str(data['year'])

            tomatoes_url = data['tomatourl']

        quality_settings = json.loads(data['quality'])

        doc = dominate.document(title='Watcher')

        with doc.head:
            script(src=core.URL_BASE +
                   '/static/js/status/movie_status_popup.js?v=12.27')

        with doc:
            with div(id='container'):
                if not data:
                    span(
                        'Unable to get movie information from database. Check logs for more information.'
                    )
                    return doc.render()

                with div(id='title'):
                    with p():
                        span(title_date, id='title', imdbid=imdbid)
                        i(cls='fa fa-times', id='close')
                        i(cls='fa fa-trash', id='remove')
                        i(cls='fa fa-cog', id='change_quality')
                        i(cls='fa fa-save', id='save_quality')
                        i(cls='fa fa-search',
                          id='search_now',
                          imdbid=data['imdbid'],
                          title=data['title'])
                with div(id='media'):
                    img(id='poster', src=poster_path)
                    with div(id='search_results'):

                        with ul(id='result_list'):
                            self.result_list(imdbid)
                        div(id='results_thinker')

                        # Panel that swaps in with quality adjustments
                        resolutions = ['4K', '1080P', '720P', 'SD']
                        with ul(id='quality', cls='wide'):
                            # Resolution Block
                            with ul(id='resolution', cls='sortable'):
                                span('Resolutions', cls='sub_cat not_sortable')

                                for res in resolutions:
                                    prior = '{}priority'.format(res)
                                    with li(cls='rbord',
                                            id=prior,
                                            sort=quality_settings['Quality']
                                            [res][1]):
                                        i(cls='fa fa-bars')
                                        i(id=res,
                                          cls='fa fa-square-o checkbox',
                                          value=quality_settings['Quality']
                                          [res][0])
                                        span(res)

                            # Size restriction block
                            with ul(id='resolution_size'):
                                with li('Size Restrictions (MB)',
                                        cls='sub_cat'):

                                    for res in resolutions:
                                        min = '{}min'.format(res)
                                        max = '{}max'.format(res)
                                        with li():
                                            span(res)
                                            input(type='number',
                                                  id=min,
                                                  value=quality_settings[
                                                      'Quality'][res][2],
                                                  min='0',
                                                  style='width: 7.5em')
                                            input(type='number',
                                                  id=max,
                                                  value=quality_settings[
                                                      'Quality'][res][3],
                                                  min='0',
                                                  style='width: 7.5em')

                            with ul(id='filters', cls='wide'):
                                with li(cls='bbord flexbox'):
                                    span('Required words:')
                                    input(type='text',
                                          id='requiredwords',
                                          value=quality_settings['Filters']
                                          ['requiredwords'],
                                          style='width: 16em')
                                with li(cls='bbord flexbox'):
                                    span('Preferred words:')
                                    input(type='text',
                                          id='preferredwords',
                                          value=quality_settings['Filters']
                                          ['preferredwords'],
                                          style='width: 16em')
                                with li(cls='flexbox'):
                                    span('Ignored words:')
                                    input(type='text',
                                          id='ignoredwords',
                                          value=quality_settings['Filters']
                                          ['ignoredwords'],
                                          style='width: 16em')

                with div(id='plot'):
                    p(data['plot'])
                with div(id='additional_info'):
                    with a(href=tomatoes_url, target='_blank'):
                        span('Rotten Tomatoes Rating: {}'.format(
                            data['tomatorating']))
                    span('Theatrical Release Date: {}'.format(
                        data['released']))
                    span('DVD Release Date: {}'.format(data['dvd']))

        return doc.render()
Пример #56
0
    def generate_file(self,
                      path: Path = Path(''),
                      words: [str] = [''],
                      sentences: [str] = [''],
                      paragraphs: [str] = [''],
                      usernames: [str] = [''],
                      background_images: [str] = [],
                      style: str = '',
                      layout: Layout = Layout.center) -> None:

        misc_prefix = ''
        for _ in range(str(path).count('/')):
            misc_prefix += '../'
        misc_prefix += self.misc_path.name
        doc = dominate.document(title='generated')

        background_images = [
            str(Path(misc_prefix).joinpath(img)) for img in background_images
        ]

        indexes: [int] = []
        possible_indexes: [int] = [0, 1, 2, 3, 4, 5, 6, 7, 8]
        random.shuffle(possible_indexes)
        for _ in range(len(background_images)):
            indexes.append(possible_indexes.pop())

        with doc.head:
            link(rel='stylesheet',
                 href=str(Path(misc_prefix).joinpath('style.css')))

        with doc.body:
            with div(cls='grid', style=style):
                if layout == Layout.center:
                    if 0 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

                elif layout == Layout.left:
                    if 0 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

                elif layout == Layout.top:
                    if 0 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

                elif layout == Layout.wall_of_text:
                    if 0 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[3]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[4]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[5]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[6]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[7]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[8]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

                elif layout == Layout.l_word_c_text:
                    if 0 not in indexes:
                        div(cls='cell').add(str_to_span(usernames[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell').add(str_to_span(usernames[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell').add(str_to_span(usernames[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell').add(str_to_span(paragraphs[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell')
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

                elif layout == Layout.words:
                    if 0 not in indexes:
                        div(cls='cell').add(str_to_span(words[0]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 1 not in indexes:
                        div(cls='cell').add(str_to_span(words[1]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 2 not in indexes:
                        div(cls='cell').add(str_to_span(words[2]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 3 not in indexes:
                        div(cls='cell').add(str_to_span(words[3]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 4 not in indexes:
                        div(cls='cell').add(str_to_span(words[4]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 5 not in indexes:
                        div(cls='cell').add(str_to_span(words[5]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 6 not in indexes:
                        div(cls='cell').add(str_to_span(words[6]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 7 not in indexes:
                        div(cls='cell').add(str_to_span(words[7]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))
                    if 8 not in indexes:
                        div(cls='cell').add(str_to_span(words[8]))
                    else:
                        div(cls='cell').add(
                            img(cls='img', src=background_images.pop()))

            script(type='text/javascript',
                   src=str(Path(misc_prefix).joinpath('script.js')))

        out_path: Path = self.save_directory.joinpath(path)
        Path(out_path).parent.mkdir(parents=True, exist_ok=True)
        with codecs.open(str(out_path) + '.html', 'w', 'utf-8-sig') as f:
            f.write(htmlmin.minify(doc.render(), remove_empty_space=True))
Пример #57
0
def open_html_doc(name, letter=None):
    html_doc = dominate.document(title=u"מילון הראיה")
    html_doc['dir'] = 'rtl'
    with html_doc.head:
        with tags.meta():
            tags.attr(charset="utf-8")
        with tags.meta():
            tags.attr(name="viewport",
                      content="width=device-width, initial-scale=1")

        tags.script(src="jquery/dist/jquery.min.js")
        tags.link(rel='stylesheet',
                  href='bootstrap-3.3.6-dist/css/bootstrap.min.css')
        tags.link(rel='stylesheet', href='style.css')
        tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js")
        tags.link(rel='stylesheet',
                  href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css")
        tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css')
        tags.script(src="milon.js")
        tags.script(src="html_demos-gh-pages/footnotes.js")
        tags.script(src="subjects_db.json")

    html_doc.footnote_ids_of_this_html_doc = []
    html_doc.name = name
    if letter:
        html_doc.letter = letter
        html_doc.section = html_docs_l[-1].section
    else:
        html_doc.section = name

    html_doc.index = len(html_docs_l) + 1
    with html_doc.body:
        with tags.div():
            tags.attr(cls="container-fluid")
            # TODO: call page_loaded to update saved URL also in other links
            tags.script("page_loaded('%s.html')" % html_doc.index)

            with tags.div():
                tags.attr(cls="fixed_top_left", id="menu_bar")
                with tags.div():
                    with tags.button(type="button"):
                        tags.attr(id="search_icon_button",
                                  type="button",
                                  cls="btn btn-default")
                        with tags.span():
                            tags.attr(cls="glyphicon glyphicon-search")
                    with tags.span():
                        tags.attr(cls="dropdown")
                        with tags.button(type="button",
                                         cls="btn btn-primary") as b:
                            tags.attr(href="#")  #, cls="dropdown-toggle")
                            with tags.span():
                                tags.attr(
                                    cls="glyphicon glyphicon-menu-hamburger")
                                # b['data-toggle'] = "dropdown"
                        with tags.ul():
                            tags.attr(
                                cls=
                                "dropdown-menu dropdown-menu-left scrollable-menu"
                            )

    return html_doc
Пример #58
0
comentarios = ""
comentariosMult = ""
palabrasReservadas = ""
lexico = [
    variables, operadores, enteros, flotante, strings, comentarios,
    comentariosMult, palabrasReservadas
]
#Se lee el archivo y se guardan las expresiones
with open("expresiones.txt", "r") as archivo:
    expresiones = archivo.readlines()
    i = 0
    for expresion in expresiones:
        lexico[i] = expresion.rstrip()
        i += 1
archivo.close()
doc = dominate.document(title='Resaltador de sintaxis de Python')

with doc.head:
    link(rel='stylesheet', href='estilo.css')
    meta(charset="UTF-8")
    meta(name="viewport", content="width= device-width, initial-scale= 1")

with doc:
    body(cls="estilo")
    with open("input.txt", "r", encoding="utf8") as input:
        lineas = input.readlines()
        i = 0
        for linea in lineas:
            with div():
                attr(cls='estilo')
                k = 0
Пример #59
0
def main():
    
    with open(sys.argv[1], encoding='utf-8') as f:
        board = json.load(f)

    # Build indexes into the JSON structure.
    labels = {lab['id']: lab for lab in board['labels']}
    members = {mem['id']: mem for mem in board['members']}
    lists = {lis['id']: lis for lis in board['lists']}
    cards = {card['id']: card for card in board['cards']}
    actions = {action['id']: action for action in board['actions']}
    checklists = {check['id']: check for check in board['checklists']}

    # Grouped collections of things.
    cards_by_list = defaultdict(list)

    for card in board['cards']:
        cards_by_list[card['id']].append(card)

    comments_by_card = defaultdict(list)

    for com in (c for c in board['actions'] if c['type'] == 'commentCard'):
        comments_by_card[com['data']['card']['id']].append(com)

    # Markdown renderer.
    md = Markdown()

    title = "Exported Trello Board: " + board['name']
    doc = dominate.document(title=title)

    with doc:
        h1(title)
        hr()
        
        with div(id="members"):
            h2("Trello Board Members")
            with ul():
                for m in board['members']:
                    li("{} (@{})".format(m['fullName'], m['username']))
        hr()

        with div(id="lists"):
            h2("Trello Lists")
            with ul():
                for l in board['lists']:
                    li("{}".format(l['name']))
        hr()

        with div(id="cards"):
            h2("Trello Cards")
            for c in board['cards']:
                with div(cls="card"):
                    h3("Card Title: {}".format(c['name']))

                    with dl(classmethod="carddetails"):
                        dt("Last Activity:")
                        dd(c['dateLastActivity'])
                        dt("Trello List:")
                        dd(lists[c['idList']]['name'])
                        if c['due']:
                            dt("Due Date:")
                            dd(c['due'])

                    if c['desc']:
                        h4("Card Description:")
                        with div(cls="carddesc"):
                            div(raw((md.reset().convert(c['desc']))))

                    if c['idMembers']:
                        with div(cls="cardmembers"):
                            h4("Card Members:")
                            with ul():
                                for m in c['idMembers']:
                                    li(members[m]['fullName'])

                    if c['idLabels']:
                        with div(cls="cardlabels"):
                            h4("Card Labels:")
                            with ul():
                                for l in c['idLabels']:
                                    li(labels[l]['name'])
                    
                    for cid in c['idChecklists']:
                        clist = checklists[cid]
                        with div(cls="checklist"):
                            h4("Checklist: {}".format(clist['name']))
                            with ul():
                                for item in clist['checkItems']:
                                    li("{} ({})".format(item['name'],item['state']))

                    if comments_by_card[c['id']]:
                        with div(cls="comments"):
                            h4("Card Comments:")
                            for com in comments_by_card[c['id']]:
                                with div(cls='cardcomment'):
                                    full = com['memberCreator']['fullName']
                                    user = com['memberCreator']['username']
                                    date = com['date']
                                    tup = (full, user, date)
                                    h4("{} ({}) : {}".format(*tup))
                                    md.reset()
                                    raw((md.convert(com['data']['text'])))

                # Line under each card.
                hr()


    with open(sys.argv[2], 'w', encoding='utf-8') as outfile:
        outfile.write(str(doc))
Пример #60
0
text_modelB = markovify.Text(textB)
text_modelC = markovify.Text(textC)
text_modelD = markovify.Text(textD)
text_modelE = markovify.Text(textE)
text_modelF = markovify.Text(textF)
text_modelG = markovify.Text(textG)

model_combo = markovify.combine([ text_modelA, text_modelB, text_modelC, text_modelD, text_modelE, text_modelF, text_modelG ], [ 1, 1, 1, 1, 1, 1, 1 ])

def make_Para():
  paragraph = ''
  for i in range(random.randint(5,20)):
    paragraph += model_combo.make_sentence()
  return paragraph
 
doc = dominate.document(title='Novel Nightmares')

with doc:
  with doc.head:
    style("body {font-family: copperplate; color: red}")
    h1("Novel Nightmares")
  for ch in range(50): 
    h2("Chapter "+ str(int(ch + 1)))
    for para in range(random.randint(10,40)):
      p(make_Para())
  
  with open("nightmare.html", "a") as f:
      f.write(str(doc))