Ejemplo n.º 1
0
    def create_questions(self):
        q1 = Question({
            "title": "question1",
            "body": "is this the real life?",
            "author_id": self.user1._id,
            "tags": ["queen"]
        })
        q1.save()
        q2 = Question({
            "title": "question2",
            "body": "is this just fantasy?",
            "author_id": self.user1._id,
            "tags": ["queen"]
        })
        q2.save()

        q3 = Question({
            "title": "question3",
            "body": "Scaramouch, scaramouch will you do the fandango?",
            "author_id": self.user2._id,
            "tags": ["queen"]
        })
        q3.save()
        self.run_tasks()

        return q1, q2, q3
Ejemplo n.º 2
0
    def test_mention_event(self):
        user = User({"username": "******", "ext_id": "test"})
        user.save()
        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, @test is mentioned",
            "tags": ["test-tag"],
            "author_id": user._id
        })
        p.save()
        self.run_tasks()
        events = user.get_new_events()
        self.assertEqual(events.count(), 0)

        a = p.create_answer({
            "author_id": other_user._id,
            "body": "this @test mention should create an event"
        })
        a.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 2)  # new comment event and mention event

        found_mention_event = False
        for event in events:
            if isinstance(event, MentionEvent):
                found_mention_event = True
                self.assertEqual(event.author_id, other_user._id)
                self.assertEqual(event.post_id, a._id)
        self.assertTrue(found_mention_event)
Ejemplo n.º 3
0
def create():
    user: User = get_user_from_app_context()
    attrs = request.json
    attrs["author_id"] = user._id
    q = Question(attrs)
    q.save()
    return json_response({"data": q.api_dict(fields=QUESTION_FIELDS)})
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]

        starts = ('How do I Sort a Multidimensional', 'What is Vlad?',
                  'SQL Server')

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(2, 4),
                                    variable_nb_words=True)
            q.text = u"%s %s %s" % (
                choice(starts),
                os.linesep,
                fake.paragraph(nb_sentences=randint(1, 4),
                               variable_nb_sentences=True),
            )
            q.user = choice(users)
            q.rating = randint(0, 1500)
            q.is_published = True
            q.id = i
            q.save()
            self.stdout.write('add question [%d]' % (q.id))
Ejemplo n.º 5
0
    def fill_db(self):
        for i in range(0, 30):
            usr = User(username='******' + str(i),
                       password='******' + str(i),
                       first_name='User')
            usr.save()
            prof = Profile(avatar='avatar.jpeg', user=usr)
            prof.save()
            try:
                tbag = Tag.objects.get(name='Bucket' + str(i % 20))
                tbag.popularity += 1
            except Exception:
                tbag = Tag(name='Bucket' + str(i % 20), popularity=1)
            tbag.save()

            quest = Question(title=str(i) + 'bucket',
                             text='see my bucket, I have a' + str(10000 - i) +
                             ' bucket remains',
                             author=prof,
                             votes=i)
            quest.save()
            quest.liked.add(prof)
            quest.tag.add(tbag)

            for j in range(0, 20):
                ans = Answer(text='Test answer' + str(i),
                             author=prof,
                             question=quest)
                ans.votes = int(((i + j) * 6) % 40)
                ans.save()
                ans.voted.add(prof)
Ejemplo n.º 6
0
def generate_questions(n):
    arr = open('/home/hase/technopark/web/AskZaytsev/scripts/text.txt',
               'r').read().split(' ')
    asize = len(arr)
    print(asize)
    tag_table_cnt = Tag.objects.count()
    print(tag_table_cnt)
    qcount = Profile.objects.count()
    for i in range(0, n):
        print(i)
        word_cnt = random.randint(20, 50)
        text = ''
        title = arr[random.randint(0, asize - 1)] + ' ' + str(i)
        own = Profile.objects.filter(id=random.randint(1, qcount))[0]
        for j in range(0, word_cnt):
            text += arr[random.randint(0, (asize - 1))] + ' '

        q = Question(owner=own, title=title, text=text)
        q.save()
        tag_cnt = random.randint(1, 5)
        print(tag_cnt)
        for j in range(0, tag_cnt):
            print(j)
            tq = Tag.objects.filter(id=random.randint(1, tag_table_cnt))[0]
            print(tq.title)
            q.tags.add(tq)
    print('que')
Ejemplo n.º 7
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = Profile.objects.all()

        starts = (
                u'Help! Nothing happens!',
                u'I tried all, help',
                u'I do not find any solutions on the Internet, save',
                u'Following problem:',
                u'I think that someone of you faced with the question',
                u'Sorry, but I am a novice in this matters',
                u'Hi! Dates burn, need advice',
                )

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(4, 6), variable_nb_words=True)[:40]
            q.text = u"%s %s %s" % (
                    choice(starts),
                    os.linesep,
                    fake.paragraph(nb_sentences=randint(4, 17), variable_nb_sentences=True),
                    )
            q.owner = choice(users)
            q.save()
            tag_cnt = randint(1,5)
            for i in range(0, tag_cnt):
                tq = Tag.objects.filter(id=randint(1, tag_cnt))[0]
                q.tags.add(tq)
            self.stdout.write('added question [%d]' % (q.id))
Ejemplo n.º 8
0
def post_query(request):
    if request.method == "POST":
        query = Question()
        query.question = request.POST.get('question-area')
        query.asked_by = Profile.objects.get(user = request.user)
        query.save()
        messages.success(request,"Your Question was posted!")
    return redirect("askCommunity:home")
Ejemplo n.º 9
0
 def handle(self, *args, **options):
     for i in range(1000):
         question = Question(title=self.text_gen(),
                             full_question=self.text_gen(40) + "?",
                             author=User.objects.get(id=1).userprofile)
         question.save()
         self.stdout.write(
             self.style.SUCCESS('Successfully created question ' +
                                question.title + ' with text ' +
                                question.full_question))
Ejemplo n.º 10
0
 def handle(self, *args, **options):
     for i in range(10):
         question = Question(
             title=self.text_gen(),
             text=self.text_gen(20) + " " + self.text_gen(20) + " " +
             self.text_gen(20) + "?",
             author=User.objects.get(id=random.randint(1, 10)))
         question.save()
         self.stdout.write(
             self.style.SUCCESS('Successfully created question ' +
                                question.title + ' with text ' +
                                question.text))
Ejemplo n.º 11
0
 def _fill_question(self):
     print('FILLING QUESTION MODEL...')
     for ix in range(500):
         temp_question = Question(title='Question{}'.format(ix + 1),
                                  text='QuestionText{}'.format(ix + 1),
                                  author=np.random.choice(
                                      User.objects.all()),
                                  rating=np.random.normal(scale=50),
                                  creation_date=timezone.now(),
                                  edit_date=timezone.now())
         temp_question.save()
     print('ADDED {} QUESTIONS'.format(Question.objects.count()))
Ejemplo n.º 12
0
    def test_tag_new_post_event(self):
        u = User({"username": "******", "ext_id": "test"})
        u.save()
        u.subscribe_to_tag("test-tag")
        u.subscribe_to_tag("test-tag2")
        u.subscribe_to_tag("test-tag3")

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": u._id
        })
        p.save()
        self.run_tasks()

        events = u.get_new_events()
        self.assertEqual(events.count(), 0)

        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": other_user._id
        })
        p.save()
        self.run_tasks()
        events = u.get_new_events()
        self.assertEqual(events.count(), 1)
        event: TagNewQuestionEvent = events[0]

        # only subscribed tags are listed in event
        self.assertCountEqual(event.tags, ["test-tag", "test-tag2"])
        self.assertEqual(event.question_id, p._id)
Ejemplo n.º 13
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]
        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(2, 4),
                                    variable_nb_words=True)
            q.text = fake.paragraph(nb_sentences=randint(4, 17),
                                    variable_nb_sentences=True)
            q.auth = choice(users)
            q.save()
Ejemplo n.º 14
0
def ask(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            q = Question(title=data['title'],
                         text=data['content'],
                         author=request.profile,
                         published=datetime.now())
            q.save()
            q.tags.add(
                *[Tag.objects.get_or_create(name=t)[0] for t in data['tags']])
            return redirect(reverse('question', kwargs={'id': q.id}))
    else:
        form = QuestionForm()
    return render(request, 'ask.html', {'form': form})
Ejemplo n.º 15
0
def generateQuestions(n):
    questionStarts = ["Who", "How", "Why", "When", "Please"]
    questionAction = ["can", "should", "to", "may", "do"]
    questionActor = [
        "I", "my mom", "django", "python", "diablo", "god", "protoss",
        "terran", "zerg"
    ]
    questionStuff = [
        "kill", "compile", "clear", "solve", "install", "banish", "love",
        "hug", "complete", "do", "make", "enjoy", "start", "delete"
    ]
    questionActee = [
        "zerg infestation", "django", "c++ code", "a barell roll", "my mom",
        "my friend", "server", "president", "iPhone", "iPad", "windows",
        "file in linux", "legolas", "world domination", "illuminati", "forum",
        "summit", "eSports", "DOTA2", "idiotism", "protoss arrogance"
    ]
    questionEnd = [
        "?", "don't tell my mom!!1?", "111", "!!!", "!", "??", "???", "!!",
        "??!!?", ""
    ]
    questionText = [
        "I really need help", "HELP ME PLEASE", "It's gonna eat me",
        "I can't live without this", "I am heartbroken"
    ]
    questionTextEnd = [
        "i wanna help ASAP!", "tell me or i'm calling cops!",
        "i hope someone will answer me.", "Anyone?"
    ]
    tags = Tag
    for i in range(n):
        title = random.choice(questionStarts)+" "+random.choice(questionAction)+" "+random.choice(questionActor)+\
        " "+random.choice(questionStuff)+" "+random.choice(questionActee)+" "+random.choice(questionEnd)
        text = random.choice(questionText) + " " + random.choice(
            questionTextEnd)
        author = UserAccount.objects.all().order_by('?')[0]
        q = Question(name=title, content=text, author=author)
        q.save()
        j = random.randint(1, 10)
        for t in Tag.objects.all().order_by('?')[:j]:
            q.tags.add(t)
        q.save()
        if i % 50 == 0:
            print i
Ejemplo n.º 16
0
    def save(self, owner):
        data = self.cleaned_data
        title = data.get('title')
        text = data.get('text')
        tags_list = data.get('tags')
        if tags_list:
            tags_list = [tag.replace(' ', '') for tag in tags_list]
            tags_list = [tag.replace('-', '_') for tag in tags_list]

        q = Question()
        q.title = title
        q.text = text
        q.owner = Profile.objects.get(user_id=owner.id)
        q.save()

        for tag in tags_list:
            tag_obj = Tag.objects.get_or_create(tag)
            q.tags.add(tag_obj)

        return q
Ejemplo n.º 17
0
def setup():
    f = Faker()
    tags = f.words(nb=20)
    for i in tags:
        a = Tag(tag=i)
        a.save()

    for i in range(100):
        tt = f.text(50)
        te = f.text()
        a = Question(title=tt, text=te, author_id=randint(2, 4))
        a.save()
        a.tags.add(randint(1, 20), randint(1, 20), randint(1, 20))

    for i in range(300):
        te = f.text()
        an = Answer(text=te,
                    author_id=randint(2, 4),
                    question_id=randint(1, 100))
        an.save()
Ejemplo n.º 18
0
def newquestion(request):
    if (request.method == "POST"):
        form = NewQuestionForm(request.POST)
        if (form.is_valid):
            if (Question.objects.filter(
                    header=request.POST["header"]).count() == 0):
                uscontent = request.POST["content"]
                usheader = request.POST["header"]
                ususer = User.objects.get(username=request.user.username)
                quest = Question(header=usheader,
                                 content=uscontent,
                                 author=ususer)
                quest.save()
                if ((request.POST.has_key("tag1")) and
                    (Tag.objects.filter(name=request.POST["tag1"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag1"])
                    quest.tag.add(tag)
                return redirect('/user/')
                if ((request.POST.has_key("tag2")) and
                    (Tag.objects.filter(name=request.POST["tag2"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag2"])
                    quest.tag.add(tag)
                return redirect('/user/')
                if ((request.POST.has_key("tag3")) and
                    (Tag.objects.filter(name=request.POST["tag3"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag3"])
                    quest.tag.add(tag)
                return redirect('/user/')
            else:
                newDict = defaultDict
                newDict["status"] = "alreadyEx"
                newDict["curUser"] = request.user
                return render(request, "newquestion.html", newDict)
    else:
        newDict = defaultDict
        newDict["status"] = "newPage"
        newDict["curUser"] = request.user
        return render(request, "newquestion.html", newDict)
Ejemplo n.º 19
0
    def test_post_comment_event(self):
        user = User({"username": "******", "ext_id": "test"})
        user.save()
        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": user._id
        })
        p.save()
        self.run_tasks()
        Event.destroy_all()

        c = p.create_comment({
            "body": "this is a self-comment, should not generate events",
            "author_id": user._id
        })
        c.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 0)

        c = p.create_comment({
            "body": "this is a real comment, should generate an event",
            "author_id": other_user._id
        })
        c.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 1)

        event: PostNewCommentEvent = events[0]
        self.assertEqual(event.post_id, p._id)
        self.assertEqual(event.comment_id, c._id)
        self.assertEqual(event.author_id, other_user._id)
Ejemplo n.º 20
0
    def test_question_new_answer_event(self):
        user = User({"username": "******", "ext_id": "test"})
        user.save()
        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": user._id
        })
        p.save()
        self.run_tasks()
        Event.destroy_all()

        a = p.create_answer({
            "body": "this is a self-answer, should not generate events",
            "author_id": user._id
        })
        a.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 0)

        a = p.create_answer({
            "body": "this is an answer by somebody else",
            "author_id": other_user._id
        })
        a.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 1)

        event: QuestionNewAnswerEvent = events[0]
        self.assertEqual(event.question_id, p._id)
        self.assertEqual(event.answer_id, a._id)
        self.assertEqual(event.author_id, other_user._id)
Ejemplo n.º 21
0
def ask(request):
    form = questionform()
    if request.method == "POST":
        form = questionform(request.POST)
        if form.is_valid():
            q = Question(title=form.cleaned_data['title'],
                         text=form.cleaned_data['text'],
                         author=get_object_or_404(Author, user=request.user),
                         pub_date=timezone.now(),
                         rating=0)
            q.save()
            for tg in form.cleaned_data['tag']:
                Tag.objects.get_or_create(name=tg)
                q.tags.add(Tag.objects.get(name=tg))
                qid = q.id
            return HttpResponseRedirect(
                reverse('ask:question', kwargs={'question_id': qid}))
    return render(
        request, 'ask/question_create.html', {
            'form': form,
            'users': Author.objects.all(),
            'tags': Tag.objects.besters(),
        })
Ejemplo n.º 22
0
 def handle(self, *args, **options):
     User.objects.all().delete()
     user = User.objects.create_user("nuf", "*****@*****.**", "nuf")
     user.save()
     tagmas = [
         'ActionScript', 'Ada', 'Bash', '(Visual) Basic', 'Bourne Shell',
         'Bro', 'C', 'C Shell', 'C#', 'C++', 'Curl', 'Fortran', 'Go',
         'Haskell', 'Java', 'JavaScript', 'Lisp', 'Maple', 'Mathematica',
         'MATLAB', 'MOO', 'Objective-C', 'Pascal', 'Perl', 'PHP', 'Python',
         'Ruby', 'Simulink', 'Verilog', 'VHDL'
     ]
     Question.objects.all().delete()
     Tags.objects.all().delete()
     for i in range(1, 10):
         q = Question(
             author=user,
             text=
             'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat.',
             title='title' + str(i),
             question_id=i,
         )
         q.save()
         t1 = Tags(name=tagmas[(i - 1) * 2])
         t2 = Tags(name=tagmas[(i - 1) * 2 + 1])
         t1.save()
         t2.save()
         t1.question.add(q)
         t2.question.add(q)
         for j in range(1, 10):
             a = Answer(
                 text=
                 'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat. In fringilla tincidunt dolor, at pulvinar lacus cursus nec. Pellentesque ultrices eget odio ac ullamcorper. Duis turpis orci, tempor vel massa id, posuere condimentum purus. Sed rutrum magna non nisi posuere interdum. Vivamus eget diam dictum mi malesuada accumsan.',
                 author=user,
                 question=q,
             )
             a.save()
Ejemplo n.º 23
0
    def handle(self, *args, **options):
        #        User.objects.all().delete()
        #        Tag.objects.all().delete()
        #        Profile.objects.all().delete()
        #        Question.objects.all().delete()
        #        Answer.objects.all().delete()
        #        Like.objects.all().delete()

        try:
            u = User.objects.get(username='******')
        except:
            u = User.objects.create(username='******',
                                    first_name='test',
                                    email='*****@*****.**')
            u.set_password('test')
            u.save()
            p = Profile.objects.create(user_id=u.id, rating=20)

        item_list = []

        for i in range(0, int(options['users'])):
            u = User(username=randomword(9) + str(i),
                     first_name=randomword(3) + str(i),
                     email=randomword(10) + str(i) + '@aithelle.com')
            item_list.append(u)
            if i % 10000 == 0:
                User.objects.bulk_create(item_list)
                item_list = []

        User.objects.bulk_create(item_list)
        um = User.objects.aggregate(Min('id'), Max('id'))

        item_list = []

        for i in range(0, int(options['users'])):
            p = Profile(user_id=um['id__max'] - i,
                        rating=random.randint(0, 20))
            item_list.append(p)
            if i % 10000 == 0:
                Profile.objects.bulk_create(item_list)
                item_list = []
        Profile.objects.bulk_create(item_list)
        print 'Users created\n'

        item_list = []
        for i in range(0, int(options['tags'])):
            t = Tag(text=randomword(5))
            item_list.append(t)
            if i % 10000 == 0:
                Tag.objects.bulk_create(item_list)
                item_list = []
        Tag.objects.bulk_create(item_list)

        tm = Tag.objects.aggregate(Min('id'), Max('id'))

        print 'Tags created\n'

        for i in range(0, int(options['questions'])):
            q = Question(author_id=random.randint(um['id__min'],
                                                  um['id__max']),
                         title=randomword(20),
                         text=randomword(10) + ' ' + randomword(20),
                         rating=random.randint(-100, 100))
            q.save()
            q.tags.add(random.randint(tm['id__min'], tm['id__max']), \
                random.randint(tm['id__min'], tm['id__max']), \
                random.randint(tm['id__min'], tm['id__max']))

        qm = Question.objects.aggregate(Min('id'), Max('id'))

        print 'Questions created\n'

        item_list = []
        for i in range(0, int(options['answers'])):
            a = Answer(author_id=random.randint(um['id__min'], um['id__max']),
                       question_id=random.randint(qm['id__min'],
                                                  qm['id__max']),
                       is_right=random.randint(0, 1),
                       text=randomword(10) + ' ' + randomword(10),
                       rating=random.randint(-100, 100))
            item_list.append(a)
            if i % 10000 == 0:
                Answer.objects.bulk_create(item_list)
                item_list = []

        Answer.objects.bulk_create(item_list)

        am = Answer.objects.aggregate(Min('id'), Max('id'))

        print 'Answers created\n'

        item_list = []
        for i in range(0, int(options['likes'])):
            item_type = random.choice(['question', 'answer'])
            if item_type == 'question':
                item = random.randint(qm['id__min'], qm['id__max'])
            else:
                item = random.randint(am['id__min'], am['id__max'])
            l = Like(author_id=random.randint(um['id__min'], um['id__max']),
                     item_type=item_type,
                     item=item,
                     is_like=random.randint(0, 1))
            item_list.append(l)
            if i % 20000 == 0:
                Like.objects.bulk_create(item_list)
                item_list = []
        Like.objects.bulk_create(item_list)

        print 'Likes created\n'