Пример #1
0
def home_view(request):
    if request.user.is_authenticated:
        ctx = {'solved': get_accept_problem_count(request.user.pk),
               'bulletin': site_settings_get('BULLETIN', ''),
               'global_rating': User.objects.filter(rating__gt=0).order_by("-rating")[:10],
               'update_log': UpdateLog.objects.all().order_by("-pk")[:10],
               'submission_count': Submission.objects.all().count()
               }
        if not is_site_closed(request):
            LIMIT, LIMIT_BLOG = 20, 15
            ctx['blog_list'] = Blog.objects.with_likes().with_likes_flag(request.user).select_related(
                "author").order_by("-create_time").filter(visible=True, recommend=True)[:LIMIT_BLOG]
            comment_list, blog_list = XtdComment.objects.filter(is_public=True, is_removed=False).order_by(
                "-submit_date").select_related("user", "content_type").prefetch_related('content_object').all()[:LIMIT], \
                                      Blog.objects.order_by("-create_time").select_related("author").filter(
                                          visible=True)[:LIMIT]
            ctx['comment_list'] = []
            i, j = 0, 0
            for k in range(LIMIT):
                if i < len(comment_list) and (j == len(blog_list) or (
                        j < len(blog_list) and comment_list[i].submit_date > blog_list[j].create_time)):
                    ctx['comment_list'].append(comment_list[i])
                    i += 1
                elif j < len(blog_list):
                    ctx['comment_list'].append(blog_list[j])
                    j += 1
                else:
                    break
            for comment in ctx['comment_list']:
                if isinstance(comment, XtdComment) and len(comment.comment) > LIMIT:
                    comment.comment = comment.comment[:LIMIT] + '...'
        return render(request, 'home_logged_in.jinja2', context=ctx)
    else:
        return render(request, 'home.jinja2', context={'bg': '/static/image/bg/%d.jpg' % randint(1, 14), })
Пример #2
0
def process_code(code: PrintCode):
    base_dir, gen_dir = settings.BASE_DIR, settings.GENERATE_DIR
    os.chdir(gen_dir)
    try:
        if not code.generated_pdf:
            with open(os.path.join(base_dir,
                                   "submission/assets/template.tex")) as f:
                tex_code = f.read()
                tex_code = tex_code.replace("$$username$$",
                                            latex_replace(code.user.username))
                tex_code = tex_code.replace("$$comment$$",
                                            latex_replace(code.comment))
                tex_code = tex_code.replace(
                    "$$code$$", code.code.replace("\\end{lstlisting}", ""))
            secret_key = random_string()
            tex_file_path = secret_key + ".tex"
            pdf_file_path = secret_key + ".pdf"
            with open(tex_file_path, "w") as f:
                f.write(tex_code)
            tex_gen = subprocess.run(["/usr/bin/xelatex", tex_file_path],
                                     check=True)
            if tex_gen.returncode != 0 or not os.path.exists(pdf_file_path):
                raise ValueError("TeX generation failed")
            code.generated_pdf = secret_key
        else:
            pdf_file_path = code.generated_pdf + ".pdf"
        pdfinfo = subprocess.check_output(["/usr/bin/pdfinfo",
                                           pdf_file_path]).decode()
        pdfinfo_match = re.match(r"Pages:\s+(\d+)", pdfinfo)
        if pdfinfo_match:
            code.pages = int(pdfinfo_match.group(1))
        code.save()
        if code.pages > code.manager.limit or \
            code.manager.printcode_set.filter(create_time__gt=datetime.now() - timedelta(days=1)).\
                aggregate(Sum("pages"))["pages__sum"] > code.manager.limit:
            # limit pages
            raise ValueError("Too many pages")
        subprocess.run([
            "/usr/bin/lp", "-d",
            site_settings_get("PRINTER_NAME", "LaserJet"), pdf_file_path
        ],
                       check=True)
        code.status = 0
    except:
        traceback.print_exc()
        code.status = 1
    os.chdir(base_dir)
    code.save()
Пример #3
0
def home_view(request):
    if request.user.is_authenticated:
        ctx = {
            'solved': get_accept_problem_count(request.user.pk),
            'bulletin': site_settings_get('BULLETIN', '')
        }
        if not is_site_closed():
            ctx['blog_list'] = Blog.objects.with_likes().with_likes_flag(
                request.user).select_related("author").order_by(
                    "-create_time").filter(visible=True, recommend=True)[:15]
        return render(request, 'home_logged_in.jinja2', context=ctx)
    else:
        return render(request,
                      'home.jinja2',
                      context={
                          'bg': '/static/image/bg/%d.jpg' % randint(1, 14),
                      })
Пример #4
0
def home_view(request):
  if request.user.is_authenticated:
    ctx = {'solved': get_accept_problem_count(request.user.pk),
           'bulletin': site_settings_get('BULLETIN', ''),
           'global_rating': User.objects.filter(rating__gt=0).order_by("-rating")[:10],
           }
    if is_site_closed(request):
      return redirect(reverse("contest:list"))
    else:
      LIMIT, LIMIT_BLOG = 20, 15
      ctx['blog_list'] = Blog.objects.with_likes().with_likes_flag(request.user).select_related(
        "author").order_by("-create_time").filter(visible=True, recommend=True, is_reward=False)[:LIMIT_BLOG]
      # prefetch more comments
      comment_list = XtdComment.objects.filter(is_public=True, is_removed=False).order_by(
        "-submit_date").select_related("user", "content_type").prefetch_related('content_object').all()[:LIMIT * 2]
      blog_list = Blog.objects.order_by("-create_time").select_related("author").filter(
        visible=True, is_reward=False)[:LIMIT]
      ctx['comment_list'] = []
      i, j = 0, 0
      for _ in range(LIMIT):
        while i < len(comment_list) and \
            comment_list[i].content_type == ContentType.objects.get_for_model(Blog) and \
            Blog.objects.filter(pk=comment_list[i].object_pk, is_reward=True).exists():
          # Skip this comment
          i += 1
        # Merge comments and blogs in time order
        if i < len(comment_list) and (j == len(blog_list) or (
            j < len(blog_list) and comment_list[i].submit_date > blog_list[j].create_time)):
          ctx['comment_list'].append(comment_list[i])
          i += 1
        elif j < len(blog_list):
          ctx['comment_list'].append(blog_list[j])
          j += 1
        else:
          break
      for comment in ctx['comment_list']:
        if isinstance(comment, XtdComment) and len(comment.comment) > LIMIT:
          comment.comment = comment.comment[:LIMIT] + '...'
    return render(request, 'home_logged_in.jinja2', context=ctx)
  else:
    return render(request, 'home.jinja2', context={'bg': '/static/image/bg/%d.jpg' % randint(1, 14), })