def compute_trending_table(submissions_list, table_type, user_id=None):
    """
        Create trending table from the rows

        @params submission_list (Rows): Submissions to be considered
        @params table_type (String): friends / global
        @params user_id (Long): ID of signed in user else None
    """

    T = current.T
    if table_type == "friends":
        table_header = T("Trending among friends")
        column_name = T("Friends")
    else:
        table_header = T("Trending Globally")
        column_name = T("Users")

    if len(submissions_list) == 0:
        table = TABLE(_class="bordered centered")
        thead = THEAD(
            TR(TH(T("Problem")), TH(T("Recent Submissions")), TH(column_name)))
        table.append(thead)
        table.append(TBODY(TR(TD("Not enough data to show", _colspan=3))))
        return table

    # Sort the rows according to the number of users
    # who solved the problem in last PAST_DAYS
    custom_compare = lambda x: (len(x[1]["users"]) + \
                                len(x[1]["custom_users"]),
                                x[1]["total_submissions"])

    problems_dict = {}
    for submission in submissions_list:
        plink = submission.problem_link
        pname = submission.problem_name
        uid = submission.user_id
        cid = submission.custom_user_id

        if plink not in problems_dict:
            problems_dict[plink] = {
                "name": pname,
                "total_submissions": 0,
                "users": set([]),
                "custom_users": set([])
            }

        pdict = problems_dict[plink]
        pdict["total_submissions"] += 1
        if uid:
            pdict["users"].add(uid)
        else:
            pdict["custom_users"].add(cid)

    trending_problems = sorted(problems_dict.items(),
                               key=custom_compare,
                               reverse=True)

    return render_trending_table(table_header,
                                 trending_problems[:current.PROBLEMS_PER_PAGE],
                                 column_name, user_id)
예제 #2
0
    def render_row(row_id, label, widget, comment, hidden=False):

        row = []
        _class = "hide" if hidden else None

        # Label on the 1st row
        row.append(
            TR(
                TD(
                    label,
                    _class="w2p_fl",
                ),
                TD(""),
                _id=row_id + "1",
                _class=_class,
            ))

        # Widget & Comment on the 2nd Row
        row.append(
            TR(
                widget,
                TD(
                    comment,
                    _class="w2p_fc",
                ),
                _id=row_id,
                _class=_class,
            ))

        return tuple(row)
예제 #3
0
파일: s3grouped.py 프로젝트: ravster/eden
    def html_render_table_footer(self, table):
        """
            Render the table footer

            @param table: the TABLE instance
        """

        data = self.data

        columns = data.get("c")
        totals = data.get("t")

        if not totals:
            return

        footer_row = TR(_class="gi-column-totals")
        if columns:
            label = None
            span = 0
            for column in columns:
                has_value = column in totals
                if label is None:
                    if not has_value:
                        span += 1
                        continue
                    else:
                        label = TD(SPAN(self.totals_label),
                                   _class = "gi-column-totals-label",
                                   _colspan = span,
                                   )
                        footer_row.append(label)
                value = totals[column] if has_value else ""
                footer_row.append(TD(value))
        table.append(TFOOT(footer_row))
def render_trending_table(caption, problems, column_name, user_id):
    """
        Create trending table from the rows
    """
    T = current.T

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem")), TH(T("Recent Submissions")), TH(column_name)))
    table.append(thead)
    tbody = TBODY()

    for problem in problems:
        tr = TR()
        link_class = get_link_class(problem[0], user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                problem_widget(problem[1]["name"], problem[0], link_class,
                               link_title)))
        tr.append(TD(problem[1]["total_submissions"]))
        tr.append(TD(len(problem[1]["users"]) + \
                     len(problem[1]["custom_users"])))
        tbody.append(tr)

    table.append(tbody)
    table = DIV(H5(caption, _class="center"), HR(), table)

    return table
예제 #5
0
def informe_mes_empleado():
    empleados = db(db.empleado.is_active is True).select(db.empleado.ALL)
    fempl = ([" "] +
             [f"{p.user_code} {p.nombre} {p.apellido}" for p in empleados])
    form = FORM(
        CENTER(
            H4('Marcadas del personal'),
            TABLE(
                TR(
                    TAG('<label class "control-label">Persona</label>'),
                    SELECT(fempl,
                           _name='fempleado',
                           _type='text',
                           _id="persona",
                           _class="form-control string")),
                TR(
                    TAG('<label class "control-label">Periodo desde</label>'),
                    INPUT(_name='fdesde',
                          _type='date',
                          _id="mesanio",
                          _class="form-control string",
                          requires=IS_NOT_EMPTY())),
                TR(
                    TAG('<label class "control-label">Periodo hasta</label>'),
                    INPUT(
                        _name='fhasta',
                        _type='date',
                        _id="mesanio",
                        _class="form-control string",
                    ))), BR(),
            INPUT(_type="submit",
                  _class="btn btn-primary btn-medium",
                  _value='Continuar')))
    if form.accepts(request, session):
        session.empleado = request.vars['fempleado']
        session.user_code = request.vars['fempleado'].split()[0]
        session.fdesde = request.vars['fdesde']
        session.fhasta = request.vars['fhasta']
        log(f"seleccionado {session.empleado}")
        log(f"desde: {session.fdesde} hasta {session.fhasta}")
        # selector = (db.empleado.user_code == user_code)
        # usuario = db(selector).select().first().as_dict()
        session.tdesde = datetime.datetime.strptime(session.fdesde, '%Y-%m-%d')
        session.thasta = datetime.datetime.strptime(session.fhasta, '%Y-%m-%d')
        lista = aplico_politica(session.user_code, session.fdesde,
                                session.fhasta)
        nombre_archivo = f'''{session.empleado}
        -{session.fdesde}-{session.fhasta}'''
        session.table = list_dict_to_table_sortable(lista, nombre_archivo)
        redirect(URL('informe'))
    else:
        log(f'acceso {request.function}')
    return dict(form=form)
예제 #6
0
파일: s3theme.py 프로젝트: nursix/eden
    def render_row(row_id, label, widget, comment, hidden=False):

        _class = "hide" if hidden else None

        row = TR(TD(label, _class="w2p_fl"),
                 TD(widget),
                 _id=row_id,
                 _class=_class)

        if comment:
            row.append(TD(DIV(_class="tooltip",
                              _title="%s|%s" % (label, comment)),
                          _class="w2p_fc"))
        return row
예제 #7
0
    def render_row(row_id, label, widget, comment, hidden=False):

        _class = "hide" if hidden else None

        row = TR(TD(label, _class="w2p_fl"),
                 TD(widget),
                 _id=row_id,
                 _class=_class)

        if comment:
            row.append(
                TD(DIV(_class="tooltip", _title="%s|%s" % (label, comment)),
                   _class="w2p_fc"))
        return row
예제 #8
0
def contact():
    """
    Controller for a simple contact form.
    """
    mail = current.mail
    keydata = {}
    with open('applications/grammateus3/private/app.keys', 'r') as keyfile:
        for line in keyfile:
            k, v = line.split()
            keydata[k] = v

    form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()),
                           Field('message_title', requires=IS_NOT_EMPTY()),
                           Field('message', 'text', requires=IS_NOT_EMPTY()),
                           submit_button='Send message',
                           separator=' ')
    captcha = Recaptcha2(request, keydata['captcha_public_key'],
                         keydata['captcha_private_key'])
    form.element('table').insert(-1, TR('', captcha, ''))
    if form.process().accepted:
        if mail.send(to='*****@*****.**',
                     subject='OCP Contact: {}'.format(form.vars.message_title),
                     message=form.vars.message):
            response.flash = 'Thank you for your message.'
            response.js = "jQuery('#%s').hide()" % request.cid
        else:
            form.errors.your_email = "Sorry, we were unable to send the email"
    return dict(form=form)
예제 #9
0
    def get_html(self):
        contest_data = self.get_data()
        card_content_table = TABLE(_class="bordered centered highlight",
                                   _style="line-height: 20px")
        tbody = TBODY()

        for contest in contest_data:
            tbody.append(
                TR(
                    TD(contest[0]),
                    TD(
                        IMG(_src=current.get_static_url("images/%s_small.png" %
                                                        str(contest[1])),
                            _class="parent-site-icon-small")),
                    TD(
                        A(I(_class="fa fa-external-link-square"),
                          _class=
                          "btn-floating btn-small accent-4 green view-contest",
                          _href=contest[2],
                          _target="_blank"))))

        card_content_table.append(tbody)

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content_table,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
예제 #10
0
파일: s3grouped.py 프로젝트: ravster/eden
    def html_render_table_header(self, table):
        """
            Render the table header

            @param table: the TABLE instance
        """

        data = self.data

        columns = data.get("c")
        labels = data.get("l")

        header_row = TR(_class="gi-column-headers")
        if columns:
            for column in columns:
                label = labels.get(column, column)
                header_row.append(TH(label))
        table.append(THEAD(header_row))
예제 #11
0
 def default_formstyle(id, label, widget, comment, hidden=False):
     """
         Provide the default Sahana Eden Form Style
         Label above the Inputs:
         http://uxmovement.com/design-articles/faster-with-top-aligned-labels
     """
     row = []
     if hidden:
         _class = "hide"
     else:
         _class = ""
     # Label on the 1st row
     row.append(
         TR(TD(label, _class="w2p_fl"), TD(""), _id=id + "1",
            _class=_class))
     # Widget & Comment on the 2nd Row
     row.append(
         TR(widget, TD(comment, _class="w2p_fc"), _id=id, _class=_class))
     return tuple(row)
예제 #12
0
    def get_html(self):
        submissions_data = self.get_data()

        card_content_table = TABLE(_class="bordered highlight")
        tbody = TBODY()

        for row in submissions_data:
            user_record = utilities.get_user_records([row[0]], "id", "id",
                                                     True)
            tr = TR(
                TD(
                    A(user_record.first_name + " " + user_record.last_name,
                      _href=URL("user",
                                "profile",
                                args=user_record.stopstalk_handle,
                                extension=False),
                      _target="_blank")))

            td = TD()
            for site in row[1]:
                if site == "total":
                    continue
                else:
                    td.append(
                        SPAN(IMG(_src=current.get_static_url(
                            "images/%s_small.png" % str(site).lower()),
                                 _class="parent-site-icon-very-small"),
                             " " + str(row[1][site]),
                             _style="padding-right: 10px;"))
            tr.append(td)
            tbody.append(tr)

        card_content_table.append(tbody)

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content_table,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
예제 #13
0
파일: config.py 프로젝트: frededk/eden
def formstyle_row(id, label, widget, comment, hidden=False):
    if hidden:
        hide = "hide"
    else:
        hide = ""
    row = TR(
        TD(
            DIV(label, _id=id + "1", _class="w2p_fl %s" % hide),
            DIV(widget, _id=id, _class="w2p_fw %s" % hide),
            DIV(comment, _id=id, _class="w2p_fc %s" % hide),
        ))
    return row
    def get_html(self):
        contest_data = self.get_data()
        card_content_table = TABLE(_class="bordered centered highlight",
                                   _style="line-height: 20px")
        tbody = TBODY()

        for contest in contest_data:
            try:
                start_time = datetime.datetime.strptime(
                    contest["start_time"], "%Y-%m-%dT%H:%M:%S.000Z")
                end_time = datetime.datetime.strptime(
                    contest["end_time"], "%Y-%m-%dT%H:%M:%S.000Z")

            except Exception as e:
                print "Unable to parse datetime", contest
                start_time = datetime.datetime.strptime(
                    contest["start_time"], "%Y-%m-%d %H:%M:%S %Z")
                end_time = datetime.datetime.strptime(contest["end_time"],
                                                      "%Y-%m-%d %H:%M:%S %Z")

            start_time += datetime.timedelta(minutes=330)
            end_time += datetime.timedelta(minutes=330)

            contest["start_time"] = start_time
            contest["end_time"] = end_time

            tbody.append(
                TR(
                    TD(contest["name"]),
                    TD(
                        IMG(_src=current.get_static_url(
                            "images/%s_small.png" %
                            str(contest["site"].lower())),
                            _class="parent-site-icon-small")),
                    TD(
                        A(I(_class="fa fa-external-link-square"),
                          _class=
                          "btn-floating btn-small accent-4 green view-contest",
                          _href=contest["url"],
                          _target="_blank")),
                    TD(utilities.get_reminder_button(contest))))

        card_content_table.append(tbody)

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content_table,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
예제 #15
0
파일: s3grouped.py 프로젝트: ravster/eden
    def html_render_group_footer(self, tbody, group, level=0):
        """
            Render the group footer (=group totals)

            @param tbody: the TBODY or TABLE to append to
            @param group: the group dict
            @param level: the grouping level

            @todo: add group label to footer if no group headers
            @todo: add totals label
        """

        data = self.data

        columns = data.get("c")
        totals = group.get("t")
        value = group.get("v")

        footer_row = TR(_class="gi-group-footer gi-level-%s" % level)
        if not totals:
            if not self.group_headers:
                footer_row.append(TD(value, _colspan = len(columns)))
                tbody.append(footer_row)
            return

        if columns:
            label = None
            span = 0
            for column in columns:
                has_value = column in totals
                if label is None:
                    if not has_value:
                        span += 1
                        continue
                    else:
                        label = TD("%s %s" % (s3_unicode(s3_strip_markup(value)),
                                              self.totals_label,
                                              ),
                                   _class = "gi-group-footer-label",
                                   _colspan = span,
                                   )
                        footer_row.append(label)
                value = totals[column] if has_value else ""
                footer_row.append(TD(value))

        tbody.append(footer_row)
예제 #16
0
파일: s3merge.py 프로젝트: nursix/eden
    def merge(self, r, **attr):
        """
            Merge form for two records

            @param r: the S3Request
            @param **attr: the controller attributes for the request

            @note: this method can always only be POSTed, and requires
                   both "selected" and "mode" in post_vars, as well as
                   the duplicate bookmarks list in session.s3
        """

        T = current.T
        session = current.session
        response = current.response

        output = {}
        tablename = self.tablename

        # Get the duplicate bookmarks
        s3 = session.s3
        DEDUPLICATE = self.DEDUPLICATE
        if DEDUPLICATE in s3:
            bookmarks = s3[DEDUPLICATE]
            if tablename in bookmarks:
                record_ids = bookmarks[tablename]

        # Process the post variables
        post_vars = r.post_vars
        mode = post_vars.get("mode")
        selected = post_vars.get("selected", "")
        selected = selected.split(",")
        if mode == "Inclusive":
            ids = selected
        elif mode == "Exclusive":
            ids = [i for i in record_ids if i not in selected]
        else:
            # Error
            ids = []
        if len(ids) != 2:
            r.error(501,
                    T("Please select exactly two records"),
                    next=r.url(id=0, vars={}))

        # Get the selected records
        table = self.table
        query = (table._id == ids[0]) | (table._id == ids[1])
        orderby = table.created_on if "created_on" in table else None
        rows = current.db(query).select(orderby=orderby, limitby=(0, 2))
        if len(rows) != 2:
            r.error(404, current.ERROR.BAD_RECORD, next=r.url(id=0, vars={}))
        original = rows[0]
        duplicate = rows[1]

        # Prepare form construction
        formfields = [f for f in table if f.readable or f.writable]

        ORIGINAL, DUPLICATE, KEEP = self.ORIGINAL, self.DUPLICATE, self.KEEP
        keep_o = KEEP.o in post_vars and post_vars[KEEP.o]
        keep_d = KEEP.d in post_vars and post_vars[KEEP.d]

        trs = []
        init_requires = self.init_requires
        index = 1
        num_fields = len(formfields)

        for f in formfields:

            # Render the widgets
            oid = "%s_%s" % (ORIGINAL, f.name)
            did = "%s_%s" % (DUPLICATE, f.name)
            sid = "swap_%s" % f.name
            init_requires(f, original[f], duplicate[f])
            if keep_o or not any((keep_o, keep_d)):
                owidget = self.widget(f,
                                      original[f],
                                      _name=oid,
                                      _id=oid,
                                      _tabindex=index)
            else:
                try:
                    owidget = s3_represent_value(f, value=original[f])
                except:
                    owidget = s3_str(original[f])
            if keep_d or not any((keep_o, keep_d)):
                dwidget = self.widget(f, duplicate[f], _name=did, _id=did)
            else:
                try:
                    dwidget = s3_represent_value(f, value=duplicate[f])
                except:
                    dwidget = s3_str(duplicate[f])

            # Swap button
            if not any((keep_o, keep_d)):
                swap = INPUT(
                    _value="<-->",
                    _class="swap-button",
                    _id=sid,
                    _type="button",
                    _tabindex=index + num_fields,
                )
            else:
                swap = DIV(_class="swap-button")

            if owidget is None or dwidget is None:
                continue

            # Render label row
            label = f.label
            trs.append(
                TR(TD(label, _class="w2p_fl"), TD(), TD(label,
                                                        _class="w2p_fl")))

            # Append widget row
            trs.append(
                TR(TD(owidget, _class="mwidget"), TD(swap),
                   TD(dwidget, _class="mwidget")))

            index = index + 1
        # Show created_on/created_by for each record
        if "created_on" in table:
            original_date = original.created_on
            duplicate_date = duplicate.created_on
            if "created_by" in table:
                represent = table.created_by.represent
                original_author = represent(original.created_by)
                duplicate_author = represent(duplicate.created_by)
                created = T("Created on %s by %s")
                original_created = created % (original_date, original_author)
                duplicate_created = created % (duplicate_date,
                                               duplicate_author)
            else:
                created = T("Created on %s")
                original_created = created % original_date
                duplicate_created = created % duplicate_date
        else:
            original_created = ""
            duplicate_created = ""

        # Page title and subtitle
        output["title"] = T("Merge records")
        #output["subtitle"] = self.crud_string(tablename, "title_list")

        # Submit buttons
        if keep_o or not any((keep_o, keep_d)):
            submit_original = INPUT(
                _value=T("Keep Original"),
                _type="submit",
                _name=KEEP.o,
                _id=KEEP.o,
            )
        else:
            submit_original = ""

        if keep_d or not any((keep_o, keep_d)):
            submit_duplicate = INPUT(
                _value=T("Keep Duplicate"),
                _type="submit",
                _name=KEEP.d,
                _id=KEEP.d,
            )
        else:
            submit_duplicate = ""

        # Build the form
        form = FORM(
            TABLE(
                THEAD(
                    TR(
                        TH(H3(T("Original"))),
                        TH(),
                        TH(H3(T("Duplicate"))),
                    ),
                    TR(
                        TD(original_created),
                        TD(),
                        TD(duplicate_created),
                        _class="authorinfo",
                    ),
                ),
                TBODY(trs),
                TFOOT(TR(
                    TD(submit_original),
                    TD(),
                    TD(submit_duplicate),
                ), ),
            ),
            # Append mode and selected - required to get back here!
            hidden={
                "mode": "Inclusive",
                "selected": ",".join(ids),
            })

        output["form"] = form

        # Add RESET and CANCEL options
        output["reset"] = FORM(
            INPUT(
                _value=T("Reset"),
                _type="submit",
                _name="reset",
                _id="form-reset",
            ),
            A(T("Cancel"), _href=r.url(id=0, vars={}), _class="action-lnk"),
            hidden={
                "mode": mode,
                "selected": ",".join(ids),
            },
        )

        # Process the merge form
        formname = "merge_%s_%s_%s" % (tablename, original[table._id],
                                       duplicate[table._id])
        if form.accepts(
                post_vars,
                session,
                formname=formname,
                onvalidation=lambda form: self.onvalidation(tablename, form),
                keepvalues=False,
                hideerror=False):

            s3db = current.s3db

            if form.vars[KEEP.d]:
                prefix = "%s_" % DUPLICATE
                original, duplicate = duplicate, original
            else:
                prefix = "%s_" % ORIGINAL

            data = Storage()
            for key in form.vars:
                if key.startswith(prefix):
                    fname = key.split("_", 1)[1]
                    data[fname] = form.vars[key]

            search = False
            resource = s3db.resource(tablename)
            try:
                resource.merge(original[table._id],
                               duplicate[table._id],
                               update=data)
            except current.auth.permission.error:
                r.unauthorised()
            except KeyError:
                r.error(404, current.ERROR.BAD_RECORD)
            except Exception:
                import sys
                r.error(424,
                        T("Could not merge records. (Internal Error: %s)") %
                        sys.exc_info()[1],
                        next=r.url())
            else:
                # Cleanup bookmark list
                if mode == "Inclusive":
                    bookmarks[tablename] = [
                        i for i in record_ids if i not in ids
                    ]
                    if not bookmarks[tablename]:
                        del bookmarks[tablename]
                        search = True
                elif mode == "Exclusive":
                    bookmarks[tablename].extend(ids)
                    if not selected:
                        search = True
                # Confirmation message
                # @todo: Having the link to the merged record in the confirmation
                # message would be nice, but it's currently not clickable there :/
                #result = A(T("Open the merged record"),
                #_href=r.url(method="read",
                #id=original[table._id],
                #vars={}))
                response.confirmation = T("Records merged successfully.")

            # Go back to bookmark list
            if search:
                self.next = r.url(method="", id=0, vars={})
            else:
                self.next = r.url(id=0, vars={})

        # View
        response.view = self._view(r, "merge.html")

        return output
예제 #17
0
def render_user_editorials_table(user_editorials,
                                 user_id=None,
                                 logged_in_user_id=None,
                                 read_editorial_class=""):
    """
        Render User editorials table

        @param user_editorials (Rows): Rows object of the editorials
        @param user_id (Number): For which user is the listing happening
        @param logged_in_user_id (Number): Which use is logged in
        @param read_editorial_class (String): HTML class for GA tracking

        @return (HTML): HTML table representing the user editorials
    """

    db = current.db
    atable = db.auth_user
    ptable = db.problem
    T = current.T

    user_ids = set([x.user_id for x in user_editorials])
    users = db(atable.id.belongs(user_ids)).select()
    user_mappings = {}
    for user in users:
        user_mappings[user.id] = user

    query = (ptable.id.belongs([x.problem_id for x in user_editorials]))
    problem_records = db(query).select(ptable.id, ptable.name, ptable.link)
    precords = {}
    for precord in problem_records:
        precords[precord.id] = {"name": precord.name, "link": precord.link}

    table = TABLE(_class="centered user-editorials-table")
    thead = THEAD(
        TR(TH(T("Problem")), TH(T("Editorial By")), TH(T("Added on")),
           TH(T("Votes")), TH()))
    tbody = TBODY()
    color_mapping = {"accepted": "green", "rejected": "red", "pending": "blue"}

    for editorial in user_editorials:
        if logged_in_user_id != 1 and user_id != editorial.user_id and editorial.verification != "accepted":
            continue

        user = user_mappings[editorial.user_id]
        record = precords[editorial.problem_id]
        number_of_votes = len(
            editorial.votes.split(",")) if editorial.votes else 0
        link_class = get_link_class(record["link"], logged_in_user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()
        tr = TR(
            TD(
                problem_widget(record["name"], record["link"], link_class,
                               link_title)))

        if logged_in_user_id is not None and \
           (editorial.user_id == logged_in_user_id or
            logged_in_user_id == 1):
            tr.append(TD(A(user.first_name + " " + user.last_name,
                         _href=URL("user",
                                   "profile",
                                   args=user.stopstalk_handle)),
                         " ",
                         DIV(editorial.verification.capitalize(),
                             _class="verification-badge " + \
                                    color_mapping[editorial.verification])))
        else:
            tr.append(
                TD(
                    A(user.first_name + " " + user.last_name,
                      _href=URL("user", "profile",
                                args=user.stopstalk_handle))))

        tr.append(TD(editorial.added_on))
        vote_class = ""
        if logged_in_user_id is not None and \
           str(logged_in_user_id) in set(editorial.votes.split(",")):
            vote_class = "red-text"
        tr.append(
            TD(
                DIV(SPAN(I(_class="fa fa-heart " + vote_class),
                         _class="love-editorial",
                         data={"id": editorial.id}),
                    " ",
                    DIV(number_of_votes,
                        _class="love-count",
                        _style="margin-left: 5px;"),
                    _style="display: inline-flex;")))

        actions_td = TD(
            A(I(_class="fa fa-eye fa-2x"),
              _href=URL("problems",
                        "read_editorial",
                        args=editorial.id,
                        extension=False),
              _class="btn btn-primary tooltipped " + read_editorial_class,
              _style="background-color: #13AA5F;",
              data={
                  "position": "bottom",
                  "delay": 40,
                  "tooltip": T("Read Editorial")
              }))
        if logged_in_user_id is not None and \
           (user.id == logged_in_user_id or logged_in_user_id == 1) and \
           editorial.verification != "accepted":
            actions_td.append(
                BUTTON(
                    I(_class="fa fa-trash fa-2x"),
                    _style="margin-left: 2%;",
                    _class="btn btn-primary red tooltipped delete-editorial",
                    data={
                        "position": "bottom",
                        "delay": 40,
                        "tooltip": T("Delete Editorial"),
                        "id": editorial.id
                    }))
        tr.append(actions_td)

        tbody.append(tr)

    table.append(thead)
    table.append(tbody)

    return table
예제 #18
0
파일: config.py 프로젝트: sahana/eden
    def event_rheader(r):
        rheader = None

        record = r.record
        if record and r.representation == "html":

            from gluon import A, DIV, TABLE, TR, TH
            from s3 import s3_rheader_tabs

            name = r.name
            if name == "incident":
                if settings.get_incident_label():  # == "Ticket"
                    label = T("Ticket Details")
                else:
                    label = T("Incident Details")
                tabs = [
                    (label, None),
                    #(T("Tasks"), "task"),
                    #(T("Human Resources"), "human_resource"),
                    #(T("Equipment"), "asset"),
                    (T("Action Plan"), "plan"),
                    (T("Incident Reports"), "incident_report"),
                    (T("Logs"), "log"),
                    (T("Expenses"), "expense"),
                    (T("Situation Reports"), "sitrep"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                record_id = r.id
                incident_type_id = record.incident_type_id

                editable = current.auth.s3_has_permission(
                    "UPDATE", "event_incident", record_id)

                if editable and r.method == "plan":
                    # Dropdown of Scenarios to select
                    # @ToDo: Move this to a Popup behind an Action Button, to make it clearer that this isn't a maintained link
                    # @ToDo: Also add 'Clear' button to clear all elements & start from a blank slate
                    stable = current.s3db.event_scenario
                    query = (stable.incident_type_id == incident_type_id) & \
                            (stable.deleted == False)
                    scenarios = current.db(query).select(
                        stable.id,
                        stable.name,
                    )
                    if len(scenarios) and r.method != "event":
                        from gluon import SELECT, OPTION
                        dropdown = SELECT(_id="scenarios")
                        dropdown["_data-incident_id"] = record_id
                        dappend = dropdown.append
                        dappend(OPTION(T("Select Scenario")))
                        for s in scenarios:
                            dappend(OPTION(s.name, _value=s.id))
                        scenarios = TR(
                            TH("%s: " % T("Apply Scenario")),
                            dropdown,
                        )
                        s3 = current.response.s3
                        script = "/%s/static/themes/SAFIRE/js/incident_profile.js" % r.application
                        if script not in s3.scripts:
                            s3.scripts.append(script)
                            s3.js_global.append(
                                '''i18n.scenarioConfirm="%s"''' %
                                T("Populate Incident with Tasks, Organizations, Positions and Equipment from the Scenario?"
                                  ))
                    else:
                        scenarios = ""
                else:
                    scenarios = ""

                if record.exercise:
                    exercise = TH(T("EXERCISE"))
                else:
                    exercise = TH()
                if record.closed:
                    closed = TH(T("CLOSED"))
                else:
                    closed = TH()

                if record.event_id or r.method == "event" or not editable:
                    event = ""
                else:
                    if settings.get_event_label():  # == "Disaster"
                        label = T("Assign to Disaster")
                    else:
                        label = T("Assign to Event")
                    event = A(label,
                              _href=URL(
                                  c="event",
                                  f="incident",
                                  args=[record_id, "event"],
                              ),
                              _class="action-btn")

                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(exercise),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.incident_type_id.label),
                            table.incident_type_id.represent(incident_type_id),
                        ),
                        TR(
                            TH("%s: " % table.location_id.label),
                            table.location_id.represent(record.location_id),
                        ),
                        # @ToDo: Add Zone
                        TR(
                            TH("%s: " % table.severity.label),
                            table.severity.represent(record.severity),
                        ),
                        TR(
                            TH("%s: " % table.level.label),
                            table.level.represent(record.level),
                        ),
                        TR(
                            TH("%s: " % table.organisation_id.label),
                            table.organisation_id.represent(
                                record.organisation_id),
                        ),
                        TR(
                            TH("%s: " % table.person_id.label),
                            table.person_id.represent(record.person_id),
                        ),
                        scenarios,
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                        TR(
                            TH("%s: " % table.date.label),
                            table.date.represent(record.date),
                        ),
                        TR(closed),
                        event,
                    ),
                    rheader_tabs)

        return rheader
예제 #19
0
def render_table(submissions, duplicates=[]):
    """
        Create the HTML table from submissions

        @param submissions (Dict): Dictionary of submissions to display
        @param duplicates (List): List of duplicate user ids

        @return (TABLE):  HTML TABLE containing all the submissions
    """

    status_dict = {"AC": "Accepted",
                   "WA": "Wrong Answer",
                   "TLE": "Time Limit Exceeded",
                   "MLE": "Memory Limit Exceeded",
                   "RE": "Runtime Error",
                   "CE": "Compile Error",
                   "SK": "Skipped",
                   "HCK": "Hacked",
                   "OTH": "Others"}

    table = TABLE(_class="striped centered")
    table.append(THEAD(TR(TH("User Name"),
                          TH("Site"),
                          TH("Site Handle"),
                          TH("Time of submission"),
                          TH("Problem"),
                          TH("Language"),
                          TH("Status"),
                          TH("Points"),
                          TH("View/Download Code"))))

    tbody = TBODY()
    for submission in submissions:
        span = SPAN()

        if submission.user_id:
            person_id = submission.user_id
        else:
            person_id = submission.custom_user_id

            # Check if the given custom_user is a duplicate
            # We need to do this because there might be a case
            # when a duplicate custom_user is created and then
            # his name or institute is changed
            for duplicate in duplicates:
                if duplicate[1] == person_id and duplicate[0]:
                    person_id = current.db.custom_friend(duplicate[0])
                    break

            span = SPAN(_class="orange tooltipped",
                        data={"position": "right",
                              "delay": "50",
                              "tooltip": "Custom User"},
                        _style="cursor: pointer; " + \
                                "float:right; " + \
                                "height:10px; " + \
                                "width:10px; " + \
                                "border-radius: 50%;")

        tr = TR()
        append = tr.append
        append(TD(DIV(span,
                      A(person_id.first_name + " " + person_id.last_name,
                        _href=URL("user", "profile",
                                  args=person_id.stopstalk_handle,
                                  extension=False),
                        _target="_blank"))))
        append(TD(submission.site))
        append(TD(A(submission.site_handle,
                    _href=get_link(submission.site,
                                   submission.site_handle),
                    _target="_blank")))
        append(TD(submission.time_stamp))
        append(TD(A(submission.problem_name,
                    _href=URL("problems",
                              "index",
                              vars={"pname": submission.problem_name,
                                    "plink": submission.problem_link},
                              extension=False),
                    _target="_blank")))
        append(TD(submission.lang))
        append(TD(IMG(_src=URL("static",
                               "images/" + submission.status + ".jpg",
                               extension=False),
                      _title=status_dict[submission.status],
                      _alt=status_dict[submission.status],
                      _style="height: 25px; width: 25px;")))
        append(TD(submission.points))

        if submission.view_link:
            if current.auth.is_logged_in():
                td = TD(A("View",
                          _href=submission.view_link,
                          _class="btn waves-light waves-effect",
                          _style="background-color: #FF5722",
                          _target="_blank"), " ")
                if submission.site != "HackerEarth":
                    td.append(A("Download",
                                _class="download-submission-button btn waves-light waves-effect",
                                _style="background-color: #2196F3",
                                _target="_blank",
                                data={"view-link": submission.view_link,
                                      "site": submission.site}))
                append(td)
            else:
                append(TD(A("View",
                            _class="btn tooltipped disabled",
                            _style="background-color: #FF5722",
                            _target="_blank",
                            data={"position": "bottom",
                                  "delay": "50",
                                  "tooltip": "Login to View"}),
                          " ",
                          A("Download",
                            _class="btn tooltipped disabled",
                            _style="background-color: #2196F3",
                            _target="_blank",
                            data={"position": "bottom",
                                  "delay": "50",
                                  "tooltip": "Login to Download"})))
        else:
            append(TD())

        tbody.append(tr)
    table.append(tbody)

    return table
예제 #20
0
파일: s3notify.py 프로젝트: nursix/eden
    def _render(cls, resource, data, meta_data, format=None):
        """
            Method to pre-render the contents for the message template

            @param resource: the S3Resource
            @param data: the data returned from S3Resource.select
            @param meta_data: the meta data for the notification
            @param format: the contents format ("text" or "html")
        """

        created_on_selector = resource.prefix_selector("created_on")
        created_on_colname = None
        notify_on = meta_data["notify_on"]
        last_check_time = meta_data["last_check_time"]
        rows = data["rows"]
        rfields = data["rfields"]
        output = {}
        new, upd = [], []

        if format == "html":
            # Pre-formatted HTML
            colnames = []

            new_headers = TR()
            mod_headers = TR()
            for rfield in rfields:
                if rfield.selector == created_on_selector:
                    created_on_colname = rfield.colname
                elif rfield.ftype != "id":
                    colnames.append(rfield.colname)
                    label = rfield.label
                    new_headers.append(TH(label))
                    mod_headers.append(TH(label))
            for row in rows:
                append_record = upd.append
                if created_on_colname:
                    try:
                        created_on = row["_row"][created_on_colname]
                    except (KeyError, AttributeError):
                        pass
                    else:
                        if s3_utc(created_on) >= last_check_time:
                            append_record = new.append
                tr = TR([TD(XML(row[colname])) for colname in colnames])
                append_record(tr)
            if "new" in notify_on and len(new):
                output["new"] = len(new)
                output["new_records"] = TABLE(THEAD(new_headers), TBODY(new))
            else:
                output["new"] = None
            if "upd" in notify_on and len(upd):
                output["upd"] = len(upd)
                output["upd_records"] = TABLE(THEAD(new_headers), TBODY(upd))
            else:
                output["upd"] = None

        else:
            # Standard text format
            labels = []
            append = labels.append

            for rfield in rfields:
                if rfield.selector == created_on_selector:
                    created_on_colname = rfield.colname
                elif rfield.ftype != "id":
                    append((rfield.colname, rfield.label))

            for row in rows:
                append_record = upd.append
                if created_on_colname:
                    try:
                        created_on = row["_row"][created_on_colname]
                    except (KeyError, AttributeError):
                        pass
                    else:
                        if s3_utc(created_on) >= last_check_time:
                            append_record = new.append

                record = []
                append_column = record.append
                for colname, label in labels:
                    append_column((label, row[colname]))
                append_record(record)

            if "new" in notify_on and len(new):
                output["new"] = len(new)
                output["new_records"] = new
            else:
                output["new"] = None
            if "upd" in notify_on and len(upd):
                output["upd"] = len(upd)
                output["upd_records"] = upd
            else:
                output["upd"] = None

        output.update(meta_data)
        return output
예제 #21
0
파일: cwa.py 프로젝트: sahana/eden
    def formatted(self, retry=False):
        """
            Formatted version of this report

            @param retry: add retry-action for sending to CWA

            @returns: a FORM containing
                      - the QR-code
                      - human-readable report details
                      - actions to download PDF, or retry sending to CWA
        """

        T = current.T
        table = current.s3db.disease_case_diagnostics

        # Personal Details
        data_repr = TABLE()
        data = self.data
        if not any(k in data for k in ("fn", "ln", "dob")):
            data_repr.append(
                TR(
                    TD(T("Person Tested")),
                    TD(T("anonymous"), _class="cwa-data"),
                ))
        else:
            labels = {
                "fn": T("First Name"),
                "ln": T("Last Name"),
                "dob": T("Date of Birth"),
            }
            for k in ("ln", "fn", "dob"):
                value = data[k]
                if k == "dob":
                    value = self.to_local_dtfmt(value)
                data_repr.append(
                    TR(
                        TD(labels.get(k)),
                        TD(value, _class="cwa-data"),
                    ))

        # Test Station, date and result
        field = table.site_id
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.site_id),
                        _class="cwa-data",
                    ),
                ))
        field = table.probe_date
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.probe_date),
                        _class="cwa-data",
                    ),
                ))
        field = table.result
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.result),
                        _class="cwa-data",
                    ),
                ))

        # Details
        details = DIV(
            H5(T("Details")),
            data_repr,
            _class="cwa-details",
        )

        # QR Code
        title = T("Code for %(app)s") % CWA
        qrcode = DIV(
            s3_qrcode_represent(self.get_link(), show_value=False),
            DIV(title, _class="cwa-qrcode-title"),
            _class="cwa-qrcode",
        )
        if retry:
            qrcode.add_class("hide")

        # Form buttons
        buttons = [
            BUTTON(
                T("Download PDF"),
                _class="tiny primary button cwa-pdf",
                _type="button",
            ),
        ]
        if retry:
            buttons[0].add_class("hide")
            buttons.append(
                BUTTON(
                    T("Retry sending to %(app)s") % CWA,
                    _class="tiny alert button cwa-retry",
                    _type="button",
                ))

        # Generate form key
        formurl = URL(
            c="disease",
            f="case_diagnostics",
            args=[self.result_id],
        )
        formkey = uuid.uuid4().hex

        # Store form key in session
        session = current.session
        keyname = "_formkey[testresult/%s]" % self.result_id
        session[keyname] = session.get(keyname, [])[-9:] + [formkey]

        form = FORM(
            DIV(
                DIV(
                    details,
                    qrcode,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            DIV(
                DIV(
                    buttons,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            hidden={
                "formurl": formurl,
                "cwadata": json.dumps(self.data),
                "_formkey": formkey,
            },
        )

        return form
예제 #22
0
파일: siglist.py 프로젝트: waidyanatha/eden
    def pdf(self, r, **attr):
        """
            Generate the PDF

            @param r: the S3Request instance
            @param attr: controller attributes
        """

        T = current.T

        db = current.db
        s3db = current.s3db

        # Look up the report organisation
        logo = None
        org_id, org_label = self.get_report_organisation(r)
        if org_id:
            # Look up the root organisation's logo
            otable = s3db.org_organisation
            rotable = otable.with_alias("root_organisation")
            join = rotable.on(rotable.id == otable.root_organisation)
            field = rotable.logo
            row = db(otable.id == org_id).select(field,
                                                 join = join,
                                                 limitby = (0, 1),
                                                 ).first()
            if row and row.logo:
                if field.uploadfolder:
                    path = field.uploadfolder
                else:
                    path = os.path.join(current.request.folder, 'uploads')
                logo = os.path.join(path, row.logo)

        # Look up the report programme
        prog_id, prog_label = self.get_report_programme(r)

        # Extract the HR records
        data, pictures = self.extract(r.resource)

        # Construct the header
        title = T("Official Volunteer List")
        header = TABLE(_class = "no-grid",
                       )
        trow = TR()
        if logo:
            trow.append(TD(IMG(_src=logo, _width="80"),
                           _rowspan = 3 if prog_id else 2,
                           ))
        trow.append(TD(H4(title), _colspan = 3))
        header.append(trow)
        if org_id:
            header.append(TR(TD(H5(org_label), _colspan = 3)))
        if prog_id:
            header.append(TR(TD(prog_label, _colspan = 3)))
        header.append(TR(TD()))

        # Should we show the branch column?
        branches = set(row["_row"]["hrm_human_resource.organisation_id"] for row in data.rows)
        if org_id:
            show_branch = len(branches) > 1
            org_repr = s3db.org_OrganisationRepresent(show_link = False,
                                                      parent = False,
                                                      acronym = True,
                                                      )
        else:
            show_branch = True
            org_repr = r.table.organisation_id.represent
        org_repr.bulk(list(branches))

        # Construct the table header
        labels = TR(TH(T("Picture")),
                    TH(T("Name")),
                    TH(T("Last Name")),
                    TH(T("National ID")),
                    TH(T("Volunteer ID")),
                    TH(T("Signature")),
                    )
        if not prog_id:
            labels.insert(1, TH(T("Program")))
        if show_branch:
            labels.insert(1, TH(T("Branch")))

        # Build the table
        body = TABLE(labels, _class="repeat-header shrink-to-fit")

        # Add the data rows
        for row in data.rows:

            raw = row._row

            # Picture
            picture = pictures.get(raw["pr_person.pe_id"])
            if picture:
                picture = IMG(_src=picture,
                              _width=80,
                              )
            else:
                picture = ""

            # Name
            name = s3_format_fullname(fname = raw["pr_person.first_name"],
                                      mname = raw["pr_person.middle_name"],
                                      lname = "",
                                      truncate = False,
                                      )

            # Build the row
            trow = TR(TD(picture),
                      TD(name),
                      TD(row["pr_person.last_name"]),
                      TD(row["pr_national_id_identity.value"]),
                      TD(row["hrm_human_resource.code"]),
                      TD(),
                      )
            if not prog_id:
                trow.insert(1, TD(row["hrm_programme_hours.programme_id"]))
            if show_branch:
                trow.insert(1, TD(org_repr(raw["hrm_human_resource.organisation_id"])))
            body.append(trow)

        footer = DIV()

        from s3.codecs.pdf import EdenDocTemplate, S3RL_PDF

        doc = EdenDocTemplate(title=title)
        printable_width = doc.printable_width

        get_html_flowable = S3RL_PDF().get_html_flowable

        header_flowable = get_html_flowable(header, printable_width)
        body_flowable = get_html_flowable(body, printable_width)
        footer_flowable = get_html_flowable(footer, printable_width)

        # Build the PDF
        doc.build(header_flowable,
                  body_flowable,
                  footer_flowable,
                  )
        filename = "siglist.pdf"

        # Return the generated PDF
        response = current.response
        response.headers["Content-Type"] = contenttype(".pdf")
        disposition = "attachment; filename=\"%s\"" % filename
        response.headers["Content-disposition"] = disposition

        return doc.output.getvalue()
def render_table(submissions, duplicates=[], user_id=None):
    """
        Create the HTML table from submissions

        @param submissions (Dict): Dictionary of submissions to display
        @param duplicates (List): List of duplicate user ids

        @return (TABLE):  HTML TABLE containing all the submissions
    """

    T = current.T
    status_dict = {
        "AC": "Accepted",
        "WA": "Wrong Answer",
        "TLE": "Time Limit Exceeded",
        "MLE": "Memory Limit Exceeded",
        "RE": "Runtime Error",
        "CE": "Compile Error",
        "SK": "Skipped",
        "HCK": "Hacked",
        "PS": "Partially Solved",
        "OTH": "Others"
    }

    table = TABLE(_class="bordered centered submissions-table")
    table.append(
        THEAD(
            TR(TH(T("Name")),
               TH(T("Site Profile")), TH(T("Time of submission")),
               TH(T("Problem")), TH(T("Language")), TH(T("Status")),
               TH(T("Points")), TH(T("View/Download Code")))))

    tbody = TBODY()
    # Dictionary to optimize lookup for solved and unsolved problems
    # Multiple lookups in the main set is bad
    plink_to_class = {}

    for submission in submissions:
        span = SPAN()

        if submission.user_id:
            person_id = submission.user_id
        else:
            person_id = submission.custom_user_id

            # Check if the given custom_user is a duplicate
            # We need to do this because there might be a case
            # when a duplicate custom_user is created and then
            # his name or institute is changed
            for duplicate in duplicates:
                if duplicate[1] == person_id and duplicate[0]:
                    person_id = current.db.custom_friend(duplicate[0])
                    break

            span = SPAN(_class="orange tooltipped",
                        data={"position": "right",
                              "delay": "50",
                              "tooltip": T("Custom User")},
                        _style="cursor: pointer; " + \
                                "float:right; " + \
                                "height:10px; " + \
                                "width:10px; " + \
                                "border-radius: 50%;")

        tr = TR()
        append = tr.append
        append(
            TD(
                DIV(
                    span,
                    A(person_id.first_name + " " + person_id.last_name,
                      _href=URL("user",
                                "profile",
                                args=person_id.stopstalk_handle,
                                extension=False),
                      _class="submission-user-name",
                      _target="_blank"))))
        append(TD(A(IMG(_src=current.get_static_url("images/" + \
                                            submission.site.lower() + \
                                            "_small.png"),
                        _style="height: 30px; width: 30px;"),
                    _class="submission-site-profile",
                    _href=current.get_profile_url(submission.site,
                                                  submission.site_handle),
                    _target="_blank")))

        append(TD(submission.time_stamp, _class="stopstalk-timestamp"))

        link_class = ""
        plink = submission.problem_link
        if plink_to_class.has_key(plink):
            link_class = plink_to_class[plink]
        else:
            link_class = get_link_class(plink, user_id)
            plink_to_class[plink] = link_class

        link_title = (" ".join(link_class.split("-"))).capitalize()

        append(
            TD(
                problem_widget(submission.problem_name,
                               submission.problem_link, link_class,
                               link_title)))
        append(TD(submission.lang))
        append(
            TD(
                IMG(_src=current.get_static_url("images/" + submission.status +
                                                ".jpg"),
                    _title=status_dict[submission.status],
                    _alt=status_dict[submission.status],
                    _class="status-icon")))
        append(TD(submission.points))

        if submission.view_link:
            submission_data = {
                "view-link": submission.view_link,
                "site": submission.site
            }
            button_class = "btn waves-light waves-effect"
            if current.auth.is_logged_in():
                if submission.site != "HackerEarth":
                    td = TD(BUTTON(T("View"),
                                   _class="view-submission-button " + button_class,
                                   _style="background-color: #FF5722",
                                   data=submission_data),
                            " ",
                            BUTTON(T("Download"),
                                   _class="download-submission-button " + \
                                          button_class,
                                   _style="background-color: #2196F3",
                                   data=submission_data))
                else:
                    td = TD(
                        A(T("View"),
                          _href=submission.view_link,
                          _class="btn waves-light waves-effect",
                          _style="background-color: #FF5722",
                          _target="_blank"))
                append(td)
            else:
                append(
                    TD(
                        BUTTON(T("View"),
                               _class="btn tooltipped disabled",
                               _style="background-color: #FF5722",
                               data={
                                   "position": "bottom",
                                   "delay": "50",
                                   "tooltip": T("Login to View")
                               }), " ",
                        BUTTON(T("Download"),
                               _class="btn tooltipped disabled",
                               _style="background-color: #2196F3",
                               data={
                                   "position": "bottom",
                                   "delay": "50",
                                   "tooltip": T("Login to Download")
                               })))
        else:
            append(TD())

        tbody.append(tr)
    table.append(tbody)

    return table
예제 #24
0
파일: config.py 프로젝트: Timileyin5/eden
    def event_rheader(r):
        rheader = None

        record = r.record
        if record and r.representation == "html":

            from gluon import A, DIV, TABLE, TR, TH
            from s3 import s3_rheader_tabs

            name = r.name
            if name == "incident":
                tabs = [
                    (T("Incident Details"), None),
                    #(T("Tasks"), "task"),
                    #(T("Human Resources"), "human_resource"),
                    #(T("Equipment"), "asset"),
                    (T("Action Plan"), "plan"),
                    (T("Incident Reports"), "incident_report"),
                    (T("Logs"), "log"),
                    (T("Expenses"), "expense"),
                    (T("Situation Reports"), "sitrep"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                record_id = r.id
                incident_type_id = record.incident_type_id

                # Dropdown of Scenarios to select
                stable = current.s3db.event_scenario
                query = (stable.incident_type_id == incident_type_id) & \
                        (stable.deleted == False)
                scenarios = current.db(query).select(
                    stable.id,
                    stable.name,
                )
                if len(scenarios) and r.method != "event":
                    from gluon import SELECT, OPTION
                    dropdown = SELECT(_id="scenarios")
                    dropdown["_data-incident_id"] = record_id
                    dappend = dropdown.append
                    dappend(OPTION(T("Select Scenario")))
                    for s in scenarios:
                        dappend(OPTION(s.name, _value=s.id))
                    scenarios = TR(
                        TH("%s: " % T("Scenario")),
                        dropdown,
                    )
                    s3 = current.response.s3
                    script = "/%s/static/themes/SAFIRE/js/incident_profile.js" % r.application
                    if script not in s3.scripts:
                        s3.scripts.append(script)
                        s3.js_global.append('''i18n.scenarioConfirm="%s"''' % T(
                            "Populate Incident with Tasks, Organizations, Positions and Equipment from the Scenario?"
                        ))
                else:
                    scenarios = ""

                if record.exercise:
                    exercise = TH(T("EXERCISE"))
                else:
                    exercise = TH()
                if record.closed:
                    closed = TH(T("CLOSED"))
                else:
                    closed = TH()

                if record.event_id or r.method == "event":
                    event = ""
                else:
                    event = A(T("Assign to Event"),
                              _href=URL(
                                  c="event",
                                  f="incident",
                                  args=[record_id, "event"],
                              ),
                              _class="action-btn")

                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(exercise),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.incident_type_id.label),
                            table.incident_type_id.represent(incident_type_id),
                        ),
                        TR(
                            TH("%s: " % table.location_id.label),
                            table.location_id.represent(record.location_id),
                        ),
                        # @ToDo: Add Zone
                        TR(
                            TH("%s: " % table.severity.label),
                            table.severity.represent(record.severity),
                        ),
                        TR(
                            TH("%s: " % table.level.label),
                            table.level.represent(record.level),
                        ),
                        TR(
                            TH("%s: " % table.organisation_id.label),
                            table.organisation_id.represent(
                                record.organisation_id),
                        ),
                        TR(
                            TH("%s: " % table.person_id.label),
                            table.person_id.represent(record.person_id),
                        ),
                        scenarios,
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                        TR(
                            TH("%s: " % table.date.label),
                            table.date.represent(record.date),
                        ),
                        TR(closed),
                        event,
                    ),
                    rheader_tabs)

            elif name == "incident_report":
                record_id = r.id
                ltable = current.s3db.event_incident_report_incident
                query = (ltable.incident_report_id == record_id)
                link = current.db(query).select(ltable.incident_id,
                                                limitby=(0, 1)).first()
                if link:
                    from s3 import S3Represent
                    represent = S3Represent(lookup="event_incident",
                                            show_link=True)
                    rheader = DIV(
                        TABLE(
                            TR(
                                TH("%s: " % ltable.incident_id.label),
                                represent(link.incident_id),
                            ), ))
                else:
                    rheader = DIV(
                        A(T("Assign to Incident"),
                          _href=URL(
                              c="event",
                              f="incident_report",
                              args=[record_id, "assign"],
                          ),
                          _class="action-btn"))

            elif name == "event":
                tabs = [
                    (T("Event Details"), None),
                    (T("Incidents"), "incident"),
                    (T("Documents"), "document"),
                    (T("Photos"), "image"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(
                            TH("%s: " % table.event_type_id.label),
                            table.event_type_id.represent(
                                record.event_type_id),
                        ),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.start_date.label),
                            table.start_date.represent(record.start_date),
                        ),
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                    ), rheader_tabs)

            elif name == "scenario":
                tabs = [
                    (T("Scenario Details"), None),
                    #(T("Tasks"), "task"),
                    #(T("Human Resources"), "human_resource"),
                    #(T("Equipment"), "asset"),
                    (T("Action Plan"), "plan"),
                    (T("Incident Reports"), "incident_report"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(
                            TH("%s: " % table.incident_type_id.label),
                            table.incident_type_id.represent(
                                record.incident_type_id),
                        ),
                        TR(
                            TH("%s: " % table.organisation_id.label),
                            table.organisation_id.represent(
                                record.organisation_id),
                        ),
                        TR(
                            TH("%s: " % table.location_id.label),
                            table.location_id.represent(record.location_id),
                        ),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                    ), rheader_tabs)

        return rheader
예제 #25
0
파일: siglist.py 프로젝트: sahana/eden
    def pdf(self, r, **attr):
        """
            Generate the PDF

            Args:
                r: the S3Request instance
                attr: controller attributes
        """

        T = current.T

        db = current.db
        s3db = current.s3db

        # Look up the report organisation
        logo = None
        org_id, org_label = self.get_report_organisation(r)
        if org_id:
            # Look up the root organisation's logo
            otable = s3db.org_organisation
            rotable = otable.with_alias("root_organisation")
            join = rotable.on(rotable.id == otable.root_organisation)
            field = rotable.logo
            row = db(otable.id == org_id).select(
                field,
                join=join,
                limitby=(0, 1),
            ).first()
            if row and row.logo:
                if field.uploadfolder:
                    path = field.uploadfolder
                else:
                    path = os.path.join(current.request.folder, 'uploads')
                logo = os.path.join(path, row.logo)

        # Look up the report programme
        prog_id, prog_label = self.get_report_programme(r)

        # Extract the HR records
        data, pictures = self.extract(r.resource)

        # Construct the header
        title = T("Official Volunteer List")
        header = TABLE(_class="no-grid", )
        trow = TR()
        if logo:
            trow.append(
                TD(
                    IMG(_src=logo, _width="80"),
                    _rowspan=3 if prog_id else 2,
                ))
        trow.append(TD(H4(title), _colspan=3))
        header.append(trow)
        if org_id:
            header.append(TR(TD(H5(org_label), _colspan=3)))
        if prog_id:
            header.append(TR(TD(prog_label, _colspan=3)))
        header.append(TR(TD()))

        # Should we show the branch column?
        branches = set(row["_row"]["hrm_human_resource.organisation_id"]
                       for row in data.rows)
        if org_id:
            show_branch = len(branches) > 1
            org_repr = s3db.org_OrganisationRepresent(
                show_link=False,
                parent=False,
                acronym=True,
            )
        else:
            show_branch = True
            org_repr = r.table.organisation_id.represent
        org_repr.bulk(list(branches))

        # Construct the table header
        labels = TR(
            TH(T("Picture")),
            TH(T("Name")),
            TH(T("Last Name")),
            TH(T("National ID")),
            TH(T("Volunteer ID")),
            TH(T("Signature")),
        )
        if not prog_id:
            labels.insert(1, TH(T("Program")))
        if show_branch:
            labels.insert(1, TH(T("Branch")))

        # Build the table
        body = TABLE(labels, _class="repeat-header shrink-to-fit")

        # Add the data rows
        for row in data.rows:

            raw = row._row

            # Picture
            picture = pictures.get(raw["pr_person.pe_id"])
            if picture:
                picture = IMG(
                    _src=picture,
                    _width=80,
                )
            else:
                picture = ""

            # Name
            name = s3_format_fullname(
                fname=raw["pr_person.first_name"],
                mname=raw["pr_person.middle_name"],
                lname="",
                truncate=False,
            )

            # Build the row
            trow = TR(
                TD(picture),
                TD(name),
                TD(row["pr_person.last_name"]),
                TD(row["pr_national_id_identity.value"]),
                TD(row["hrm_human_resource.code"]),
                TD(),
            )
            if not prog_id:
                trow.insert(1, TD(row["hrm_programme_hours.programme_id"]))
            if show_branch:
                trow.insert(
                    1, TD(org_repr(raw["hrm_human_resource.organisation_id"])))
            body.append(trow)

        footer = DIV()

        from s3.codecs.pdf import EdenDocTemplate, S3RL_PDF

        doc = EdenDocTemplate(title=title)
        printable_width = doc.printable_width

        get_html_flowable = S3RL_PDF().get_html_flowable

        header_flowable = get_html_flowable(header, printable_width)
        body_flowable = get_html_flowable(body, printable_width)
        footer_flowable = get_html_flowable(footer, printable_width)

        # Build the PDF
        doc.build(
            header_flowable,
            body_flowable,
            footer_flowable,
        )
        filename = "siglist.pdf"

        # Return the generated PDF
        response = current.response
        response.headers["Content-Type"] = contenttype(".pdf")
        disposition = "attachment; filename=\"%s\"" % filename
        response.headers["Content-disposition"] = disposition

        return doc.output.getvalue()
예제 #26
0
 def create_balance_table(self):
     table_keys = THEAD(TR(*[TD(B(k)) for k in self.balance_table_columns]))
     table_rows = [TR(*[TD(v) for k, v in row.items()])
                   for row in self.balance_per_category]
     balance_table = TABLE(table_keys, table_rows, _class='web2py_grid')
     return balance_table
예제 #27
0
파일: s3notify.py 프로젝트: xuebozhu/eden
    def _render(cls, resource, data, meta_data, format=None):
        """
            Method to pre-render the contents for the message template

            @param resource: the S3Resource
            @param data: the data returned from S3Resource.select
            @param meta_data: the meta data for the notification
            @param format: the contents format ("text" or "html")
        """

        created_on_selector = resource.prefix_selector("created_on")
        created_on_colname = None
        notify_on = meta_data["notify_on"]
        last_check_time = meta_data["last_check_time"]
        rows = data["rows"]
        rfields = data["rfields"]
        output = {}
        new, upd = [], []

        if format == "html":
            # Pre-formatted HTML
            colnames = []

            new_headers = TR()
            mod_headers = TR()
            for rfield in rfields:
                if rfield.selector == created_on_selector:
                    created_on_colname = rfield.colname
                elif rfield.ftype != "id":
                    colnames.append(rfield.colname)
                    label = rfield.label
                    new_headers.append(TH(label))
                    mod_headers.append(TH(label))
            for row in rows:
                append_record = upd.append
                if created_on_colname:
                    try:
                        created_on = row["_row"][created_on_colname]
                    except (KeyError, AttributeError):
                        pass
                    else:
                        if s3_utc(created_on) >= last_check_time:
                            append_record = new.append
                tr = TR([TD(XML(row[colname])) for colname in colnames])
                append_record(tr)
            if "new" in notify_on and len(new):
                output["new"] = len(new)
                output["new_records"] = TABLE(THEAD(new_headers), TBODY(new))
            else:
                output["new"] = None
            if "upd" in notify_on and len(upd):
                output["upd"] = len(upd)
                output["upd_records"] = TABLE(THEAD(new_headers), TBODY(upd))
            else:
                output["upd"] = None

        else:
            # Standard text format
            labels = []
            append = labels.append

            for rfield in rfields:
                if rfield.selector == created_on_selector:
                    created_on_colname = rfield.colname
                elif rfield.ftype != "id":
                    append((rfield.colname, rfield.label))

            for row in rows:
                append_record = upd.append
                if created_on_colname:
                    try:
                        created_on = row["_row"][created_on_colname]
                    except (KeyError, AttributeError):
                        pass
                    else:
                        if s3_utc(created_on) >= last_check_time:
                            append_record = new.append

                record = []
                append_column = record.append
                for colname, label in labels:
                    append_column((label, row[colname]))
                append_record(record)

            if "new" in notify_on and len(new):
                output["new"] = len(new)
                output["new_records"] = new
            else:
                output["new"] = None
            if "upd" in notify_on and len(upd):
                output["upd"] = len(upd)
                output["upd_records"] = upd
            else:
                output["upd"] = None

        output.update(meta_data)
        return output
예제 #28
0
    def event_rheader(r):
        rheader = None

        record = r.record
        if record and r.representation == "html":

            from gluon import DIV, TABLE, TR, TH
            from s3 import s3_rheader_tabs

            name = r.name
            if name == "incident":
                # Incident Controller
                tabs = [
                    (T("Incident Details"), None),
                    #(T("Tasks"), "task"),
                    #(T("Human Resources"), "human_resource"),
                    #(T("Equipment"), "asset"),
                    (T("Action Plan"), "plan"),
                    (T("Incident Reports"), "incident_report"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                incident_type_id = record.incident_type_id
                # Dropdown of Scenarios to select
                stable = current.s3db.event_scenario
                query = (stable.incident_type_id == incident_type_id) & \
                        (stable.deleted == False)
                scenarios = current.db(query).select(
                    stable.id,
                    stable.name,
                )
                if len(scenarios):
                    from gluon import SELECT, OPTION
                    dropdown = SELECT(_id="scenarios")
                    dropdown["_data-incident_id"] = r.id
                    dappend = dropdown.append
                    dappend(OPTION(T("Select Scenario")))
                    for s in scenarios:
                        dappend(OPTION(s.name, _value=s.id))
                    scenarios = TR(
                        TH("%s: " % T("Scenario")),
                        dropdown,
                    )
                    s3 = current.response.s3
                    script = "/%s/static/themes/SAFIRE/js/incident_profile.js" % r.application
                    if script not in s3.scripts:
                        s3.scripts.append(script)
                        s3.js_global.append('''i18n.scenarioConfirm="%s"''' % T(
                            "Populate Incident with Tasks, Positions and Equipment from the Scenario?"
                        ))
                else:
                    scenarios = ""

                if record.exercise:
                    exercise = TH(T("EXERCISE"))
                else:
                    exercise = TH()
                if record.closed:
                    closed = TH(T("CLOSED"))
                else:
                    closed = TH()
                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(exercise),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.incident_type_id.label),
                            table.incident_type_id.represent(incident_type_id),
                        ),
                        TR(
                            TH("%s: " % table.person_id.label),
                            table.person_id.represent(record.person_id),
                        ),
                        scenarios,
                        TR(
                            TH("%s: " % table.location_id.label),
                            table.location_id.represent(record.location_id),
                        ),
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                        TR(
                            TH("%s: " % table.date.label),
                            table.date.represent(record.date),
                        ),
                        TR(closed),
                    ), rheader_tabs)

            elif name == "scenario":
                # Scenarios Controller
                tabs = [
                    (T("Scenario Details"), None),
                    #(T("Tasks"), "task"),
                    #(T("Human Resources"), "human_resource"),
                    #(T("Equipment"), "asset"),
                    (T("Action Plan"), "plan"),
                    (T("Incident Reports"), "incident_report"),
                ]

                rheader_tabs = s3_rheader_tabs(r, tabs)

                table = r.table
                rheader = DIV(
                    TABLE(
                        TR(
                            TH("%s: " % table.incident_type_id.label),
                            table.incident_type_id.represent(
                                record.incident_type_id),
                        ),
                        TR(
                            TH("%s: " % table.name.label),
                            record.name,
                        ),
                        TR(
                            TH("%s: " % table.comments.label),
                            record.comments,
                        ),
                    ), rheader_tabs)

        return rheader
예제 #29
0
def render_table(submissions, duplicates=[]):
    """
        Create the HTML table from submissions
    """

    status_dict = {
        "AC": "Accepted",
        "WA": "Wrong Answer",
        "TLE": "Time Limit Exceeded",
        "MLE": "Memory Limit Exceeded",
        "RE": "Runtime Error",
        "CE": "Compile Error",
        "SK": "Skipped",
        "HCK": "Hacked",
        "OTH": "Others"
    }

    table = TABLE(_class="striped centered")
    table.append(
        THEAD(
            TR(TH("User Name"), TH("Site"), TH("Site Handle"),
               TH("Time of submission"), TH("Problem"), TH("Language"),
               TH("Status"), TH("Points"), TH("View Code"))))

    tbody = TBODY()
    for submission in submissions:
        tr = TR()
        append = tr.append
        span = SPAN()

        if submission.user_id:
            person_id = submission.user_id
        else:
            person_id = submission.custom_user_id

            # Check if the given custom_user is a duplicate
            # We need to do this because there might be a case
            # when a duplicate custom_user is created and then
            # his name or institute is changed
            for f in duplicates:
                if f[1] == person_id and f[0] != None:
                    person_id = current.db.custom_friend(f[0])
                    break
            span = SPAN(_class="orange tooltipped",
                        data={"position": "right",
                              "delay": "50",
                              "tooltip": "Custom User"},
                        _style="cursor: pointer; " + \
                                "float:right; " + \
                                "height:10px; " + \
                                "width:10px; " + \
                                "border-radius: 50%;")

        append(
            TD(
                DIV(
                    span,
                    A(person_id.first_name + " " + person_id.last_name,
                      _href=URL("user",
                                "profile",
                                args=[person_id.stopstalk_handle],
                                extension=False),
                      _target="_blank"))))
        append(TD(submission.site))
        append(
            TD(
                A(submission.site_handle,
                  _href=get_link(submission.site, submission.site_handle),
                  _target="_blank")))
        append(TD(submission.time_stamp))
        append(
            TD(
                A(submission.problem_name,
                  _href=URL("problems",
                            "index",
                            vars={
                                "pname": submission.problem_name,
                                "plink": submission.problem_link
                            },
                            extension=False),
                  _target="_blank")))
        append(TD(submission.lang))
        append(
            TD(
                IMG(_src=URL("static",
                             "images/" + submission.status + ".jpg",
                             extension=False),
                    _title=status_dict[submission.status],
                    _alt=status_dict[submission.status],
                    _style="height: 25px; width: 25px;")))
        append(TD(submission.points))

        if submission.view_link:
            append(
                TD(
                    A("View",
                      _href=submission.view_link,
                      _class="btn waves-light waves-effect",
                      _style="background-color: #FF5722",
                      _target="_blank")))
        else:
            append(TD())

        tbody.append(tr)
    table.append(tbody)
    return table
예제 #30
0
파일: config.py 프로젝트: nursix/eden
    def ucce_rheader(r):
        """
            Custom rheaders
        """

        if r.representation != "html":
            # RHeaders only used in interactive views
            return None

        # Need to use this format as otherwise req_match?viewing=org_office.x
        # doesn't have an rheader
        from s3 import s3_rheader_resource, s3_rheader_tabs
        tablename, record = s3_rheader_resource(r)

        if record is None:
            # List or Create form: rheader makes no sense here
            return None

        from gluon import A, DIV, TABLE, TR, TH, URL

        if tablename == "dc_template":
            #tabs = [(T("Basic Details"), None),
            #        (T("Participants"), "participant"),
            #        ]

            #rheader_tabs = s3_rheader_tabs(r, tabs)

            db = current.db
            s3db = current.s3db

            ttable = s3db.dc_target
            target = db(ttable.template_id == record.id).select(ttable.id,
                                                                ttable.status,
                                                                limitby = (0, 1)
                                                                ).first()
            try:
                target_id = target.id
                target_status = target.status
            except AttributeError:
                target_id = None
                target_status = None

            if not target_status:
                # No Target linked...something odd happening
                button = ""
            elif target_status == 2:
                # Active
                button = A(T("Deactivate"),
                           _href=URL(c="dc", f="target",
                                     args=[target_id, "deactivate.popup"],
                                     ),
                           _class="action-btn s3_modal",
                           _title=T("Deactivate Survey"),
                           )
            else:
                # Draft / Deactivated
                button = A(T("Activate"),
                           _href=URL(c="dc", f="target",
                                     args=[target_id, "activate.popup"],
                                     ),
                           _class="action-btn s3_modal",
                           _title=T("Activate Survey"),
                           )

            ptable = s3db.project_project
            ltable = s3db.project_project_target
            query = (ltable.target_id == target_id) & \
                    (ltable.project_id == ptable.id)
            project = db(query).select(ptable.name,
                                       limitby = (0, 1)
                                       ).first()
            try:
                project_name = project.name
            except AttributeError:
                project_name = ""

            #table = r.table
            rheader = DIV(TABLE(TR(# @ToDo: make this editable
                                   TH("%s: " % T("Survey name")),
                                   record.name,
                                   TH("%s: " % T("Project")),
                                   project_name,
                                   button,
                                   )),
                          #rheader_tabs,
                          )

        return rheader
예제 #31
0
def drk_org_rheader(r, tabs=None):
    """ ORG custom resource headers """

    if r.representation != "html":
        # Resource headers only used in interactive views
        return None

    from s3 import s3_rheader_resource, s3_rheader_tabs, S3ResourceHeader
    from .uioptions import get_ui_options

    s3db = current.s3db

    tablename, record = s3_rheader_resource(r)
    if tablename != r.tablename:
        resource = s3db.resource(tablename, id=record.id)
    else:
        resource = r.resource

    rheader = None
    rheader_fields = []

    if record:
        T = current.T
        record_id = record.id

        ui_options = get_ui_options()
        is_admin = current.auth.s3_has_role("ADMIN")

        if tablename == "org_organisation":

            table = resource.table

            if record.root_organisation == record_id:
                branch = False
            else:
                branch = True

            # Custom tabs
            tabs = [(T("Basic Details"), None),
                    (T("Branches"), "branch"),
                    (T("Facilities"), "facility"),
                    (T("Staff & Volunteers"), "human_resource"),
                    #(T("Projects"), "project"),
                    (T("Counseling Themes"), "response_theme"),
                    ]

            if is_admin or ui_options.get("response_themes_needs"):
                # Ability to manage org-specific need types
                # as they are used in themes:
                tabs.append((T("Counseling Reasons"), "need"))

            if not branch and \
               (is_admin or \
                ui_options.get("case_document_templates") and \
                current.auth.s3_has_role("ORG_ADMIN")):
                tabs.append((T("Document Templates"), "document"))

            rheader_tabs = s3_rheader_tabs(r, tabs)

            # Custom header
            from gluon import TABLE, TR, TH, TD
            rheader = DIV()

            # Name
            record_data = TABLE(TR(TH("%s: " % table.name.label),
                                   record.name,
                                   ),
                                )

            # Parent Organisation
            if branch:
                btable = s3db.org_organisation_branch
                query = (btable.branch_id == record_id) & \
                        (btable.organisation_id == table.id)
                row = current.db(query).select(table.id,
                                               table.name,
                                               limitby = (0, 1),
                                               ).first()
                if row:
                    record_data.append(TR(TH("%s: " % T("Branch of")),
                                          A(row.name, _href=URL(args=[row.id, "read"])),
                                          ))

            # Website as link
            if record.website:
                record_data.append(TR(TH("%s: " % table.website.label),
                                      A(record.website, _href=record.website)))

            logo = s3db.org_organisation_logo(record)
            if logo:
                rheader.append(TABLE(TR(TD(logo),
                                        TD(record_data),
                                        )))
            else:
                rheader.append(record_data)

            rheader.append(rheader_tabs)
            return rheader

        elif tablename == "org_facility":

            if not tabs:
                tabs = [(T("Basic Details"), None),
                        ]

            rheader_fields = [["name", "email"],
                              ["organisation_id", "phone1"],
                              ["location_id", "phone2"],
                              ]

        rheader = S3ResourceHeader(rheader_fields, tabs)(r,
                                                         table=resource.table,
                                                         record=record,
                                                         )
    return rheader
예제 #32
0
def render_table(submissions):
    """
        Create the HTML table from submissions
    """

    status_dict = {
        "AC": "Accepted",
        "WA": "Wrong Answer",
        "TLE": "Time Limit Exceeded",
        "MLE": "Memory Limit Exceeded",
        "RE": "Runtime Error",
        "CE": "Compile Error",
        "SK": "Skipped",
        "HCK": "Hacked",
        "OTH": "Others"
    }

    table = TABLE(_class="striped centered")
    table.append(
        THEAD(
            TR(TH("User Name"), TH("Site"), TH("Site Handle"),
               TH("Time of submission"), TH("Problem"), TH("Language"),
               TH("Status"), TH("Points"), TH("View Code"))))

    tbody = TBODY()
    for submission in submissions:
        tr = TR()
        append = tr.append

        person_id = submission.custom_user_id
        if submission.user_id:
            person_id = submission.user_id

        append(
            TD(
                A(person_id.first_name + " " + person_id.last_name,
                  _href=URL("user",
                            "profile",
                            args=[submission.stopstalk_handle]),
                  _target="_blank")))
        append(TD(submission.site))
        append(
            TD(
                A(submission.site_handle,
                  _href=get_link(submission.site, submission.site_handle),
                  _target="_blank")))
        append(TD(submission.time_stamp))
        append(
            TD(
                A(submission.problem_name,
                  _href=URL("problems",
                            "index",
                            vars={
                                "pname": submission.problem_name,
                                "plink": submission.problem_link
                            }),
                  _target="_blank")))
        append(TD(submission.lang))
        append(
            TD(
                IMG(_src=URL("static", "images/" + submission.status + ".jpg"),
                    _title=status_dict[submission.status],
                    _style="height: 25px; width: 25px;")))
        append(TD(submission.points))

        if submission.view_link:
            append(
                TD(
                    A("View",
                      _href=submission.view_link,
                      _class="btn waves-light waves-effect",
                      _style="background-color: #FF5722",
                      _target="_blank")))
        else:
            append(TD())

        tbody.append(tr)
    table.append(tbody)
    return table