Example #1
0
    def remove_from_book(self):
        user = self.session.auth.user if self.session.auth else None
        if user:
            try:
                article_id = int(self.request.args(0))
            except Exception:
                article_id = False

            if article_id:
                try:
                    query = (self.db.CookRecipeBook.article_id == int(
                        self.request.args(0))) & (
                            self.db.CookRecipeBook.user_id == user.id)
                    self.db(query).delete()
                except Exception, e:
                    self.context.error = str(e)
                    self.db.rollback()
                    return "alert('Error')"
                else:
                    self.db.commit()
                    if not 'show' in self.request.args:
                        return "jQuery('#article_%s').remove();" % str(
                            article_id)
                    else:
                        return BUTTON(
                            TAG.I(_class="icon-plus",
                                  _style="margin-right:5px"),
                            self.T("Add to my book"),
                            _class=
                            "button button not-on-book btn btn-success addtobookbutton",
                            _onclick="ajax('%s', [], 'addtobookbutton');" %
                            URL('cookrecipe',
                                'addtobook',
                                args=[self.request.args(0), 'show']))
Example #2
0
 def add_to_book_button(self):
     user = self.session.auth.user if self.session.auth else None
     if user:
         already = self.db.CookRecipeBook(article_id=int(self.request.args(0)), user_id=user.id)
         if already:
             bt = BUTTON(self.T("On your book! (remove)"),
                         _class="button already-on-book",
                         _onclick="ajax('%s', [], 'addtobookbutton');" % URL('cookrecipe', 'removefrombook', args=self.request.args(0)))
         else:
             bt = BUTTON(self.T("Add to my book"),
                         _class="button button not-on-book",
                         _onclick="ajax('%s', [], 'addtobookbutton');" % URL('cookrecipe', 'addtobook', args=self.request.args(0)))
     else:
         bt = BUTTON(self.T("Add to my book"),
                         _class="button button not-on-book",
                         _onclick="window.location = '%s';" % URL('default', 'user',
                              args='login', vars=dict(_next=self.CURL('article', 'show', args=self.request.args(0)))))
     return bt
Example #3
0
 def add_to_book_button(self):
     user = self.session.auth.user if self.session.auth else None
     if user:
         already = self.db.CookRecipeBook(article_id=int(
             self.request.args(0)),
                                          user_id=user.id)
         if already:
             bt = BUTTON(
                 TAG.I(_class="icon-minus", _style="margin-right:5px"),
                 self.T("Remove from book!"),
                 _class=
                 "button already-on-book btn btn-danger addtobookbutton",
                 _onclick="ajax('%s', [], 'addtobookbutton');" %
                 URL('cookrecipe',
                     'removefrombook',
                     args=[self.request.args(0), 'show']))
         else:
             bt = BUTTON(
                 TAG.I(_class="icon-plus", _style="margin-right:5px"),
                 self.T("Add to my book"),
                 _class=
                 "button button not-on-book btn btn-success addtobookbutton",
                 _onclick="ajax('%s', [], 'addtobookbutton');" %
                 URL('cookrecipe',
                     'addtobook',
                     args=[self.request.args(0), 'show']))
     else:
         bt = BUTTON(
             TAG.I(_class="icon-plus", _style="margin-right:5px"),
             self.T("Add to my book"),
             _class=
             "button button not-on-book btn btn-success addtobookbutton",
             _onclick="window.location = '%s';" %
             URL('person',
                 'account',
                 args='login',
                 vars=dict(_next=self.CURL(
                     'article', 'show', args=[self.request.args(0), 'show'
                                              ]))))
     return bt
Example #4
0
    def buttons():
        """
            Generate the submit/cancel buttons for the anonymize-form

            @return: the buttons row (DIV)
        """

        T = current.T

        return DIV(BUTTON(T("Submit"),
                          _class = "small alert button anonymize-submit",
                          _disabled = "disabled",
                          _type = "button",
                          ),
                   A(T("Cancel"),
                     _class = "cancel-form-btn action-lnk anonymize-cancel",
                     _href = "javascript:void(0)",
                     ),
                   _class = "anonymize-buttons",
                   )
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
Example #6
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
Example #7
0
File: cwa.py Project: 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
Example #8
0
def MODAL(triggertext,
          headertext,
          body,
          footer=None,
          modal_classes='',
          trigger_classes=None,
          id='mymodal',
          trigger_type='link',
          attributes=None):
    '''
    Returns a bootstrap 3 modal widget wrapped in a web2py CAT() helper.

    The returned widget can be included in a view as a single helper, in which
    case the hidden modal window is placed immediately following the trigger
    element in the DOM. This is not desireable, though, if the parent of the
    trigger element has relative positioning, since the modal window will
    appear behind its dark background mask (and possibly behind other page
    elements). In that case, one can include the link alone as MODAL()[0]. The
    modal window can then be included separately at a higher level of the html
    structure by calling MODAL()[1] at the appropriate point in the view.

    The following positional arguments are required:
        [0] triggertext     (str) The text for the link to trigger the modal.
        [1] headertext      (str or 0) The text for the modal header. If the
                            value is 0, no header will be included.
        [2] body            (str or helper obj) The content to be displayed in
                            the modal body. If this is a LOAD helper the body
                            content will be loaded via ajax *on page load*, not
                            when the modal is shown.

    The following named arguments are optional:
        :footer              (str, helper obj, or 0) The content to be displayed in
                            the modal footer. If this argument is not provided,
                            the default footer is a simple "Close" button. If
                            the value is the integer 0, no footer will be
                            included at all.
        :modal_classes       (str) A string including the extra classes to be
                            assigned to the modal div.
        :trigger_classes     (str) A string including the extra classes to be
                            assigned to the button/link triggering the modal.
        :id                  (str or int) The id to be assigned to the modal div.
                            defaults to 'mymodal'. If multiple modals are
                            present on a paget this value must be specified
                            (and distinct) for each. The id for the trigger
                            will always be this same string with the suffix
                            '_trigger'.
        :trigger_type        (str: 'button' | 'link') Specifies the html entity
                            to be used to trigger the modal. Defaults to 'link'
                            which returns an A() helper.
        :attributes          (dict) The names and values of any attributes to
                            be assigned to the modal trigger. These can include
                            data-attributes for setting additional modal
                            options (as per the bootstrap 2.3.2 api). These
                            attributes can also include an _href url (if the
                            trigger type is 'link'). Otherwise the trigger link
                            will not have any href value, since it is not
                            needed by the Bootstrap modal script.

    The close button in the default footer requires no extra javascript (beyond
    the Bootstrap modal plugin).
    '''
    # create trigger
    t_classes = trigger_classes if trigger_classes else ''
    if trigger_type == 'button':
        t_classes += 'btn'
    t_args = {
        '_data-toggle': 'modal',
        '_data-target': '#{}'.format(id),
        '_data-keyboard': True,
        '_href': '#{}'.format(id),
        '_id': '{}_trigger'.format(id),
        '_class': t_classes
    }
    if attributes:
        t_args.update(attributes)
    if trigger_type == 'link':
        trigger = A(triggertext, **t_args)
    else:
        trigger = BUTTON(triggertext, **t_args)

    # create wrapper div for modal
    modal_attrs = {
        '_tabindex': '-1',
        '_role': 'dialog',
        '_data-keyboard': 'true',
        '_aria-labelledby': '{}_trigger'.format(id),
        '_aria-hidden': 'true'
    }
    modal = DIV(DIV(DIV(_class="modal-content"),
                    _class="modal-dialog modal-lg"),
                _class="modal fade {}".format(modal_classes),
                _id=id,
                **modal_attrs)

    # add header
    if headertext != 0:
        m_head = DIV(H3(headertext, _id="myModalLabel", _class="modal-title"),
                     _class="modal-header")
        modal[0][0].append(m_head)
    else:
        pass

    # add body content
    modal[0][0].append(DIV(body, _class='modal-body {}'.format(modal_classes)))
    # add footer
    if footer and footer != 0:
        modal[0][0].append(DIV(footer, _class='modal-footer'))
    elif not footer:
        attrs = {
            '_type': 'button',
            '_data-dismiss': "modal",
            '_class': "pull-right",
            '_aria-hidden': "true"
        }
        modal[0][0].append(DIV(BUTTON('Close', **attrs),
                               _class='modal-footer'))
    else:
        pass

    return CAT(trigger, modal)
Example #9
0
def getGameFormBtn(game, user, gameStats):
    """
	Gets a dictionary of form buttons that do stuff for the game page.

	Keyword Arguments:
	game    -- row representing the current game
	user    -- row representing the current user

	Return Values:
	formBtn -- dictionary of web2py forms
	        -- 'start'  Start Game button
	        -- 'join'   Join Game button
	        -- 'leave'  Leave Game button
	        -- 'target' Target Eliminated button
	        -- 'dead'   I have been eliminated button
	"""

    from gluon import current, INPUT, FORM, redirect, URL, BUTTON
    db = current.db

    formBtn = {
        'start': 'start',
        'join': 'join',
        'leave': 'leave',
        'target': 'target',
        'dead': 'dead'
    }

    if gameStats['players'] > 1:
        formBtn['start'] = FORM(
            INPUT(
                _type='submit',
                _value='(Host) Start Game',
                _class='btn btn-large btn-block btn-inverse abtn-large',
                _onclick=
                'return confirm(\'Are you sure you want to start this game?\');'
            ))
    else:
        formBtn['start'] = BUTTON(
            '(Host) Start Game',
            _class='btn btn-large btn-block btn-inverse abtn-large',
            _onclick='alert(\'You need at least 2 players to start a game?\');'
        )

    formBtn['join'] = FORM(
        INPUT(_type='submit',
              _value='Join Game',
              _class='btn btn-large btn-block btn-inverse abtn-large'))
    formBtn['leave'] = FORM(
        INPUT(
            _type='submit',
            _value='Leave Game',
            _class='btn btn-block abtn-small',
            _onclick=
            'return confirm(\'Are you sure you want to leave this game?\');'))
    formBtn['target'] = FORM(
        INPUT(_type='submit',
              _value='Target Eliminated',
              _class='btn btn-large btn-block btn-inverse abtn-large'))
    formBtn['dead'] = FORM(
        INPUT(
            _type='submit',
            _value='I am dead.',
            _class='btn btn-block abtn-small',
            _onclick=
            'return confirm(\'Are you sure you want to eliminate yourself?\');'
        ))

    if gameStats['players'] > 1 and formBtn['start'].process(
            formname='formBtnStart').accepted:
        startGameAssassins(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['join'].process(formname='formBtnJoin').accepted:
        joinGame(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['leave'].process(formname='formBtnLeave').accepted:
        leaveGame(game.id, user)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['target'].process(formname='formBtnTarget').accepted:
        killCompletedAssassins(game.id, user.id)
        redirect(URL('default', 'game', args=game.id))

    if formBtn['dead'].process(formname='formBtnDead').accepted:
        query = db((db.player.game_id == game.id)
                   & (db.player.player_id == user.id)).select(db.player.id)[0]
        killPlayer(game.id, user.id)
        #wasKilledAssassins()
        redirect(URL('default', 'game', args=game.id))

    return formBtn