コード例 #1
1
 def processFooter(self):
     doc, tag, text = Doc().tagtext()
     with tag('html'):
         with tag('head'):
             with tag('title'):
                 text('footer html generates by ARG101')
             with tag('style'):
                 text('span{text-align: left;}')
         with tag('body'):
             doc.stag('hr')
             with tag('span'):
                 text("{} ({})".format(self.studentName,self.enrollmentId))
     return doc.getvalue()
コード例 #2
1
    def build(self):
        doc, tag, text, line = Doc().ttl()

        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                doc.stag('meta', charset="utf-8")
                with tag('script'):
                    doc.attr(src="https://code.jquery.com/jquery-3.3.1.slim.min.js")
                    doc.attr(integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo")
                    doc.attr(crossorigin="anonymous")
                with tag('script'):
                    doc.attr(src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js")
                    doc.attr(integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49")
                    doc.attr(crossorigin="anonymous")
                doc.stag('link',
                         rel="stylesheet",
                         href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css",
                         integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO",
                         crossorigin="anonymous")
                with tag('script'):
                    doc.attr(src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js")
                    doc.attr(integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy")
                    doc.attr(crossorigin="anonymous")
                line('title', self.title)
            with tag('body'):
                for element in self._content:
                    if element['type'] == self.LINE:
                        doc.asis('<p>' + element['element'] + '</p>')
                
                    elif element['type'] == self.TABLE:
                        table = element['element']
                        with tag('table', klass='table table-bordered table-striped'):
                            with tag('thead'):
                                with tag('tr'):
                                    for cell in table[0]:
                                        line('th', cell)
                            with tag('tbody'):
                                for row in range(1, len(table)):
                                    with tag('tr'):
                                        for cell in table[row]:
                                            c = str(cell)
                                            c = c.replace('=>', '=&gt;')
                                            doc.asis('<td>' + c + '</td>')

        result = indent(doc.getvalue())
        with open(self._file_path, 'w') as out_file:
            out_file.write(result)
コード例 #3
0
def print_document(X, Y, T, cams):
    doc, tag, text = Doc().tagtext()

    prepro = Preprocessor(cache_path=cache_dir / 'train_text.json')
    X_text = prepro.to_text(X_sample)

    with tag('html'):
        with tag('body', style="width: 900px;"):
            for i, p in enumerate(X_text):
                cam = cams[i]
                # normalize cam
                heatmap = cam / np.ptp(cam)
                color_map = cv2.applyColorMap(
                    np.uint8(255 * heatmap), cv2.COLORMAP_AUTUMN)
                with tag('div'):
                    with tag('p'):
                        words = p.split(' ')
                        for j, word in enumerate(words):
                            color = color_map[j][0]
                            with tag('span', style=f'background: rgba({color[2]}, {color[1]}, {color[0]}, {heatmap[j]});', title=int(X_test[i, j])):
                                text(word + ' ')
                    with tag('p'):
                        text(
                            f'Pred: {Y[i]}, Label: {T[i]}')
                    doc.stag('hr')

    with open(out_dir / 'out.html', 'w') as f:
        f.write(doc.getvalue())
コード例 #4
0
def generate_html_file_matchups(matchups, file_name):
    from yattag import Doc
    from yattag import indent

    doc, tag, text, line = Doc().ttl()

    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('body'):
            line('p', time_string('day'))
            line('p', time_string('time'))
            line('h1', 'Lines')
            with tag('head'):
                doc.stag('link', rel='stylesheet', href='style.css')
            for matchup in matchups:
                with tag('table'):
                    with tag('tr'):
                        line('td', matchup.website, rowspan=3, klass='site')
                        line('th', 'Team')
                        line('th', 'Spread')
                        line('th', 'Money Line')
                        line('th', 'O/U')
                    with tag('tr'):
                        line('td', matchup.team_one)
                        line('td', matchup.spread_one.get_string())
                        line('td', matchup.mline_one.get_string())
                        line('td', matchup.over.get_string(), rowspan=2)
                    with tag('tr'):
                        line('td', matchup.team_two)
                        line('td', matchup.spread_two.get_string())
                        line('td', matchup.mline_two.get_string())

    file = open(file_name, 'w')
    file.write(indent(doc.getvalue()))
コード例 #5
0
def MessagesToHTML(rows, submission_form):
    # format rows into rich text email
    doc, tag, text = Doc().tagtext()
    with tag('html'):
        with tag('h1', ('align', 'center')):
            text('Blockmate Newsletter!')
        with tag('body', ('align', 'center')):
            for row in rows:
                # submitter's name and date
                with tag('h3', id=row['name']):
                    with tag('font', ('color', row['color'].lower())):
                        date = row['timestamp'].split(' ', 1)[0]
                        text(row['name'] + ' on ' + date)
                # submitter's message
                with tag('p', id=row['name']):
                    with tag('font', ('color', row['color'].lower())):
                        text(row['msg'])
                        doc.attr(style="color:" + row['color'].lower() + ';"')
                # submitter's photos
                photo_urls = [x.strip() for x in row['photos'].split(',')]
                for photo in photo_urls:
                    # use uc?export format instead of open
                    url = photo.replace('open?', 'uc?export=view&', 1)
                    with tag('div', id='photo-container'):
                        doc.stag('img', src=url, width=300)
            with tag('p', id='submit_again'):
                reminder = message_text.WHERE_TO_SUBMIT.format(submission_form)
                text(reminder)
    return (doc.getvalue())
コード例 #6
0
 def as_junit_xml(self):
     """
     Return Junit-format XML fragment.
     """
     xml, tag, text = XML().tagtext()
     with tag('testsuite',
              name=self.name,
              hostname=self.hostname,
              time=(self.stop - self.start),
              tests=len(self._testcases),
              timestamp=datetime.fromtimestamp(self.start).isoformat(),
              errors=self.errored,
              failures=self.failed,
              skipped=self.skipped,
     ):
         if self._id is not None:
             xml.attr(id=self._id)
         with tag('properties'):
             for key, value in self._properties.iteritems():
                 xml.stag('property', name=key, value=str(value))
         for testcase in self._testcases:
             if testcase.status is None:
                 with tag('error'):
                     text('Unknown outcome of this step.')
             else:
                 xml.asis(testcase.as_junit_xml())
     return xml.getvalue()
コード例 #7
0
def build_posts_html(posts):
    doc, tag, text, line = Doc().ttl()
    with tag('table'):
        for post in posts:
            with tag('tr', klass='post'):
                line('td', post.score, klass='score')

                with tag('td', klass='post-thumb'):
                    with tag('a', href=post.url, target='_blank'):
                        doc.stag('img', src=post.thumbnail)

                with tag('td', klass='post-content'):
                    with tag('a', href=post.url, target='_blank'):
                        line('h2', post.title)
                    line('a',
                         str(post.num_comments) + ' comments ',
                         href='https://reddit.com' + post.permalink,
                         target='_blank')
                    text(
                        date.utcfromtimestamp(int(post.created_utc)).strftime(
                            'Submitted on %b %d, %Y to '))
                    line('a',
                         str(post.subreddit),
                         href='https://reddit.com/r/' + str(post.subreddit),
                         target='_blank')
    return doc.getvalue()
コード例 #8
0
ファイル: utils.py プロジェクト: catedraunescoups/arise
def generarTabla(estructura, titulo, borde=1):
    doc, tag, text = Doc().tagtext()
    columnas = get_table_columns(estructura)
    m = max(columnas) - 1
    valor = ''
    
    doc.stag('br')
    with tag('h3', ('class','strong')):
        text(titulo)
    with tag('table', border=str(borde), cellpadding='4'):
        for i in range(0, len(estructura)):
            with tag('tr'):
                for j in range(0,columnas[i]):
                    valor = str(estructura[i][j])
                    print(valor)
                    if(valor != 'None'):
                        l = len(valor)
                        if valor.startswith(':s:', 0 ,l):
                            with tag('td', colspan=str(m), id="id_j"):
                                text(valor[3:])
                        else:
                            if valor.startswith(':b:', 0 ,l):
                                with tag('td', id='id_b'):
                                    text(valor[3:])
                            else:
                                with tag('td', id='id_c'):
                                    text(valor)
                    else:
                        with tag('td', id='id_c'):
                            text('')
    res = doc.getvalue()
    return res
コード例 #9
0
   def htmlPage(self, count=8):
      characters = []
      for ii in range(count):
         characters.append(YoungThug())
         characters[ii].generate()

      doc, tag, text = Doc().tagtext()
      with tag("html"):
         with tag("head"):
           pass
         with tag("body"):
            with tag("table", width = '100%', border=2, cellpadding=10, style='table-layout: fixed;'):
               for ii in range(int(count/2)):
                  with tag("tr", border=2):
                    for jj in range(2):
                      with tag('td', width = '50%', height = '25%', padding='15', border=2, style='word-wrap:break-word;'):
                        ch = characters[((ii*2)+(jj-1))-1]
                        tmp = ch.html()
                        doc.asis(tmp)
            doc.asis('<br>')
            with tag('small'):
               with tag('center'):
                  text('Traveller is a registered trademark of Far Future Enterprises.')
                  doc.stag('br')
                  text('Generated by Joshua Levy "Young Thugs" web server in 2017 version %s' % self.version)
      return doc.getvalue()
コード例 #10
0
ファイル: video.py プロジェクト: noisyoscillator/MaTiSSe
 def to_html(self):
     """Convert self data to its html stream."""
     doc = Doc()
     with doc.tag('div', id='video-' + str(self.number)):
         if self.style:
             doc.attr(style=self.style)
         else:
             doc.attr(klass='video')
         if self.cap_position is not None and self.cap_position.upper(
         ) == 'TOP':
             self.put_caption(doc=doc, klass='video-caption')
         with doc.tag('video', klass='video-content'):
             if self.controls:
                 doc.attr(controls='controls')
             if self.autoplay:
                 doc.attr(autoplay='autoplay')
             if self.ctn_options:
                 doc.attr(style=self.ctn_options)
             else:
                 doc.attr(style='width:100%;')
             doc.stag('source', src=self.ctn)
         if self.cap_position is None or self.cap_position.upper(
         ) == 'BOTTOM':
             self.put_caption(doc=doc, klass='video-caption')
     return doc.getvalue()
コード例 #11
0
 def html(self):
     doc, tag, text = Doc().tagtext()
     text('Name: %s --- %s --- %d years old' % (self.name, self.strUpp(),self.age))
     doc.asis('<br>')
     text('%s (%d term%s)              Cr%d' % (self.strCareer(), self.terms, ("s" if (self.terms!=1) else ""), self.availableMoney()))
     doc.asis('<p>')
     text(self.strSkills())
     if self.personality is not None:
        doc.stag('br') 
        text('Personality: %s' % ', '.join(self.personality))       
     doc.asis('<br>') 
     text('Equipment: %s' % ', '.join(self.equipment))
     doc.asis('<br>')
     text('Possessions: %s' % ', '.join(self.possessions))
     doc.asis('<br>')       
     text('Money: %d in pocket, %d in bank, %d in pension' %
                (self.money['pocket'], self.money['bank'], self.money['pension']))
     doc.asis('<br>')
     text('Looks: %s' % self.looks)
     doc.asis('<br>')       
     #with tag('ol'):
     #   for history in self.history:
     #      with tag('li'):
     #         text(history)
     return doc.getvalue() 
コード例 #12
0
ファイル: survey_submit.py プロジェクト: vtluu/workshop
def lambda_handler(event, context):
    account_id = acc_id_from_arn(context.invoked_function_arn)
    table = get_ddb_table(account_id)
    item_data = {'id': str(account_id)}
    for param in event["queryStringParameters"]:
        value = event["queryStringParameters"][param]
        if not value:
            value = "-"
        item_data[param] = value
    table.put_item(
        Item=item_data
    )
    doc, tag, text = Doc().tagtext()
    with tag('html'):
        with tag('body'):
            with tag('div', align='center'):
                with tag('h1'):
                    count = 0
                    while count < 6:
                        count += 1
                        doc.stag('br')
                    text("Your answer was submitted!")
    html_result = doc.getvalue()
    return {
            'statusCode': "200",
            'body': html_result,
            'headers': {
                'Content-Type': 'text/html',
                "Refresh": "5;url=newsurvey",
            }
        }
コード例 #13
0
 def to_html_by_part_of_speech(self, path, file_open_modif):
     doc, tag, text = Doc().tagtext()
     groups = self.data.groupby('part_of_speech')
     with tag('strong'):
         text(', '.join(self.data.loc[:, 'word'].unique()))
     for name, group in groups:
         with tag('div', style='margin-bottom:20px;'):
             with tag('div'):
                 with tag('span', style='padding-left:10px;'):
                     with tag('strong'):
                         text(name)
             for index, row in group.iterrows():
                 with tag(
                         'div',
                         style=
                         'padding-left:20px;padding-right:20px; margin-bottom: 8px'
                 ):
                     text(row['definition'])
                     with tag('div',
                              style='padding-left:15px;color:#545454'):
                         for example in row['examples']:
                             if example != 'None':
                                 text(example)
                                 doc.stag('br')
                         # examples
     with open(path, file_open_modif) as A_file:
         A_file.write(doc.getvalue())
         A_file.write('\n\n' + '=' * 100 + '\n\n')
         A_file.close()
コード例 #14
0
    def get_html(self, report):
        doc, tag, text = Doc().tagtext()
        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('body'):
                with tag('h1'):
                    text(report.title)

                #loop report sections and output
                for section in report.sections:
                    if section.title:
                        with tag('h4'):
                            text(section.title)

                    if section.media:
                        with tag('figure'):
                            doc.stag('embed',
                                     type='image/svg+xml',
                                     src=section.media)

                    if section.comments:
                        with tag('div'):
                            for comment in section.comments:
                                text(comment)
                                doc.stag('br')

        return doc.getvalue()
コード例 #15
0
class HtmlRecorder(RecordInterface):
    @contextlib.contextmanager
    def start_draw(self, output_path, filename='index.html'):
        self._check_dir(output_path)
        self.doc, self.tag, self.text = Doc().tagtext()
        with open(os.path.join(output_path, filename), 'w') as outfile:
            with self.tag('html'):
                with self.tag('body'):
                    self.index = 1
                    yield
            result = indent(self.doc.getvalue())
            outfile.write(result)

    def draw_image(self, image, title=''):
        with self.tag('h3'):
            self.text('%d : %s' % (self.index, title))
            self.index += 1
        with self.tag('div', style='display:inline-block'):
            self.doc_image(image)

    def doc_image(self, img, width=500):
        img_buf = cv2.imencode('.jpg', img)[1]
        self.doc.stag("img",
                      style="width:%dpx;padding:5px" % width,
                      src="data:image/png;base64," +
                      str(base64.b64encode(img_buf))[2:-1])
コード例 #16
0
ファイル: changelog.py プロジェクト: MiroslavRepka/GJAR_IoT
    def save(self, path):
        print("Adding {} new changelogs.".format(self.counter))
        self.save_yaml(path)
        doc, tag, text = Doc().tagtext()
        doc.asis('<!DOCTYPE html>')
        doc.asis("<!-- AUTOMATICALLY GENERATED - NOT TO BE MODIFIED MANUALLY -->")
        with tag('html'):
            with tag("head"):
                doc.stag("meta", charset="utf-8")
                doc.line("title", "GJAR IoT Changelog")
                with open(os.path.join(path, "changelog.css"), "r") as f:
                    doc.line("style", f.read())
            with tag('body'):
                doc.line("h1", "GJAR IoT Changelog")
                doc.line("i", "Last generated: {}".format(date))
                for d in sorted(self.logs.keys()):
                    with tag("div"):
                        doc.line("h2", d)
                        with tag("ul"):
                            for item in self.logs[d]:
                                with tag("li"):
                                    doc.line("h3", item.author)
                                    with tag("ul"):
                                        for ch in item.changes:
                                            doc.line("li", ch.value, klass="type-" + ch.type)

        if not args.no_changes:
            with open(os.path.join(path, "changelog.html"), "w") as f:
                f.write(indent(doc.getvalue()))
            verbose("Saving changelog.html")
        else:
            verbose("Would save changelog.html")
コード例 #17
0
ファイル: view.py プロジェクト: pigpenguin/netlify-test
def render_users():
    users, stats = User.compute_stats()
    print("rendering user pages")
    with ProgressBar(max_value = len(users)) as bar:
        for i, data in enumerate(users):
            steam_id = data[0]
            user = data[1]
            path="users/{}/".format(steam_id)
            yield path, user_html(user)
            bar.update(i)

    print("rendering user index page")
    doc, tag, text, line = Doc().ttl()
    with tag("header"):
        line("h1", "Users")
        doc.stag("hr")
        with tag("p"):
            text("There are a total of ")
            line("b", "{:,}".format(stats["total users"]))
            text(" players with a total of ")
            line("b", "{:,}".format(stats["total times"]))
            text(" times set for an average of ")
            line("b", "{:,}".format(stats["average times"]))
            text(" times per player.")
        doc.stag("hr")
    with tag("div", klass="body"):
        with tag("table", klass="user-list"):
            with tag("tb"):
                doc.asis(user_list(users))

    yield "users", template(doc.getvalue())
コード例 #18
0
def get_multiple_systems_html_report(orig_sents, sys_sents_list, refs_sents, system_names, test_set, lowercase, tokenizer, metrics):
    doc = Doc()
    doc.asis('<!doctype html>')
    with doc.tag('html', lang='en'):
        doc.asis(get_head_html())
        with doc.tag('body', klass='container-fluid m-2 mb-5'):
            doc.line('h1', 'EASSE report', klass='mt-4')
            with doc.tag('a', klass='btn btn-link', href='https://forms.gle/J8KVkJsqYe8GvYW46'):
                doc.text('Any feedback welcome!')
            doc.stag('hr')
            doc.line('h2', 'Test set')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_test_set_description_html(
                    test_set=test_set,
                    orig_sents=orig_sents,
                    refs_sents=refs_sents,
                ))
            doc.line('h2', 'Scores')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.line('h3', 'System vs. Reference')
                doc.stag('hr')
                doc.asis(get_score_table_html_multiple_systems(orig_sents, sys_sents_list, refs_sents, system_names, lowercase, tokenizer, metrics))
            doc.line('h2', 'Qualitative evaluation')
            doc.stag('hr')
            with doc.tag('div', klass='container-fluid'):
                doc.asis(get_multiple_systems_qualitative_examples_html(orig_sents, sys_sents_list, refs_sents, system_names))
    return indent(doc.getvalue())
コード例 #19
0
def save_html(html_name, messages):
    doc, tag, text = Doc().tagtext()
    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('body', style="background-color: #edeef0;"):
            for message in messages:
                with tag('div', style="margin: 5px;"):
                    with tag('span',
                             style="margin-right: 5px;font-weight: bold;"):
                        text(message['name'])
                    with tag('span', style="color: gray;"):
                        text(time.ctime(message['date']))
                    with tag(
                            'p',
                            style=
                            "margin: 6px;margin-left: 0px;margin-bottom: 11px;"
                    ):
                        text(message["text"])
                    if len(message["photos"]) != 0:
                        with tag('div', style="height: 150px;"):
                            for photo in message["photos"]:
                                doc.stag('img',
                                         style="height: 100%;",
                                         src=photo)

    with open(html_name, "w") as f:
        f.write(doc.getvalue())
コード例 #20
0
ファイル: plots.py プロジェクト: protivinsky/python-utils
    def save(self, path, inner=False):
        os.makedirs(path, exist_ok=True)
        n = len(self.figs)
        for i in range(n):
            self.figs[i].savefig(f'{path}/fig_{i+1:03d}.{self.format}')
        plt.close('all')

        doc, tag, text = Doc().tagtext()

        doc.asis('<!DOCTYPE html>')
        with tag('html'):
            with tag('head'):
                with tag('title'):
                    text(self.title or 'Chart')
            with tag('body'):
                with tag('h1'):
                    text(self.title or 'Chart')
                num_rows = (n + self.cols - 1) // self.cols
                for r in range(num_rows):
                    with tag('div'):
                        for c in range(min(self.cols, n - self.cols * r)):
                            doc.stag('img', src=f'fig_{self.cols * r + c + 1:03d}.{self.format}')

        file = open('{}/page.htm'.format(path), 'w', encoding='utf-8')
        file.write(indent(doc.getvalue()))
        file.close()
コード例 #21
0
ファイル: pubtator.py プロジェクト: tagtog/PubTator2Anndoc
    def __to_html(self, pmid, title, abstract, output_dir):
        """Generate HTML file for Anndoc

        Write a HTML file required for Anndoc, formatted according to TagTog's
        standards that can be viewed at the link below.
        https://github.com/jmcejuela/tagtog-doc/wiki

        By default, the MEDLINE identifier will be used as the title, unless
        something else is specified.

        Args:
            title (str): Title of the paper
            abstract (str): Abstract contents of the paper
            output_file (Optional[str]): Path to the output file. Defaults to
                                        none.

        """
        from yattag import Doc
        from yattag import indent
        from os.path import join

        doc, tag, text = Doc().tagtext()

        # Compute hashId (TODO find out what hashing is used, currently random)
        hashId = self.__random_hashId(pmid)

        # Use Yattag to generate HTML syntax
        doc.asis('<!DOCTYPE html>')
        with tag('html',
                ('data-origid', pmid),
                ('data-anndoc-version', "2.0"),
                ('lang', ""), ('xml:lang', ""),
                ('xmlns', "http://www.w3.org/1999/xhtml"),
                klass='anndoc',
                id=hashId):
            with tag('head'):
                doc.stag('meta', charset='UTF-8')
                doc.stag('meta', name='generator', content='org.rostlab.relna')
                with tag('title'):
                    text(hashId)
            with tag('body'):
                with tag('article'):
                    with tag('section', ('data-type', 'title')):
                        with tag('h2', id='s1h1'):
                            text(title)
                    with tag('section', ('data-type', 'abstract')):
                        with tag('h3', id='s2h1'):
                            text("Abstract")
                        with tag('div', klass='content'):
                            with tag('p', id='s2p1'):
                                text(abstract)

        # Write to file
        result = indent(doc.getvalue())
        try:
            with open(join(output_dir, pmid+'.html'), 'w') as fw:
                fw.write(result)
        except IOError as e:
            print('I/O Error({0}): {1}'.format(e.errno, e.strerror))
            raise
コード例 #22
0
ファイル: genHtmlKPose.py プロジェクト: mtlong/poseLabel
def main():
    numRecord = 1000
    numCol = 5
    numRow = numRecord // numCol
    htmldoc, htmltag, htmltext = Doc().tagtext()
    htmldoc.asis('<!DOCTYPE html>')
    with htmltag('html'):
        with htmltag('head'):
            with htmltag('style'):
                htmldoc.asis('table,th,td{')
                htmldoc.asis('border: 1px solid black;')
                htmldoc.asis('align: center;')
                htmldoc.asis('}')

        with htmltag('body'):
            with htmltag('h2', align='center'):
                htmltext('K-mean K pose Visualization :K=1000')
            with htmltag('table'):
                for row in range(numRow):
                    with htmltag('tr'):
                        for col in range(numCol):
                            idx = row * numCol + col
                            imgName = '{:04d}.jpg'.format(idx)
                            with htmltag('td', colspan='2'):
                                htmldoc.stag('img',
                                             src='K_pose_Adam/' + imgName,
                                             width='300')

    htmlFile = open(outprefix + 'KPose.html', 'w')
    htmlFile.write(htmldoc.getvalue())
    htmlFile.close()
コード例 #23
0
 def get_html(self):
     doc, tag, text = Doc().tagtext()
     with tag('div'):
         text(self.name)
         stripped_name = self.name.replace(" ", "-")
         doc.stag('input', type='file', id='upload-file-'+stripped_name, name=stripped_name)
     return doc.getvalue()
コード例 #24
0
ファイル: figure.py プロジェクト: noisyoscillator/MaTiSSe
 def to_html(self):
     """Convert self data to its html stream."""
     doc = Doc()
     with doc.tag('div', id='Figure-' + str(self.number)):
         if self.style:
             doc.attr(style=self.style)
         else:
             doc.attr(klass='figure')
         with doc.tag(self.ctn_type):
             if self.cap_position is not None and self.cap_position.upper(
             ) == 'TOP':
                 self.put_caption(doc=doc, klass='figure-caption')
             if self.ctn_options:
                 doc.stag('img',
                          src=self.ctn,
                          klass='figure-content',
                          style=self.ctn_options,
                          alt='Figure-' + self.ctn)
             else:
                 doc.stag('img',
                          src=self.ctn,
                          klass='figure-content',
                          style='width:100%;',
                          alt='Figure-' + self.ctn)
             if self.cap_position is None or self.cap_position.upper(
             ) == 'BOTTOM':
                 self.put_caption(doc=doc, klass='figure-caption')
     return doc.getvalue()
コード例 #25
0
ファイル: utils.py プロジェクト: RinatR/ad_and_israel
def generate_html(banner_image, trafkey, campaign_hash):

    click_count_url = f"https://log.rinads.com/?src=bw&s_act=c&trk={trafkey}"
    nurl_count_url = f"https://log.rinads.com/?src=bw&s_act=n&trk={trafkey}"
    impression_count_url = f"https://log.rinads.com/?src=bw&s_act=s&trk={trafkey}"

    # print(banner_image.split('/'))
    splitted_banner_image_path = banner_image.split('/')
    doc, tag, text = Doc().tagtext()
    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('meta', charset="utf-8"):
                with tag(
                        'meta',
                        name="viewport",
                        content=
                        "width=device-width, initial-scale=1, shrink-to-fit=no"
                ):
                    with tag('body'):
                        with tag('a', href=click_count_url, target="_blank"):
                            doc.stag('img',
                                     src="/static/campaigns/" + campaign_hash +
                                     "/" + splitted_banner_image_path[-1],
                                     klass="banner")
    return doc.getvalue()
コード例 #26
0
def generate_html_string(users):
    """
    generate html table from users dictionary
    returns html code string
    """
    headers = ['First Name', 'Last Name', 'Picture']
    doc, tag, text = Doc().tagtext()
    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('title'):
                text('10clouds_1sun')
        with tag('body'):
            with tag('h1'):
                text('Random users:')
            with tag('table', style='width:50%'):
                # header
                with tag('tr'):
                    for header  in headers:
                        with tag('th'):
                            text(header)
                # data
                for user in users:
                    with tag('tr'):
                        with tag('td'):
                            text(user['name']['first'])
                        with tag('td'):
                            text(user['name']['last'])
                        with tag('td'):
                            doc.stag('img', src=thumbnail_path(user))
    return doc.getvalue()
コード例 #27
0
def _figure_to_html(fig: Figure):
    doc = Doc()
    if fig.rel_save_path:
        doc.stag("img", src=fig.rel_save_path, width=f"{fig.scale * 100}%")
    else:
        doc.stag('img', src=f'data:image/{fig.extension};base64,{fig.content}')
    return doc.getvalue()
コード例 #28
0
ファイル: html.py プロジェクト: fennekki/unikko
def html_from_tree(tree):
    """Generate indented HTML from VOTL Object tree.

    Params:
        tree (Object): A VOTL Object containing the tree, from which HTML will
                       be generated.

    Returns: String containing a pretty-formatted HTML document.
    """
    doc, tag, text = Doc().tagtext()

    doc.asis("<!DOCTYPE html>")

    first = tree.children[0]
    if first.object_type == "header":
        title = first.first_line
    else:
        title = "Untitled"

    with tag("html"):
        with tag("head"):
            with tag("title"):
                text(title)
            doc.stag("meta", charset="utf-8")
        with tag("body"):
            _recurse_tags(tree, doc, tag, text)

    return indent(doc.getvalue())
コード例 #29
0
ファイル: apple_modal.py プロジェクト: Nixer/apple_modal
def html_generate(url_list):
    file = open(os.getcwd() + "/styles.css", "r")
    css = file.read()
    file.close()
    css = html.unescape(css)
    dirname = md(url_list[0][1])
    doc, tag, text, line = Doc().ttl()
    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('style'):
                text(css)
        with tag('body'):
            with tag('table'):
                for i in range(len(url_list)):
                    with tag('tr'):
                        with tag('td'):
                            doc.stag('img',
                                     src=url_list[i][0],
                                     width="50%",
                                     height="50%")
                        with tag('td', ('align', 'left')):
                            with tag('a', ('href', url_list[i][1])):
                                text(url_list[i][1])
    with open(dirname + "/report.html", "w") as f:
        f.write(indent(doc.getvalue()))
コード例 #30
0
    def reading(self,question,mode):
        '''
        This renders a reading question

        Returns
        -------
        tuple (str,int)
            the string is the doc tree to send to the output, the int is the
            required number of pixels to rais the subsequent hiragana block
            - this should be a negative number and will be used as a partameter
            to css margin-left attribute
        '''

        doc, tag, text = Doc().tagtext()
        rise_next = 0
        #create the tags
        with tag('div',('class','kanji_reading-'+self.render_mode[mode])):
            with tag('div'):
                # extract the kanji characters and out put them in the div
                text(question[0:question.find(self.te_reading)])
            # check if the question needs more space for the hiragaana te_writing
            # this is requested by adding 'japanse spaces' to the kanji characeter
            if (' ' in question[0:question.find(self.te_reading)]):
                rise_next = -40 #if so then tell the main rendere to raise the next hiragana block

            # now eat the block nom nom nom
            with tag('div',('class','kanji_reading_brackets-'+self.render_mode[mode])):
                doc.stag('img', src='/static/top_bracket.png', width="100%")
                with tag('div'):
                    for i in range(len(question[0:question.find(self.te_reading)])):
                        with tag('span',('class','kanji-reading-spacer')):
                            text(' ')
                doc.stag('img', src='/static/btm_bracket.png', width="100%")
        return (doc.getvalue(), rise_next)
コード例 #31
0
def generateHTML(documents, category):
    doc, tag, text = Doc().tagtext()

    with tag('html'):
        with tag('body'):
            for document in documents:
                with tag('div', id='news', align='center'):
                    with tag('h1'):
                        text("Category:")

                    text(category)

                    with tag('h1'):
                        text("Keywords:")

                    with tag('div', id='photo-container'):
                        path = "img/" + category + "-plt.png"
                        doc.stag('img', src=path, klass="photo")
                        with tag('br'):
                            pass
                        path = "img/" + category + "-cloud.png"
                        doc.stag('img', src=path, klass="photo")

                with tag('br'):
                    pass

    return doc.getvalue()
コード例 #32
0
ファイル: article.py プロジェクト: gnouf1/ActualiT
def model(A):
    doc, tag, text, line = Doc().ttl()
    try:
        with tag('html'):
            with tag('body'):
                # Download the image
                if A.lien_img is not None and A.lien_img != '':
                    try:
                        urllib.request.urlretrieve(A.lien_img,
                                                   "cache/articleImg.png")
                        with tag('div', klass='Front image'):
                            doc.stag('img',
                                     align="middle",
                                     height='300',
                                     src='cache/articleImg.png')
                    except:
                        pass
                line('h1', A.titre)
                with tag('b', klass='SourceAndAuthor'):
                    if A.auteur is not None:
                        text(A.auteur + "  |  ")
                    text(A.info_source)

                    doc.stag('br')

                with tag('div', klass='description'):
                    text(A.resume)

                with tag('a', href=A.lien):
                    line('b', '\nEn voir plus...')
    except TypeError as e:
        print(e)
    return doc.getvalue()
コード例 #33
0
def getUnderstandReport(udb_path, report_dir_path):

    # set plotly credentials
    plotly.tools.set_credentials_file(username='', api_key='')

    # open the udb file
    db = understand.open(udb_path)
    images = []

    for a in db.root_archs():
        if (len(a.children()) > 0):
            for child in a.children():
                #print(child.longname())
                child.draw(
                    'Internal Dependencies',
                    report_dir_path + '/dependency_' + child.name() + '.png')
                images.append('dependency_' + child.name() + '.png')

    metric_list = 'CountLineBlank', 'CountLineCode', 'CountLineCodeDecl', 'CountLineCodeExe', 'CountLineComment'
    met = db.metric(metric_list)
    trace = go.Pie(labels=list(met.keys()), values=list(met.values()))
    plot = [trace]
    layout = go.Layout(title='Code Lines', width=800, height=640)
    fig = go.Figure(data=plot, layout=layout)

    py.image.save_as(fig, filename=report_dir_path + '/code_lines.png')

    db.close()

    doc, tag, text = Doc().tagtext()
    doc.asis('<!DOCTYPE html>')
    with tag('html'):
        with tag('head'):
            with tag('style'):
                text(
                    'table, th, td {border: 1px solid black; border-collapse: collapse; padding:10px;white-space: nowrap;}'
                )
        with tag('body'):
            with tag('h1'):
                text('Code BreakDown')
            with tag('table'):
                for key, value in met.items():
                    with tag('tr'):
                        with tag('td'):
                            text(key)
                        with tag('td'):
                            text(value)
            doc.stag('img', src=report_dir_path + '/code_lines.png')
            with tag('h1'):
                text('Dependency Graphs')
            for image in images:
                doc.stag('img', src=report_dir_path + "/" + image)

    report = open(report_dir_path + "/report.html", "w")
    report.write(doc.getvalue())
    report.close()


#getUnderstandReport(udbPath, abspathname + '/'+repo_name)
コード例 #34
0
ファイル: actions.py プロジェクト: orenmazor/oozie.py
    def as_xml(self, indentation=False):
        doc, tag, text = Doc().tagtext()
        with tag('sub-workflow'):
            with tag('app-path'):
                text("/"+self.sub_wf_path + "/" + self.name)
            doc.stag("propagate-configuration")

        xml = doc.getvalue()
        if indentation:
            return indent(xml)
        else:
            return xml
コード例 #35
0
ファイル: test_datasets.py プロジェクト: dvischi/TissueMAPS
 def as_junit_xml(self):
     xml, tag, text = XML().tagtext()
     with tag('testcase',
              name=self.name,
              time=(self.stop - self.start)):
         if self.classname is not None:
             xml.attr(classname=self.classname)
         if self.assertions is not None:
             xml.attr(assertions=self.assertions)
         with tag('properties'):
             for key, value in self._properties.iteritems():
                 xml.stag('property', name=key, value=str(value))
         if self.status == 'error':
             with tag('error', message=self._msg):
                 text(self._msg)
         elif self.status == 'failure':
             with tag('failure', message=self._msg):
                 text(self._msg)
         elif self.status == 'skipped':
             xml.stag('skipped', message=self._msg)
         if self.stdout is None:
             xml.stag('system-out')
         else:
             with tag('system-out'):
                 text(str(self.stdout))
         if self.stderr is None:
             xml.stag('system-err')
         else:
             with tag('system-err'):
                 text(str(self.stderr))
     return xml.getvalue()
コード例 #36
0
ファイル: fromGIFT.py プロジェクト: CultureNumerique/cn_app
    def to_html(self, feedback_option=False):
        """ From a question object, write HTML representation """
        doc, tag, text = Doc().tagtext()
        # FIXME : add comment line here ?
        doc.asis('\n')
        doc.asis('<!-- New question -->')
        with tag('div', klass='question'):
            with tag('h3', klass='questiontitle'):
                text(self.title)
            with tag('div', klass='questiontext'):
                if self.text_format == 'html':
                    doc.asis(self.text)
                else:
                    logging.info ("printing Markdown/ source = %s" % (self.text))
                    html_text = markdown.markdown(self.text, MARKDOWN_EXT, output_format='xhtml')
                    doc.asis(html_text)
            # If type MULTICHOICE, MULTIANSWER give choices
            if self.type in ['MULTICHOICE', 'MULTIANSWER', 'TRUEFALSE']:
                with tag('ul', klass=self.type.lower()):
                    for answer in self.answers:
                        if self.type in ['MULTICHOICE', 'TRUEFALSE']:
                            if answer['is_right'] and bool(feedback_option):
                                answer_class = 'right_answer'
                            elif bool(feedback_option):
                                answer_class = 'wrong_answer'
                            else:
                                answer_class = ''
                            with tag('li', klass=answer_class):
                                doc.stag('input', type='radio', name="name")
                                doc.asis(answer['answer_text'].strip('</p>'))
                        elif self.type == 'MULTIANSWER':
                            if float(answer['credit']) > 0.0 and feedback_option:
                                answer_class = 'right_answer'
                            elif feedback_option:
                                answer_class = 'wrong_answer'
                            else:
                                answer_class = ''
                            with tag('li', klass=answer_class):
                                doc.stag('input', type='checkbox', name="name")
                                doc.asis(answer['answer_text'].strip('</p>'))

            if (feedback_option and len(self.global_feedback) > 1):
                with tag('div', klass='global_feedback'):
                    doc.asis('<b><em>Feedback:</em></b><br/>'+self.global_feedback)
        doc.asis('\n\n')
        return((doc.getvalue()))
コード例 #37
0
def generate_html(img_data, obj_type, lat, lng, loc_num):
    doc, tag, text = Doc().tagtext()

    with tag("html"):
        with tag("body"):
            with tag('h2'):
                text("%ss near (%f, %f)" % (obj_type, lat, lng))
            for img in img_data:
                with tag("a", href=img["link"], id="sat-img-container"):
                    doc.stag("img", src=img["path"])
                with tag("p"):
                    text("%s at (%f, %f)" % (obj_type, img["lat"], img["lng"]))

    html_to_write = doc.getvalue()

    with open("%s%d.html" % (obj_type, loc_num), "w") as f:
        f.write(html_to_write)
コード例 #38
0
ファイル: figure.py プロジェクト: szaghi/MaTiSSe
 def to_html(self):
   """Convert self data to its html stream."""
   doc = Doc()
   with doc.tag('div', id='Figure-' + str(self.number)):
     if self.style:
       doc.attr(style=self.style)
     else:
       doc.attr(klass='figure')
     with doc.tag(self.ctn_type):
       if self.cap_position is not None and self.cap_position.upper() == 'TOP':
         self.put_caption(doc=doc, klass='figure-caption')
       if self.ctn_options:
         doc.stag('img', src=self.ctn, klass='figure-content', style=self.ctn_options, alt='Figure-' + self.ctn)
       else:
         doc.stag('img', src=self.ctn, klass='figure-content', style='width:100%;', alt='Figure-' + self.ctn)
       if self.cap_position is None or self.cap_position.upper() == 'BOTTOM':
         self.put_caption(doc=doc, klass='figure-caption')
   return doc.getvalue()
コード例 #39
0
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    
    doc, tag, text = Doc().tagtext()
    
    doc.asis('<!DOCTYPE html>')
    with tag('head'):
        doc.stag('meta', name = 'viewport', content = 'width=device-width, initial-scale=1')
        with tag('title'):
            text('Chameleon Docker Demo')
        doc.stag('link', rel = 'stylesheet', href = 
        'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css')
    with tag('body'):
        with tag('div', klass = 'container-fluid'):
            with tag('div', klass = 'row'):
                with tag('div', klass = 'col-xs-12 col-md-6 col-md-offset-3'):
                    with tag('h1', klass = 'text-center'):
                        text('Chameleon Cloud Docker Demo')
                    input_file = codecs.open("description.md", mode="r")
                    doc.asis(str(markdown.markdown(input_file.read())))
                    input_file.close()
            try:
                with tag('div', klass = 'row'):
                    with tag('div', klass = 'col-xs-12 col-md-2 col-md-offset-5'):
                        with tag('div', klass = 'list-group'):
                            conn = psycopg2.connect(host = socket.gethostbyname('postgres'), user = '******',
                            password = '******', database = 'docker')
                            cur = conn.cursor()
                            cur.execute('select name from demosite')
                            for row in cur.fetchall():
                                with tag('div', klass = 'list-group-item'):
                                    text(row[0])
                            cur.close()
                            conn.close()
            except:
                print "Postgres error:", sys.exc_info()
                with tag('div', klass = 'row'):
                    with tag('div', klass = 'col-xs-12 col-md-6 col-md-offset-3'):
                        with tag('div', klass = 'alert alert-warning text-center', role = 'alert'):
                            with tag('b'):
                                text('Error!')
                            text(' ')
                            text('Unable to retrieve database items.')
    return doc.getvalue()
コード例 #40
0
ファイル: video.py プロジェクト: nunb/MaTiSSe
 def to_html(self):
   """Convert self data to its html stream."""
   doc = Doc()
   with doc.tag('div', id='video-' + str(self.number)):
     if self.style:
       doc.attr(style=self.style)
     else:
       doc.attr(klass='video')
     if self.cap_position is not None and self.cap_position.upper() == 'TOP':
       self.put_caption(doc=doc, klass='video-caption')
     with doc.tag('video', klass='video-content', controls=''):
       if self.ctn_options:
         doc.attr(style=self.ctn_options)
       else:
         doc.attr(style='width:100%;')
       doc.stag('source', src=self.ctn)
     if self.cap_position is None or self.cap_position.upper() == 'BOTTOM':
       self.put_caption(doc=doc, klass='video-caption')
   return doc.getvalue()
コード例 #41
0
ファイル: metadata.py プロジェクト: szaghi/MaTiSSe
  def logo_to_html(self, match):
    """Convert logo metadata to html stream.

    Parameters
    ----------
    match: re.match object

    Returns
    -------
    str:
      html stream
    """
    doc = Doc()
    style = None
    if match.group('style'):
      style = str(match.group('style'))
    if style is not None:
      doc.stag('img', src=self.value, alt=self.value, style=style)
    else:
      doc.stag('img', src=self.value, alt=self.value)
    return doc.getvalue()
コード例 #42
0
ファイル: video.py プロジェクト: nunb/MaTiSSe
 def to_html(self):
     """Convert self data to its html stream."""
     doc = Doc()
     with doc.tag("div", id="video-" + str(self.number)):
         if self.style:
             doc.attr(style=self.style)
         else:
             doc.attr(klass="video")
         if self.cap_position is not None and self.cap_position.upper() == "TOP":
             self.put_caption(doc=doc, klass="video-caption")
         with doc.tag("video", klass="video-content"):
             if self.controls:
                 doc.attr(controls="controls")
             if self.autoplay:
                 doc.attr(autoplay="autoplay")
             if self.ctn_options:
                 doc.attr(style=self.ctn_options)
             else:
                 doc.attr(style="width:100%;")
             doc.stag("source", src=self.ctn)
         if self.cap_position is None or self.cap_position.upper() == "BOTTOM":
             self.put_caption(doc=doc, klass="video-caption")
     return doc.getvalue()
コード例 #43
0
ファイル: figure.py プロジェクト: nunb/MaTiSSe
 def to_html(self):
   """Method for inserting box to the html doc."""
   doc = Doc()
   with doc.tag('div',klass='figure'):
     doc.attr(('id','Figure-'+str(self.number)))
     if self.style:
       doc.attr(style=self.style)
     elif Figure.theme.data.data['style'][0]:
       doc.attr(style=Figure.theme.data.data['style'][0])
     with doc.tag(self.ctn_type):
       if self.ctn_options:
         doc.stag('img',src=self.ctn,klass='image',style=self.ctn_options,alt='Figure-'+self.ctn)
       elif Figure.theme.data.data['content'][0]:
         doc.stag('img',src=self.ctn,klass='image',style=Figure.theme.data.data['content'][0],alt='Figure-'+self.ctn)
       else:
         doc.stag('img',src=self.ctn,klass='image',style='width:100%;',alt='Figure-'+self.ctn)
       self.put_caption(doc=doc)
   return doc.getvalue()
コード例 #44
0
def outputHTML(downloadFolder):
    #downloadFolder = getOutputFolder(outputConfig)
    videos = ('.mp4','.webm')
    #downloadFolder = './images_20160214_2129/'
    doc, tag, text = Doc().tagtext()
    with tag('html'):
        with tag('head'):
            with tag('title'):
                text('Any old title')
            with tag('style'):
                text('body { background-color: black; }')
                text('h1 { color: maroon; margin-left: 40px; } ')
                text('img.displayed { display: block; margin-left: auto; margin-right: auto }')
                text('video.displayed { display: block; margin-left: auto; margin-right: auto }')
        with tag('body'):
            for eachItem in os.listdir(downloadFolder):
                if (eachItem.endswith(videos)):
                    doc.asis('<video width="540" class="displayed" controls><source src="'+eachItem+'" ></video>')
                    #with tag('video', width='540', klass='displayed', src=eachItem):
                    #with tag('video', width='540', klass='displayed'):
                    #    doc.stag('source', src=eachItem)
                    doc.stag('br')
                elif (not eachItem.startswith('.')):
                    image = os.path.join(downloadFolder, eachItem)
                    try:
                        img = Image.open(image)
                        width,height = img.size
                        outputWidth, outputHeight = calculateImgOutputSizes(width,height)
                        with tag('a', href=eachItem):
                            doc.stag('img', style="width:"+str(outputWidth)+"px; height:"+str(outputHeight)+"px;)", klass='displayed', src=eachItem)
                            doc.stag('br')
                    except:
                        logger.error("An error occurred while processing "+image+". Skipping.")
    
    with open(downloadFolder+'index.htm', 'a') as out: out.write(indent(doc.getvalue(), indent_text = True))
    print('HTML saved to '+downloadFolder+'index.htm')
    logger.info('HTML saved to '+downloadFolder+'index.htm')
コード例 #45
0
ファイル: toIMS.py プロジェクト: nburlot/cn_app
def create_ims_test(questions, test_id, test_title):
    """
    Supported types : ESSAY, MULTICHOICE, MULTIANSWER, TRUEFALSE, DESCRIPTION 
    
    """
    # create magic yattag triple
    doc, tag, text = Doc().tagtext()
    doc.asis(HEADER_TEST+'\n')
    if 'ESSAY' in questions[0].type:
        max_attempts = 'unlimited' 
    else:
        max_attempts = 1
    with tag('assessment', ident=test_id, title=test_title):
        doc.asis(set_qti_metadata(max_attempts))
        #<!-- Titre de l'execercice  -->
        with tag('rubric'):
            with tag('material', label="Summary"):
                with tag('mattext', texttype="text/html"):
                    text()
        # only one section in a test
        with tag('section', ident='section_1_test_'+test_id):
        # loop on questions
            for idx, question in enumerate(questions):
                with tag('item', ident='q_'+str(idx), title=question.title):
                    #<!--  metatata  -->
                    with tag('itemmetadata'):
                        with tag('qtimetadata'):
                            with tag('qtimetadatafield'):
                                with tag('fieldlabel'):
                                    text("cc_profile")
                                with tag('fieldentry'):
                                    #print ("question = %s \ntype ? %s \n" % (question.text, question.type ))
                                    try:
                                        text(CC_PROFILES[question.type])
                                    except:
                                        # default to essay
                                        text(CC_PROFILES['ESSAY'])
                            with tag('qtimetadatafield'):
                                with tag('fieldlabel'):
                                    text("cc_question_category")
                                with tag('fieldentry'):
                                    text('Quiz Bank '+test_title)
                    #Contenu de la question 
                    with tag('presentation'):
                        # Enoncé
                        with tag('material'):
                            with tag('mattext', texttype='text/html'):
                                text(question.text)
                        # réponses possibles
                        if 'ESSAY' in question.type:
                            with tag('response_str', rcardinality='Single', ident='response_'+str(question.id)):
                                doc.stag('render_fib', rows=5, prompt='Box', fibtype="String")
                        elif question.type in (('MULTICHOICE', 'MULTIANSWER', 'TRUEFALSE')):
                            if question.type == 'MULTIANSWER':
                                rcardinality = 'Multiple'
                            else:
                                rcardinality = 'Single'
                            # rcardinality optional, but a priori 'Single' form MChoice, 'Multiple' for Manswer; 
                            with tag('response_lid', rcardinality=rcardinality, ident='response_'+str(question.id)):
                                with tag('render_choice', shuffle='No'):
                                    for id_a, answer in enumerate(question.answers):
                                        with tag('response_label', ident='answer_'+str(question.id)+'_'+str(id_a)):
                                            with tag('material'):
                                                with tag('mattext', texttype="text/html"):
                                                    text(answer['answer_text'])
                        else: # FIXME add support for NUMERIC, MATCHING, etc
                            pass
                    # Response Processing
                    with tag('resprocessing'):
                        # outcomes: FIXME: allways the same ?
                        with tag('outcomes'):
                            doc.stag('decvar', varname='SCORE', vartype='Decimal', minvalue="0", maxvalue="100")
                        # respconditions pour décrire quelle est la bonne réponse, les interactions, etc
                        ## pour afficher le ne pourrait-elle pas feedback general
                        if question.global_feedback != '':
                            with tag('respcondition', title='General feedback', kontinue='Yes'):
                            #with tag('respcondition', title='General feedback'):
                                with tag('conditionvar'):
                                    doc.stag('other')
                                doc.stag('displayfeedback', feedbacktype="Response", linkrefid='general_fb')
                        ## lister les autres interactions/conditions
                        if question.type in (('MULTICHOICE','TRUEFALSE')):
                            for id_a, answer in enumerate(question.answers):
                                score = 0
                                if answer['is_right']:
                                    title = 'Correct'
                                    score = 100
                                else:
                                    title = ''
                                    score = answer['credit']
                                with tag('respcondition', title=title):
                                    with tag('conditionvar'):
                                        with tag('varequal', respident='response_'+str(question.id)): # respoident is id of response_lid element
                                            text('answer_'+str(question.id)+'_'+str(id_a))
                                    with tag('setvar', varname='SCORE', action='Set'):
                                        text(score)
                                    doc.stag('displayfeedback', feedbacktype='Response', linkrefid='feedb_'+str(id_a))
                        elif question.type == 'MULTIANSWER':
                            # Correct combination
                            with tag('respcondition', title="Correct", kontinue='No'):
                                with tag('conditionvar'):
                                    with tag('and'):
                                        for id_a, answer in enumerate(question.answers):
                                            score = 0
                                            try:
                                                score = float(answer['credit'])
                                            except:
                                                pass
                                            if score <= 0:
                                                with tag('not'):
                                                    with tag('varequal', case='Yes', respident='response_'+str(question.id)): # respoident is id of response_lid element
                                                        text('answer_'+str(question.id)+'_'+str(id_a))
                                            else:
                                                with tag('varequal', case='Yes', respident='response_'+str(question.id)): # respoident is id of response_lid element
                                                    text('answer_'+str(question.id)+'_'+str(id_a))
                                with tag('setvar', varname='SCORE', action='Set'):
                                    text('100')
                                doc.stag('displayfeedback', feedbacktype='Response', linkrefid='general_fb')
                            # default processing in any case
                            for id_a, answer in enumerate(question.answers):    
                                with tag('respcondition', kontinue='No'):
                                    with tag('conditionvar'):
                                        with tag('varequal', respident='response_'+str(question.id), case="Yes"):    
                                            text('answer_'+str(question.id)+'_'+str(id_a))     
                                    doc.stag('displayfeedback', feedbacktype='Response', linkrefid='feedb_'+str(id_a))      
                        else:
                            pass
                    # liste les feedbacks 
                    ## feedback general
                    if question.global_feedback != '':
                        with tag('itemfeedback', ident='general_fb'):
                            with tag('flow_mat'):
                                with tag('material'):
                                    with tag('mattext', texttype='text/html'):
                                        text(question.global_feedback)
                    ## autres feedbacks
                    for id_a, answer in enumerate(question.answers):
                        with tag('itemfeedback', ident='feedb_'+str(id_a)):
                            with tag('flow_mat'):
                                with tag('material'):
                                    with tag('mattext', texttype='text/html'):
                                        text(answer['feedback'])
                    ## FIXME add wrong and correct feedbacks for TRUEFALSE
    doc.asis('</questestinterop>\n')
    doc_value = indent(doc.getvalue())
    doc_value = doc_value.replace('kontinue', 'continue')
    return doc_value
コード例 #46
0
ファイル: toIMS.py プロジェクト: CultureNumerique/cn_module_1
def generateIMSManifest(data):
    """ parse data from config file 'toIMSconfig.json' and recreate imsmanifest.xml """
    # create magic yattag triple
    doc, tag, text = Doc().tagtext()
    # open tag 'manifest' with default content:
    doc.asis('<?xml version="1.0" encoding="UTF-8"?><manifest xmlns="http://www.imsglobal.org/xsd/imsccv1p1/imscp_v1p1" xmlns:lomimscc="http://ltsc.ieee.org/xsd/imsccv1p1/LOM/manifest" xmlns:lom="http://ltsc.ieee.org/xsd/imsccv1p1/LOM/resource" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" identifier="M_3E1AEC6D" xsi:schemaLocation="http://www.imsglobal.org/xsd/imsccv1p1/imscp_v1p1 http://www.imsglobal.org/profile/cc/ccv1p1/ccv1p1_imscp_v1p2_v1p0.xsd http://ltsc.ieee.org/xsd/imsccv1p1/LOM/manifest http://www.imsglobal.org/profile/cc/ccv1p1/LOM/ccv1p1_lommanifest_v1p0.xsd http://ltsc.ieee.org/xsd/imsccv1p1/LOM/resource http://www.imsglobal.org/profile/cc/ccv1p1/LOM/ccv1p1_lomresource_v1p0.xsd">')
    # Print metadata
    with tag('metadata'):
        with tag('schema'):
            text('IMS Common Cartridge')
        with tag('schemaversion'):
            text('1.1.0')
        with tag('lomimscc:lom'):
            with tag('lomimscc:general'):
                with tag('lomimscc:title'):
                    with tag('lomimscc:string', language=data["lom_metadata"]["language"]):
                        text(data["lom_metadata"]["title"])
                with tag('lomimscc:language'):
                    text(data["lom_metadata"]["language"])
                with tag('lomimscc:description'):
                    doc.stag('lomimscc:string', language=data["lom_metadata"]["language"])
                with tag('lomimscc:identifier'):
                    with tag('lomimscc:catalog'):
                        text('category')
                    with tag('lomimscc:entry'):
                        text(data["lom_metadata"]["category"])
    # Print organization
    resources = []
    with tag('organizations'):
        with tag('organization', identifier="organization0", structure='rooted-hierarchy'):
            with tag('item', identifier='root'):
                for idA, section in enumerate(data["sections"]):
                    section_id = "sec_"+(str(idA))
                    with tag('item', identifier=section_id):
                        with tag('title'):
                            text(str(idA))
                        for idB, subsection in enumerate(data["sections"][idA]["subsections"]):
                            href = data["sections"][idA]["subsections"][idB]["source_file"]
                            filename = href.rsplit('/',1)[1]
                            resources.append(filename)
                            with tag('item', identifier=("subsec_"+str(idA)+"_"+str(idB)), identifierref=("doc_"+str(idA)+"_"+str(idB))):
                                with tag('title'):
                                    text(data["sections"][idA]["subsections"][idB]["title"])
    # Print resources
    with tag('resources'):
        # retrieve images and add dependency when needed
        doc.asis("<!-- Images -->")
        images = {}
        for idx, filename in enumerate(os.listdir(os.getcwd()+'/img')):
            if filename in resources:
                pass # avoid duplicating resources
            else:
                doc_id = "img_"+str(idx)
                images[filename] = doc_id # store img id for further reference
                with tag('resource', identifier=doc_id, type="webcontent", href="img/"+filename):
                    doc.stag('file', href="img/"+filename)

        doc.asis("<!-- Webcontent -->")
        for idA, section in enumerate(data["sections"]):
            for idB, subsection in enumerate(data["sections"][idA]["subsections"]):
                doc_id = "doc_"+str(idA)+"_"+str(idB)
                file_type = FILETYPES[data["sections"][idA]["subsections"][idB]["type"]]
                href = data["sections"][idA]["subsections"][idB]["source_file"]
                with tag('resource', identifier=doc_id, type=file_type, href=href):
                     doc.stag('file', href=href)
                     # add dependency if needed (html only)
                     if file_type == "webcontent":
                         html_doc = html.parse(href)
                         img_sources = html_doc.xpath('//@src')
                         for img in img_sources:
                             img = img.rsplit('/', 1)[1]
                             if img in images:
                                 # add dependency
                                 doc.stag('dependency', identifierref=images[img])
                        # rewrite absolute href links
                        #  body = html_doc.find('body')
                        #  body.rewrite_links(replaceLink)
                        #  f = open(href,"wb")
                        #  f.write(html.tostring(body))
                        #  f.close()

    doc.asis("</manifest>")
    imsfile = open('imsmanifest.xml', 'w')
    imsfile.write(indent(doc.getvalue()))
    imsfile.close()
    return True
コード例 #47
0
ファイル: toIMS.py プロジェクト: nburlot/cn_app
def generateIMSManifest(data):
    """ parse data from config file 'moduleX.config.json' and recreate imsmanifest.xml """
    # create magic yattag triple
    doc, tag, text = Doc().tagtext()
    # open tag 'manifest' with default content:
    doc.asis(IMS_HEADER)
    # Print metadata
    with tag('metadata'):
        with tag('schema'):
            text('IMS Common Cartridge')
        with tag('schemaversion'):
            text('1.1.0')
        with tag('lomimscc:lom'):
            with tag('lomimscc:general'):
                with tag('lomimscc:title'):
                    with tag('lomimscc:string', language=data["language"]):
                        text(data["menutitle"])
                with tag('lomimscc:language'):
                    text(data["language"])
                with tag('lomimscc:description'):
                    doc.stag('lomimscc:string', language=data["language"])
                with tag('lomimscc:identifier'):
                    with tag('lomimscc:catalog'):
                        text('category')
                    with tag('lomimscc:entry'):
                        try:
                            text(data["category"])
                        except:
                            text('D')
    # Print organization
    resources = []
    with tag('organizations'):
        with tag('organization', identifier="organization0", structure='rooted-hierarchy'):
            with tag('item', identifier='root'):
                # add empty section as section "0 . Généralités" to avoid wrong numbering
                with tag('item', identifier='section_generalites'):
                    with tag('title'):
                        text('')
                for idA, section in enumerate(data["sections"]):
                    section_id = "sec_"+(str(idA))
                    with tag('item', identifier=section_id):
                        with tag('title'):
                            text(section['num']+' '+section['title'])
                        for idB, subsection in enumerate(section["subsections"]):
                            href = subsection["folder"]+'/'+subsection["filename"]
                            # when adding moodle-test type change file suffix from .html to .xml
                            if subsection["folder"] in ['auto-evaluation', 'devoirs', 'Activite', 'ActiviteAvancee', 'Comprehension']:
                                href = href.replace('html', 'xml')
                            filename = href.rsplit('/',1)[1]
                            resources.append(filename)
                            with tag('item', identifier=("subsec_"+str(idA)+"_"+str(idB)), identifierref=("doc_"+str(idA)+"_"+str(idB))):
                                with tag('title'):
                                    text(subsection['num']+' '+subsection["title"])
    # Print resources
    with tag('resources'):
        # retrieve images and add dependency when needed
        doc.asis("<!-- Media -->")
        media_dir ="media"
        images = {}
        try:
            for idx, filename in enumerate(os.listdir(os.path.join(os.getcwd(), media_dir))):
                if filename in resources:
                    pass # avoid duplicating resources
                else:
                    doc_id = media_dir+"_"+str(idx)
                    images[filename] = doc_id # store img id for further reference
                    with tag('resource', identifier=doc_id, type="webcontent", href=media_dir+"/"+filename):
                        doc.stag('file', href=media_dir+"/"+filename)
        except Exception as e:
            logging.warn("[toIMS] No media found for this module : %s" % e)
            pass
        

        doc.asis("<!-- Webcontent -->")
        for idA, section in enumerate(data["sections"]):
            for idB, subsection in enumerate(section["subsections"]):
                doc_id = "doc_"+str(idA)+"_"+str(idB)
                file_type = FILETYPES[subsection["folder"]]
                # When adding moodle test resource change file suffix from .html to .xml
                href = subsection["folder"]+'/'+subsection["filename"]
                if subsection["folder"] in ['auto-evaluation', 'devoirs', 'Activite', 'ActiviteAvancee', 'Comprehension']:
                    href = href.replace('html', 'xml')
                with tag('resource', identifier=doc_id, type=file_type, href=href):
                     doc.stag('file', href=href)
                     # add dependency if needed (html only)
                     if file_type in ["webcontent", "cours", "correction"]:
                        try:
                            html_doc = html.parse(href)
                            for img in html_doc.xpath('//@src'):
                                img_filename = img.rsplit('/', 1)[1]
                                if img_filename in images:
                                    # add dependency
                                    doc.stag('dependency', identifierref=images[img_filename])
                        except:
                            logging.error(" [toIMS]Error while parsing doc: %s" % (href))
                            continue

    doc.asis("</manifest>")
    imsfile = open('imsmanifest.xml', 'w', encoding='utf-8')
    imsfile.write(indent(doc.getvalue()))
    imsfile.close()
    return True
コード例 #48
0
def scrape_github():
    print("Starting WS-DL GitHub repository html generation")
    dt = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/' \
         'DTD/xhtml1-transitional.dtd">'

    commented_style = '<!-- ' \
            'ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; }' \
            'code.escaped { white-space: nowrap; } .vspace { margin-top:1.33em; } '\
            '.indent { margin-left:40px; } .outdent { margin-left:40px; text-indent:-40px; } '\
            'a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; }'\
            'a.createlink { text-decoration:none; position:relative; top:-0.5em;'\
            'font-weight:bold; font-size:smaller; border-bottom:none; } img { border:0px; }'\
            '.editconflict { color:green; font-style:italic; margin-top:1.33em; margin-bottom:1.33em; }'\
            'table.markup { border:2px dotted #ccf; width:90%; }'\
            'td.markup1, td.markup2 { padding-left:10px; padding-right:10px; }'\
            'table.vert td.markup1 { border-bottom:1px solid #ccf; }'\
            'table.horiz td.markup1 { width:23em; border-right:1px solid #ccf; }'\
            'table.markup caption { text-align:left; }'\
            'div.faq p, div.faq pre { margin-left:2em; }'\
            'div.faq p.question { margin:1em 0 0.75em 0; font-weight:bold; }'\
            'div.faqtoc div.faq * { display:none; }'\
            'div.faqtoc div.faq p.question'\
            '{ display:block; font-weight:normal; margin:0.5em 0 0.5em 20px; line-height:normal; }'\
            'div.faqtoc div.faq p.question * { display:inline; }'\
            '.frame { border:1px solid #cccccc; padding:4px; background-color:#f9f9f9; }'\
            '.lfloat { float:left; margin-right:0.5em; } .rfloat { float:right; margin-left:0.5em; }'\
            'a.varlink { text-decoration:none; }'\
            '-->'

    span_style = 'text-align: center; margin-top: 0px; margin-right: 10px; margin-bottom: 10px; margin-left: 10px;'

    desc = 'Web Science and Digital Libraries Research Group in' \
           'the Department ofComputer Science at Old Dominion University'

    foot_text = 'This page was last modified on '+strftime('%B %d, %Y at %I:%M %p EST') +'<br>' \
                'Copyright &#169; 2013, Old Dominion University. All rights reserved.'


    # this list contains the items to be placed inside the link bar as href -> text
    linkbar_items = [('https://ws-dl.cs.odu.edu/', 'Home'), ('http://ws-dl.blogspot.com/', 'Blog'),
                     ('https://ws-dl.cs.odu.edu/Main/People', 'People'),
                     ('https://ws-dl.cs.odu.edu/Main/Pubs', 'Publications'),
                     ('https://ws-dl.cs.odu.edu/Main/Software', 'Software'),
                     ('https://ws-dl.cs.odu.edu/Main/Press', 'Press'),
                     ('https://ws-dl.cs.odu.edu/Main/GitHub', 'GitHub')]

    # use OAuth token set as a environment variable for a user to log in to GitHub
    g = Github(getenv('GitOath'))
    user = g.get_user()
    wsdl_org = None

    # loop through the logged in user and find the WS-DL org
    for org in user.get_orgs():
        if org.name == 'ODU Web Science / Digital Libraries Research Group':
            wsdl_org = org
            break

    if wsdl_org is None:
        print(user.name+" you are not a member of the WS-DL at ODU-CS exiting")
        exit()

    # see www.yattag.org or github.com/leforestier/yattag
    doc, tag, text = Doc().tagtext()
    # use asis to ensure that < > characters of <!DOCTYPE html> do not get substituted with &lt; and &gt;
    doc.asis(dt)

    with tag('html', xmlns='http://www.w3.org/1999/xhtml'):
        with tag('head'):
            with tag('title'):
                text('GitHub')
            # stag is self closing tag
            doc.stag('meta', ('http-equiv', 'Content-Style-Type'), content='text/css')
            doc.stag('meta', name='google-site-verification', content='IaM4qV58mAMQVvEkegBKwOgICTYZsEdO2l4HVs1jREg')
            doc.stag('link', rel='stylesheet', href='https://ws-dl.cs.odu.edu/pub/skins/public/public.css',
                     type='text/css')
            with tag('style', type='text/css'):
                doc.asis(commented_style)
            doc.stag('meta', ('http-equiv', 'Content-Type'), content='text/html; charset=utf-8')
            doc.stag('meta', name='robots', content='index,follow')
        with tag('body'):
            with tag('table', id='wikimid', cellspacing='0', cellpadding='0', width='95%'):
                with tag('tbody'):
                    with tag('tr'):
                        with tag('td', id='wikileft', valign='top'):
                            pass
                        with tag('td', id='wikibody', valign='top'):
                            with tag('div', id='title'):
                                text('WS-DL at ODU-CS')
                            with tag('div', id='description'):
                                text(desc)
                            with tag('div', id='linkbar'):
                                with tag('ul'):
                                    for item in linkbar_items:
                                        with tag('li'):
                                            with tag('a', href=item[0]):
                                                text(item[1])
                            # klass is used a substitute for class
                            with tag('h1', klass='pagetitle'):
                                text('GitHub Repositories')
                            with tag('div', id='wikitext'):
                                for repo in wsdl_org.get_repos():
                                    # noticed that the WS-DL GitHub has non-code repos so skip them
                                    if ".io" in repo.name or 'ORS' == repo.name:
                                        continue
                                    with tag('div'):
                                        with tag('span', klass='lfloat', style=span_style):
                                            doc.stag('img', src=wsdl_org.avatar_url, width='75px')
                                    with tag('p'):
                                        with tag('strong'):
                                            with tag('a', klass='urllink',href=repo.html_url, rel='nofollow'):
                                                text(runderscore_capitalize(repo.name))
                                        doc.stag('br')
                                        text(repo.description)
                                        doc.stag('br', clear='all')
                                with tag('div', klass='vspace'):
                                    pass
                    with tag('tr'):
                        with tag('td'):
                            pass
                        with tag('td', id='wikibody', valign='top'):
                            pass
            with tag('div', id='footer'):
                doc.stag('hr')
                with tag('table'):
                    with tag('tbody'):
                        with tag('tr'):
                            with tag('td', valign='top'):
                                doc.stag('img', src='Software_files/odu2l.png', width='130px')
                            with tag('td'):
                                with tag('div', id='wikifoot'):
                                    doc.asis(foot_text)
                                with tag('div', id='actionfoot'):
                                    with tag('p'):
                                        with tag('a', klass='wikilink', href='https://ws-dl.cs.odu.edu/Main/Software?action=print'):
                                            text('Print')
                                        text(' - ')
                                        with tag('a', klass='wikilink', href='https://ws-dl.cs.odu.edu/Main/Software?action=login'):
                                            text('Admin')

    git_html = open('GitHub.html', 'w+')
    git_html.write(indentation.indent(doc.getvalue()))
    git_html.close()
    print("Finished WS-DL GitHub repository html generation")
    print("File generated is called GitHub.html")
コード例 #49
0
def parseresults(results):
	doc, tag, text = Doc().tagtext()
	listed_details = ['_id', 'bio', "distance_mi", "teaser", 
		"common_interests", "schools"]
	doc.asis('<!DOCTYPE html>')
	with tag('html'):
		with tag('title'):
			text('Tinder Viewer')
		with tag('body'):
			for person in results:
				with tag('div'):
					with tag('h2'):
						text(person['name'])
					with tag('div'):
						print('{0} is {1}'.format(person['name'].encode('utf-8'), person['_id']))
						for item in listed_details:
							text(item + ': ')
							try:
								text(bytes(json.dumps(person[item]), 'utf-8').decode('unicode-escape'))
							except UnicodeEncodeError:
								good_text = ''.join(
									c for c in bytes(
										json.dumps(person[item]),
										'utf-8'
									).decode('unicode-escape') if c in string.printable
								)
								text(good_text)
							doc.stag('br')
						text('age is: ')
						text(calc_age(person['birth_date']))
						doc.stag('br')
					for i in range(len(person['photos'])):
						address = person['photos'][i]['processedFiles'][0]['url']
						doc.stag('img', src=address)
					doc.stag('br')
					if 'instagram' in person.keys() and person['instagram'] is not None:
						with tag('h3'):
							text('Instagram:')
						for photo in person['instagram']['photos']:
							with tag('a', href= photo['image'], target='_blank'):
								doc.stag('img', src=photo['thumbnail'])
				doc.stag('br')
	open_html(doc.getvalue())
コード例 #50
0
ファイル: datablad.py プロジェクト: y0m0/Datablad
def make_html(prod_dict):
    for prodcode, prod in prod_dict.items():

        doc, tag, text = Doc().tagtext()

        doc.asis('<!DOCTYPE html>')
        with tag('html', lang='eng'):

            with tag('head'):
                doc.asis('<meta charset="UTF-8" />')
                doc.asis('<link rel="stylesheet" type="text/css" href="style.css">')
                doc.asis('<meta name="viewport" content="width=device-width">')
                with tag('title'):
                    text(prod.prodid.text)

            with tag('body', klass='main'):
                with tag('header', klass='main-header'):
                    doc.stag('img', klass='logo', src='logo.jpg', alt='Villa Import AS')
                    with tag('h1', klass='prodname'):
                        text(prod.desc.text)

                with tag('div', klass='content'):
                    with tag('div', klass='primary-content group'):

                        with tag('div', klass='product-picture'):
                            doc.stag('img', src='http://www.villaimport.no/images/produktbilder/Full%20Size/'+ prod.prodid.text + '.jpg', alt=prod.desc.text)

                        with tag('div', klass='product-details'):
                            with tag('div', klass='basic-info'):
                                with tag('h2'):
                                    text('Produktinformasjon')
                                with tag('ul', klass='field'):
                                    with tag('li'):
                                        text('Varenummer: ' + prod.prodid.text)
                                    with tag('li'):
                                        text('Produktgruppe: ' + prod.prodgroupex.text)
                                    with tag('li'):
                                        text('Pakning: ' + re.sub('.000', '',
                                                                  prod.weight.text) + ' ' + prod.weightunit.text)

                            with tag('div', klass='ingredients'):
                                with tag('h2'):
                                    text('Ingredienser')
                                with tag('p', klass='field'):
                                    text(prod.prodnote.text)

                    with tag('div', klass='secondary-content'):
                        with tag('div', klass='energy'):
                            with tag('h2'):
                                text('Næringsinnehold Pr. 100 gram.')
                            with tag('ul', klass='field'):
                                for value in re.split('\n', prod.technote.text):
                                    if value.lstrip() != "":
                                        with tag('li'):
                                            text(value.lstrip())

                        with tag('div', klass='allergens'):
                            with tag('h2'):
                                text('Allergener')
                            with tag('ul', klass='field'):
                                for word in set(re.split('[\[\]/{}.,() ]+', prod.prodnote.text)):
                                    if word.isupper():
                                        with tag('li'):
                                            text(word.capitalize())

                        with tag('div', klass='storage'):
                            with tag('h2'):
                                text('Oppbevaring')
                            with tag('ul', klass='field'):
                                for word in re.findall(r'[A-Z][^A-Z]*', prod.annenote.text):
                                    with tag('li'):
                                        text(word)

                with tag('footer', klass='main-footer'):
                    with tag('p'):
                        doc.asis(
                            '''<a href="www.villaimport.no">www.villaimport.no</a> &#9702;
                            <a href="tel:+4723229999">+47 23229999</a> &#9702;
                            <a href="mailto:[email protected]">[email protected]</a>''')
                    with tag('p'):
                        doc.asis('&copy; Villa Import AS - 2016')

        with codecs.open(prodcode + '.html', 'w', 'utf-8') as file:
            file.write(indent(doc.getvalue()))
コード例 #51
0
ファイル: workflow.py プロジェクト: orenmazor/oozie.py
    def as_xml(self):
        doc, tag, text = Doc().tagtext()
        doc.asis("<?xml version='1.0' encoding='UTF-8'?>")
        with tag('workflow-app', ('xmlns:sla', 'uri:oozie:sla:0.2'), name=self.name, xmlns="uri:oozie:workflow:0.5"):
            doc.stag('start', to=self.actions[0].name)
            for index, action in enumerate(self.actions):
                with tag("action", name=action.name):
                    doc.asis(action.as_xml(indent))
                    if index + 1 < len(self.actions):
                        next_action = self.actions[index+1]
                        doc.stag("ok", to=next_action.name)
                    else: 
                        doc.stag("ok", to="end")
                    doc.stag("error", to="notify")

            with tag("action", name="notify"):
                with tag("email", xmlns="uri:oozie:email-action:0.1"):
                    with tag("to"):
                        text(self.email)
                    with tag("subject"):
                        text("WF ${wf:name()} failed at ${wf:lastErrorNode()}")
                    with tag("body"):
                        text("http://hue.data.shopify.com/oozie/list_oozie_workflow/${wf:id()}")
                doc.stag("ok", to="kill")
                doc.stag("error", to="kill")

            with tag("kill", name="kill"):
                with tag("message"):
                    text("${wf:lastErrorNode()} - ${wf:id()}")
            doc.stag('end', name="end")

        return indent(doc.getvalue())
コード例 #52
0
ファイル: index.py プロジェクト: nenadilic84/OpenVPNChanger
            with tag('br'):
                text('Default OpenVPN configuration path: ' + OPENVPN_PATH)
            with tag('br'):
                text('Curent server: ' + current_server)
            with tag('br'):
                text('')
            with tag('label'):
                text("Select a VPN server")
            with doc.select(name = 'server'):
                lst = os.listdir(OPENVPN_PATH)
                lst.sort()
                for file in lst:
                    if file.endswith(".conf"):
                        with doc.option(value = file):
                            text(file.split(".conf")[0])
            doc.stag('input', type = "submit", value = "Set")

        if query.has_key('server'):
            server = query['server'][0]
            info = set_server(server).split("\n")
            for openvpn_info in info:
                with tag('br'):
                     text(openvpn_info)

print "Content-type: text/html\n"

result = indent(
    doc.getvalue(),
    indentation = '    ',
    newline = '\r\n'
)
コード例 #53
0
def _write_html_row(script_name, action_type, expected, result_type, screenshot, similarity):
    doc, tag, text = Doc().tagtext()
    # Create the row
    # Status, Time and Date, Test name, Action, Expected, Screenshot, Similarity
    with tag("tr"):
        if result_type == "Success":
            with tag("td", ('bgcolor', 'green')):
                text("+++")
        elif result_type == "Fail":
            with tag("td", ('bgcolor', 'red')):
                text("---")
        else:
            with tag("td"):
                text("???")
        with tag("td"):
            text(time.strftime("%H:%M:%S %x"))
        with tag("td"):
            text(script_name)
        with tag("td"):
            text(action_type)
        with tag("td"):
            # If 'expected' is given, figure out what kind
            # of thing it is
            if expected:
                expected_path = ""
                # If it's a pattern, get the image
                if isinstance(expected, sikuli.Pattern):
                    full_path = _find_valid_image(expected.getFilename())
                    expected_path = _copy_testfile(full_path)
                # If it's a match or a region, take a
                # screenshot of the area
                elif (isinstance(expected, sikuli.Match) or
                      isinstance(expected, sikuli.Region)):
                    screencap = sikuli.capture(expected)
                    expected_path = _copy_testfile(screencap)
                elif isinstance(expected, sikuli.Location):
                    # Create an area 50px around the location
                    r = sikuli.Region(expected.getX(), expected.getY(), 0, 0)
                    r = r.nearby()
                    # take a screenshot
                    screencap = sikuli.capture(r)
                    expected_path = _copy_testfile(screencap)
                elif isinstance(expected, str):
                    full_path = _find_valid_image(expected)

                    # If a path was found, add a clickable image.
                    # If not, add text.
                    if full_path:
                        expected_path = _copy_testfile(full_path)

                if expected_path == "":
                    text(str(expected))
                else:
                    with tag("a", href="./log/"+expected_path):
                        doc.stag("img", src="./log/"+expected_path)

        with tag("td"):
            screenshot_path = _copy_testfile(screenshot)
            with tag("a", href="./log/"+screenshot_path):
                doc.stag("img", src="./log/"+screenshot_path)
        with tag("td"):
            text(similarity)

    # Write the row to the partial html file
    with open(_partialHTML, "a") as f:
        f.write(doc.getvalue())
コード例 #54
0
ファイル: presentation.py プロジェクト: nunb/MaTiSSe
 def to_html(self):
   """Method for producing and html string document from presentation object."""
   doc, tag, text = Doc().tagtext()
   doc.asis('<!DOCTYPE html>')
   with tag('html'):
     doc.attr(title = self.metadata.data.data['title'][0])
     with tag('head'):
       doc.stag('meta',charset='utf-8')
       doc.stag('meta',author=' and '.join(self.metadata.data.data['authors'][0]))
       with tag('title'):
         text(self.metadata.data.data['title'][0])
       doc.stag('meta',subtitle=self.metadata.data.data['subtitle'][0])
       doc.stag('link',rel='stylesheet', href='css/normalize.css')
       if __config__.highlight:
         doc.stag('link',rel='stylesheet', href='js/highlight/styles/'+__config__.highlight_style)
       doc.stag('link',rel='stylesheet', href='css/theme.css')
     with tag('body',onload="resetCountdown("+self.metadata.data.data['max_time'][0]+");"):
       with tag('div',id='impress'):
         if self.titlepage.found:
           html = self.titlepage.to_html(position = self.pos, theme = self.theme.slide)
           html = self.metadata.parse(html)
           html = self.toc.parse(html)
           doc.asis(html)
         for section in self.sections:
           for subsection in section.subsections:
             for slide in subsection.slides:
               html = slide.to_html(position = self.pos, theme = self.theme.slide)
               html = self.metadata.parse(html)
               html = self.toc.parse(html,current=[int(slide.data['sectionnumber']),int(slide.data['subsectionnumber']),slide.number])
               doc.asis(html)
       with tag('script'):
         doc.attr(src='js/countDown.js')
       with tag('script'):
         doc.attr(src='js/impress.js')
       with tag('script'):
         doc.asis('impress().init();')
       if __config__.online_mathjax:
         with tag('script'):
           doc.attr(('type','text/javascript'))
           doc.attr(src='http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML')
       else:
         with tag('script'):
           doc.attr(('type','text/x-mathjax-config'))
           doc.text("""
             MathJax.Hub.Config({
               extensions: ["tex2jax.js"],
               jax: ["input/TeX", "output/HTML-CSS"],
               tex2jax: {
                 inlineMath: [ ['$','$'], ["\\(","\\)"] ],
                 displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
                 processEscapes: true
               },
               "HTML-CSS": { availableFonts: ["Neo-Euler"] }
             });
           """)
         with tag('script'):
           doc.attr(('type','text/javascript'))
           doc.attr(src='js/MathJax/MathJax.js')
       if __config__.highlight:
         with tag('script'):
           doc.attr(src='js/highlight/highlight.pack.js')
         with tag('script'):
           doc.text("""hljs.initHighlightingOnLoad();""")
   if __config__.indented:
     return indent(doc.getvalue())
   else:
     return doc.getvalue()
コード例 #55
0
    def processHTML(self):
        allProblems = self.recordProblemsFile()
        doc, tag, text = Doc().tagtext()
        numberOfProblems = len(allProblems)
        with tag('html'):
            with tag('head'):
                with tag('title'):
                    text('generated from ARG-101')
                with tag('style'):
                    doc.asis(
                        '''
                        body {
                            padding-top:40px;
                            text-align: justify;
                            max-width: 1600px;
                            word-wrap: break-word;
                            font-family: 'Times';
                            font-size: 18px;
                        }
                        h1 {
                            font-family: 'Times';
                            font-size: 27px;
                            font-weight: bold;
                            text-decoration: underline;
                            margin-top: 0px;
                            margin-bottom: 0px;
                            text-align: center;
                        }
                        p.question{
                            font-weight: bold;
                           text-align: left;
                        }
                        div.image {
                            margin-top: 18px;
                            max-height:100%;
                            max-width:100%;
                            height:72px;
                            margin-bottom: 18px;
                            align-content: left;
                        }

                        '''
                        )

            with tag('body'):
                with tag('h1'):
                    text("Assignment {}".format(self.assignmentNumber))
                doc.stag('br')
                problem_count, line_count = 0, 0
                for problemo in allProblems:
                    with tag('p', klass='question'):
                        text(problemo)
                        doc.stag('br')
                    program = self.recordProgramByPath("{}/{}.{}".format(self.programsDirectory,problem_count+1,self.programmingLanguage))
                    
                    for statement in program:
                        text(statement)
                        doc.stag('br')

                    with tag('div',klass="image"):
                        doc.stag('img', src="{}/{}.png".format(self.screenshotsDirectory,problem_count+1),style="height: 100%; width: 100%; object-fit: contain;")

        main_html = doc.getvalue()
        with open("try44.html","w+") as ht:
            ht.write(main_html)

        
        with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as footer_html:
            self.pdf_options['footer-html'] = footer_html.name
            footer_html.write(self.processFooter().encode('utf-8'))

        config = pdfkit.configuration(wkhtmltopdf=os.getcwd()[:-6]+"/Dependencies/wkhtmltox/bin/wkhtmltopdf")
        pdfkit.from_string(main_html,'out.pdf',configuration=config, options=self.pdf_options)
        os.remove(self.pdf_options['footer-html'])
コード例 #56
0
def _display_log():
    #
    # Display a log that has been generated by running tests and logging with TestHelper.
    #

    # Make sure the folder exists
    if not os.path.exists(_artifactFolder):
        print("Folder not found: " + _artifactFolder + "\n")
        exit(1)

    # Make sure there is one and only one .log file in the folder
    glob_result_log = glob.glob(_artifactFolder + "/*.log")
    if len(glob_result_log) < 1:
        print("No .log file found in folder: " + _artifactFolder + "\n")
        exit(1)
    elif len(glob_result_log) > 1:
        print("Multiple .log files found in folder: " + _artifactFolder + "\n")
        exit(1)
    else:
        log_file = glob_result_log[0]

    # Make sure there is one and only one .css file in the folder
    glob_result_css = glob.glob(_artifactFolder + "/*.css")
    if len(glob_result_css) < 1:
        print("No css file found in folder: " + _artifactFolder + "\n")
        exit(1)
    elif len(glob_result_css) > 1:
        print("Multiple css files found in folder: " + _artifactFolder + "\n")
        exit(1)
    else:
        css_file = os.path.basename(glob_result_css[0])

    # Build the html log
    with open(os.path.join(_logToFolder, "log.html"), "w") as html_file:
        doc, tag, text = Doc().tagtext()
        doc.asis('<!DOCTYPE html>')

        with tag("html", lang="en_us"):
            with tag("head"):
                with tag("title"):
                    text("Test Results")
                doc.stag("link", href="./log/"+css_file, rel="stylesheet", type="text/css")
            with tag("body"):
                with tag("table"):
                    with tag("thead"):
                        with tag("tr"):
                            with tag("th"):
                                text("Status")
                            with tag("th"):
                                text("Time and Date")
                            with tag("th"):
                                text("Test name")
                            with tag("th"):
                                text("Action")
                            with tag("th"):
                                text("Expected")
                            with tag("th"):
                                text("Screenshot")
                            with tag("th"):
                                text("Similarity")
                    with tag("tbody"):
                        # Add in the .log file, which should contain table rows
                        with open(log_file, "r") as f:
                            doc.asis(f.read())

        # Write the html document to the file
        html_file.write(doc.getvalue())

    # Open a browser tab with the file displayed in it
    new = 2  # open in a new tab if possible
    url = "file://" + os.path.normpath(os.path.join(_logToFolder, "log.html")).replace("\\", "/")
    print url
コード例 #57
0
    def makeFcpxml(self):
        # minimal file for Premiere to accept:
        # condensed <element/> not allowed!
        # <?xml version="1.0"?>
        # <xmeml version="4">
	#   <project>
	#     <name>name</name>
	#     <children></children>
	#   </project>
	# </xmeml>

        uid = 1

        root = ET.Element('xmeml', {'version': '4'})
        project = ET.SubElement(root, 'project')
        name = ET.SubElement(project, 'name')
        name.text = self.metadata['PROJECT_NAME']
        children = ET.SubElement(project, 'children')
        children.tail = ' '  #prevent condensing

##        project_children_bin = ET.SubElement(children, 'bin')
##        name = ET.SubElement(project_children_bin, 'name')
##        name.text = 'Assets'
##        children = ET.SubElement(project_children_bin, 'children')
##        children.tail = ' '  #prevent condensing
        
        for cookie in self.items:
            item = self.items[cookie]

            if item["Type"] == "edit":
                # Describes an edited sequence.

                doc, tag, text = Doc().tagtext()

                with tag('sequence', id='sequence-%s' % uid):
                    uid += 1
                    with tag('rate'):
                        with tag('timebase'):
                            text('30')
                        with tag('ntsc'):
                            text('TRUE')
                    with tag('name'):
                        text(self.metadata['PROJECT_NAME'])
                    with tag('media'):
                        with tag('video'):
                            with tag('format'):
                                with tag('samplecharacteristics'):
                                    with tag('rate'):
                                        with tag('timebase'):
                                            text('30')
                                        with tag('ntsc'):
                                            text('TRUE')
                                    with tag('width'):
                                        text('1920')
                                    with tag('height'):
                                        text('1080')
                                    with tag('anamorphic'):
                                        text('FALSE')
                                    with tag('pixelaspectratio'):
                                        text('square')
                                    with tag('fielddominance'):
                                        text('none')
                                    with tag('colordepth'):
                                        text('24')

                            with tag('track'):
                                edits = item['.ed5'].edit_cells
                                self.fixEdits(edits)

                                for c in edits:
                                    if c['reel'] == 'BL':
                                        # black frame
                                        pass
                                    else:
                                        id_clipitem = 'clipitem-%s' % uid
                                        uid += 1
                                        with tag('clipitem', id=id_clipitem):
                                            with tag('start'):
                                                text('1')
                                            with tag('end'):
                                                text('11')
                                            with tag('in'):
                                                text('21')
                                            with tag('out'):
                                                text('31')
                                            doc.stag('file', id='file-%s' % c['reel'])
                                            with tag('link'):
                                                with tag('linkclipref'):
                                                    text(id_clipitem)
                                                with tag('mediatype'):
                                                    text('video')
                                                with tag('trackindex'):
                                                    text('1')
                                                with tag('clipindex'):
                                                    text('1')

##                                            b.reel = c['reel']
##                                            b.channels = c['track']
##                                            b.transition = 'C'
##                                            #b.transDur = ?
##                                            b.srcIn = c['src_in']
##                                            b.srcOut = c['src_out']
##                                            b.recIn = c['rec_in']
##                                            b.recOut = c['rec_out']
##                                            #c['aud'], c['from_clip']

                children.append( ET.fromstring(doc.getvalue()) )

            elif item["Type"] == "shot":
                # Describes a video clip.
                # Tested by importing into Premiere CS6.
                # Elements and values below are required; Pre will crash or
                #  simply fail to see the clip otherwise.
                # P requires certain elements, even if empty.
                # P requires 'id' attribute on some elements, but not all.
                
                doc, tag, text = Doc().tagtext()

                ed5 = item['.ed5'].EHP
                keys = ed5.keys()
                files = set()
                for k in keys:
                    if k.startswith("ORIGINAL_FILE_"):
                        files.add(ed5[k])
                if len(files) == 0:
                    logging.error('cookie has zero files: %s' % item["Cookie"])
                    filepath = ""
                elif len(files) > 1:
                    logging.error('cookie has many files: %s => %s' % [item["Cookie"], files])
                    filepath = next(iter(files))
                else:
                    filepath = next(iter(files))

                if len(filepath) > 0:
                    filepath = pathlib.Path(filepath).as_uri()

                with tag('clip', id=item['Cookie']):
                    with tag('ismasterclip'):
                        text('TRUE')
                    with tag('rate'):
                        with tag('timebase'):
                            text('30')
                        with tag('ntsc'):
                            text('TRUE')
                    with tag('name'):
                        text(item['Cookie'])

                    with tag('media'):
                        with tag('video'):
                            with tag('track'):
                                with tag('clipitem', id='clipitem-%s' % uid):
                                    uid += 1
                                    with tag('file', id='file-%s' % item['Cookie']):
                                        with tag('pathurl'):
                                            text(filepath)
                                        with tag('media'):
                                            with tag('video'):
                                                text(' ')
                                            with tag('audio'):
                                                text(' ')

                children.append( ET.fromstring(doc.getvalue()) )

            else:
                logging.error('unknown asset type %s' % item["Type"])
        
        return ET.ElementTree(root)
コード例 #58
0
            with tag('title'):
                text(header_info['name'])
        doc.asis('<link href="css/bootstrap.min.css" rel="stylesheet">')
        doc.asis('<link href="css/font-awesome.css" rel="stylesheet">')
        doc.asis('<link href="css/main.css" rel="stylesheet">')

    with tag('body'):
        with tag('div', klass='container'):

            # HEADER
            with tag('div', klass='row'):
                with tag('div', klass='col-xs-12'):
                    with tag('div', id='photo-header', klass='text-center'):
                        with tag('div', id='photo'):
                            if 'photo' in header_info:
                                doc.stag('img', src=header_info['photo'], alt='photo')
                        with tag('div', id='text-header'):
                            with tag('h1'):
                                if 'name' in header_info:
                                    text(header_info['name'])
                                if 'title' in header_info:
                                    text(' ')
                                    with tag('sup'):
                                        text(header_info['title'])
                                    doc.stag('br')
                                if 'position' in header_info:
                                    text(header_info['position'])
                                    if 'affiliation' in header_info:
                                        text(', ')
                                        if 'affiliation_link' in header_info:
                                            with tag('a', target='_blank', href=header_info['affiliation_link']):