Exemple #1
0
def judge_submission(submission):
    '''
        Judge the target submission
    '''
    if submission.language is None:
        raise RuntimeError('Unknown Language')
    else:
        upload_result(
            Report(result=Judge_result.PR, submission=submission.submission))
    st, info = pull(lock=gloal_problem_lock.get(submission.problem),
                    problem=submission.problem)
    if not st:
        raise RuntimeError("Pull error: " + str(info))
    st, info = create_tempfile(sourcefile=submission.sourcefile,
                               work_dir=submission.work_dir,
                               lang=submission.language,
                               code=submission.code)
    if st != 'Success':
        raise RuntimeError("Judger Error during creating tempfile: " +
                           str(info))
    if submission.language.value.compile is True:
        result, information = compile(submission=submission)
        if result is Judge_result.CE:
            upload_result(
                Report(result=result,
                       complete=True,
                       submission=submission.submission,
                       compileerror_msg=information))
            return
        elif result is Judge_result.JE:
            raise RuntimeError("Judger Error during compiling: " +
                               str(information))
    submission.case = get_test_case(submission.problem)
    if len(submission.case) == 0:
        raise RuntimeError("Judger Error, because there is no test-data")
Exemple #2
0
def report_event(request, event_category, event_slug):
    """Report specific event.

    Returns:
    HttpResponseObject -- report event page

    """
    event = check_event(request,
                        event_category=event_category,
                        event_slug=event_slug)
    if event:
        if request.method == 'POST':
            report_form = ReportForm(request.POST)
            if report_form.is_valid():
                report = Report(event=event,
                                report_type=request.POST['report_type'],
                                detail=request.POST['detail'])
                report.save()
                messages.warning(request, f'{event.title} is reported.')
                return redirect('events:feed')
        else:
            report_form = ReportForm()
        return render(request, 'events/report_event.html', {
            'report_form': report_form,
            'event': event
        })
    else:
        return redirect('events:feed')
Exemple #3
0
def add_item(request, report_id):
    if request.method == 'POST':
        form_1 = Item1Form(request.POST)
        form_2 = Item2Form(request.POST)
        form_3 = Item3Form(request.POST)

        if form_1.is_valid():
            item_stage1 = request.POST.getlist('item_stage1_name')
            for item in item_stage1:
                if item != '':
                    report_obj = Report(pk=report_id)
                    item_obj = Items(name=item, stage=1, report_id=report_obj)
                    item_obj.save()

        elif form_2.is_valid():
            item_stage2 = request.POST.getlist('item_stage2_name')
            for item in item_stage2:
                if item != '':
                    report_obj = Report(pk=report_id)
                    item_obj = Items(name=item, stage=2, report_id=report_obj)
                    item_obj.save()

        elif form_3.is_valid():
            item_stage3 = request.POST.getlist('item_stage3_name')
            for item in item_stage3:
                if item != '':
                    report_obj = Report(pk=report_id)
                    item_obj = Items(name=item, stage=3, report_id=report_obj)
                    item_obj.save()

        return HttpResponseRedirect(
            reverse("report.views.edit_report",
                    args=(),
                    kwargs={'pk': report_id}))
Exemple #4
0
    def test_total_profit_by_month(self):
        report = Report()
        create_recent_sells(self, self.stock, self.user)
        monthly_profit = report.total_monthly_profit()
        cur_month = datetime.now().month

        self.assertEqual("{0:.2f}".format(monthly_profit[cur_month]), "679.96")
        self.assertEqual("{0:.2f}".format(monthly_profit[3]), "0.00")
 def setUp(self):
     rep = Report()
     rep.name = u'ReportTest'
     rep.slug = u'RT'
     rep.description = u'ReportTest description'
     rep.parent_model = Report.get_models()[0]
     rep.distinct = True
     rep.save()
Exemple #6
0
    def _set_up_test_data(self):
        # Create some CWEs. These CWEs will be used by all the test methods.
        cwe_01 = CWE(code=101, name='CWE 01')
        cwe_01.save()

        report_01 = Report(title='Sample report title', description='Sample report title')
        report_01.save()

        return report_01
Exemple #7
0
    def destroy(self, validated_data):
        user = self.context['request'].user

        object_id = self.get_object_id(validated_data=validated_data)
        app_model = self.get_app_model(validated_data=validated_data)

        Report = Report.objects.get_obj(user, object_id, model=app_model)
        if Report:
            Report.delete()
        else:
            raise NotFound(detail='Item not found', code=None)
def report_post(request):
    post = request.data
    photo = fromDataUrlToFile(post.get("photo", None))
    geolocation = Point(*post["geolocation"])
    type = post["type"]
    rep = Report(photo=photo,
                 geolocation=geolocation,
                 type=type,
                 user=request.user)
    rep.save()

    return Response(ReportSerializer(rep).data)
    def _set_up_test_data(self):
        # Create some CWEs. These CWEs will be used by all the test methods.
        cwe_01 = CWE(code=101, name='CWE 01')
        cwe_01.save()

        report_01 = Report(title='Sample report title', description='Sample report title')
        report_01.save()

        issue_report_01 = IssueReport(name="Issue/00001", type='incorrect', report=report_01)
        issue_report_01.save()

        return issue_report_01
Exemple #10
0
def get_submission_task(submission):
    name = current_process().name
    try:
        submission = parse(**submission)
        sub = Submission(
            **{
                **submission,
                **{
                    'work_dir': path.join(base_work_dir, name),
                    'output_limit': 64,
                    'stack_limit': 64,
                    'sourcefile': 'Main'
                }
            })
        logging.info('%s got submission, start judging(%s)', name,
                     sub.submission)
        judge_submission(sub)
    except Exception as e:
        from update import upload_result
        from report.models import Report
        upload_result(
            Report(result=Judge_result.JE,
                   complete=True,
                   submission=sub.submission,
                   judgererror_msg=str(e)))
        logging.error('%s error happen: %s', name, e)
Exemple #11
0
 def model_save_with_retry(self, report: Report):
     """
     sqlite 似乎不支持这么高的并发, 一直会报错 database is locked
     https://docs.djangoproject.com/en/3.1/ref/databases/#database-is-locked-errors
     FIXME: 暂时用无限重试解决
     """
     retry = 1
     while retry > 0:
         try:
             logger.info(
                 f'writing {report.user.username:10} to database, retry={retry}'
             )
             report.save()
             retry = -1
         except OperationalError:
             retry += 1
Exemple #12
0
    def setUp(self):
        """
        This method does the general setup needed for the test methods.
        It creates a reviewer user and creates an issue report.
        """
        self.reviewer = User.objects.create(username='******')
        self.reviewer.save()

        report = Report()
        report.save()

        issue_report = IssueReport.objects.create(description="this is the issue", type="spam",
                                                 report=report)
        issue_report.save()

        self.issue_report = issue_report
Exemple #13
0
def create_bot_report(product, description, check_if_already_exists=False):
    if check_if_already_exists
        and Report.filter(product=product, client='krs-bot', description=description).exists():
        return

    report = Report(description=description)
    report.product = product
    report.client = 'krs-bot'
    report.save()
Exemple #14
0
    def get(self, request, *args, **kwargs):
        if Criterion.objects.filter(parent__isnull=True).count() == 0 or \
                Criterion.objects.filter(parent__isnull=False).count() == 0 or\
                Supplier.objects.count() == 0:
            # no data
            return HttpResponseRedirect(reverse('home'))

        report = Report.create_report(request.user)
        return HttpResponseRedirect(
            reverse('criterion-score', args=[report.id]))
Exemple #15
0
def create_report(request):
    if not Authorize.authorize(request.user, ["superuser"]):
        return HttpResponseRedirect("/amrs_user_validation/access_denied")

    if request.method == "POST":
        print request.POST
        name = get_var(request.POST, "report_name")
        description = get_var(request.POST, "description")
        template = get_var(request.POST, "template")
        report_id = get_var(request.POST, "report_id")
        if name:
            if report_id:
                r = Report.objects.get(id=report_id)
                r.name = name
                r.description = description
            else:
                r = Report(name=name, description=description)
            r.save()
            cur_index = 2
            while True:
                row = get_var(request.POST, "report_table_values_" + str(cur_index))
                if row is None:
                    break
                rm = ReportMember(report_id=r.id)
                args = row.split(";;;")

                for arg in args:
                    split = arg.split("===")
                    setattr(rm, split[0], split[1])
                rm.save()
                cur_index += 1

        return HttpResponseRedirect("/")
    else:
        report_id = get_var(request.GET, "report_id")
        report_tables = ReportTable.objects.all().order_by("name")
        r = None
        if report_id:
            r = Report.objects.get(id=report_id)
        return render(request, "amrs_reports/create_report.html", {"report": r, "report_tables": report_tables})
    def save(self, validated_data):
        request = self.context['request']
        # Obtain record info
        date_paid = validated_data.get('date_paid')
        payperiod_start = validated_data.get('payperiod_start')
        payperiod_end = validated_data.get('payperiod_end')
        company = request.user.company

        already_paid = company.employees.filter(
            record__date_paid=date_paid).exists()
        host_url = request.META.get(
            'wsgi.url_scheme') + '://' + request.META['HTTP_HOST']

        if not already_paid:
            record_list = []
            total_paid = 0

            new_report = Report(company_id=company.id, )
            new_report.save()

            for employee in company.employees.all():
                new_record = Record(date_paid=date_paid,
                                    payperiod_start=payperiod_start,
                                    payperiod_end=payperiod_end,
                                    user_id=employee.id,
                                    company_id=company.id,
                                    report_id=new_report.id)
                new_record.save()
                payslip_pdf(employee, new_record, host_url)
                record_list.append(new_record)
                total_paid += new_record.user.salary.gross_month

            report_pdf(company, record_list, total_paid, new_report, employee,
                       new_record, host_url)

        else:
            raise ValidationError(
                'You have already scheduled payments on this day')

        return
Exemple #17
0
def cashier_save(request):
    cash = request.POST.get('cash_name')
    shop = request.POST.get('shop_name')
    if cash and shop:
        report = Report()
        report.cashier = request.user.username
        report.cash = cash
        report.shop = shop
        report.save()
        return redirect('cashier_interface')
    else:
        return redirect('log_cash')
Exemple #18
0
def add_report(request, station_id, available_bikes, broken_bikes):
    if int(available_bikes) >= int(broken_bikes):
        if station_id in stations:
            new_report = Report(report_date=timezone.now(),
                                station_id=station_id,
                                available_bikes=available_bikes,
                                broken_bikes=broken_bikes)
            new_report.save()
            if(int(broken_bikes)>=2):
                return HttpResponse("Thanks for reporting broken bikes. We note that at the moment, %s bikes out of %s are broken at station #%s."
                                    % (broken_bikes, available_bikes, station_id))
            elif(int(broken_bikes)==1):
                return HttpResponse("Thanks for reporting broken bikes. We note that at the moment, 1 bike out of %s is broken at station #%s."
                                    % (available_bikes, station_id))
            else:
                return HttpResponse("Thanks for reporting broken bikes. We note that at the moment, no bikes are broken at station #%s."
                                    % station_id)
        else:
            return HttpResponse("Sorry, but #%s is not a valid station id."
                                    % station_id)
    else:
        return HttpResponse("Sorry, but it is absurd that %s bikes are broken out of %s at station #%s."
                                    % (broken_bikes, available_bikes, station_id))
Exemple #19
0
    def post(self, request):
        """
        Aquí entra si la petición es POST (como debe ser)
        """
        success_message = ''
        report = Report()
        form = ReportForm(request.POST, instance=report)

        if form.is_valid():
            new_report = form.save()
            form = ReportForm
            success_message = u'Tu denuncia ha sido guardada con éxito!'

        context = {'form': form, 'success_message': success_message}
        return render(request, 'report/new_report.html', context)
Exemple #20
0
    def create(self, request):
        post_data = request.data
        print(post_data)
        #user = post_data['user']
        user = User.objects.get(pk=1)
        locX = post_data['locationX']
        locY = post_data['locationY']
        ts = post_data['timestamp']
        img = post_data['image']
        description = post_data['description']
        floodLevel = post_data['floodLevel']
        obj = Report(user=user, locationX=locX, locationY=locY,timestamp=ts,image=img, description=description, floodLevel=floodLevel)
        obj.save()
        q = FloodProneArea.objects.filter(locationX=locX,locationY=locY)
        if q.count()==0:
            fpa = FloodProneArea(locationX=locX, locationY=locY)
            fpa.save()

            url = 'http://api.openweathermap.org/data/2.5/weather'
            url += '?lat=' + locX + '&lon=' + locY
            url += '&appid=67aa636d02df1df62ef01de2db58fa49'
            r = requests.get(url)
            data = json.loads(r.content.decode())
            w_id = data['weather'][0]['id']
            w_temp = data['main']['temp']
            w_desc = data['weather'][0]['description']
            w_icon = data['weather'][0]['icon']
            w = Weather(w_id=w_id, w_temp=w_temp, w_description=w_desc, w_icon=w_icon)
            w.save()

            FloodForecast(location=fpa, weather=w).save()

        serializer_context = {
            'request': request,
        }
        return Response(ReportSerializer(obj, context=serializer_context).data)
Exemple #21
0
    def validate(self, data):
        creating = self.context.get('creating')

        if creating:
            owner = self.context.get('owner')
            data['owner'] = owner
            name = data.get('name')
            folder_list = Folder.objects.filter(owner=owner)
            for folder in folder_list:
                if folder.name == name:
                    raise serializers.ValidationError(
                        "User already has a report with this name")

        report_list = data.get('reports', None)
        if report_list == None:
            raise serializers.ValidationError(
                "Must specify at least one report")
        if len(report_list) == 0:
            raise serializers.ValidationError(
                "Must specify at least one report")

        new_report_list = []
        new_group_list = []

        r = Report()
        for report in report_list:
            try:
                new_report_list.append(Report.objects.get(pk=report))
            except ObjectDoesNotExist:
                raise serializers.ValidationError(
                    "At least one report name was invalid")

        data['reports'] = new_report_list

        group_list = data.get('groups', None) or []

        g = Group()
        for group in group_list:
            try:
                new_group_list.append(Group.objects.get(name=group))
            except ObjectDoesNotExist:
                raise serializers.ValidationError(
                    "At least one group name was invalid")

        data['groups'] = new_group_list
        return data
Exemple #22
0
def save_report(req):
    if req.method != 'POST':
        return HttpResponse('ya gotta send a post request')
    form = json.loads(req.body)

    problem = form['problem']
    explanation = form['explanation']
    report = Report()
    report.problem = problem
    report.explanation = explanation
    report.ip_address = get_client_ip(req)
    scholarship_id = decrypt_sk(form['sk'])
    scholarship = Scholarship.objects.get(id=scholarship_id)
    report.scholarship = scholarship
    report.save()
    # tell sentry we got a report

    client.captureMessage("Scholarship problem reported.", problem=problem, explanation=explanation)

    return HttpResponse('{"msg": "thanks"}', content_type='application/json')
Exemple #23
0
    def generate_report(cls, start_time, end_time=None):
        if end_time is None:
            end_time = start_time + timedelta(days=1)

        assert (isinstance(start_time, datetime))
        assert (isinstance(start_time, datetime))

        path = cls.get_file_path(start_time, end_time)

        content = cls.generate_report_content(start_time, end_time)

        path = storage.save(path, ContentFile(content))
        report = Report(name=cls.get_report_name(start_time, end_time))
        report.file = path
        report.content = content
        report.save()
        return report
Exemple #24
0
    def generate_report(cls, start_time, end_time=None, **kwargs):
        if end_time is None:
            end_time = start_time + timedelta(days=1)

        assert (isinstance(start_time, datetime))
        assert (isinstance(start_time, datetime))

        path = cls.get_file_path(start_time, end_time)

        if kwargs.get('type'):
            content = cls.generate_report_content(start_time, end_time,
                                                  kwargs.get('type'))
        else:
            content = cls.generate_report_content(start_time, end_time)

        encrypted_content = ReportCrypto.encrypt_file(content)
        path = storage.save(path, ContentFile(encrypted_content))

        report = Report(name=cls.get_report_name(start_time, end_time))
        report.file = path
        report.content = content
        report.save()
        return report
Exemple #25
0
    def handle(self, *args, **options):
        
        read_report = DictReader(open('./total_rent.csv'))
        print("loading record data")
        for row in read_report:
            report = Report()
            report.car_id = row['Car_ID']
            report.brand_name = row['BrandName']
            report.type = row['type']
            report.tranmission = row['Tranmission']
            report.luggage_size = row['LuggageSize']
            report.seat_number = row['SeatNumber']
            report.release_year = row['ReleaseYear']
            report.total_rent_january = row['Total_Rent_January']
            report.total_rent_february = row['Total_Rent_February']
            report.total_rent_march = row['Total_Rent_March']
            report.total_rent_april = row['Total_Rent_April']
            report.total_rent_may = row['Total_Rent_May']
            report.total_rent_june = row['Total_Rent_June']
            report.total_rent_july = row['Total_Rent_July']
            report.total_rent_august = row['Total_Rent_August']
            report.total_rent_september = row['Total_Rent_September']
            report.total_rent_october = row['Total_Rent_October']
            report.total_rent_november = row['Total_Rent_November']
            report.total_rent_december = row['Total_Rent_December']

            report.save()
        print("report data imported")
Exemple #26
0
    return render_to_response('new.html', { 'form': form }, 
        context_instance=RequestContext(request))

@csrf_exempt
def submit(request):

    if request.method != 'POST':
        return HttpResponse(json.dumps({'success': False, 'reason': 'I only speak POST'}), mimetype='application/json')

    try:
        json_data = json.loads(request.raw_post_data)
    except Exception, e:
        return HttpResponse(json.dumps({'success': False, 'reason': 'Bad JSON.', 'exception': str(e)}), mimetype='application/json')

    try:
        report = Report()
        report.agency = json_data['report'].get('agency', None)
        report.description = json_data['report'].get('description', None)
        report.lat = json_data['report'].get('latitude', None)
        report.lon = json_data['report'].get('longitude', None)
        report.location = json_data['report'].get('location', None)
        report.date = string_to_date(json_data['report']['date'])
        report.uuid = json_data['report'].get('uuid', None)
        report.address_1 = json_data['user'].get('address_1', None)
        report.address_2 = json_data['user'].get('address_2', None)
        report.alternate = json_data['user'].get('alternate', None)
        report.first_name = json_data['user'].get('first_name', None)
        report.last_name = json_data['user'].get('last_name', None)
        report.email = json_data['user'].get('email', None)
        report.phone = json_data['user'].get('phone', None)
        report.city = json_data['user'].get('city', None)
    # QUICK DJANGO ENV CLEANING UP SO THAT IT'S ABLE TO BE CALLED ANY UNDER PROJECT

    from report.models import Report
    text_file = open(
        '/home/docker/code/app/report/initial_data/is_data_initialized.txt',
        'r')
    is_initialized_data = int(text_file.read())
    text_file.close()

    if is_initialized_data:
        print "it's already initialized! Continue."
    else:
        reports = initial_data.reports.data
        print "initializing human tables..."

        for report in reports:
            reportToSave = Report()
            reportToSave.reference_id = report["id"]
            reportToSave.status = report["state"]
            reportToSave.message = report["payload"]["message"]
            reportToSave.report_type = report["payload"]["reportType"]
            reportToSave.save()
        print "... Populating Reports DONE!"

        text_file = open(
            '/home/docker/code/app/report/initial_data/is_data_initialized.txt',
            'w')
        text_file.write('1')

        print "All Done successfully! woo foo!!"
Exemple #28
0
    def get(self, request, format=None):
        report = Report()

        serializer = ReportTotalProfitMonthlySerializer(report)

        return Response(serializer.data)
Exemple #29
0
    def do_report(self, report: Report):
        url = 'https://app.nwu.edu.cn/ncov/wap/open-report/save'

        headers = {
            "Content-Type":
            "application/x-www-form-urlencoded",
            "Accept":
            "application/json, text/plain, */*",
            "Host":
            "app.nwu.edu.cn",
            "Accept-Language":
            "en-us",
            "Accept-Encoding":
            "br, gzip, deflate",
            "Origin":
            "https://app.nwu.edu.cn",
            "Referer":
            "https://app.nwu.edu.cn/site/ncov/dailyup",
            "Connection":
            "keep-alive",
            "Content-Length":
            "1780",
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) "
            "AppleWebKit/605.1.15 (KHTML, like Gecko) "
            "Version/13.1 Safari/605.1.15",
            "X-Requested-With":
            "XMLHttpRequest",
        }

        data = {
            "sfzx": "1" if report.sfzx else "0",
            "tw": "1",
            "address": report.address,
            "area": report.area,
            "province": report.province,
            "city": report.city,
            "geo_api_info": report.geo_api_info,
            "sfcyglq": "0",
            "sfyzz": "0",
            "qtqk": "",
            "ymtys": "",
        }

        cookie_jar = pickle.loads(report.user.cookie)
        try:
            cookie_dict = cookie_jar.get_dict()
            cookie_str = ''
            for i in cookie_dict:
                cookie_str += i + '=' + cookie_dict[i] + '; '
            headers['Cookie'] = cookie_str
            r = requests.post(url, headers=headers, data=data)
            r = json.loads(r.text)
            if r['e'] == 1 or r['e'] == 0:
                logger.info(
                    f'{report.user.username}-{report.user.name} {r["m"]}')
                if report.last_report_message:
                    report.last_report_message = ''
                    self.model_save_with_retry(report)
                return True
            else:
                logger.warning(
                    f'{report.user.username}-{report.user.name} {r}')
                report.last_report_message = f'[{datetime.now()} {r}]'
                self.model_save_with_retry(report)
                return False
        except requests.exceptions.ConnectionError as e:
            logger.warning(f'{report.user.username}-{report.user.name} 连接失败\n'
                           f'错误信息: {e}')
            report.last_report_message = f'[{datetime.now()} 连接失败\n' f'错误信息: {e}]'
            self.model_save_with_retry(report)
        return False
def create_bot_report(product, description):
    report = Report(description=description)
    report.product = product
    report.client = 'krs-bot'
    report.save()
Exemple #31
0
def collect1(request, start_date, end_date, gcid, fcid):
    client = GoogleClient.objects.get(pk=gcid)
    client_id = client.client_id
    client_name = client.client_name

    #account = FacebookAccount.objects.get(account_name='Western Health Advantage')
    account = FacebookAccount.objects.get(pk=fcid)
    try:
        fb_acc = SocialAccount.objects.get(user_id=request.user.id,
                                           provider='facebook')
        #google_acc = SocialAccount.objects.get(user_id = request.user.id,provider='google')
        fb_tok = SocialToken.objects.get(account=fb_acc)
        #google_tok = SocialToken.objects.get(account=google_acc)
    except:
        return HttpResponse("error connecting Social Accounts")

    #clear the database
    GoogleCampaign.objects.all().delete()
    GoogleAdGroup.objects.all().delete()
    GoogleKeyword.objects.all().delete()

    #FacebookAccount.objects.all().delete()
    Report.objects.all().delete()

    report_model = Report()
    report_model.user = request.user.username
    report_model.date_taken = datetime.now()
    report_model.google_account = client_name

    if (start_date == '1' and end_date == '1'):
        report_model.date_range = "All Time"
        report_model.save()
        account.report = report_model
        account.save()
        all_google_data(request, client_id)
        return render(request, 'report/onetwo.html')
        return redirect("../2")
    elif (start_date == '2' and end_date == '2'):
        report_model.date_range = "Last 30 Days"
        report_model.save()
        account.report = report_model
        account.save()
        month_google_data(request, client_id)
        #"../../../../view"
        return render(request, 'report/onetwo.html')
        return redirect("../2")

    i_y = start_date[0] + start_date[1] + start_date[2] + start_date[3]
    i_m = start_date[5] + start_date[6]
    i_d = start_date[8] + start_date[9]

    f_y = end_date[0] + end_date[1] + end_date[2] + end_date[3]
    f_m = end_date[5] + end_date[6]
    f_d = end_date[8] + end_date[9]

    googstartDate = i_y + i_m + i_d
    googendDate = f_y + f_m + f_d

    fbstartDate = i_y + '-' + i_m + '-' + i_d
    fbendDate = f_y + '-' + f_m + '-' + f_d

    report_model.date_range = fbstartDate + " to " + fbendDate
    report_model.save()

    account.report = report_model
    account.save()

    #get the google data
    google_data(request, client_id, googstartDate, googendDate)

    #get the facebook data

    return render(request, 'report/onetwo.html')
    return redirect("../2")
Exemple #32
0
            running_command = running_arguments.format(
                time_limit=sub.time_limit,
                memory_limit=sub.memory_limit * 1024 * 1024,
                output_limit=sub.output_limit * 1024 * 1024,
                stack_limit=sub.stack_limit * 1024 * 1024,
                input_sourcefile=posixpath.join(data_dir, x[0]),
                output_sourcefile='user.out',
                answer_sourcefile=posixpath.join(data_dir, x[1]),
                running_arguments=sub.language.value.running_command.format(
                    sourcefile=sub.sourcefile),
                checker_sourcefile=sub.checker)
            ret = s.exec_run(cmd=running_command)
            logging.info("exit code: %s, output: %s", ret[0],
                         ret[1].decode('utf-8'))
            exit_code, output = int(ret[0]), loads(ret[1].decode('utf-8'))
            output['result'] = get_judge_result(output['result'])
            output['case'] = i + 1
            output['submission'] = sub.submission
            if output['result'] is Judge_result.AC and i != len(sub.case) - 1:
                output['complete'] = False
            else:
                output['complete'] = True
            upload_result(report=Report(**output))
            if output['result'] is not Judge_result.AC:
                break
    except Exception as e:
        raise RuntimeError("Judger Error during running: " + str(e))
    finally:
        if 's' in dir():
            s.remove(force=True)
Exemple #33
0
def create_report(request):
    if request.method == 'POST':

        form = ReportForm(request.POST)
        if form.is_valid():  #check rules in forms.py
            report_name = request.POST.get('report_name')  #from html
            report_obj = Report(name=report_name)  #get data into Report Model
            report_obj.user_id = request.user  #from user that login
            report_obj.save()  #save data intp database

            item_stage1_name = request.POST.getlist('stage1')
            for item in item_stage1_name:
                if item != '':
                    item_obj = Items(name=item, stage=1, report_id=report_obj)
                    item_obj.save()

            item_stage2_name = request.POST.getlist('stage2')
            for item in item_stage2_name:
                if item != '':
                    item_obj = Items(name=item, stage=2, report_id=report_obj)
                    item_obj.save()

            item_stage3_name = request.POST.getlist('stage3')
            for item in item_stage3_name:
                if item != '':
                    item_obj = Items(name=item, stage=3, report_id=report_obj)
                    item_obj.save()

            if request.POST.get("check_default", False):
                Items.objects.bulk_create([
                    Items(name="Do I know what topic I would like to write?",
                          stage=1,
                          report_id=report_obj),
                    Items(name="Do I have enough information to write?",
                          stage=1,
                          report_id=report_obj),
                    Items(name="Does the report have the title?",
                          stage=2,
                          report_id=report_obj),
                    Items(name="Does the report have the table of content?",
                          stage=2,
                          report_id=report_obj),
                    Items(name="Does the report have the content?",
                          stage=2,
                          report_id=report_obj),
                    Items(name="Does the report have the references?",
                          stage=2,
                          report_id=report_obj),
                    Items(
                        name=
                        "Do I send an email to my lecturer that I complete the report?",
                        stage=3,
                        report_id=report_obj),
                    Items(name="Do I post it on my Facebook?",
                          stage=3,
                          report_id=report_obj),
                ])

            return HttpResponseRedirect(
                reverse('report.views.create_report'))  #redirect after POST
    else:
        form = ReportForm()
    return render(request, 'create_report.html', {})
Exemple #34
0
def run(sub):
    '''
        Run target submission
    '''
    data_dir = '/opt'
    working_dir = '/home'
    try:
        client = docker.from_env()
        running_core_file = 'core.bin'
        running_checker_file = sub.checker + '.bin'
        running_source_file = sub.sourcefile + sub.language.value.running_extension
        upload_result(Report(result=Judge_result.RN,
                             submission=sub.submission))
        s = client.containers.run(
            image=docker_repo_arguments.format(
                repo_lang=sub.language.value.image),
            volumes={
                sub.data_dir: {
                    'bind': data_dir,
                    'mode': 'ro'
                },
            },
            network_disabled=True,
            # https://docs.docker.com/config/containers/resource_constraints/#cpu
            cpu_period=100000,
            cpu_quota=100000,
            working_dir=working_dir,
            tty=True,
            detach=True,
            auto_remove=True,
        )
        with BytesIO() as tarstream:
            with tarfile.TarFile(fileobj=tarstream, mode='w') as tar:
                tar.add(path.join(core_dir, running_core_file),
                        running_core_file,
                        filter=set_mode(0o700))
                tar.add(path.join(checker_dir, running_checker_file),
                        running_checker_file,
                        filter=set_mode(0o700))
                tar.add(path.join(sub.work_dir, running_source_file),
                        running_source_file,
                        filter=set_mode(0o777))
            tarstream.seek(0)
            s.put_archive(working_dir, tarstream)
        for i, x in enumerate(sub.case):
            running_command = running_arguments.format(
                time_limit=sub.time_limit,
                memory_limit=sub.memory_limit * 1024 * 1024,
                output_limit=sub.output_limit * 1024 * 1024,
                stack_limit=sub.stack_limit * 1024 * 1024,
                input_sourcefile=posixpath.join(data_dir, x[0]),
                output_sourcefile='user.out',
                answer_sourcefile=posixpath.join(data_dir, x[1]),
                running_arguments=sub.language.value.running_command.format(
                    sourcefile=sub.sourcefile),
                checker_sourcefile=sub.checker)
            ret = s.exec_run(cmd=running_command)
            logging.info("exit code: %s, output: %s", ret[0],
                         ret[1].decode('utf-8'))
            exit_code, output = int(ret[0]), loads(ret[1].decode('utf-8'))
            output['result'] = get_judge_result(output['result'])
            output['case'] = i + 1
            output['submission'] = sub.submission
            if output['result'] is Judge_result.AC and i != len(sub.case) - 1:
                output['complete'] = False
            else:
Exemple #35
0
    def test_total_profit(self):
        report = Report()
        create_operations(self, self.stock, self.user)

        self.assertEqual("{0:.2f}".format(report.total_profit()), "665.96")
Exemple #36
0
def collect1(request,start_date,end_date,gcid,fcid):
  client = GoogleClient.objects.get(pk=gcid)
  client_id = client.client_id
  client_name = client.client_name
  
  #account = FacebookAccount.objects.get(account_name='Western Health Advantage')
  account = FacebookAccount.objects.get(pk=fcid)
  try:
    fb_acc = SocialAccount.objects.get(user_id = request.user.id,provider='facebook')
    #google_acc = SocialAccount.objects.get(user_id = request.user.id,provider='google')
    fb_tok = SocialToken.objects.get(account=fb_acc)
    #google_tok = SocialToken.objects.get(account=google_acc)
  except:
    return HttpResponse("error connecting Social Accounts")

  #clear the database
  GoogleCampaign.objects.all().delete()
  GoogleAdGroup.objects.all().delete()
  GoogleKeyword.objects.all().delete()

  #FacebookAccount.objects.all().delete()
  Report.objects.all().delete()

  report_model = Report()
  report_model.user = request.user.username
  report_model.date_taken = datetime.now()
  report_model.google_account = client_name

  if(start_date == '1' and end_date == '1'):
    report_model.date_range = "All Time"
    report_model.save()
    account.report = report_model
    account.save()
    all_google_data(request, client_id)
    return render(request, 'report/onetwo.html')
    return redirect("../2")
  elif(start_date == '2' and end_date == '2'):
    report_model.date_range = "Last 30 Days"
    report_model.save()
    account.report = report_model
    account.save()
    month_google_data(request, client_id)
    #"../../../../view"
    return render(request, 'report/onetwo.html') 
    return redirect("../2")
	
  i_y = start_date[0] + start_date[1] + start_date[2] + start_date[3]
  i_m = start_date[5] + start_date[6]
  i_d = start_date[8] + start_date[9]

  f_y = end_date[0] + end_date[1] + end_date[2] + end_date[3]
  f_m = end_date[5] + end_date[6]
  f_d = end_date[8] + end_date[9]


  googstartDate = i_y+i_m+i_d
  googendDate = f_y+f_m+f_d

  fbstartDate = i_y + '-' + i_m + '-' + i_d
  fbendDate = f_y + '-' + f_m + '-' + f_d

  report_model.date_range = fbstartDate + " to " + fbendDate
  report_model.save()
  
  account.report = report_model
  account.save()

  #get the google data
  google_data(request, client_id, googstartDate, googendDate)

  #get the facebook data

  
  return render(request, 'report/onetwo.html')
  return redirect("../2")