Ejemplo n.º 1
0
def comicmain(request, page_title=""):
    """ show content as main page item. Loads pages from the main project """
    challenge_short_name = settings.MAIN_PROJECT_NAME
    if Challenge.objects.filter(short_name=challenge_short_name).count() == 0:
        link = reverse('challenges:create')
        link = link + "?short_name=%s" % challenge_short_name
        link_html = create_HTML_a(
            link, "Create project '%s'" % challenge_short_name
        )
        html = """I'm trying to show the first page for main project '%s' here,
        but '%s' does not exist. %s.""" % (
            challenge_short_name, challenge_short_name, link_html
        )
        p = create_temp_page(title="no_pages_found", html=html)
        return render(
            request, 'temppage.html', {'site': p.challenge, 'currentpage': p}
        )

    pages = getPages(challenge_short_name)
    if pages.count() == 0:
        link = reverse('pages:list', args=[challenge_short_name])
        link_html = create_HTML_a(link, "admin interface")
        html = """I'm trying to show the first page for main project '%s' here,
        but '%s' contains no pages. Please add
        some in the %s.""" % (
            challenge_short_name, challenge_short_name, link_html
        )
        p = create_temp_page(title="no_pages_found", html=html)
        return render(
            request, 'temppage.html', {'site': p.challenge, 'currentpage': p}
        )

    elif page_title == "":
        # if no page title is given, just use the first page found
        p = pages[0]
        p.html = renderTags(request, p)
    else:
        try:
            p = Page.objects.get(
                challenge__short_name=challenge_short_name, title=page_title
            )
        except Page.DoesNotExist:
            raise Http404

    p.html = renderTags(request, p)
    # render page contents using django template system
    # This makes it possible to use tags like '{% dataset %}' in page
    # to display pages from main project at the very bottom of the site as
    # general links
    metafooterpages = getPages(settings.MAIN_PROJECT_NAME)
    return render(
        request,
        'mainpage.html',
        {
            'site': p.challenge,
            'currentpage': p,
            "pages": pages,
            "metafooterpages": metafooterpages,
        },
    )
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        self.challenge = kwargs.pop('challenge', None)
        super().__init__(*args, **kwargs)
        if self.challenge is not None and 'html' in self.fields:
            self.fields['html'].widget.config.update({
                'filebrowserUploadUrl':
                reverse(
                    'uploads:ck-create',
                    kwargs={'challenge_short_name': self.challenge.short_name},
                ),
                'filebrowserBrowseUrl':
                reverse(
                    'uploads:ck-browse',
                    kwargs={'challenge_short_name': self.challenge.short_name},
                ),
            })

            if self.challenge.allow_unfiltered_page_html:
                self.fields['html'].widget.config.update({
                    'allowedContent':
                    True,
                })

        self.helper = FormHelper(self)
        self.helper.layout.append(Submit('save', 'Save'))
Ejemplo n.º 3
0
def test_external_challenge_buttons(client):
    create_url = reverse("challenges:external-create")
    list_url = reverse("challenges:external-list")

    response = get_view_for_user(client=client, viewname="challenges:list")

    assert create_url not in response.rendered_content
    assert list_url not in response.rendered_content

    user = UserFactory()

    response = get_view_for_user(client=client,
                                 viewname="challenges:list",
                                 user=user)

    assert create_url not in response.rendered_content
    assert list_url not in response.rendered_content

    staff_user = UserFactory(is_staff=True)

    response = get_view_for_user(client=client,
                                 viewname="challenges:list",
                                 user=staff_user)

    assert create_url in response.rendered_content
    assert list_url in response.rendered_content
Ejemplo n.º 4
0
def comicmain(request, page_title=""):
    """ show content as main page item. Loads pages from the main project """
    challenge_short_name = settings.MAIN_PROJECT_NAME

    try:
        site = getSite(challenge_short_name)
    except Challenge.DoesNotExist:
        link = reverse("challenges:create")
        link = link + "?short_name=%s" % challenge_short_name
        link_html = create_HTML_a(
            link, "Create project '%s'" % challenge_short_name
        )
        html = """I'm trying to show the first page for main project '%s' here,
        but '%s' does not exist. %s.""" % (
            challenge_short_name,
            challenge_short_name,
            link_html,
        )
        page = create_temp_page(title="no_pages_found", html=html)

        return render(
            request,
            "temppage.html",
            {"site": page.challenge, "currentpage": page},
        )

    pages = site.page_set.all()

    if len(pages) == 0:
        link = reverse("pages:list", args=[challenge_short_name])
        link_html = create_HTML_a(link, "admin interface")
        html = """I'm trying to show the first page for main project '%s' here,
        but '%s' contains no pages. Please add
        some in the %s.""" % (
            challenge_short_name,
            challenge_short_name,
            link_html,
        )
        page = create_temp_page(title="no_pages_found", html=html)

        return render(
            request,
            "temppage.html",
            {"site": page.challenge, "currentpage": page},
        )

    if page_title:
        pages = [p for p in pages if p.title.lower() == page_title.lower()]

        if len(pages) != 1:
            raise ValueError(
                f"More than 1 page with title {page_title} was found for {site}"
            )

    page = pages[0]
    page.html = renderTags(request, page)

    return render(request, "page.html", {"currentpage": page})
Ejemplo n.º 5
0
def test_annotationset_creation(client, settings):
    # Override the celery settings
    settings.task_eager_propagates = (True,)
    settings.task_always_eager = (True,)
    settings.broker_url = ("memory://",)
    settings.backend = "memory"

    user = UserFactory(is_staff=True)
    client.login(username=user.username, password=SUPER_SECURE_TEST_PASSWORD)

    imageset = ChallengeFactory().imageset_set.get(phase=ImageSet.TRAINING)

    url = reverse(
        "datasets:annotationset-create",
        kwargs={
            "challenge_short_name": imageset.challenge.short_name,
            "base_pk": imageset.pk,
        },
    )

    response = client.get(url)
    assert response.status_code == 200

    response = client.post(url, data={"kind": AnnotationSet.GROUNDTRUTH})
    assert response.status_code == 302

    annotationset = AnnotationSet.objects.get(
        base=imageset, kind=AnnotationSet.GROUNDTRUTH
    )

    assert len(annotationset.images.all()) == 0
    assert annotationset.creator == user
    assert response.url == reverse(
        "datasets:annotationset-add-images",
        kwargs={
            "challenge_short_name": annotationset.base.challenge.short_name,
            "pk": annotationset.pk,
        },
    )

    images = ["image10x10x10.zraw", "image10x10x10.mhd"]
    session, uploaded_images = create_raw_upload_image_session(
        images, annotationset=annotationset
    )

    response = client.get(annotationset.get_absolute_url())

    assert "image10x10x10.mhd" in response.rendered_content
    assert str(session.pk) in response.rendered_content

    annotationset.refresh_from_db()

    assert len(annotationset.images.all()) == 1
Ejemplo n.º 6
0
def test_admins_see_links(view, client, TwoChallengeSets):
    url = reverse(
        'challenge-homepage',
        args=[TwoChallengeSets.ChallengeSet1.challenge.short_name],
    )
    expected = reverse(
        view, args=[TwoChallengeSets.ChallengeSet1.challenge.short_name])
    validate_admin_only_text_in_page(
        url=url,
        expected_text=f'"{str(expected)}"',
        two_challenge_set=TwoChallengeSets,
        client=client,
    )
def test_registration_request_create_get(client, ChallengeSet):
    validate_logged_in_view(
        viewname="participants:registration-create",
        challenge_set=ChallengeSet,
        client=client,
    )
    # Make sure the link to register is in the challenge page
    url = reverse("challenge-homepage",
                  args=[ChallengeSet.challenge.short_name])
    response = get_view_for_user(url=url, client=client)
    expected_link = reverse(
        "participants:registration-create",
        args=[ChallengeSet.challenge.short_name],
    )
    assert f'"{expected_link}"' in str(response.content)
Ejemplo n.º 8
0
def send_new_result_email(result):
    recipient_emails = [o.email for o in result.challenge.get_admins()]
    message = (
        f'There is a new result for {result.challenge.short_name} from '
        f'{result.job.submission.creator.username}. The following metrics '
        f'were calculated:\n\n'
        f'{json.dumps(result.metrics, indent=2)}\n\n')
    if result.public:
        leaderboard_url = reverse(
            'evaluation:result-list',
            kwargs={'challenge_short_name': result.challenge.short_name},
        )
        message += (f'You can view the result on the leaderboard here: '
                    f'{leaderboard_url}')
        recipient_emails.append(result.job.submission.creator.email)
    else:
        message += (f'You can publish the result on the leaderboard here: '
                    f'{result.get_absolute_url()}')
    for email in recipient_emails:
        send_mail(
            subject=f'New Result for {result.challenge.short_name}',
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[email],
        )
Ejemplo n.º 9
0
def test_challenge_list_is_filtered(client, TwoChallengeSets):
    c1 = TwoChallengeSets.ChallengeSet1.challenge.short_name
    c2 = TwoChallengeSets.ChallengeSet2.challenge.short_name
    tests = [
        ([], [c1, c2], TwoChallengeSets.ChallengeSet1.non_participant),
        ([c1], [c2], TwoChallengeSets.ChallengeSet1.participant),
        ([c1], [c2], TwoChallengeSets.ChallengeSet1.participant1),
        ([c1], [c2], TwoChallengeSets.ChallengeSet1.creator),
        ([c1], [c2], TwoChallengeSets.ChallengeSet1.admin),
        ([], [c1, c2], TwoChallengeSets.ChallengeSet2.non_participant),
        ([c2], [c1], TwoChallengeSets.ChallengeSet2.participant),
        ([c2], [c1], TwoChallengeSets.ChallengeSet2.participant1),
        ([c2], [c1], TwoChallengeSets.ChallengeSet2.creator),
        ([c2], [c1], TwoChallengeSets.ChallengeSet2.admin),
        ([c1, c2], [], TwoChallengeSets.admin12),
        ([c1, c2], [], TwoChallengeSets.participant12),
        ([c1, c2], [], TwoChallengeSets.admin1participant2),
    ]
    for test in tests:
        response = get_view_for_user(url=reverse('challenges:users-list'),
                                     client=client,
                                     user=test[2])
        for short_name in test[0]:
            assert short_name in response.rendered_content
        for short_name in test[1]:
            assert short_name not in response.rendered_content
Ejemplo n.º 10
0
 def get_success_url(self):
     return reverse(
         'teams:list',
         kwargs={
             'challenge_short_name': self.object.team.challenge.short_name
         },
     )
Ejemplo n.º 11
0
def test_new_registration_email(participant_review, client, ChallengeSet):
    user = UserFactory()
    ChallengeSet.challenge.require_participant_review = participant_review
    ChallengeSet.challenge.save()
    assert not RegistrationRequest.objects.filter(
        user=user, challenge=ChallengeSet.challenge).exists()
    response = get_view_for_user(
        viewname="participants:registration-create",
        client=client,
        method=client.post,
        user=user,
        challenge=ChallengeSet.challenge,
    )
    assert response.status_code == 302
    assert RegistrationRequest.objects.filter(
        user=user, challenge=ChallengeSet.challenge).exists()
    if participant_review:
        email = mail.outbox[-1]
        approval_link = reverse(
            "participants:registration-list",
            args=[ChallengeSet.challenge.short_name],
        )
        assert ChallengeSet.admin.email in email.to
        assert "New participation request" in email.subject
        assert ChallengeSet.challenge.short_name in email.subject
        assert approval_link in email.alternatives[0][0]
    else:
        with pytest.raises(IndexError):
            # No emails if no review
            # noinspection PyStatementEffect
            mail.outbox[-1]
Ejemplo n.º 12
0
 def render(self, context):
     try:
         projectname = context["site"].short_name
     except (AttributeError, KeyError):
         projectname = settings.MAIN_PROJECT_NAME
     url = reverse("challenge-homepage", args=[projectname])
     return url
Ejemplo n.º 13
0
 def replace_links(self, filename, contents, currentpage):
     """Relative urls which work on disk might not
     work properly when used in included file. Make sure any links in contents
     still point to the right place 
     
     """
     # any relative link inside included file has to be replaced to make it work within the COMIC
     # context.
     base_url = reverse(
         "pages:insert-detail",
         kwargs={
             "challenge_short_name": currentpage.challenge.short_name,
             "page_title": currentpage.title,
             "dropboxpath": "remove",
         },
     )
     # for some reason reverse matching does not work for emtpy dropboxpath (maybe views.dropboxpage
     # throws an error?. Workaround is to add 'remove' as path and chop this off the returned link.
     # nice.
     base_url = base_url[:-7]  # remove "remove/" from baseURL
     current_path = (ntpath.dirname(filename) + "/"
                     )  # path of currently inserted file
     replaced = self.replacer.replace_links(contents, base_url,
                                            current_path)
     html_out = replaced
     return html_out
Ejemplo n.º 14
0
def send_new_result_email(result):
    recipient_emails = [o.email for o in result.challenge.get_admins()]
    message = (
        f"There is a new result for {result.challenge.short_name} from "
        f"{result.job.submission.creator.username}."
    )
    if result.published:
        leaderboard_url = reverse(
            "evaluation:result-list",
            kwargs={"challenge_short_name": result.challenge.short_name},
        )
        message += (
            f"You can view the result on the leaderboard here: "
            f"{leaderboard_url}"
        )
        recipient_emails.append(result.job.submission.creator.email)
    else:
        message += (
            f"You can publish the result on the leaderboard here: "
            f"{result.get_absolute_url()}"
        )
    for email in recipient_emails:
        send_mail(
            subject=f"New Result for {result.challenge.short_name}",
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[email],
        )
Ejemplo n.º 15
0
    def render(self, context):
        challenge_short_name = context.page.challenge.short_name
        projectpath = challenge_short_name + "/" + self.path
        storage = DefaultStorage()
        try:
            filenames = storage.listdir(projectpath)[1]
        except OSError as e:
            return self.make_dataset_error_msg(str(e))

        filenames.sort()
        # if extensionsFilter is given,  show only filenames with those extensions
        if "extensionFilter" in self.args.keys():
            extensions = self.args["extensionFilter"].split(",")
            filenames = filter_by_extension(filenames, extensions)
        links = []
        for filename in filenames:
            downloadlink = reverse(
                "serving:challenge-file",
                kwargs={
                    "challenge_short_name": challenge_short_name,
                    "path": f"{self.path}/{filename}",
                },
            )
            links.append('<li><a href="' + downloadlink + '">' + filename +
                         " </a></li>")
        htmlOut = '<ul class="dataset">' + "".join(links) + "</ul>"
        return htmlOut
Ejemplo n.º 16
0
 def get_success_url(self):
     return reverse(
         "teams:list",
         kwargs={
             "challenge_short_name": self.object.team.challenge.short_name
         },
     )
Ejemplo n.º 17
0
 def get_absolute_url(self):
     return reverse(
         "teams:detail",
         kwargs={
             "pk": self.pk,
             "challenge_short_name": self.challenge.short_name,
         },
     )
Ejemplo n.º 18
0
 def get_absolute_url(self):
     return reverse(
         'evaluation:job-detail',
         kwargs={
             'pk': self.pk,
             'challenge_short_name': self.challenge.short_name,
         },
     )
Ejemplo n.º 19
0
 def get_success_url(self):
     return reverse(
         "datasets:annotationset-add-images",
         kwargs={
             "challenge_short_name": self.object.base.challenge.short_name,
             "pk": self.object.pk,
         },
     )
Ejemplo n.º 20
0
 def get_absolute_url(self):
     return reverse(
         'teams:detail',
         kwargs={
             'pk': self.pk,
             'challenge_short_name': self.challenge.short_name,
         },
     )
Ejemplo n.º 21
0
 def get_absolute_url(self):
     return reverse(
         "datasets:imageset-detail",
         kwargs={
             "challenge_short_name": self.challenge.short_name,
             "pk": self.pk,
         },
     )
Ejemplo n.º 22
0
 def get_success_url(self):
     return reverse(
         "datasets:imageset-detail",
         kwargs={
             "challenge_short_name": self.kwargs["challenge_short_name"],
             "pk": self.kwargs["pk"],
         },
     )
Ejemplo n.º 23
0
 def get_absolute_url(self):
     return reverse(
         "evaluation:job-detail",
         kwargs={
             "pk": self.pk,
             "challenge_short_name": self.challenge.short_name,
         },
     )
Ejemplo n.º 24
0
def user_profile_link(user: AbstractUser) -> str:
    return format_html(
        ('<div style="vertical-align:middle; display:inline; white-space: nowrap;">'
         '  <a href="{0}">'
         '    <img class="mugshot" src="{1}" alt="User Mugshot" '
         '         style="height: 1.5em; vertical-align: middle;"/>'
         "    {2}"
         "  </a>"
         "</div>"),
        reverse("userena_profile_detail", kwargs={"username": user.username}),
        user.user_profile.get_mugshot_url(),
        user.username,
    )
Ejemplo n.º 25
0
def user_profile_link(user: AbstractUser) -> str:
    return format_html(
        ('<div style="vertical-align:middle; display:inline;">'
         '  <a href="{0}">'
         '    <img class="mugshot" src="{1}" alt="User Mugshot" '
         '         style="height: 1.5em; vertical-align: middle;"/>'
         '    {2}'
         '  </a>'
         '</div>'),
        reverse('userena_profile_detail', kwargs={'username': user.username}),
        user.user_profile.get_mugshot_url(),
        user.username,
    )
Ejemplo n.º 26
0
def comic_site_to_grand_challenge_html(comic_site, link=""):
    """ Return an html overview of the given ComicSite, in the same style as 
    listings on grand_challenge.org 
    
    """
    if link == "":
        link = reverse('challenge-homepage', args=[comic_site.short_name])
    html = create_HTML_a(link, comic_site.short_name)
    if comic_site.description != "":
        html += " - " + comic_site.description
    img_html = create_HTML_a_img(link, comic_site.logo)
    html = "<table class=\"upcoming comic\"><tbody><tr valign=\"top\"><td><span class=\"plainlinks\" id=\"" + comic_site.short_name + "\"><a href=\"" + link + "\"><img alt=\"\" src=\"" + comic_site.logo + "\" height=\"100\" border=\"0\" width=\"100\"></td></a></span><td>" + comic_site.description + "<br>Website: <a class=\"external free\" title=\"" + comic_site.short_name + "\"href=\"" + link + "\">" + link + "</a><br>Event: <a class=\"external text\" title=\"none\" href=\"\">MICCAI, September 22, 2013</a></td></tr></tbody></table>"
    return html
Ejemplo n.º 27
0
 def to_projectlink(self):
     """
     Return a ProjectLink representation of this comicsite, to show in an
     overview page listing all projects
     """
     thumb_image_url = reverse('project_serve_file',
                               args=[self.short_name, self.logo])
     args = {
         "abreviation": self.short_name,
         "title": self.title if self.title else self.short_name,
         "description": self.description,
         "URL": reverse('challenge-homepage', args=[self.short_name]),
         "download URL": "",
         "submission URL": self.get_submission_url(),
         "event name": self.event_name,
         "year": "",
         "event URL": self.event_url,
         "image URL": self.logo,
         "thumb_image_url": thumb_image_url,
         "website section": "active challenges",
         "overview article url": self.publication_url,
         "overview article journal": self.publication_journal_name,
         "overview article citations": "",
         "overview article date": "",
         "submission deadline": "",
         "workshop date": self.workshop_date,
         "open for submission":
         "yes" if self.is_open_for_submissions else "no",
         "data download": "yes" if self.offers_data_download else "no",
         "dataset downloads": self.number_of_downloads,
         "registered teams": "",
         "submitted results": self.number_of_submissions,
         "last submission date": self.last_submission_date,
         "hosted on comic": True,
         "created at": self.created_at,
     }
     projectlink = ProjectLink(args)
     return projectlink
Ejemplo n.º 28
0
    def __init__(self, *args, **kwargs):
        self.challenge = kwargs.pop("challenge", None)
        super().__init__(*args, **kwargs)
        if self.challenge is not None and "html" in self.fields:
            self.fields["html"].widget.config.update({
                "filebrowserUploadUrl":
                reverse(
                    "uploads:ck-create",
                    kwargs={"challenge_short_name": self.challenge.short_name},
                ),
                "filebrowserBrowseUrl":
                reverse(
                    "uploads:ck-browse",
                    kwargs={"challenge_short_name": self.challenge.short_name},
                ),
            })

            if self.challenge.allow_unfiltered_page_html:
                self.fields["html"].widget.config.update(
                    {"allowedContent": True})

        self.helper = FormHelper(self)
        self.helper.layout.append(Submit("save", "Save"))
Ejemplo n.º 29
0
    def render(self, context):
        # get the url the default django method would give.
        url = super().render(context)

        if subdomain_is_projectname() and (
            (self.view_name.var
             in ["challenge-homepage", "project_serve_file"]) or
            (self.view_name.var.split(":")[0] in [
                "evaluation",
                "teams",
                "pages",
                "participants",
                "admins",
                "uploads",
                "datasets",
            ])):
            # Interpret subdomain as a challenge. What would normally be the
            # path to this challenge?
            args = [arg.resolve(context) for arg in self.args]
            kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}

            try:
                project = args[0]
            except IndexError:
                # No project was set, so must be part of the main site
                project = kwargs.get("challenge_short_name",
                                     settings.MAIN_PROJECT_NAME)

            if project == settings.MAIN_PROJECT_NAME:
                # this url cannot use the domain name shortcut, so it is
                # probably meant as a link the main comicframework site.
                # in that case hardcode the domain to make sure the sub-
                # domain is gone after following this link
                return settings.MAIN_HOST_NAME + url

            else:
                path_to_site = reverse_djangocore("challenge-homepage",
                                                  args=[project])

                if url.startswith(path_to_site):
                    url = url.replace(path_to_site, "/")

                scheme_subsite_and_host = reverse("challenge-homepage",
                                                  args=[project])

                return urljoin(scheme_subsite_and_host, url)

        return url
Ejemplo n.º 30
0
    def submission_url(self):
        """ What url can you go to to submit for this project? """
        url = reverse("challenge-homepage", args=[self.short_name])
        if self.submission_page_name:
            if self.submission_page_name.startswith(
                    "http://") or self.submission_page_name.startswith(
                        "https://"):
                # the url in the submission page box is a full url
                return self.submission_page_name

            else:
                page = self.submission_page_name
                if not page.endswith("/"):
                    page += "/"
                url += page
        return url