Exemple #1
0
def generateResults(stage = None):
    response = Match.all()
    results = []
    for match in response:
        if match['round'] == int(stage):
            if match['player_a'] == str(-1) or match['player_b'] == str(-1):
                continue
            set_count = 0
            w_a = 0
            w_b = 0
            while set_count < match['sets']:
                set_count += 1
                result = generate_result()
                if result[0] > result[1]:
                    w_a += 1
                else:
                    w_b += 1
                
                r = Result(match_id = match['match_id'],
                           set_id = set_count,
                           result_a = result[0],
                           result_b = result[1])
                results.append(r.serialize())
                db.session.add(r)
                if w_a == 3 or w_b == 3:
                    break
    try:
        db.session.commit()
    except:
        print sys.exc_info()
        return prepare_response(None, "Error while inserting")
    return prepare_response(True)
Exemple #2
0
    def test_add_rov_result(self):
        """
        Multi-test
        """

        # conditions I expect from fixture...
        self.assertTrue(
            Result.objects.ases_have_been_seen_not_doing_rov(self.asn))
        self.assertFalse(Result.objects.ases_have_been_seen_doing_rov(
            self.asn))
        self.assertEqual(Result.objects.results_seen_doing_rov().count(), 0)

        new = Result(json=Result.rov_signal)
        new.json.update({"asn": self.asn, "finished-on-time": True})
        new.save()

        # Test the new object is the only one seen doing ROV
        self.assertTrue(Result.objects.ases_are_new_to_rov(self.asn))

        # Results for this ASN still should report as have seen
        # not doing ROV (previous results)
        self.assertTrue(
            Result.objects.ases_have_been_seen_not_doing_rov(self.asn))

        # ...but also report doing ROV now (new result)
        self.assertTrue(Result.objects.ases_have_been_seen_doing_rov(self.asn))

        # The total amount is 1
        self.assertEqual(Result.objects.results_seen_doing_rov().count(), 1)
Exemple #3
0
def fakeDb():
    dropDatabase()
    words = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','None']
    for i in range(80):
        letters = string.ascii_lowercase
        result_str = random.choice(words)
        seq = Result.objects.count()
        seq = seq + 1
        result =Result(result= result_str, seq= seq)
        result.save()
Exemple #4
0
def save_result(asset, algorithm, value, passed, point_list):
    # find existing results that are active, or were active and are still unacknowledged
    result = Result.query.filter(
        Result.asset_id == asset.id, Result.algorithm_id == algorithm.id,
        (Result.active == True) | (Result.acknowledged == False)).first()
    # note: do not change the acknowledged state, if the result already exists

    # or create a new one if none
    if result is None:
        result = Result(first_timestamp=datetime.datetime.now(),
                        asset_id=asset.id,
                        algorithm_id=algorithm.id,
                        occurances=0,
                        priority=asset.priority)
        result.acknowledged = passed
        db.session.add(result)

    # update with details of the algorithm check
    result.recent_timestamp = datetime.datetime.now()
    result.value = value
    result.passed = passed
    result.active = not passed
    result.occurances += 1
    result.points = point_list
    result.recent = True
    db.session.commit()

    return result
Exemple #5
0
def add():
    form = ResultForm()
    form.case.choices = [(c.id, c.name) for c in Case.query.all()]
    if form.validate_on_submit():

        result = Result()
        form.populate_obj(result)
        result.case = Case.query.filter(Case.id==form.case.data).first_or_404()
        result.author = current_user
        result.save()
        flash("Add Test Result successfully")
        return redirect(url_for("result.view", result_id=result.id))
    return render_template("result/add.html", form=form)
Exemple #6
0
    def start(self):
        print(self.case_list)
        for i in self.case_list:
            c = C(i)
            c.run()
            self.result.append({"case_id": i, "case_result": c.res})
            print("用例:%d 执行完成====================" % i)

        print(self.result)
        new_result = Result(r_time=time.strftime("%Y-%m-%d %H:%M:%S",
                                                 time.localtime()),
                            task_id=self.task_id,
                            r_content=str(self.result))
        new_result.create()
Exemple #7
0
def create_result(json):
    """ Create a result with a prediction from results from rankenstein """
    p1 = Player.query.get(int(json['winnerId']))
    p2 = Player.query.get(int(json['loserId']))
    year, month, day = json['date'].split('-')

    if p1 and p2:
        _, pred_p1_score, pred_p2_score, _ = get_prediction(p1, p2)
        upset = p1.rating < p2.rating

        return Result(id=json['id'],
                      p1_id=json['winnerId'],
                      p2_id=json['loserId'],
                      p1=json['winnerName'],
                      p2=json['loserName'],
                      p1_score=3,
                      p2_score=json['resultDetails']['loserScore'],
                      pred_p1_score=pred_p1_score,
                      pred_p2_score=pred_p2_score,
                      upset=upset,
                      date=dt.date(year=int(year),
                                   month=int(month),
                                   day=int(day)),
                      entry_date=dt.datetime.strptime(json['entryDate'],
                                                      '%Y-%m-%d %H:%M:%S'))

    return None
Exemple #8
0
def getMatchesInCompetition(stage = None, competitionID = None):
    if competitionID:
        response = Match.getByCompetitionID(competitionID)
    else:
        response = Match.all()
        
    all_matches = {}
    aux = []
    if stage is not None:
        aux = [match for match in response if match['round'] == int(stage) or match['round'] == int(stage)+1]
    else:
        aux = response
    
    response = aux
    for match in response:
        r = match['round']
        match['result'] = Result.getByMatchID(match['match_id'])
        if r not in all_matches.keys():
            all_matches[r] = []
#         match['offset'] = 2**(match['round'] - 1) - 1
#         match['height'] = 2**match['round'] - 1
#         match['offset'] = 2**(len(all_matches) - 1) - 1
#         match['height'] = 2**len(all_matches) - 1
        match['offset'] = 2**(len(all_matches) - 1) - 1
        match['height'] = len(all_matches)**2 - len(all_matches)
        all_matches[r].append(match)
    return prepare_response(all_matches)
Exemple #9
0
def exam():

    questions = Question.query.filter_by(text_question=False)
    mcq = MCQ.query.all()
    score = 0

    # if the quiz form on quiz.html has been submitted
    if request.method == "POST":

        # check if the answer submitted are correct for the short answer questions and generate the result accordingly
        for question in questions:
            ques_id = str(question.id)
            request_name = request.form[ques_id]
            if MCQ.query.filter_by(
                    options_content=request_name).first().correct:
                score += 1

        #check if quiz has been done by a user previously if not add a quiz table for the result of the user
        if not bool(Result.query.filter_by(user_id=current_user.id).first()):
            outcome = Result(user_result=current_user)
            db.session.add(outcome)
            db.session.commit()
        current_user.outcome[0].result = score
        db.session.commit()
        return redirect(url_for('feedback'))

    return render_template('exam.html',
                           title='Quiz',
                           questions=questions,
                           mcq=mcq)
Exemple #10
0
def post_test_result():
    if not current_user.is_authenticated:
        return json.dumps({'state': 3}), 200, {
            'ContentType': 'application/json'
        }

    if not request.json or not 'result' in request.json:
        return json.dumps({'error': 'incorrect_params'}), 400, {
            'ContentType': 'application/json'
        }

    result = json.loads(request.json['result'])
    themeId = result['themeId']
    result = result['answers']
    resultClient = Result(datecreate=datetime.datetime.now(),
                          clientid=current_user.id,
                          themeid=themeId)
    db.session.add(resultClient)
    db.session.commit()
    for element in result:
        element['correct'] = Answer.query.filter_by(
            questionid=element['questionId']).filter_by(
                iscorrect=True).first().serialize()["id"]

        resultId = Result.query.filter_by(clientid=current_user.id).all()
        resultId = resultId[len(resultId) - 1].id
        resultAnswer = Resultanswer(resultid=resultId,
                                    answerid=element['answerId'])
        db.session.add(resultAnswer)
    db.session.commit()

    return json.dumps(result), 200, {'ContentType': 'application/json'}
Exemple #11
0
def test_run(name, timestamp, spec_name):
    # ts = datetime.strptime(timestamp, '%b %d %Y %I:%M%p')
    now = datetime.datetime.now()
    ts = now
    tests = [row2dict(x) for x in test_all_show()]

    test_id = None
    status = None
    for x in tests:
        if x["name"] == name:
            test_id = x["id"]
        if x["data"] != "":
            status = "passed"
        else:
            status = "failed"

    if test_id is None:
        raise ValueError

    ms = randint(25, 100)
    res = Result(status=status,
                 timestamp=ts,
                 test_id=test_id,
                 spec_name=spec_name,
                 time=ms)
    db.session.add(res)
    db.session.commit()
Exemple #12
0
def get_party_votes(row, party):
	results = []

	index = 19

	first_vote_total = row[15]
	second_vote_total = row[17]

	while index < len(row) - 1:

		first_vote = 0
		second_vote = 0

		try:
			if row[index]:
				first_vote = row[index]


		except IndexError:
			pass

		try:
			if row[index + 1]:
				second_vote = row[index + 1]

		except IndexError:
			pass

		results.append(Result(first_vote = first_vote, second_vote = second_vote, first_vote_total = first_vote_total, second_vote_total = second_vote_total , party = party[int((index - 19) / 4 )] ))
		index += 4

		#print(results)
	return results
Exemple #13
0
def create(default_data=True, sample_data=False):
    "Creates database tables from sqlalchemy models"
    db.create_all()

    ray = add_user(username="******", password="******", email="*****@*****.**")
    simon = add_user(username="******", password="******", email="*****@*****.**")
    xiang = add_user(username="******", password="******", email="*****@*****.**")

    case = Case(name="TestCase001", author_id=ray.id,
        description = "This is the first test case"
    )
    case.save()

    result = Result(name="TestResult001" , author_id=ray.id,
        link="http://www.baidu.com", case_id=case.id
    )
    result.save()
Exemple #14
0
def data_access():
    if not request.data:  # neu khong co data
        raw_data = 'No Data'
    else:
        raw_data = request.get_data(as_text=True)
    try:
        cleaned_data = data_handle(raw_data)
        seq = Result.objects.count()
        seq = seq + 1
        result = Result(result=cleaned_data, seq = seq)
        result.save()
        socketio.emit('newData')
        return_data = 'Post successfully'
    except Exception as e:
        print(e)
        return_data = str(e)
    return jsonify({'return_data': return_data})
Exemple #15
0
    def test_create_result(self):
        """Tests if new results can be created"""
        r = Result(identifier='alksdjfklt1034', module=1)
        db.session.add(r)
        db.session.commit()

        g = Grade(name='pi1', score=6, weight=1, result=r.id)
        db.session.add(g)
        db.session.commit()
Exemple #16
0
    def submit_test(course_id, test_id):
        test = Test.query.filter_by(id=test_id).first()
        user_id = current_user.id
        questions = test.questions  # Question.query.filter_by(test_id=test_id)
        submissions = test.get_user_submissions(user_id)

        total = 0
        for submission in submissions:
            submission.auto_mark()
            total += submission.score

        result = Result(user_id=user_id, test_id=test_id, score=total)
        db.session.add(result)
        db.session.commit()

        if not any([q.question_type == 3 for q in questions]):
            result.needs_marking = False

        return redirect(url_for('course_view', course_id=course_id))
Exemple #17
0
def generate_result(mission_id):
    mission = Mission.query.filter_by(id=mission_id).first()
    if mission:
        avg_rt, min_rt, max_rt, rt_p50, rt_p75, rt_p95, rt_p99, f_rate, samples, ok, ko, tps = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0
        if mission.loadtool == "gatling":
            Domino.get("report-%s.tar.gz" % mission_id, save=True, unzip=True, savepath="report-gatling")
            stat = json.loads(cache.get("mission_%s_stats" % mission_id))
            api = stat.get("stats")
            samples = api.get("numberOfRequests").get("total")
            ok = api.get("numberOfRequests").get("ok")
            ko = api.get("numberOfRequests").get("ko")
            f_rate = round(float(ko) / ok * 100, 1) if ok else 100
            min_rt = api.get("minResponseTime").get("ok")
            max_rt = api.get("maxResponseTime").get("ok")
            avg_rt = api.get("meanResponseTime").get("ok")
            rt_p50 = api.get("percentiles1").get("ok")
            rt_p75 = api.get("percentiles2").get("ok")
            rt_p95 = api.get("percentiles3").get("ok")
            rt_p99 = api.get("percentiles4").get("ok")
        elif mission.loadtool == "jmeter":
            dashboard = cache.get("dashboard_js-%s" % mission_id)
            graph = cache.get("graph_js-%s" % mission_id)
            with open(os.path.join(Config.REPORT_FOLDER, "report-jmeter", "content", "js", "dashboard-%s.js" % mission_id), "wb") as f:
                f.write(dashboard)
            with open(os.path.join(Config.REPORT_FOLDER, "report-jmeter", "content", "js", "graph-%s.js" % mission_id), "wb") as f:
                f.write(graph)
            for page in ["OverTime", "ResponseTimes", "Throughput"]:
                with open(os.path.join(Config.REPORT_FOLDER, "report-jmeter", "content", "pages", "%s-%s.html" % (page, mission_id)), "wb") as f:
                    f.write(Template(jmeter_report_template_dict.get(page)).render(mission_id=mission_id))
            with open(os.path.join(Config.REPORT_FOLDER, "report-jmeter", "index-%s.html" % mission_id), "wb") as f:
                f.write(Template(jmeter_report_template_dict.get("jmeter_report_index_template")).render(mission_id=mission_id))
            stat = json.loads(dashboard.split("statisticsTable\"), ")[1].split(", function")[0])
            api = stat.get("overall").get("data")
            samples = api[1]
            ko = api[2]
            ok = samples - ko
            f_rate = round(api[3], 1)
            min_rt = api[5]
            max_rt = api[6]
            avg_rt = api[4]
            rt_p50 = 0
            rt_p75 = 0
            rt_p95 = api[8]
            rt_p99 = api[9]
            tps = api[10]

        result = Result(
            mission.project, mission.api_name, mission.concurrent, avg_rt, min_rt, max_rt, rt_p50, rt_p75,
            rt_p95, rt_p99, f_rate, samples, ok, ko, tps, mission_id
        )
        mission.status = 1
        db.session.add(result)
        db.session.add(mission)
        db.session.commit()
        db.session.close()
Exemple #18
0
def draw_lottery():
    json_data = request.get_json()
    num_winners = json_data['num_winners']
    announcement_delay = json_data['announcement_delay']
    cand_names = json_data['candidates']

    created_at = datetime.now(timezone(timedelta(hours=9)))
    created_at = created_at.replace(tzinfo=None)
    published_at = created_at + timedelta(minutes=announcement_delay)
    seed = int(created_at.timestamp() * 1000)
    result = Result(created_at=created_at,
                    published_at=published_at,
                    seed=seed,
                    drawer_ip=request.remote_addr)
    candidates = [Candidate(name=name, result=result) for name in cand_names]

    random.seed(seed)
    cand_indices = list(range(len(cand_names)))
    for _ in range(10):
        random.shuffle(cand_indices)
    winner_indices = random.sample(cand_indices, num_winners)
    winners = [candidates[i] for i in winner_indices]
    for winner in winners:
        winner.is_winner = True

    db.session.add(result)
    db.session.commit()

    winner_dicts = []
    for winner in winners:
        winner_dict = {}
        winner_dict['name'] = winner.name
        unfair_stats_week = calculate_unfair_score(name=winner.name, days=7)
        unfair_stats_month = calculate_unfair_score(name=winner.name, days=30)
        winner_dict['unfair'] = {
            'week': {
                'num_tries': unfair_stats_week[0],
                'num_wins': unfair_stats_week[1],
                'unfair_score': unfair_stats_week[2]
            },
            'month': {
                'num_tries': unfair_stats_month[0],
                'num_wins': unfair_stats_month[1],
                'unfair_score': unfair_stats_month[2]
            }
        }
        winner_dicts.append(winner_dict)

    result_url = url_for('views.show_result', result_id=result.id)
    return jsonify({
        'winners': winner_dicts,
        'result_id': result.id,
        'result_url': result_url
    })
def index():
    ecb = Request('ECB')

    interest_rate_date = fetch_interest_rate(ecb)
    inflation_rate_data = fetch_inflation_rate(ecb)
    exchange_rate_data = fetch_exchange_rate(ecb)

    result = Result(interest_rate_date, inflation_rate_data,
                    exchange_rate_data)

    return render_template('index.html', result=result)
Exemple #20
0
def check_results(matchID = None):
    if matchID is None:
        matches = Match.all()
    else:
        matches = Match.getById(matchID)
         
    for match in matches:
        match['results'] = Result.getByMatchID(match['match_id'])
        calculate_winner(match['player_a'], match['player_b'], match['results'], match['match_id'])
        
    return prepare_response(True)    
Exemple #21
0
def choose_player(player1, player2):
    player1 = Player.query.get(int(player1))
    player2 = Player.query.get(int(player2))

    selection = player1.player_id
    elo_ranking(player1, player2)

    result = Result(player1_id=player1.player_id,
                    player2_id=player2.player_id,
                    selection=player1.player_id)
    db.session.add(result)
    db.session.commit()
    return redirect(url_for('main.kickoff'))
Exemple #22
0
def create(default_data=True, sample_data=False):
    "Creates database tables from sqlalchemy models"
    db.create_all()

    ray = add_user(username="******", password="******", email="*****@*****.**")
    simon = add_user(username="******",
                     password="******",
                     email="*****@*****.**")
    xiang = add_user(username="******",
                     password="******",
                     email="*****@*****.**")

    case = Case(name="TestCase001",
                author_id=ray.id,
                description="This is the first test case")
    case.save()

    result = Result(name="TestResult001",
                    author_id=ray.id,
                    link="http://www.baidu.com",
                    case_id=case.id)
    result.save()
Exemple #23
0
def result(request):
    correct = len(correct_lst)
    wrong = len(wrong_lst)

    if (correct > 5):
        result = "pass"
    else:
        result = "Fail"

    current_user = request.user
    username = current_user.username

    save_ans = Result(username=username,
                      correct_answers=correct,
                      wrong_answers=wrong,
                      status=result)
    save_ans.save()

    return render(request, 'result.html', {
        'correct': correct,
        'wrong': wrong,
        'result': result
    })
Exemple #24
0
def calculate_expression(query):
    try:
        answer = simple_eval(query)

        result = Result(expr=query, answer=answer)
        db.session.add(result)
        db.session.commit()

        emit('result', {'query': query, 'answer': answer}, broadcast=False)
        emit('calculation', {'query': query, 'answer': answer}, broadcast=True)
    except:
        emit('invalid query',
             {'response': 'Invalid query. Please check and try again.'},
             broadcast=False)
 def test_get_test_result(self):
     project = Project(**PROJECT, user=self.user)
     db.session.add(project)
     test = Test(**TEST, project=project, user=self.user)
     db.session.add(test)
     result = Result(test=test,
                     user=self.user,
                     status=Status.SUCCEEDED.value)
     db.session.add(result)
     db.session.commit()
     response = self.client.get('/api/v1/{0}/{1}/{2}'.format(
         PROJECT['name'], TEST['name'], result.run_id),
                                headers=self.headers)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.json['status'], Status.SUCCEEDED.value)
Exemple #26
0
 def insert_into_results(self):
     for match in self.data.matches:
         match_id = Match.query.filter_by(api_id=match['api_id']).first()
         team = Team.query.filter_by(api_id=match['winner_id']).first()
         result_to_add = Result(
             match_id=match_id.id,
             score_t1=match['score_t1'],
             score_t2=match['score_t2'],
             winner_id=0 if team == None else
             team.id,  #Need to handle this before in self.data_requests.py
         )
         try:
             db.session.add(result_to_add)
             db.session.commit()
         except IntegrityError:
             db.session.rollback()
Exemple #27
0
    def dump_links2db(self, res):
        res_dumped = json.dumps(res, default=json_util.default)
        result = Result(domain=self.domain, result=res_dumped)
        db.session.add(result)
        db.session.commit()

        raw_broken_links = redis_store.lrange('broken_links_%s' % (self.real_domain), 0, -1)
        broken_links = [link.decode() for link in raw_broken_links]
        link = Link.query.filter_by(domain=self.domain).first()
        link.broken_links = broken_links
        link.last_check_result_id = result.id
        if broken_links:
            link.status = 'Failed'
        else:
            link.status = 'OK'
        db.session.add(link)
        db.session.commit()
Exemple #28
0
 def set_choice(self, player_name, choice):
     """Add player choice to DB"""
     print 'Set choice for player {} - {}'.format(player_name, choice)
     player = Player.query.filter_by(name=player_name).first()
     if not self.round_id:
         cur_round = Round(round=self.round, game_id=self.game_id)
         db.session.add(cur_round)
         db.session.commit()
         print "ROUND", cur_round
         self.round_id = cur_round.id
     else:
         cur_round = Round.query.get(self.round_id)
     result = Result(round_id=cur_round.id,
                     choice=choice,
                     player_id=player.id)
     db.session.add(result)
     db.session.commit()
     db.session.close()
Exemple #29
0
def draw(request):
    # winsound.PlaySound(path + '/static/app/bigwinBgm.mp3', winsound.SND_ASYNC | winsound.SND_ALIAS)
    result = finders.find('app/PEOPLE_LIST.txt')
    result2 = finders.find('app/PRIZE_LIST.txt')
    searched_locations = finders.searched_locations
    with open(result, 'r', encoding='utf-8') as in_file:
        for line in in_file.readlines():
            line = line.strip('\n\r')
            line = line.strip('\ufeff')
            people.append(line)
    with open(result2, 'r', encoding='utf-8') as in_file:
        for line in in_file.readlines():
            line = line.strip('\n\r')
            line = line.strip('\ufeff')
            prizes.append(line)
    random.shuffle(prizes)
    random.shuffle(people)
    while len(prizes) > 0 and len(people) > 0:
        win_prize = random.choice(prizes)
        w_p.append(win_prize)
        winner = random.choice(people)
        w.append(winner)
        prizes_n[winner] = win_prize
        prizes.remove(win_prize)
        people.remove(winner)
        rest = people

    # 把資料存入DB(model: Result)
    for i in prizes_n:
        r = Result()
        # print(i, prizes_n[i])
        r.prize = i
        r.winner = prizes_n[i]
        r.save()

    # 把資料存入DB(model: Verylucky)
    for j in people:
        v = Verylucky()
        v.luckymen = j
        v.save()

    # 人配獎品
    print(prizes_n)
    # 還沒被抽的(剩下的獎)
    # print(prizes)
    # 還沒被抽的(剩下的人)
    print(rest)
    if not prizes:
        print("第一波抽獎結束!")
        # messages.info(request, "抽獎結束囉")
    return HttpResponseRedirect(reverse('list'))
Exemple #30
0
def csv_result(csvList, task_id):
    # Generating the csv filename and file_path
    filename = task_id + '.csv'
    file_path = os.path.join(app.config['DOWNLOAD_FOLDER'], filename)
    csvwriter = csv.writer(open(file_path, "w"))
    for row in csvList:
        # Keeping track of AsyncResult state
        if (AsyncResult(task_id, app=celery).state == 'PENDING'):
            csvwriter.writerow(row)
        else:
            # Revoke Action on Download Operation
            if (AsyncResult(task_id, app=celery).state == 'REVOKED'):
                # Keeping track of Revoked Tasks
                rev = RevokedTask(task_id=task_id)
                db.session.add(rev)
                db.session.commit()
                # Updating status of Task to REVOKED
                task = Task.query.filter_by(id=task_id).first()
                task.state = 'REVOKED'
                db.session.add(task)
                db.session.commit()
                # Performing Revoke Operation
                revoke(task_id, terminate=True, signal='SIGKILL')
                raise Ignore
            # Pause Action on Download Operation
            task = Task.query.filter_by(id=task_id).first()
            task.state = 'PAUSED'
            db.session.commit()
            return False
    # Writing csv data to Result model
    _file = open(file_path, 'rb')
    result = Result(task_id=task_id,
                    name=filename,
                    path=file_path,
                    data=_file.read())
    db.session.add(result)
    db.session.commit()
    # Success Action on Download Operation
    task = Task.query.filter_by(id=task_id).first()
    task.state = 'SUCCESS'
    task.complete = True
    db.session.commit()
    return True
Exemple #31
0
def test_endpoint():
    data = request.json
    print(data)
    time, request_dict = entrypoint(data["url"], int(data["requests"]),
                                    int(data["concurrency"]))
    results = Results(time, request_dict)
    response = {
        "objects": request_dict,
        "total_time": time,
        "slowest": results.slowest(),
        "fastest": results.fastest(),
        "average": results.average_time(),
        "requests_per_min": results.requests_per_min(),
        "requests_per_sec": results.requests_per_sec()
    }
    obj = Result(url=data["url"], total_time=time, result_all=response)
    db.session.add(obj)
    db.session.commit()
    return jsonify(response)
Exemple #32
0
 def post(self):
     raw_json = request.get_json(force=True)
     try:
         result = Result()
         result.import_data(raw_json)
         result.add(result)
         query = Result.query.get(result.id)
         results = schema.dump(query).data
         return results, 201
     except SQLAlchemyError as e:
         db.session.rollback()
         resp = jsonify({"error": str(e)})
         resp.status_code = 401
         return resp
Exemple #33
0
def add():
    form = ResultForm()
    form.case.choices = [(c.id, c.name) for c in Case.query.all()]
    if form.validate_on_submit():

        result = Result()
        form.populate_obj(result)
        result.case = Case.query.filter(
            Case.id == form.case.data).first_or_404()
        result.author = current_user
        result.save()
        flash("Add Test Result successfully")
        return redirect(url_for("result.view", result_id=result.id))
    return render_template("result/add.html", form=form)
Exemple #34
0
def count_and_save_words(url):
    errors = []

    try:
        r = requests.get(url)

    except:
        errors.append(
            "Unable to get URL. Please make sure it is valid and try again")
        return {"error": errors}

    # text processing
    #  beautifulsoup to clean the text, by removing the HTML tags
    raw = BeautifulSoup(r.text, 'html.parser').get_text()
    nltk.data.path.append('./nltk_data/')  #set the path to find punkt file
    tokens = nltk.word_tokenize(
        raw)  # Tokenize the raw text (break up the text into individual words)
    text = nltk.Text(tokens)  # Turn the tokens into an nltk text object.

    # remove punctuation, count raw words
    nonPunct = re.compile(
        '.*[A-Za-z].*'
    )  # regular expression that matched anything not in the standard alphabet
    raw_words = [w for w in text if nonPunct.match(w)]
    raw_word_count = Counter(raw_words)
    # stop words
    no_stop_words = [w for w in raw_words if w.lower() not in stops]
    no_stop_words_count = Counter(no_stop_words)

    # save the result
    try:
        from app.models import Result
        from app import db
        result = Result(url=url,
                        result_all=raw_word_count,
                        result_no_stop_words=no_stop_words_count)
        db.session.add(result)
        db.session.commit()
        return result.id

    except:
        errors.append("unable to add item to database.")
Exemple #35
0
def run_query(query_type, query_text, \
    from_year, locations, affils, api_key, \
    querying_user):
    """
    Query data is returned in a nested dictionary and assigned to `obj_dicts` which is stored in the db.
    """
    ### Import create_app because this function is run by the worker
    from app import create_app
    from app.models import Result

    app = create_app()
    app.app_context().push()

    if query_type == 'author_papers':
        obj_dicts = query_author_papers(query=query_text,
                                        from_year=from_year,
                                        locations=locations,
                                        n_authors=25,
                                        affils=affils,
                                        api_key=api_key,
                                        api_out=False)
    elif query_type == 'affil_papers':
        obj_dicts = query_affil_papers(query=query_text,
                                       from_year=from_year,
                                       locations=locations,
                                       n_authors=25,
                                       affils=affils,
                                       api_key=api_key,
                                       api_out=False)

    result = Result(query_type=query_type,
                    query_text=query_text,
                    query_from=from_year,
                    query_affiliations=affils,
                    query_locations=locations,
                    user_querying=querying_user,
                    length_of_results=len(obj_dicts.keys()),
                    result_all=obj_dicts)
    db.session.add(result)
    db.session.commit()
    return result.id
Exemple #36
0
def send_result():
    result = request.get_json()

    try:
        r = Result()
        r.tamanho_atual = result["tamanho_atual"]
        r.tempo_importacao = result["tempo_importacao"]
        r.total_tabelas = result["total_tabelas"]
        r.ultima_tabela = result["ultima_tabela"]
        r.data_coleta = datetime.strptime(result["data_coleta"], "%d/%m/%Y %H:%M:%S")
        db.session.add(r)
        db.session.commit()
    except:
        return jsonify(
            {'detail': u"Argumentos inválidos"}
        ), status.HTTP_400_BAD_REQUEST

    return jsonify({}), status.HTTP_201_CREATED
Exemple #37
0
 def test_all(self):
     
     all_results = Result.all()
     self.assertEqual(len(all_results), 10)