Esempio n. 1
0
def discussions(request, action=None, id=None):
    """
	Handle discussions.
	"""
    ctx = {
        'title': 'Discussions » PizzaHackers - Doers of NIT Jamshedpur',
        'description': 'PizzaHackers is the doer community of NIT Jamshedpur.'
    }

    if request.method == 'POST':
        fields = ['title', 'description', 'tags']
        data = request.POST.dict()

        if data.has_key('id'):
            discussion = get_object_or_404(Discussion, id=data['id'])
        else:
            discussion = Discussion(hacker=request.user.hacker)

        for field in fields:
            setattr(discussion, field, data[field])

            try:
                discussion.save()

            except Exception, e:
                ctx['error'] = e
                return render(request, 'discussions_edit.html', ctx)

        return redirect(request.META['HTTP_REFERER'])
def reply_post():
    if request.method == 'POST':
        Cno = request.args.get('Cno')
        current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        post_id = request.args.get('post_id')
        temp = Discussion.query.filter_by(Discuss_no=post_id)
        this_post = temp[0]
        current_student, courses = get_info()
        content = request.form.get('content')
        isAnonymousReply = request.form.get('isAnonymousReply')
        if isAnonymousReply == "1":
            new_reply = Discussion(Content=content,
                                   Discuss_date=current_time,
                                   reply_which=post_id)
            new_reply.students.append(get_Anonymous())
            this_post.reply_amount += 1
            db.session.add(new_reply)
            db.session.commit()
            return redirect(
                url_for('course.post_info', Cno=Cno, post_id=post_id))
        else:
            new_reply = Discussion(Content=content,
                                   Discuss_date=current_time,
                                   reply_which=post_id)
            print(current_student[0])
            current_student[0].discussions.append(new_reply)
            this_post.reply_amount += 1
            db.session.add(new_reply)
            db.session.commit()
            return redirect(
                url_for('course.post_info', Cno=Cno, post_id=post_id))
    def test_parse_discussion(self):

        response = u'''{"discussion": {
                 "attrs": {"flags": "c,l,s"},
                 "creation_date": "2013-10-12 14:29:26",
                 "last_activity_date": "2013-10-12 14:29:26",
                 "last_user_access_date": "2013-10-12 14:29:26",
                 "like_count": 1,
                 "liked_it": false,
                 "message": "Topic in the {group:47241470410797}Кока-Кола{group} group",
                 "new_comments_count": 0,
                 "object_id": "62190641299501",
                 "object_type": "GROUP_TOPIC",
                 "owner_uid": "163873406852",
                 "ref_objects": [{"id": "47241470410797",
                                   "type": "GROUP"}],
                 "title": "Кока-Кола  один из спонсоров  Олимпиады в Сочи.  Хотелось бы  видеть фото- и видео-  репортажи с Эстафеты  олимпийского огня !",
                 "total_comments_count": 137},
                 "entities": {"groups": [{"main_photo": {"id": "507539161645",
                                                    "pic128x128": "http://itd0.mycdn.me/getImage?photoId=507539161645&photoType=23&viewToken=a6WsJVtOYvuLUbMSMQVMGg",
                                                    "pic50x50": "http://groupava2.mycdn.me/getImage?photoId=507539161645&photoType=4&viewToken=a6WsJVtOYvuLUbMSMQVMGg",
                                                    "pic640x480": "http://dg54.mycdn.me/getImage?photoId=507539161645&photoType=0&viewToken=a6WsJVtOYvuLUbMSMQVMGg"},
                                    "name": "Кока-Кола",
                                    "uid": "47241470410797"}],
                       "themes": [{"id": "62190641299501",
                                    "title": "Кока-Кола  один из спонсоров  Олимпиады в Сочи.  Хотелось бы  видеть фото- и видео-  репортажи с Эстафеты  олимпийского огня !"}],
                       "users": [{"first_name": "Любовь",
                                   "gender": "female",
                                   "last_name": "Гуревич",
                                   "pic128x128": "http://umd2.mycdn.me/getImage?photoId=432276861828&photoType=6&viewToken=P_qCWfSCiGBGVoiqWQMgsw",
                                   "pic50x50": "http://i508.mycdn.me/getImage?photoId=432276861828&photoType=4&viewToken=P_qCWfSCiGBGVoiqWQMgsw",
                                   "pic640x480": "http://uld9.mycdn.me/getImage?photoId=432276861828&photoType=0&viewToken=P_qCWfSCiGBGVoiqWQMgsw",
                                   "uid": "163873406852"}]}}'''
        instance = Discussion()
        instance.parse(json.loads(response))
        instance.save()

        self.assertEqual(instance.id, 62190641299501)
        self.assertEqual(instance.object_type, 'GROUP_TOPIC')
        self.assertEqual(instance.message, u"Topic in the {group:47241470410797}Кока-Кола{group} group")
        self.assertEqual(instance.title, u"Кока-Кола  один из спонсоров  Олимпиады в Сочи.  Хотелось бы  видеть фото- и видео-  репортажи с Эстафеты  олимпийского огня !")
        self.assertEqual(instance.new_comments_count, 0)
        self.assertEqual(instance.comments_count, 137)
        self.assertEqual(instance.likes_count, 1)
        self.assertEqual(instance.liked_it, False)
        self.assertEqual(instance.author, User.objects.get(pk=163873406852))
        self.assertEqual(instance.owner, Group.objects.get(pk=47241470410797))
        self.assertTrue(isinstance(instance.last_activity_date, datetime))
        self.assertTrue(isinstance(instance.last_user_access_date, datetime))
        self.assertTrue(isinstance(instance.date, datetime))
        self.assertTrue(isinstance(instance.entities, dict))
        self.assertTrue(isinstance(instance.attrs, dict))
Esempio n. 4
0
def create(data):
    post_guid = data.pop('post_guid', None)
    data['post'] = post_guid and get(post_guid)
    obj = Discussion.create_one(**data)
    db.session.commit()

    return obj
def new_post():
    Cno = request.args.get('Cno')
    current_course = Course.query.filter_by(Cno=Cno)
    current_student, courses = get_info()
    if request.method == 'GET':
        return render_template('courseNewThread.html',
                               course=current_course[0],
                               student=current_student[0])
    else:
        Cno = request.args.get('Cno')
        current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        current_student, courses = get_info()
        content = request.form.get('content')
        isAnonymousThread = request.form.get('isAnonymousThread')
        title = request.form.get('title')
        new_post = Discussion(Content=content,
                              Discuss_date=current_time,
                              Discuss_title=title,
                              isNew=1)
        if isAnonymousThread == "1":
            new_post.students.append(get_Anonymous())
        else:
            new_post.students.append(current_student[0])
        current_course[0].discussions.append(new_post)
        db.session.add(new_post)
        db.session.commit()
        flash('发帖成功!', 'success')
        return redirect(url_for('course.discussion', Cno=Cno))
Esempio n. 6
0
def discussion_create(request):
    """
    Page to create a discussion.
    """
    if request.method == "POST":
        course = get_object_or_404(Course, name=request.POST['course_name'])
        name = request.POST['name']
        size = request.POST['size']
        organizer = request.user
        # TODO respect user selected time
        event_datetime = datetime.now()
        # no information for location or attendees yet
        discussion = Discussion(course=course, organizer=organizer, name=name, size=size, datetime=event_datetime)
        discussion.save()
        return HttpResponseRedirect(discussion.id)
    else:  # Get page here
        return render(request, 'class_discuss_site/discussions_create.html', {})
Esempio n. 7
0
def create_mock_discussion(**kwargs):
    fake = Faker()
    discussion = Discussion.create_one(
        body=fake.sentences(),
        author=kwargs.get('author', create_mock_user()),
        enrollment=kwargs.get('enrollment'),
        post=kwargs.get('post'),
    )
    db.session.commit()
    return discussion
Esempio n. 8
0
    async def on_message(self, message):
        if message.author == self.user:
            return
        channel_id = message.channel.id
        channel_name = message.channel.name
        author_id = message.author.id
        author_name = message.author.name
        text = message.content

        #with db as db_session:
        channel, _ = get_or_create(db_session, Channel, name=channel_name)
        author, created = get_or_create(db_session, User, nick=author_name)
        if created:
            author.color = ColorHash(author_name).hex
        if message.content.startswith('!save'):
            print("Discussion:", message.content)
            reg = re.compile(
                r"!save (?P<nick>.+) (?P<lines>\d+) (?P<topic>.+)")
            m = reg.match(message.content)
            if m:
                # Create a discussion
                starter, _ = get_or_create(db_session,
                                           User,
                                           nick=m.group('nick'))
                msg_count = int(m.group('lines'))
                # First message
                am = db_session.query(Message).filter(
                    channel == channel).order_by(
                        Message.when.desc()).limit(msg_count)
                start_time = am[am.count() - 1].when
                disc = Discussion(starter=starter,
                                  channel=channel,
                                  topic=m.group('topic'),
                                  time_start=start_time,
                                  time_end=message.created_at)
                db_session.add(disc)
                db_session.commit()
                reply = "Discussion saved, {}/{}/{}".format(
                    FRONT_BASE, channel_name, disc.id)
                await message.channel.send(reply)
        else:
            msg, _ = get_or_create(db_session,
                                   Message,
                                   author=author,
                                   when=message.created_at,
                                   channel=channel)
            for m in message.mentions:
                print(m)
            # Append attachments
            for a in message.attachments:
                if len(text) > 0:
                    text += "\r\n"
                text += a.url
            msg.text = text
            db_session.commit()
Esempio n. 9
0
def receive_comment(sid, data):
    our_guy = clients[str(sid)]

    comment = Comment(data['commentId'], data['postId'], data['authorId'],
                      data['text'], data['mentions'])
    if comment.postId == "-1":
        print("Discussion - bad id.")
        sio.emit('comment_reply', 'Error. Bad id.')

    response = Discussion.query.filter_by(postId=comment.postId).all()
    if (not response) or (comment.mentions == ['-1']
                          and comment.authorId == our_guy):
        print("Discussion: no discussion. Creating new one.")
        print([
            comment.commentId, comment.mentions, comment.text, comment.authorId
        ])
        new_disc = Base(comment.postId, [[
            comment.commentId, comment.mentions, comment.text, comment.authorId
        ]])
        users_disc = [u for u in new_disc.comments]
        db_disc = Discussion(comment.postId + comment.commentId,
                             comment.postId, comment.commentId,
                             comment.authorId, users_disc,
                             jsonpickle.encode(new_disc.comments),
                             len(new_disc.comments), False, False)

        db.session.add(db_disc)
        db.session.commit()
    else:
        for discussion in response:
            comments = [
                [k] + v
                for (k, v) in jsonpickle.decode(discussion.discussion).items()
            ]
            new_disc = Base(discussion.rootId, comments)
            new_disc.addnew(comment.mentions, comment.text, comment.commentId,
                            comment.authorId)
            users_disc = [u for u in new_disc.comments]
            discussion.users = users_disc
            discussion.discussion = jsonpickle.encode(new_disc.comments)
            discussion.length = len(new_disc.comments)
        db.session.commit()

    export_to_ml()
    send_veil()
Esempio n. 10
0
def create_app(assistant=assistant):
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    app.register_blueprint(index, url_prefix='/')
    app.register_blueprint(teacher, url_prefix='/teacher')
    app.register_blueprint(student, url_prefix='/student')
    app.register_blueprint(course, url_prefix='/course')
    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(assistant, url_prefix='/assistant')
    app.app_context().push()
    bootstrap.init_app(app)
    t1 = Teacher(
        Tno="20201217",
        Tname="金波",
        Tpw="123456",
        Tsex="男",
        Tage=40,
        Ttel="13700000000",
        Taddr="浙江省杭州市西湖区浙大路38号",
        profile="教授,博士生导师。1993年6月毕业于浙江大学流体传动及控制专业,获学士学位。1998年9"
        "月于浙江大学流体传动及控制专业获得博士学位,同年留校任教。作为主要完成人获得国家技术发明奖二等奖一项,省部级科技进步一等奖两项。承担多项国家自然科学基金、863"
        "计划重点项目及浙江省自然科学基金重点项目。承担多项横向科研项目,均圆满地完成了研发任务。共在国内外学术刊物与国际会议上发表论文七十余篇,其中SCI/EI"
        "收录三十余篇。获得国家发明专利、软件著作权二十余项。",
        Tprofessional='计算机学院')
    t2 = Teacher(
        Tno="20201218",
        Tname="苏德矿",
        Tpw="123456",
        Tsex="男",
        Tage=40,
        Ttel="13700000000",
        Taddr="浙江省杭州市西湖区浙大路38号",
        profile=
        "浙江大学理学院数学系教授,浙江省精品课程《微积分》课程负责人、浙江大学公共数学基础课教学指导委员会副主任,浙江大学微积分课程负责人,浙江省高校高等数学教学研究会常务理事兼秘书长,清华大学萧树铁教授主持的前国家教委“面向21世纪教学内容和课程体系改革”研究课题组成员。",
        Tprofessional='数学学院')
    t3 = Teacher(
        Tno="20201219",
        Tname="邵健",
        Tpw="123456",
        Tsex="男",
        Tage=40,
        Ttel="13700000000",
        Taddr="浙江省杭州市西湖区浙大路38号",
        profile=
        "2003年7月从南京大学电子科学与工程系获得理学学士学位;2008年7月从中国科学院声学研究所获得信号与信息处理专业工学博士学位;2008年7"
        "月博士毕业后直接进入浙江大学计算机学院计算机应用学科从事师资博后研究工作,并在2010年9"
        "月留校,浙大工作期间研究方向拓展为视音频智能分析、跨媒体挖掘与检索、分布式计算,作为负责人承担了中国博士后基金面上与特别资助项目、教育部-微软重点实验室联合项目、省优先主题社会发展项目子课题等多个项目,并作为青年骨干参与承担了973项目子课题、NSFC重大研究计划、核高基重大专项子课题等多个项目。",
        Tprofessional='计算机学院')
    s1 = Student(Sno="3180100000",
                 Sname="王小明",
                 Spw="123456",
                 Ssex="男",
                 Sage=20,
                 Stel="13700000000",
                 Saddr="浙江省杭州市西湖区浙大路38号",
                 Class="软工1802",
                 Syear="2018",
                 avatar_path='/student/static/avatar/3180100000.jpg',
                 Sprofessional='软件工程')
    s2 = Student(Sno="3180100001",
                 Sname="韩梅梅",
                 Spw="123456",
                 Ssex="女",
                 Sage=20,
                 Stel="13700000000",
                 Saddr="浙江省杭州市西湖区浙大路38号",
                 Class="计科1802",
                 Syear="2018",
                 Sprofessional='计算机科学与技术')
    s3 = Student(Sno="0000000000", Sname="匿名")
    a1 = Admin(Ano='admin',
               Aname='管理员',
               Atel='13700000000',
               Aaddr='玉泉',
               Aage=30,
               Asex='男',
               Apw='123456')
    Doc1 = Document(Doc_no=1,
                    Doc_name="客户投诉处理.pptx",
                    Doc_path="static/files/100001/chapter1/courseware",
                    Doc_type="pptx",
                    Doc_chapter=7,
                    Doc_description="客户投诉处理相关事务",
                    Doc_authority='可下载')
    Ass1 = Assignment(Assign_no=1,
                      Assign_path='static/files/100001/chapter1',
                      Begin_time='2020-12-31 10:00:20',
                      End_time='2021-1-30 11:30:20',
                      Description='平时作业1,请大家参照作业要求的ppt完成',
                      Assign_chapter=7,
                      Assign_name='C1.3作业',
                      type='docx',
                      percent=15,
                      score=90)
    Ass2 = Assignment(Assign_no=2,
                      Assign_path='static/files/100001/chapter1',
                      Begin_time='2020-12-15 10:00:45',
                      End_time='2020-12-25 11:11:45',
                      Description='平时作业2,请大家参照模板完成',
                      Assign_chapter=8,
                      Assign_name='C1.4作业',
                      type='docx',
                      percent=15)
    Doc1.Doc_preview_address = create_preview_address(Doc1)
    D1 = Discussion(Discuss_no=1,
                    Discuss_date='2020-1-1 12:00:00',
                    Discuss_title='请问大家需求优先级排序有些什么好方法呢?',
                    Content='rt,大家组里都是采用什么办法来排需求优先级呢,我觉得QFD比较完善...',
                    isTop=1,
                    isNew=1,
                    reply_amount=1)
    D2 = Discussion(Discuss_no=2,
                    Discuss_date='2020-1-2 12:00:00',
                    Content='我觉得我们这个项目三层优先级就够了',
                    isTop=0,
                    isNew=0,
                    reply_amount=0,
                    reply_which=1)
    D3 = Discussion(Discuss_no=3,
                    Discuss_date='2020-1-1 13:10:08',
                    Discuss_title='关于期末答辩的安排',
                    Content='各位同学:期末教学总体安排的'
                    '通知及4个附件已发布,请查阅,并遵照执'
                    '行。最后一周的那次上课就调整到16日的'
                    '答辩了',
                    isTop=1,
                    isNew=1,
                    reply_amount=0,
                    poster_identity='教师')
    a1 = Admin(Ano="admin",
               Aname="张小红",
               Apw="123456",
               Asex="女",
               Aaddr="浙江省杭州市西湖区浙大路38号",
               Aage=23,
               Atel="13771011111",
               Aemail='*****@*****.**',
               Abirth='1995-5-20')
    assistant = Assistant(Asno="123",
                          Asname="助教",
                          Aspw="123456",
                          Assex="男",
                          Asage=23,
                          Asaddr="浙江省杭州市西湖区浙大路38号")
    course1 = Course(Cno='100001',
                     Ctype='计算机类',
                     Cname='软件工程管理',
                     Cdate='2020-9-27',
                     Ctime="周三2、3、4节",
                     Is_ongoing="正在进行",
                     Cover_path="/course/static/cover/100001.jpg",
                     introduction="软件工程管理是为了使软件项目能够按照预定的成本、"
                     "进度、质量顺利完成,而对人员(People)、产品("
                     "Product)、过程(Process)和项目(Project)"
                     "进行分析和管理的活动。")
    course2 = Course(Cno='100002',
                     Ctype='自然科学类',
                     Cname='微积分甲',
                     Cdate='2020-9-28',
                     Ctime="周四1、2节",
                     Is_ongoing="已结课",
                     Cover_path="/course/static/cover/100002.jpg",
                     introduction="微积分学,数学中的基础分支。内容主要包括函数、极"
                     "限、微分学、积分学及其应用。函数是微积分研究的基"
                     "本对象,极限是微积分的基本概念,微分和积分是特定过程特定形式的极限。17"
                     "世纪后半叶,英国数学家艾萨克·牛顿和德国数学家G.W"
                     ".莱布尼兹,总结和发展了几百年间前人的工作,建立了"
                     "微积分,但他们的出发点是直观的无穷小量,因此尚缺"
                     "乏严密的理论基础。19世纪A.-L.柯西和K.魏尔斯特"
                     "拉斯把微积分建立在极限理论的基础上;加之19世纪后"
                     "半叶实数理论的建立,又使极限理论有了严格的理论基"
                     "础,从而使微积分的基础和思想方法日臻完善。")
    course1.students = [s1]
    course1.assignments = [Ass1, Ass2]
    course1.discussions = [D1, D2, D3]
    course1.assistants = [assistant]
    D1.students = [s1]
    s2.discussions = [D2]
    course1.documents = [Doc1]
    course1.teachers = [t1, t3]
    course2.students = [s1]
    course2.teachers = [t2]
    t1.discussions = [D3]

    db.drop_all()
    db.create_all()
    db.session.add_all([course2, t2, t1, t3, s1, s3, s2, assistant, a1])
    db.session.commit()
    return app
Esempio n. 11
0
def get(guid):
    obj = Discussion.get_one(guid=guid)
    if not obj:
        raise EntryDoesNotExist

    return obj
 def test_3_delete_discussion(self):
     resp = self.client.delete(f'/discussions/{self.threads[1].guid}')
     assert resp.status_code == 204
     assert Discussion.get_one(guid=self.threads[1].guid) is None