Exemple #1
0
def save_solution(assignment, path):
    code = Code()
    solution = Solution()

    if current_user.role.name in ["teacher", "admin"]:
        solution = Solution.query.filter_by(
            assignment_id=assignment.id, is_default=True).first()
        if not solution:
            solution = Solution()
            solution.is_default = True
    else:
        solution = Solution.query.filter_by(
            assignment_id=assignment.id, is_default=False, is_submitted=False, user_id=current_user.id).first()
        if not solution:
            solution = Solution()
            solution.is_default = False

    solution.set_user(current_user)
    solution.set_assignment(assignment)

    # no multiple solutions only one code..
    if solution and solution.code:
        code = solution.code

    code.path = path
    solution.set_code(code)

    db.session.add(assignment)
    db.session.add(code)
    db.session.add(solution)
    db.session.commit()
Exemple #2
0
def code_award(award_id):
    """Display award data and coding form. Process form submission.
    
    Args:
        award_id (int): The ID of the current award.
        
    Returns:
        Redirect to coding form on first visit, or a redirect to
            get_award on form submit.
    """
    award = Award.query.get(award_id)
    abstract = award.abstract
    abstract_paras = abstract.split('\\n')
    form = CodingForm()

    if form.validate_on_submit():
        code = Code(pervasive_data=form.pervasive_data.data,
                    data_science=form.data_science.data,
                    big_data=form.big_data.data,
                    data_synonyms=form.data_synonyms.data,
                    comments=form.comments.data)
        code.award = award
        code.user = current_user
        db.session.commit()
        flash('Coding data submitted.')
        return redirect(url_for('coding.get_award'))

    return render_template(
        'coding.html',
        award=award,
        form=form,
        abstract_paras=abstract_paras,
    )
Exemple #3
0
def create_code():
    '''创建代码'''
    if not g.current_user:
        return BaseResponse.return_unauthorized('请先登录')
    args = request.json
    item = Code.create_or_update(**args)
    return BaseResponse.return_success(item.format())
Exemple #4
0
def savecode():
    form = SaveCodeForm()
    code_recieved = request.form["code"]
    cd = Code(code_recieved)
    print(cd)
    db.session.add(cd)
    db.session.commit()
    return redirect(url_for('index'))
Exemple #5
0
def create_one_code():
    title = request.form.get('title')
    content = request.form.get('content')
    if not (title and content):
        raise BadRequestError("The request body is not present")
    new_code = Code(title=title, body=content)
    db.session.add(new_code)
    db.session.commit()
    return render_template('code.html', code=new_code)
Exemple #6
0
def save_test(assignment, path):
    code = Code()

    if assignment.test:
        test = assignment.test
        if test.code:
            code = test.code
        else:
            code.path = path
    else:
        test = Test()
        assignment.set_test(test)
        code.path = path

    test.set_code(code)
    db.session.add(code)
    db.session.add(test)
    db.session.add(assignment)
    db.session.commit()
Exemple #7
0
def save_template(assignment, path):
    code = Code()

    if assignment.template:
        template = assignment.template
        if template.code:
            code = template.code
        else:
            code.path = path
    else:
        template = Template()
        assignment.set_template(template)
        code.path = path

    template.set_code(code)
    db.session.add(code)
    db.session.add(template)
    db.session.add(assignment)
    db.session.commit()
Exemple #8
0
    def post(self, request, *args, **kwargs):
        data = request.data
        user = data['creator']
        code = eval(data['code'])
        code = Code(title=code['title'], content=code['content'], language=code['language'], creator_id=user)
        try: 
            code.clean_fields()
            code.save()
        except Exception as error:
            return Response(error, status=status.HTTP_400_BAD_REQUEST)

        smells = eval(data['smells'])
        for s in smells:
            smell = CodeSmell(code_id=code.id, user_id=user, line=s['line'], smell=s['smell'])
            try:
                smell.clean_fields()
                smell.save()
            except Exception as error:
                return Response(error, status=status.HTTP_400_BAD_REQUEST)
        return Response(CodeSerializer(code).data, status=status.HTTP_201_CREATED)
Exemple #9
0
def upload_code(message):
    # 接收並儲存 localApp上傳的程式碼 -- 0122/2019
    # {'code':code,'user_id':json_obj['user_id'],'commit_msg':commit_msg,'game_id':obj[3],'file_end':obj[7]}
    # Language.filename_extension
    sid = request.sid
    lan_id = set_language_id(message['file_end'])
    code = Code(body=message['code'], commit_msg=message['commit_msg'],game_id=message['game_id'],compile_language_id=lan_id,user_id=message['user_id'])
    
    try:
        db.session.add(code)
        db.session.commit()
        the_model = message['ml_model'].split(",")
        if len(the_model[-1])>20:
            code.attach_ml=True
            db.session.commit()
            save_file(code.id,the_model[-1])
        emit('upload_ok',"ok, code save in web", room=sid)
    except:
        db.session.rollback()
    finally:
        pass
Exemple #10
0
 def create_code(award, user):
     code = Code(time=datetime.utcnow(),
                 pervasive_data=False,
                 data_science=False,
                 big_data=False,
                 data_synonyms='None',
                 comments='None')
     award.codes.append(code)
     user.codes.append(code)
     db.session.add(award)
     db.session.commit()
     return code
Exemple #11
0
    def post(self, request, *args, **kwargs):
        data = request.data
        user = data['creator']
        code = eval(data['code'])
        code = Code(title=code['title'],
                    content=code['content'],
                    language=code['language'],
                    creator_id=user)
        try:
            code.clean_fields()
            code.save()
        except Exception as error:
            return Response(error, status=status.HTTP_400_BAD_REQUEST)

        smells = eval(data['smells'])
        for s in smells:
            smell = CodeSmell(code_id=code.id,
                              user_id=user,
                              line=s['line'],
                              smell=s['smell'])
            try:
                smell.clean_fields()
                smell.save()
            except Exception as error:
                return Response(error, status=status.HTTP_400_BAD_REQUEST)
        return Response(CodeSerializer(code).data,
                        status=status.HTTP_201_CREATED)
Exemple #12
0
def custom_code():
    form = GetCustomURLForm()
    if form.validate_on_submit():
        u = URL.query.filter_by(url=form.url.data).first()
        if u is None:
            u = URL(url=form.url.data)
            db.session.add(u)
        c = Code(code=form.customcode.data, url=u)
        db.session.add(c)
        db.session.commit()

        return render_template("custom.html.jinja",
                               title="Custom URL",
                               form=form,
                               code=c.code)

    return render_template("custom.html.jinja", title="Custom URL", form=form)
Exemple #13
0
def index():
    form = GetURLForm()
    if form.validate_on_submit():
        u = URL.query.filter_by(url=form.url.data).first()
        if u is None:
            u = URL(url=form.url.data)
            db.session.add(u)
            c = Code(code=code_generator(), url=u)
            db.session.add(c)
            db.session.commit()
        else:
            c = u.codes.order_by(func.length(Code.code)).first()
        return render_template("index.html.jinja",
                               title="Index",
                               form=form,
                               code=c.code)
    return render_template("index.html.jinja", title="Index", form=form)
Exemple #14
0
    def post(self, request, *args, **kwargs):
        """
        Submit a new code snippet with a list of codesmells together.

        Example POST body:
        <code>

            {
                "creator" : 18,
                "code" : "{'title' : 'Third Code Snippet!', 'content' : 'sum = 3+4', 'language' : 'Python'}",
                "smells" : "[{'line': 1, 'smell': 'Vague string'}, {'line': 2, 'smell': 'Bad variable name'}]"
            }

        </code>
        ---
        parameters:
            - name: body
              paramType: body
              description: See example POST body above
        consumes:
            - application/json
        """
        data = request.data
        user = data['creator']
        code = eval(data['code'])
        code = Code(title=code['title'], content=code['content'], language=code['language'], creator_id=user)
        try: 
            code.clean_fields()
            code.save()
        except Exception as error:
            return Response(error, status=status.HTTP_400_BAD_REQUEST)

        smells = eval(data['smells'])
        for s in smells:
            smell = CodeSmell(code_id=code.id, user_id=user, line=s['line'], smell=s['smell'])
            try:
                smell.clean_fields()
                smell.save()
            except Exception as error:
                return Response(error, status=status.HTTP_400_BAD_REQUEST)
        return Response(CodeSerializer(code).data, status=status.HTTP_201_CREATED)
Exemple #15
0
# settings.configure()

from app.models import Code, Score, CodeSmell, Smell
from django.contrib.auth.models import User

import subprocess

subprocess.call(['./manage.py', 'flush'])

User.objects.create_superuser('admin', '*****@*****.**', 'admin')
user = User.objects.create_user('test', '*****@*****.**', 'test')
user.save()

code = Code(title='hello world',
            content='print "hello world"',
            language='Python',
            creator_id=1)
code.save()
code = Code(title='var x', content='x = 0', language='Python', creator_id=1)
code.save()

codesmell = CodeSmell(code_id=1, user_id=1, line=1, smell='too many bugs')
codesmell.save()
codesmell = CodeSmell(code_id=1,
                      user_id=1,
                      line=1,
                      smell='too hard to understand')
codesmell.save()

with open('codesmells.txt') as f:
    for line in f:
Exemple #16
0
def game_view(logId):
    commit_form = CommitCodeForm()  #current_log.id
    comment_form = CommentCodeForm()  #current_log.id
    name = session.get('name', '')
    room = session.get('room', '')
    if request.method == 'GET':

        if name == '' or room == '':
            return redirect(url_for('.index'))

        commit_form.body.data = logId  #current_log.code_id
        commit_form.commit_msg.data = logId  #current_log.commit_msg
        current_code = logId  #current_log.code_id
        page = request.args.get('page', 1, type=int)
        comments = Comment.query.filter_by(code_id=current_code).order_by(
            Comment.timestamp.desc()).paginate(
                page, current_app.config['POSTS_PER_PAGE'], False)

        # next_url = url_for('games.game_view', page=comments.next_num, logId=current_log) \
        # if comments.has_next else None
        # prev_url = url_for('games.game_view',page = comments.prev_num, logId=current_log) \
        # if comments.has_prev else None
        return render_template(
            'games/game_view.html',
            logId=current_log,
            title='Commit Code',
            commit_form=commit_form,
            comment_form=comment_form,
            comments=comments.items,
            name=name,
            room=room)  #next_url=next_url, prev_url=prev_url

    elif commit_form.validate_on_submit():
        code = Code(log_id=logId,
                    body=commit_form.body.data,
                    commit_msg=commit_form.commit_msg.data,
                    game_id=logId,
                    user_id=commit_form.user_id.data)
        db.session.add(code)
        db.session.commit()
        flash('Your code have been saved.')
        current_code = code.id
        ws = create_connection("ws://localhost:6005")
        print("Sending 'Hello, World'...")
        ws.send(
            json.dumps({
                'code': code.body,
                'room': room,
                'logId': logId,
                'userId': commit_form.user_id.data
            }))
        print("Receiving...")
        result = ws.recv()
        print("Received '%s'" % result)
        ws.close()

        #emit to game server

        # return redirect(url_for('games.game_view',logId='01')) #不重新整理頁面

    elif comment_form.validate_on_submit():
        current_code = logId
        comment = Comment(
            code_id=current_code,
            body=comment_form.body.data)  #comment_form.code_id.data
        db.session.add(comment)
        db.session.commit()
        flash('Your code have been saved.')
    return render_template('games/game_view.html',
                           logId=current_log,
                           title='Commit Code',
                           commit_form=commit_form,
                           comment_form=comment_form,
                           name=name,
                           room=room)
Exemple #17
0
def list_code():
    args = BaseRequest.get_args()
    args['per_page'] = 100
    logger.debug(request)
    pagination = Code.query_by(**args)
    return render_template('admin/code_list.html', pagination=pagination)
Exemple #18
0
def push():
    code = json.loads(request.get_data())
    code_obj = Code(code["code"])
    db.session.add(code_obj)
    db.session.commit()
    return "success!"
Exemple #19
0
def code_detail(id):
    '''获取详情'''

    item = Code.query_by_id(id)
    print(item)
    return BaseResponse.return_success(item.format())
Exemple #20
0
		smell.save()

# parse and save code samples from file 'codesamples.txt'
title = ''
content = ''
num_lines = 0
smells = map(lambda x:x.name, Smell.objects.all())
flag = False
with open('codesamples.txt') as f:
	for line in f:
		# '==' followed by a title denotes the start of a new code sample
		if line[:2] == '==':
			# skip saving if on first code sample
			if flag:
				# save previous code sample with admin as creator
				code = Code(title=title, content=content, language='Python', creator=admin)
				code.save()
				used_lines = []
				origsmells = []
				usersmells = []
				# randomly select codesmells to be assigned to code sample by admin
				for i in range(num_lines/2):
					newsmell = (randint(1, num_lines), smells[randint(0, len(smells) - 1)])
					if newsmell[0] in used_lines:
						continue
					used_lines.append(newsmell[0])
					origsmells.append(newsmell)
					codesmell = CodeSmell(code=code, user=admin, line=newsmell[0], smell=newsmell[1])
					codesmell.save()
				# select random number of codesmells for test to answer correctly
				correct = randint(0, len(origsmells))