def _render_trending(caption, problems, flag):
    """
        Create trending table from the rows
    """

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

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

        tr.append(
            TD(
                utilities.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
Esempio n. 2
0
def todo():

    ptable = db.problem
    tltable = db.todo_list

    res = db(tltable.user_id == session.user_id).select(tltable.problem_link)
    table = TABLE(_class="bordered centered")
    table.append(
        THEAD(
            TR(TH(T("Problem")), TH(T("Site")), TH(T("Total submissions")),
               TH(T("Users solved")), TH(T("Remove")))))

    plinks = [x.problem_link for x in res]
    tbody = TBODY()

    rows = db(ptable.link.belongs(plinks)).select(ptable.name, ptable.link,
                                                  ptable.total_submissions,
                                                  ptable.user_ids,
                                                  ptable.custom_user_ids)
    link_class = ""

    def _get_ids(ids):
        ids = ids.split(",")
        return [] if ids[0] == "" else ids

    for row in rows:
        if row.link in current.solved_problems:
            link_class = "solved-problem"
        elif row.link in current.unsolved_problems:
            link_class = "unsolved-problem"
        else:
            link_class = "unattempted-problem"

        uids, cuids = _get_ids(row.user_ids), _get_ids(row.custom_user_ids)

        link_title = (" ".join(link_class.split("-"))).capitalize()
        tbody.append(TR(TD(utilities.problem_widget(row.name,
                                                    row.link,
                                                    link_class,
                                                    link_title,
                                                    disable_todo=True)),
                        TD(IMG(_src=URL("static",
                                        "images/" + \
                                        utilities.urltosite(row.link) + \
                                        "_small.png"),
                               _style="height: 30px; weight: 30px;")),
                        TD(row.total_submissions),
                        TD(len(uids) + len(cuids)),
                        TD(I(_class="red-text text-accent-4 fa fa-times remove-from-todo",
                             data={"link": row.link}))))
    table.append(tbody)
    div = DIV(DIV(H2(T("ToDo List")),
                  HR(),
                  BR(),
                  table,
                  BR(),
                  _class="col offset-s2 s8 z-depth-2"),
              _class="row")

    return dict(div=div)
Esempio n. 3
0
def get_solved_unsolved():

    if request.extension != "json" or \
       request.vars.user_id is None or \
       request.vars.custom is None:
        raise HTTP(400, "Bad request")
        return

    user_id = int(request.vars.user_id)
    custom = (request.vars.custom == "True")

    solved_problems, unsolved_problems = utilities.get_solved_problems(
        user_id, custom)
    if auth.is_logged_in() and session.user_id == user_id and not custom:
        user_solved_problems, user_unsolved_problems = solved_problems, unsolved_problems
    else:
        if auth.is_logged_in():
            user_solved_problems, user_unsolved_problems = utilities.get_solved_problems(
                session.user_id, False)
        else:
            user_solved_problems, user_unsolved_problems = set([]), set([])

    category_wise_solved_problems, category_wise_unsolved_problems = \
        utilities.get_category_wise_problems(solved_problems,
                                             unsolved_problems,
                                             user_solved_problems,
                                             user_unsolved_problems)

    return dict(solved_problems=category_wise_solved_problems,
                unsolved_problems=category_wise_unsolved_problems,
                solved_html_widget=str(
                    utilities.problem_widget("", "", "solved-problem",
                                             "Solved problem", None)),
                unsolved_html_widget=str(
                    utilities.problem_widget("", "", "unsolved-problem",
                                             "Unsolved problem", None)),
                unattempted_html_widget=str(
                    utilities.problem_widget("", "", "unattempted-problem",
                                             "Unattempted problem", None)))
Esempio n. 4
0
    def get_html(self):
        problem_details = self.get_data()

        self.ctas = [
            dict(btn_text="Write Editorial",
                 btn_url=URL("problems",
                             "editorials",
                             args=problem_details["id"],
                             vars=dict(write_editorial=True)),
                 btn_class="last-solved-problem-write-editorial"),
            dict(btn_text="Suggest tags",
                 btn_url=URL("problems",
                             "index",
                             vars=dict(problem_id=problem_details["id"],
                                       suggest_tag=True)),
                 btn_class="last-solved-problem-suggest-tags"),
            dict(btn_text="Suggest difficulty",
                 btn_url=URL("problems",
                             "index",
                             vars=dict(problem_id=problem_details["id"],
                                       suggest_difficulty=True)),
                 btn_class="last-solved-problem-suggest-difficulty")
        ]

        card_content = SPAN(
            "You just solved ",
            utilities.problem_widget(problem_details["name"],
                                     problem_details["link"], "solved-problem",
                                     "Solved Problem", problem_details["id"]),
            ". You can write editorials on StopStalk and help the community.")

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
Esempio n. 5
0
def get_solved_unsolved():

    if request.extension != "json" or \
       request.vars.user_id is None or \
       request.vars.custom is None:
        raise HTTP(400, "Bad request")
        return

    user_id = int(request.vars.user_id)
    custom = (request.vars.custom == "True")

    solved_problems, unsolved_problems = utilities.get_solved_problems(
        user_id, custom)
    if auth.is_logged_in() and session.user_id == user_id and not custom:
        user_solved_problems, user_unsolved_problems = solved_problems, unsolved_problems
    else:
        if auth.is_logged_in():
            user_solved_problems, user_unsolved_problems = utilities.get_solved_problems(
                session.user_id, False)
        else:
            user_solved_problems, user_unsolved_problems = set([]), set([])

    solved_ids, unsolved_ids = [], []
    ptable = db.problem
    sttable = db.suggested_tags
    ttable = db.tag
    all_tags = db(ttable).select()
    all_tags = dict([(tag.id, tag.value) for tag in all_tags])

    query = ptable.id.belongs(solved_problems.union(unsolved_problems))
    # id => [problem_link, problem_name, problem_class]
    # problem_class =>
    #    0 (Logged in user has solved the problem)
    #    1 (Logged in user has attemted the problem)
    #    2 (User not logged in or not attempted the problem)
    problem_details = {}
    pids = []
    for problem in db(query).select(ptable.id, ptable.link, ptable.name):
        pids.append(problem.id)

        problem_status = 2
        if problem.id in user_unsolved_problems:
            # Checking for unsolved first because most of the problem links
            # would be found here instead of a failed lookup in solved_problems
            problem_status = 1
        elif problem.id in user_solved_problems:
            problem_status = 0

        problem_details[problem.id] = [
            problem.link, problem.name, problem_status, problem.id
        ]

        if problem.id in solved_problems:
            solved_ids.append(problem.id)
        else:
            unsolved_ids.append(problem.id)

    problem_tags = {}
    query = (sttable.problem_id.belongs(pids)) & \
            (sttable.user_id == 1)
    for prow in db(query).select(sttable.tag_id, sttable.problem_id):
        if prow.problem_id not in problem_tags:
            problem_tags[prow.problem_id] = set([])
        problem_tags[prow.problem_id].add(prow.tag_id)

    categories = {
        "Dynamic Programming": set([1]),
        "Greedy": set([28]),
        "Strings": set([20]),
        "Hashing": set([32]),
        "Bit Manipulation": set([21, 42]),
        "Trees": set([6, 9, 10, 11, 17, 31]),
        "Graphs": set([4, 5, 15, 22, 23, 24, 26]),
        "Algorithms": set([12, 14, 27, 29, 35, 36, 37, 38, 44, 51]),
        "Data Structures": set([2, 3, 7, 8, 33, 34, 49]),
        "Math": set([16, 30, 39, 40, 41, 43, 45, 50, 54]),
        "Implementation": set([13, 18, 19]),
        "Miscellaneous": set([46, 47, 48, 52])
    }
    ordered_categories = [
        "Dynamic Programming", "Greedy", "Strings", "Hashing",
        "Bit Manipulation", "Trees", "Graphs", "Algorithms", "Data Structures",
        "Math", "Implementation", "Miscellaneous"
    ]

    displayed_problems = set([])

    def _get_categorized_json(problem_ids):
        result = dict([(category, []) for category in ordered_categories])
        for pid in problem_ids:
            this_category = None
            if pid not in problem_tags:
                this_category = "Miscellaneous"
            else:
                ptags = problem_tags[pid]
                category_found = False
                for category in ordered_categories:
                    if len(categories[category].intersection(ptags)) > 0:
                        this_category = category
                        category_found = True
                        break
                if not category_found:
                    this_category = "Miscellaneous"
            pdetails = problem_details[pid]
            plink, pname, _, _ = pdetails
            psite = utilities.urltosite(plink)
            if (pname, psite) not in displayed_problems:
                displayed_problems.add((pname, psite))
                result[this_category].append(problem_details[pid])
        return result

    return dict(solved_problems=_get_categorized_json(solved_ids),
                unsolved_problems=_get_categorized_json(unsolved_ids),
                solved_html_widget=str(
                    utilities.problem_widget("", "", "solved-problem",
                                             "Solved problem", None)),
                unsolved_html_widget=str(
                    utilities.problem_widget("", "", "unsolved-problem",
                                             "Unsolved problem", None)),
                unattempted_html_widget=str(
                    utilities.problem_widget("", "", "unattempted-problem",
                                             "Unattempted problem", None)))
def index():
    """
        The main problem page
    """
    from json import dumps

    if request.vars.has_key("problem_id") is False:
        # Disables direct entering of a URL
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))
        return

    try:
        problem_id = int(request.vars["problem_id"])
    except ValueError:
        session.flash = T("Invalid problem!")
        redirect(URL("default", "index"))
        return

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = T("Login to view your/friends' submissions")
        submission_type = "global"

    stable = db.submission
    ptable = db.problem
    pstable = db.problem_setters

    problem_record = ptable(problem_id)
    if problem_record is None:
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))

    setters = db(pstable.problem_id == problem_id).select(pstable.handle)
    setters = [x.handle for x in setters]
    query = (stable.problem_id == problem_id)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = T("Login to view your/friends' submissions")

    submissions = db(query).select(orderby=~stable.time_stamp,
                                   limitby=(0, 300))
    try:
        all_tags = problem_record.tags
        if all_tags:
            all_tags = eval(all_tags)
        else:
            all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    lower_site = utilities.urltosite(problem_record.link)
    site = utilities.get_actual_site(lower_site)
    problem_details = DIV(_class="row")
    details_table = TABLE(_style="font-size: 140%; float: left; width: 50%;")
    problem_class = ""

    link_class, link_title = utilities.get_link_class(problem_id, session.user_id)

    tbody = TBODY()
    tbody.append(TR(TD(),
                    TD(STRONG(T("Problem Name") + ":")),
                    TD(utilities.problem_widget(problem_record.name,
                                                problem_record.link,
                                                link_class,
                                                link_title,
                                                problem_id,
                                                anchor=False,
                                                disable_todo=True),
                       _id="problem_name")))
    tbody.append(TR(TD(),
                    TD(STRONG(T("Site") + ":")),
                    TD(site)))

    links = DIV(DIV(A(I(_class="fa fa-link"), " " + T("Problem"),
                      _href=problem_record.link,
                      _class="problem-page-site-link",
                      _style="color: black;",
                      _target="blank"),
                    _class="chip lime accent-3"),
                " ",
                DIV(A(I(_class="fa fa-book"), " " + T("Editorials"),
                      _href=URL("problems", "editorials", args=problem_record.id),
                      _class="problem-page-editorials",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip deep-purple darken-1",
                    _id="problem-page-editorial-button"))

    if auth.is_logged_in():
        links.append(DIV(A(I(_class="fa fa-edit"), " " + T("Suggest Difficulty"),
                             _style="color: white;"),
                         _class="chip",
                         _style="background-color: #9b4da9; cursor: pointer;",
                         _id="problem-page-difficulty-button"))
    tbody.append(TR(TD(),
                    TD(STRONG(T("Links") + ":")),
                    links))

    suggest_tags_class = "disabled btn chip tooltipped suggest-tags-plus-logged-out"
    suggest_tags_data = {"position": "right",
                         "delay": "50",
                         "tooltip": T("Login to suggest tags")}
    suggest_tags_id = "disabled-suggest-tags"
    if auth.is_logged_in():
        suggest_tags_class = "green chip waves-light waves-effect tooltipped suggest-tags-plus modal-trigger"
        suggest_tags_data["target"] = "suggest-tags-modal"
        suggest_tags_data["tooltip"] = T("Suggest tags")
        suggest_tags_id = "suggest-trigger"

    tbody.append(TR(TD(),
                    TD(STRONG(T("Tags") + ":")),
                    TD(DIV(SPAN(A(I(_class="fa fa-tag"), " Show Tags",
                                 _id="show-tags",
                                 _class="chip orange darken-1",
                                 data={"tags": dumps(all_tags)}),
                                _id="tags-span"),
                           " ",
                           BUTTON(I(_class="fa fa-plus"),
                                  _style="color: white; margin-top: 7px;",
                                  _class=suggest_tags_class,
                                  _id=suggest_tags_id,
                                  data=suggest_tags_data)))))

    if len(setters) > 0:
        tbody.append(TR(TD(),
                        TD(STRONG(T("Problem setters") + ":")),
                        TD(DIV(utilities.problem_setters_widget(setters,
                                                                site)))))

    details_table.append(tbody)
    problem_details.append(details_table)
    problem_details.append(DIV(_style="width: 50%; height: 200px; margin-top: 3%",
                               _id="chart_div",
                               _class="right"))

    if len(submissions):
        table = utilities.render_table(submissions, cusfriends, session.user_id)
    else:
        table = DIV(T("No submissions found"))

    return dict(site=site,
                problem_details=problem_details,
                problem_name=problem_record.name,
                problem_link=problem_record.link,
                problem_id=problem_id,
                submission_type=submission_type,
                submission_length=len(submissions),
                table=table)
def tag():
    """
        Tag search page
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem Name")), TH(T("Problem URL")), TH(T("Site")),
           TH(T("Accuracy")), TH(T("Users solved")), TH(T("Tags"))))
    table.append(thead)

    ttable = db.tag
    generalized_tags = db(ttable).select(ttable.value, orderby=ttable.value)
    generalized_tags = [x.value for x in generalized_tags]

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    q = request.vars.get("q", None)
    clubbed_tags = request.vars.get("generalized_tags", None)
    clubbed_tags = None if clubbed_tags == "" else clubbed_tags
    if q is None and not clubbed_tags:
        return dict(table=table, generalized_tags=generalized_tags)

    try:
        sites = request.vars.get("site", "")
        if sites == "":
            sites = []
        elif isinstance(sites, str):
            sites = [sites]
    except:
        sites = []

    orderby = request.vars.get("orderby", None)
    if orderby not in ("accuracy-asc", "accuracy-desc", "solved-count-asc",
                       "solved-count-desc"):
        orderby = None

    try:
        curr_page = int(request.vars["page"])
    except:
        curr_page = 1
    PER_PAGE = current.PER_PAGE

    ptable = db.problem
    query = True

    if q is not None and not clubbed_tags:
        # Enables multiple space seperated tag search
        q = q.split(" ")
        for tag in q:
            if tag == "":
                continue
            # Decision to make & or |
            # & => Search for problem containing all these tags
            # | => Search for problem containing one of the tags
            query &= ptable.tags.contains(tag)
    else:
        clubbed_tags = [clubbed_tags] if isinstance(clubbed_tags,
                                                    str) else clubbed_tags
        ttable = db.tag
        sttable = db.suggested_tags

        tag_ids = db(ttable.value.belongs(clubbed_tags)).select(ttable.id)
        tag_ids = [x.id for x in tag_ids]

        problem_ids = db(sttable.tag_id.belongs(tag_ids)).select(
            sttable.problem_id)
        problem_ids = [x.problem_id for x in problem_ids]

        query &= ptable.id.belongs(problem_ids)

    site_query = None
    for site in sites:
        if site_query is not None:
            site_query |= ptable.link.contains(current.SITES[site])
        else:
            site_query = ptable.link.contains(current.SITES[site])
    if site_query:
        query &= site_query

    accuracy_column = (ptable.solved_submissions * 1.0 /
                       ptable.total_submissions)
    kwargs = dict(distinct=True,
                  limitby=((curr_page - 1) * PER_PAGE, curr_page * PER_PAGE))
    if orderby and orderby.__contains__("accuracy"):
        query &= ~(ptable.link.contains("hackerrank.com"))
        kwargs[
            "orderby"] = ~accuracy_column if orderby == "accuracy-desc" else accuracy_column

    if orderby and orderby.__contains__("solved-count"):
        kwargs["reverse"] = True if orderby == "solved-count-desc" else False

    query &= (ptable.solved_submissions != None)
    query &= (ptable.total_submissions != None) & (ptable.total_submissions !=
                                                   0)
    query &= (ptable.user_ids != None)
    query &= (ptable.custom_user_ids != None)

    total_problems = db(query).count()
    total_pages = total_problems / PER_PAGE
    if total_problems % PER_PAGE != 0:
        total_pages = total_problems / PER_PAGE + 1

    if request.extension == "json":
        return dict(total_pages=total_pages)

    if orderby and orderby.__contains__("solved-count"):
        all_problems = db(query).select(cache=(cache.ram, 3600),
                                        cacheable=True).as_list()
        all_problems.sort(key=lambda x: x["user_count"] + \
                                        x["custom_user_count"],
                          reverse=kwargs["reverse"])
        all_problems = all_problems[kwargs["limitby"][0]:kwargs["limitby"][1]]
    else:
        # No need of caching here
        all_problems = db(query).select(**kwargs)

    tbody = TBODY()
    for problem in all_problems:
        tr = TR()
        link_class = utilities.get_link_class(problem["link"], session.user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                utilities.problem_widget(problem["name"], problem["link"],
                                         link_class, link_title)))
        tr.append(
            TD(
                A(I(_class="fa fa-link"),
                  _href=problem["link"],
                  _class="tag-problem-link",
                  _target="_blank")))
        tr.append(TD(IMG(_src=get_static_url("images/" + \
                                             utilities.urltosite(problem["link"]) + \
                                             "_small.png"),
                         _style="height: 30px; width: 30px;")))
        tr.append(TD("%.2f" % (problem["solved_submissions"]  * 100.0 / \
                               problem["total_submissions"])))
        tr.append(TD(problem["user_count"] + problem["custom_user_count"]))

        td = TD()
        all_tags = eval(problem["tags"])
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems",
                                "tag",
                                vars={
                                    "q": tag.encode("utf8"),
                                    "page": 1
                                }),
                      _class="tags-chip",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table, generalized_tags=generalized_tags)
def index():
    """
        The main problem page
    """
    from json import dumps

    if request.vars.has_key("pname") is False or \
       request.vars.has_key("plink") is False:

        # Disables direct entering of a URL
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = T("Login to view your/friends' submissions")
        submission_type = "global"

    stable = db.submission
    ptable = db.problem

    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = T("Login to view your/friends' submissions")

    submissions = db(query).select(orderby=~stable.time_stamp)
    problem_record = db(ptable.link == problem_link).select().first()
    try:
        all_tags = problem_record.tags
        if all_tags:
            all_tags = eval(all_tags)
        else:
            all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    site = utilities.urltosite(problem_link).capitalize()
    problem_details = DIV(_class="row")
    details_table = TABLE(_style="font-size: 140%; float: left; width: 50%;")
    problem_class = ""

    link_class = utilities.get_link_class(problem_link, session.user_id)
    link_title = (" ".join(link_class.split("-"))).capitalize()

    tbody = TBODY()
    tbody.append(
        TR(
            TD(), TD(STRONG(T("Problem Name") + ":")),
            TD(utilities.problem_widget(problem_name,
                                        problem_link,
                                        link_class,
                                        link_title,
                                        anchor=False),
               _id="problem_name")))
    tbody.append(TR(TD(), TD(STRONG(T("Site") + ":")), TD(site)))

    links = DIV(
        DIV(A(I(_class="fa fa-link"),
              " " + T("Problem"),
              _href=problem_link,
              _class="problem-page-site-link",
              _style="color: black;",
              _target="blank"),
            _class="chip lime accent-3"))

    row = db(ptable.link == problem_link).select().first()
    if row:
        links.append(" ")
        links.append(
            DIV(A(I(_class="fa fa-book"),
                  " " + T("Editorials"),
                  _href=URL("problems", "editorials", args=row.id),
                  _class="problem-page-editorials",
                  _style="color: white;",
                  _target="_blank"),
                _class="chip deep-purple darken-1"))

    tbody.append(TR(TD(), TD(STRONG(T("Links") + ":")), links))

    suggest_tags_class = "disabled btn chip tooltipped suggest-tags-plus-logged-out"
    suggest_tags_data = {
        "position": "right",
        "delay": "50",
        "tooltip": T("Login to suggest tags")
    }
    suggest_tags_id = "disabled-suggest-tags"
    if auth.is_logged_in():
        suggest_tags_class = "green chip waves-light waves-effect tooltipped suggest-tags-plus modal-trigger"
        suggest_tags_data["target"] = "suggest-tags-modal"
        suggest_tags_data["tooltip"] = T("Suggest tags")
        suggest_tags_id = "suggest-trigger"

    tbody.append(
        TR(
            TD(), TD(STRONG(T("Tags") + ":")),
            TD(
                DIV(
                    SPAN(A(I(_class="fa fa-tag"),
                           " Show Tags",
                           _id="show-tags",
                           _class="chip orange darken-1",
                           data={"tags": dumps(all_tags)}),
                         _id="tags-span"), " ",
                    BUTTON(I(_class="fa fa-plus"),
                           _style="color: white; margin-top: 7px;",
                           _class=suggest_tags_class,
                           _id=suggest_tags_id,
                           data=suggest_tags_data)))))

    details_table.append(tbody)
    problem_details.append(details_table)
    problem_details.append(
        DIV(_style="width: 50%; margin-top: 3%",
            _id="chart_div",
            _class="right"))

    table = utilities.render_table(submissions, cusfriends, session.user_id)

    return dict(site=site,
                problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                submission_type=submission_type,
                table=table)
Esempio n. 9
0
def search():
    """
        Search page for problems
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem Name")), TH(T("Problem URL")), TH(T("Site")),
           TH(T("Accuracy")), TH(T("Users solved")), TH(T("Editorial")),
           TH(T("Tags"))))
    table.append(thead)

    ttable = db.tag
    uetable = db.user_editorials

    problem_name = request.vars.get("name", None)
    orderby = request.vars.get("orderby", None)
    clubbed_tags = request.vars.get("generalized_tags", None)
    q = request.vars.get("q", None)
    sites = request.vars.get("site", None)

    generalized_tags = db(ttable).select(ttable.value, orderby=ttable.value)
    generalized_tags = [x.value for x in generalized_tags]

    if any([problem_name, orderby, clubbed_tags, q, sites]) is False:
        if request.extension == "json":
            return dict(total_pages=0)
        else:
            if len(request.get_vars):
                # No filter is applied
                response.flash = "No filter is applied"
            return dict(table=DIV(), generalized_tags=generalized_tags)

    include_editorials = request.vars.get("include_editorials", "")

    clubbed_tags = None if clubbed_tags == "" else clubbed_tags

    try:
        if sites == None or sites == "":
            sites = []
        elif isinstance(sites, str):
            sites = [sites]
    except:
        sites = []

    if orderby not in ("accuracy-asc", "accuracy-desc", "solved-count-asc",
                       "solved-count-desc"):
        orderby = None

    try:
        curr_page = int(request.vars["page"])
    except:
        curr_page = 1
    PER_PAGE = current.PER_PAGE

    ptable = db.problem
    query = True

    rows = db(uetable.verification == "accepted").select(uetable.problem_id)
    problem_with_user_editorials = set([x["problem_id"] for x in rows])

    if q is not None and not clubbed_tags:
        # Enables multiple space seperated tag search
        q = q.split(" ")
        for tag in q:
            if tag == "":
                continue
            # Decision to make & or |
            # & => Search for problem containing all these tags
            # | => Search for problem containing one of the tags
            query &= ptable.tags.contains(tag)
    elif clubbed_tags:
        clubbed_tags = [clubbed_tags] if isinstance(clubbed_tags,
                                                    str) else clubbed_tags
        ttable = db.tag
        sttable = db.suggested_tags

        tag_ids = db(ttable.value.belongs(clubbed_tags)).select(ttable.id)
        tag_ids = [x.id for x in tag_ids]

        problem_ids = db(sttable.tag_id.belongs(tag_ids)).select(
            sttable.problem_id)
        problem_ids = [x.problem_id for x in problem_ids]

        query &= ptable.id.belongs(problem_ids)

    if problem_name:
        query &= ptable.name.contains(problem_name)

    if include_editorials:
        # Check if the site editorial link is present or the problem id exists
        # in user_editorials table with accepted status
        query &= (((ptable.editorial_link != None) & \
                   (ptable.editorial_link != "")) | \
                  (ptable.id.belongs(problem_with_user_editorials)))

    site_query = None
    for site in sites:
        if site_query is not None:
            site_query |= ptable.link.contains(current.SITES[site])
        else:
            site_query = ptable.link.contains(current.SITES[site])
    if site_query:
        query &= site_query

    accuracy_column = (ptable.solved_submissions * 1.0 /
                       ptable.total_submissions)
    kwargs = dict(distinct=True,
                  limitby=((curr_page - 1) * PER_PAGE, curr_page * PER_PAGE))
    if orderby and orderby.__contains__("accuracy"):
        query &= ~(ptable.link.contains("hackerrank.com"))
        kwargs[
            "orderby"] = ~accuracy_column if orderby == "accuracy-desc" else accuracy_column

    if orderby and orderby.__contains__("solved-count"):
        kwargs["reverse"] = True if orderby == "solved-count-desc" else False

    query &= (ptable.solved_submissions != None)
    query &= (ptable.total_submissions != None) & (ptable.total_submissions !=
                                                   0)
    query &= (ptable.user_ids != None)
    query &= (ptable.custom_user_ids != None)

    if request.extension == "json":
        total_problems = db(query).count()

        total_pages = total_problems / PER_PAGE
        if total_problems % PER_PAGE != 0:
            total_pages = total_problems / PER_PAGE + 1

        return dict(total_pages=total_pages)

    if orderby and orderby.__contains__("solved-count"):
        all_problems = db(query).select().as_list()
        all_problems.sort(key=lambda x: x["user_count"] + \
                                        x["custom_user_count"],
                          reverse=kwargs["reverse"])
        all_problems = all_problems[kwargs["limitby"][0]:kwargs["limitby"][1]]
    else:
        # No need of caching here
        all_problems = db(query).select(**kwargs)

    tbody = TBODY()
    for problem in all_problems:
        tr = TR()

        link_class = utilities.get_link_class(problem["id"], session.user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                utilities.problem_widget(problem["name"], problem["link"],
                                         link_class, link_title,
                                         problem["id"])))
        tr.append(
            TD(
                A(I(_class="fa fa-link"),
                  _href=problem["link"],
                  _class="tag-problem-link",
                  _target="_blank")))
        tr.append(TD(IMG(_src=get_static_url("images/" + \
                                             utilities.urltosite(problem["link"]) + \
                                             "_small.png"),
                         _style="height: 30px; width: 30px;")))
        tr.append(TD("%.2f" % (problem["solved_submissions"]  * 100.0 / \
                               problem["total_submissions"])))
        tr.append(TD(problem["user_count"] + problem["custom_user_count"]))

        if problem["id"] in problem_with_user_editorials or \
           problem["editorial_link"] not in ("", None):
            tr.append(
                TD(
                    A(I(_class="fa fa-book"),
                      _href=URL("problems", "editorials", args=problem["id"]),
                      _target="_blank",
                      _class="problem-search-editorial-link")))
        else:
            tr.append(TD())

        td = TD()
        all_tags = eval(problem["tags"])
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems",
                                "tag",
                                vars={
                                    "q": tag.encode("utf8"),
                                    "page": 1
                                }),
                      _class="tags-chip",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table, generalized_tags=generalized_tags)
Esempio n. 10
0
def tag():
    """
        Tag search page
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem Name")), TH(T("Problem URL")), TH(T("Site")),
           TH(T("Tags"))))
    table.append(thead)

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    if request.vars.has_key("q") is False:
        return dict(table=table)

    q = request.vars["q"]
    try:
        sites = request.vars.get("site", "")
        if sites == "":
            sites = []
        elif isinstance(sites, str):
            sites = [sites]
    except:
        sites = []

    try:
        curr_page = int(request.vars["page"])
    except:
        curr_page = 1
    PER_PAGE = current.PER_PAGE

    # Enables multiple space seperated tag search
    q = q.split(" ")
    ptable = db.problem

    query = None
    for tag in q:
        if query is not None:
            # Decision to make & or |
            # & => Search for problem containing all these tags
            # | => Search for problem containing one of the tags
            query &= ptable.tags.contains(tag)
        else:
            query = ptable.tags.contains(tag)

    site_query = None
    for site in sites:
        if site_query is not None:
            site_query |= ptable.link.contains(current.SITES[site])
        else:
            site_query = ptable.link.contains(current.SITES[site])
    if site_query:
        query &= site_query

    total_problems = db(query).count()
    total_pages = total_problems / PER_PAGE
    if total_problems % PER_PAGE != 0:
        total_pages = total_problems / PER_PAGE + 1

    if request.extension == "json":
        return dict(total_pages=total_pages)

    all_problems = db(query).select(ptable.name,
                                    ptable.link,
                                    ptable.tags,
                                    distinct=True,
                                    limitby=((curr_page - 1) * PER_PAGE,
                                             curr_page * PER_PAGE))

    tbody = TBODY()
    for problem in all_problems:

        tr = TR()
        link_class = ""

        if problem.link in current.solved_problems:
            link_class = "solved-problem"
        elif problem.link in current.unsolved_problems:
            link_class = "unsolved-problem"
        else:
            link_class = "unattempted-problem"

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

        tr.append(
            TD(
                utilities.problem_widget(problem.name, problem.link,
                                         link_class, link_title)))
        tr.append(
            TD(A(I(_class="fa fa-link"), _href=problem.link,
                 _target="_blank")))
        tr.append(TD(IMG(_src=URL("static",
                                  "images/" + \
                                  utilities.urltosite(problem.link) + \
                                  "_small.png"),
                         _style="height: 30px; width: 30px;")))
        all_tags = eval(problem.tags)
        td = TD()
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems", "tag", vars={
                          "q": tag,
                          "page": 1
                      }),
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)
    return dict(table=table)