Example #1
0
def new_assignment():
    days_given = require_arguments('days_given')
    try:
        days_given = int(days_given)
    except ValueError:
        raise InvalidArgument('days given must be an integar')
    students = request.json.get('student')
    if students is None:
        raise InvalidArgument('students required')
    token = request.json.get('token')
    if not token:
        raise InvalidArgument('token required')
    problems = request.json.get('problems')
    if not problems:
        raise InvalidArgument('problems required')

    user = auth_by_token(token,min_privilege='teacher')
    for student in students:
        if User.objects(id=students).count() == 0:
            raise InvalidArgument('user '+student+' does not exist')
        scored_problems = []
        for problem in problems:
            problem_id = problem.get('id')
            point = problem.get('point')
            scored_problems.append(ScoredProblem(problem=Problem.objects(id=problem_id).first(),point=point))
        date = datetime.datetime.now()
        assignment = Assignment(owner=user,scored_problems=scored_problems,students=students,assign_time=date,days_given=days_given).save()
        return success({'id':str(assignment.id)})        
Example #2
0
def auth_by_token(token, *, min_privilege='student'):
    token = Token.objects(token=token).first()
    if not token:
        raise InvalidArgument('token required')
    if datetime.datetime.now() > token.expire:
        raise InvalidArgument('token required')
    if min_privilege == 'admin' and token.user.type_ not in ['teacher']:
        raise InvalidArgument('insufficient permission')
    return token.user
Example #3
0
def change_username():
    [token, new_username] = require_arguments('token', 'username')
    user = auth_by_token(token)
    if ' ' in new_username:
        raise InvalidArgument('invalid username')
    if new_username == user.username:
        raise InvalidArgument("username hasn't been changed")
    if User.objects(username=new_username).count() > 0:
        raise InvalidArgument('duplicated username')
    user.username = new_username
    user.save()
    return {'status': 'success'}
Example #4
0
def change_phone_number():
    [token, new_phone_number] = require_arguments('token', 'new_phone_number')
    user = auth_by_token(token)
    if ' ' in new_phone_number:
        raise InvalidArgument('invalid phonename')
    if new_phone_number == user.phone_number:
        raise InvalidArgument("phone number hasn't been changed")
    if User.objects(phone_number=new_phone_number).count() > 0:
        raise InvalidArgument('duplicated phone number')
    user.phone_number = new_phone_number
    user.save()
    return {'status': 'success'}
Example #5
0
def send_password():
    [email_address, phone_number] = require_arguments('email_address',
                                                      'phone_number')
    user = User.objects(email_address=email_address).first()
    if user.phone_number != phone_number:
        raise InvalidArgument('invalid email address or phone number')
    return user.password
Example #6
0
def require_arguments(*args):
    ret = []
    for arg in args:
        if arg not in request.form:
            raise InvalidArgument(arg + ' required')
        ret.append(request.form[arg])
    return ret
Example #7
0
def note_edit():
    [token,note_id,note_content] = require_arguments('token','note_id','note_content')
    #这个错怎么处理
    user = auth_by_token(token)
    if not user:
        raise InvalidArgument('token required')
    other_note = note_by_id(note_id)
    other_note.note_content = note_content
    other_note.save()
    # if 'title' in request.form:
    #     title = request.form['title']
    #     other_note.title=title
    #     other_note.save()
    # if 'text' in request.form:
    #     text = request.form['text']
    #     note_content.text=text
    #     note_content.save()
    #     other_note.note_content=note_content
    #     other_note.save()
    # if 'image_url' in request.form:
    #     image_url = request.form['image_url']
    #     note_content.image_url=image_url
    #     note_content.save()
    #     other_note.note_content=note_content
    #     other_note.save()
    return {'status':'success'}
Example #8
0
def note_delete():
    [token,note_id] = require_arguments('token','note_id')
    #需弹窗确认是否删除
    user = auth_by_token(token)
    if not user:
        raise InvalidArgument('token required')
    Other_note.objects(id=note_id).delete()
    return {'status':'success'}
Example #9
0
def change_class_name():
    [token, new_class_name] = require_arguments('token', 'new_class_name')
    user = auth_by_token(token)
    if new_class_name == user.class_name:
        raise InvalidArgument("class_name hasn't been changed")
    user.class_name = new_class_name
    user.save()
    return {'status': 'success'}
Example #10
0
def note_by_id(id):
    other_note = Other_note.objects(id=id).first()
    if not Other_note:
        raise InvalidArgument('id does not exist')    
    # return success({'owner':assignment.owner,
    # 'scored problems':assignment.scored_problems,
    # 'students':assignment.students
    # })
    return other_note
Example #11
0
def answer_by_id(id):
    #id = require_arguments('id')
    answer = AssignmentAnswer.objects(id=id).first()
    if not answer:
        raise InvalidArgument('id does not exist')    
    # return success({'owner':assignment.owner,
    # 'scored problems':assignment.scored_problems,
    # 'students':assignment.students
    # })
    return answer
Example #12
0
def assignment_by_id():
    id = require_arguments('id')
    assignment = Assignment.objects(id=id).first()
    if not assignment:
        raise InvalidArgument('id does not exist')    
    # return success({'owner':assignment.owner,
    # 'scored problems':assignment.scored_problems,
    # 'students':assignment.students
    # })
    return success(assignment)
Example #13
0
def problem_add():

    [token,problem,key,type_,difficulty] = require_arguments('token','problem','key','type_','difficulty')
    user = auth_by_token(token,min_privilege='teacher')
    try:
        difficulty = int(difficulty)
    except ValueError:
        raise InvalidArgument('difficulty must be an integar')
    problem = Problem(problem=problem,key=key,type_=type_,owner=user,difficulty=difficulty).save()

    return success({'id':str(problem.id)})
Example #14
0
def user_login():
    [username, password] = require_arguments('username', 'password')
    user = auth_by_password(username, password)
    if not user:
        raise InvalidArgument('invalid username or password')
    id = str(uuid.uuid4()).replace('-', '')
    token = Token(user=user,
                  token=id,
                  expire=datetime.datetime.now() + datetime.timedelta(days=30))
    token.save()
    return success({'token': id, 'type': user.type_})
Example #15
0
def process_by_id(id):
    try:
        process = Process.objects.get(id=id)
    except:
        process = None
        # process_name = '学习'
        # process_brief_intro = '复习所学内容'
        # Process(owner=user,process_name=process_name,process_brief_intro=process_brief_intro).save()
    if not process:
        raise InvalidArgument('id does not exist')
    return process
Example #16
0
def change_password():
    [token, email_address, phone_number, old_password,
     new_password] = require_arguments('token', 'email_address',
                                       'phone_number', 'old_password',
                                       'new_password')
    user = auth_by_token(token)

    # 前端来做
    # if 'confirm_password' in request.form:
    #     confirm_password = request.form['confirm_password']
    # else:
    #     return {'status':'failed','data':'confirm password required'}
    # if new_password != confirm_password:
    #     return {'status':'failed','data':'the confirm password differs from the former one'}use
    if email_address != user.email_address:
        raise InvalidArgument('email_address is wrong')
    if phone_number != user.phone_number:
        raise InvalidArgument('phone number is wrong')
    if old_password == new_password:
        raise InvalidArgument('the new password is the same as the old')
    if len(new_password) < 8 or len(new_password) > 16:
        raise InvalidArgument(
            'the length of password should be between 8 and 16')
    if ' ' in new_password:
        raise InvalidArgument('illegal character in password')
    if old_password != user.password:
        raise InvalidArgument('invalid password')
    user.password = new_password
    user.save()
    return success(user.password)  #这个要改,不能直接传密码
Example #17
0
def user_register():
    '''
    route:/user_register
    method:POST
    fields:username,password,type
    usernam不能与已知用户重复
    password不能有空格,长度介于8到16之间
    type只可为teacher,student,admin之一
    '''
    [username, password, type_] = require_arguments('username', 'password',
                                                    'type')
    if ' ' in username:
        raise InvalidArgument('invalid username')
    if type_ not in ['student', 'teacher']:
        raise InvalidArgument('user type invalid')
    if User.objects(username=username).count() > 0:
        raise InvalidArgument('duplicated username')
    if len(password) > 16 or len(password) < 8:
        raise InvalidArgument('password length should be between 8 and 16')
    if ' ' in password:
        raise InvalidArgument('Invalid password')
    User(username=username, password=password, type_=type_).save()
    return {'status': 'success'}
Example #18
0
def fill_information():
    [
        token, real_name, student_id, email_address, phone_number, school_name,
        grade_name, class_name
    ] = require_arguments('token', 'real_name', 'student_id', 'email_address',
                          'phone_number', 'school_name', 'grade_name',
                          'class_name')
    user = auth_by_token(token)
    if 'qq_number' in request.form:
        qq_number = request.form['qq_number']
        if qq_number != None:
            if ' ' in qq_number:
                raise InvalidArgument('invalid qq number')
            if len(qq_number) < 5 or len(qq_number) > 10:
                raise InvalidArgument('invalid qq number')
            user.qq_number = qq_number
    if len(phone_number) != 11:
        raise InvalidArgument('invalid phone number')
    if '@' not in email_address:
        raise InvalidArgument('invalid email address')

    if User.objects(email_address=email_address).count() > 0:
        if email_address == user.email_address:
            pass
        else:
            raise InvalidArgument('duplicated email address')

    user.real_name = real_name
    user.phone_number = phone_number
    user.email_address = email_address
    user.student_id = student_id
    user.school_name = school_name
    user.grade_name = grade_name
    user.class_name = class_name
    user.save()
    return {'status': 'success'}
Example #19
0
def user_full_info():
    [token] = require_arguments("token")
    user = auth_by_token(token)
    if not user:
        raise InvalidArgument("token invalid")
    # if user.real_name==None and user.student_id==None:
    #     if user.phone_number == None and user.email_address == None:
    #         if user.qq_number == None and user.school_name == None:
    #             if user.grade_name == None and user.class_name == None:
    #                 return None
    return success({
        'real_name': user.real_name,
        'student_id': user.student_id,
        'phone_number': user.phone_number,
        'email_address': user.email_address,
        'qq_number': user.qq_number,
        'school_name': user.school_name,
        'grade_name': user.grade_name,
        'class_name': user.class_name
    })
Example #20
0
def auto_check_answer():
    [token,answer_id]=require_arguments('token','answer_id')
    user = auth_by_token(token)
    answers = answer_by_id(answer_id)
    assignment = answers.assignment
    problems = answers.assignment.scored_problems

    submit_time = datetime.datetime.now()
    t = assignment.days_given
    deadline = assignment.assign_time + datetime.timedelta(days=t)
    if submit_time > deadline:
        raise InvalidArgument('you have missed the deadline')
    for index,answer in enumerate(answers):
        problem = problems[index]
        if answer == problem.problem.key:
            answer.points_get.append(problems[index].point)
        else:
            fault_answer = FaultAnswer(answer=answer,problems=problem).save()
            fault = Fault(owner=user,fault_answer=fault_answer)
            fault.save()
    answer.save()
    return success(answer)
Example #21
0
def stock_select(pool, targets, date, score, benchmark=None):
    """
    选股
    :param pool: pd.Series, index 为order_book_id, value 为 0/1/2,其中0表示最高优先级股票池,1表示次优先选择股票池,2表示备选股票池
    :param targets: [TotalStockCountTarget | IndustryStockCountTarget]
    :param date: 选股日期
    :param score: RiskScore | RiskReturnScore | TargetStyleScore
    :param benchmark: 基准
    :return: [order_book_id]
    """
    selected = []
    pool_0 = pool[pool == 0].index.tolist()
    pool_1 = pool[pool == 1].index.tolist()
    pool_2 = pool[pool == 2].index.tolist()

    date = to_date(date)

    if benchmark is not None:
        if isinstance(benchmark, str):
            benchmark = IndexBenchmark(benchmark)
        if not isinstance(benchmark, OptimizeBenchmark):
            raise InvalidArgument(
                '无效的benchmark:{};对于指数,可以直接传入对应的order_book_id;'
                '对于自定义基准,请传入一个 OptimizeBenchmark 的对象'.format(benchmark))

    helper = OptimizeHelper(pool_0 + pool_1 + pool_2, date, benchmark,
                            CovModel.FACTOR_MODEL_DAILY)
    if not isinstance(score, pd.Series):
        score = score.get_score(helper)

    pools = [
        score[pool_0].sort_values(ascending=False),
        score[pool_1].sort_values(ascending=False),
        score[pool_2].sort_values(ascending=False)
    ]

    industry_stock_count_targets = [
        t for t in targets if isinstance(t, IndustryStockCountTarget)
    ]

    for t in industry_stock_count_targets:
        mapping = helper.get_industry_mapping(t.classification)
        candidates = set(mapping[mapping == t.industry].index)

        need = t.count
        for pool in pools:
            pool_candidates = [s for s in pool.index if s in candidates]
            selected += pool_candidates[:need]
            need -= len(pool_candidates)
            for s in pool_candidates:
                del pool[s]
            if need <= 0:
                break

        if need > 0:
            warnings.warn('股票池中行业 {} 股票数目不足'.format(t.industry),
                          category=OptimizerWarning)

    total_stock_count_target = [
        t for t in targets if isinstance(t, TotalStockCountTarget)
    ]
    if len(total_stock_count_target) > 1:
        raise ValueError('TotalStockCountTarget 仅允许一个')

    if total_stock_count_target:
        t = total_stock_count_target[0]
        if len(selected) > t.count:
            raise ValueError('根据行业选股要求选择股票后,股票数目超过了总股票数目')
        need = t.count - len(selected)
        for pool in pools:
            selected += pool.index.tolist()[:need]
            need -= len(pool.index)
            if need <= 0:
                break

        if t.count > len(selected):
            raise ValueError('候选股票池股票数不够')

    return selected
Example #22
0
def event_by_id(id):
    event = Event.objects(id=id).first()
    if not event:
        raise InvalidArgument('id does not exist')
    return event
Example #23
0
def user_info():
    [token] = require_arguments("token")
    user = auth_by_token(token)
    if not user:
        raise InvalidArgument("token invalid")
    return success({"username": user.username, "type": user.type})