Beispiel #1
0
def article(article_slug):
    article = Article.query.filter(Article.slug == article_slug).first()
    if not article.published:
        abort(403)

    article.views += 1

    db.session.add(article)
    db.session.commit()

    from sqlalchemy.sql.expression import func
    related_articles = Article.query.search(article.keywords[0]).\
        filter(Article.id != article.id).order_by(func.random()).limit(3)

    _base_query = Article.query.public()

    # Tags
    tags = Tag.query.order_by(Tag.views.desc()).all()

    # recommended articles top 5
    recommended_articles = _base_query.filter_by(recommended=True).limit(9)
    popular_articles = _base_query.\
        order_by(Article.views.desc()).limit(9)

    random_articles = _base_query.order_by(func.random()).limit(9)

    return render_template('article.html',
                           article=article,
                           tags=tags,
                           related_articles=related_articles,
                           recommended_articles=recommended_articles,
                           popular_articles=popular_articles,
                           random_articles=random_articles)
Beispiel #2
0
def profile_product_redirect(attr_type):
    '''fetch random product'''
    if attr_type == "hs":
        p = getattr(attr_models, attr_type.capitalize()).query.order_by(func.random()).first_or_404()
    else:
        p = getattr(attr_models, attr_type.capitalize()).query.order_by(func.random()).first_or_404()

    return redirect(url_for(".profile_product", attr_type=attr_type, attr_id=p.get_display_id()))
Beispiel #3
0
def motive():
	prefix = Prefix.query.order_by( func.random() ).first()

	if 'GET' == request.method :
		m = Madlib.query.order_by( func.random() ).first()
	else:
		m = Madlib.query.get( request.form['madlib_id'] )

	sentence = m.text

	regex = re.compile( r"\{\{(.+?)\}\}" )

	if 'GET' == request.method :
		# fill in with random words from the dictionary
		sentence = regex.sub( fill_in_word, sentence )

	else:
		# for each match, replace with next word in submitted form
		tags = regex.findall( sentence )

		i=0
		for tag in tags:
			word = request.form["madlib-blank-" + str( i )].strip()
			i += 1

			# entering blanks means we pick a random word
			if '' == word:
				t = Tag.query.filter( Tag.text == tag ).first()
				if None is t or [] == t.words:
					word = tag
				word = choice( t.words ).text

			else:
				# add new words to the dictionary

				# force to lowercase unless it's a proper noun
				if tag not in ['person', 'place'] :
					word = word.lower()

				w = Word.query.filter( Word.text == word ).first()

				if None is w:
					w = Word( word, [ tag ] )
					db_session.add( w )

				else:
					# add these tags if they don't exist
					t = Tag.query.filter( Tag.text == tag ).first()
					w.tags.append( t )

			sentence = sentence.replace( "{{" + tag + "}}", word, 1 )

		db_session.commit()

		# TODO save generated sentence for posterity - maybe only on up-vote?

	return render_template( 'motive.html', prefix=prefix, motivation=sentence )
Beispiel #4
0
 def r(self):
     if self.url.startswith('sqlite'):
         return func.random()
     if self.url.startswith('mysql'):
         return func.rand()
     if self.url.startswith('postgresql'):
         return func.random()
     if self.url.startswith('oracle'):
         return 'dbms_random.value'
     raise NotImplementedError()
Beispiel #5
0
def feed_discover():
    off = request.args.get("start_index")
    if off:
        entries = db.session.query(db.Books).order_by(func.random()).offset(off).limit(config.NEWEST_BOOKS)
    else:
        entries = db.session.query(db.Books).order_by(func.random()).limit(config.NEWEST_BOOKS)
        off = 0
    xml = render_template('feed.xml', entries=entries, next_url="/feed/discover?start_index=%d" % (int(config.NEWEST_BOOKS) + int(off)))
    response = make_response(xml)
    response.headers["Content-Type"] = "application/xml"
    return response
Beispiel #6
0
def recommend_repos_for_user(username, limit=10):
    """
    1. store user stars to db if not there yet
    2. find 10 most similar users in db
    3. get 10 most starred repo of these users (not starred yet)

    :param username:
    :return: [repo object, ...]
    """

    user = User.query.filter_by(username=username).first()
    if not user:
        store_user_data(username)

    user_repo_map = dict()
    repos_enc = set()

    user_list = list(User.query.order_by(func.random()).limit(100).options(joinedload('repos')))
    for u in user_list + [user]:
        user_repo_map[u.id] = set()
        for repo in u.repos:
            user_repo_map[u.id].add(repo.id)
            repos_enc.add(repo.id)

    repos_enc = list(repos_enc)
    user_repo_enc = {
        u.id: [bool(repo_id in user_repo_map[u.id]) for repo_id in repos_enc] for u in user_list + [user]
    }

    user_scores = []
    for u in user_list:
        user_scores.append((u.id, jscore(user_repo_enc[u.id], user_repo_enc[user.id])))

    user_scores.sort(key=lambda item: item[1], reverse=True)

    repo_count_map = defaultdict()
    for uid, score in user_scores[1:30]:
        for repo in user_repo_map[uid]:
            if repo in user_repo_map[user.id]:
                continue

            if repo not in repo_count_map:
                repo_count_map[repo] = 0
            repo_count_map[repo] += 1

    repo_id_list = [repo_id for repo_id, _ in sorted(
        repo_count_map.items(), key=lambda item: item[1], reverse=True
    )][:limit]

    return Repo.query.filter(Repo.id.in_(repo_id_list)).order_by(func.random()).values('name', 'url')
Beispiel #7
0
def category(slug, page=1):
    category = Category.query.filter_by(slug=slug).first()
    _base_query = Article.query.public().filter_by(category=category)

    all_articles = _base_query.order_by(Article.created_at.desc()).\
        paginate(page, Article.PER_PAGE, False).items

    # Tags
    tags = Tag.query.order_by(Tag.views.desc()).all()

    # recommended articles top 5
    recommended_articles = _base_query.filter_by(recommended=True).limit(5)
    popular_articles = _base_query.\
        order_by(Article.views.desc()).limit(5)

    from sqlalchemy.sql.expression import func
    random_articles = _base_query.order_by(func.random()).limit(5)

    return render_template('index.html',
                           page=page,
                           tags=tags,
                           category=category,
                           all_articles=all_articles,
                           recommended_articles=recommended_articles,
                           popular_articles=popular_articles,
                           random_articles=random_articles)
def return_radom_question_set(n):
    """ It goes through the question bank
    and selects n random Questions along with it's answer list
    it also randomizes the answer choice sequence
    """
    #select.order_by(func.random())
    questions= Questions.query.order_by(func.random()).first()
    #print (questions.question)
    #print (questions)
    questions_answers = Questions.query.order_by(func.random()).join(Answers).limit(3)
#    questions_answers = Questions.query.rder_by(func.random()).join(Answers).limit(10)

    for k in questions_answers :
        print (k.question)
    #print (questions_answers.column_descriptions)
    q_a= Questions.query.join(Answers)
Beispiel #9
0
def schedule_yuyue(s):
    user_list = s.query(User).filter(
        User.flag == True,
        User.yuyue_cnt < User.req_yuyue_cnt,  # 已经预约量小于预约总数
        User.yuyue_start_time < time.time(),  # 开始时间到了吗
        User.last_yuyue_time + User.yuyue_interval + random.randint(157, 678) < time.time(),  # 评价时间间隔,并且加上随机性
        User.yuyue_per_day_cnt < User.rdm_yuyue_per_day_cnt,  # 每天预约量小于客户每天规定的预约量
        # User.yuyue_per_day_cnt < User.req_yuyue_cnt / User.req_day_cnt  # 今天预约量是否够了,不够的才继续
    ).order_by(func.random()).all()
    len_user = len(user_list)
    if not len_user:
        print u'当前没有符合条件的预约yy'
        return True
    print u'共有预约人数:', len_user
    idx_cnt = 0
    for user in user_list:
        if len(user.urls) == 0:
            print user.id, u'没有urls'
            continue
        print
        #global_adsl.reconnect()  # adsl重连
        # time.sleep(3)
        idx_cnt += 1
        print datetime.now(), '约第', idx_cnt, '/', len_user, '个人:', user.shop_id, user.id, user.qq, user.wangwang, user.company, ',原来约:', user.original_yuyue_cnt, '已经约:', user.yuyue_cnt, ',今天约了:', user.yuyue_per_day_cnt, ',今天还要约:', user.rdm_yuyue_per_day_cnt - user.yuyue_per_day_cnt
        # random_url = random.choice([url for url in user.urls if url.flag == True])
        random_url = random.choice(user.urls)
        try:
            m_yuyue(s, user, random_url.href)
        except Exception, e:
            print e
            print traceback.format_exc()
            continue
        # time.sleep(random.randint(1, 5))
        pass
Beispiel #10
0
 def getRandomFeatureId(self, bodId):
     models = models_from_bodid(bodId)
     with self.getSession() as session:
         t = session.query(models[0]).limit(500).subquery('t')
         query = session.query(t).order_by(func.random()).limit(1)
         reslt = query.one()
     return reslt[0]
Beispiel #11
0
def classifier():
    user = current_user
    exp = request.args.get('experiment', 'creativity')
    eclass = experiment_classes[exp]
    pattern = experiment_classes[exp]['pattern']
    classes = experiment_classes[exp]['labels']
    if request.method == 'POST':
        if 'class' in request.form:
            labels = request.form.getlist('class')
            value = 1
            img_id = int(request.form['img_id'])
            for label in labels:
                db.session.add(Classification(img_id=img_id, user_id=user.id, label=label, value=value))
            db.session.commit()

    q_existing = db.session.query(Classification, Image).filter(Classification.user_id==user.id).filter(Image.id==Classification.img_id)
    q_existing = q_existing.subquery()
    q_existing = aliased(Image, q_existing)
    q_existing = Image.query.join(q_existing)
    q_all = Image.query.filter(Image.url.like(pattern))
    q = q_all.except_(q_existing)
    q = q.order_by(func.random())
    nb = q.count()
    if nb == 0:
        return render_template('done.html')
    q = q.limit(1)
    img = q.one()
    img.url = parse(img.url)
    return render_template('classify_one.html', img=img, classes=classes, w=eclass.get('w', 250), h=eclass.get('h', 250), page_width=eclass.get('page_width'), nb=nb)
Beispiel #12
0
def build_msg(cursor, speaker, start):
    location = 'target' if speaker.startswith('#') else 'source'
    count = cursor.query(Babble_count).filter(Babble_count.type == location, Babble_count.key == speaker).first()
    if count is None:
        return "%s hasn't said anything =(" % speaker
    markov = cursor.query(Babble).filter(getattr(Babble, location) == speaker).offset(random.random() * count.count).first()
    if start is None:
        prev = markov.key
    else:
        # FIXME: use Babble_count?
        if len(start) == 1:
            markov = cursor.query(Babble).filter(Babble.key.like(start[0] + ' %'))
        elif len(start) == 2:
            markov = cursor.query(Babble).filter(Babble.key == " ".join(start))
        else:
            return "Please specify either one or two words for --start"
        markov = markov.filter(getattr(Babble, location) == speaker).order_by(func.random()).first()
        if markov:
            prev = markov.key
        else:
            return "%s hasn't said %s" % (speaker, " ".join(start))
    msg = prev
    while len(msg) < 256:
        data = cursor.query(Babble).filter(Babble.key == prev, getattr(Babble, location) == speaker).all()
        if not data:
            break
        next_word = weighted_next(data)
        msg = "%s %s" % (msg, next_word)
        prev = "%s %s" % (prev.split()[1], next_word)
    return "%s says: %s" % (speaker, msg)
Beispiel #13
0
def mark_available_phrases(
        user_id: int, language: str,
        limit: int) -> List[int]:
    phrases = db.session.query(
        Phrase.id
    ).filter(
        Phrase.user_id == user_id,
        Phrase.language == language,
        Phrase.status == Phrase.Status.visible.value,
        Phrase.date_available < datetime.now(),
        Phrase.progress_status < Phrase.ProgressStatus.after_two_week.value,
    ).order_by(
        func.random()
    ).limit(limit)
    phrase_ids = [phrase.id for phrase in phrases]

    if not phrase_ids:
        return []

    redis_store.lpush(
        PHRASE_REDIS_KEY_TEMPLATE.format(
            user_id=user_id,
            language=language,
        ),
        *phrase_ids
    )
    return phrase_ids
Beispiel #14
0
def visualize_redirect(app_name='tree_map'):
    '''fetch random country'''
    c = Country.query.get(choice(random_countries))
    latest_hs_year = [available_years['hs92'][-1]]

    if app_name in ["tree_map", "stacked", "network"]:
        year = [available_years['hs92'][0], available_years['hs92'][-1]] if app_name == "stacked" else latest_hs_year
        redirect_url = url_for('.visualize', lang=g.locale, app_name=app_name, \
                        classification="hs92", trade_flow="export", \
                        origin_id=c.id_3char, dest_id="all", prod_id="show", year=year)
    elif app_name in ["geo_map", "rings"]:
        '''fetch random product'''
        p = Hs92.query.filter(Hs92.hs92 != None).filter(func.length(Hs92.hs92) == 4) \
                            .order_by(func.random()).limit(1).first()
        origin = "show"
        if app_name == "rings":
            origin = c.id_3char
        redirect_url = url_for('.visualize', lang=g.locale, app_name=app_name, \
                        classification="hs92", trade_flow="export", \
                        origin_id=origin, dest_id="all", prod_id=p.hs92, year=latest_hs_year)
    elif app_name in ["scatter"]:
        redirect_url = url_for('.visualize', lang=g.locale, app_name=app_name, \
                        classification="hs92", trade_flow="gdp", \
                        origin_id="show", dest_id="all", prod_id="all", year=latest_hs_year)
    else:
        abort(404)
    return redirect(redirect_url)
Beispiel #15
0
def get_issues(id=None):
    '''Regular response option for issues.
    '''

    filters = request.args
    filters, querystring = get_query_params(request.args)

    if id:
        # Get one issue
        filter = Issue.id == id
        issue = db.session.query(Issue).filter(filter).first()
        if issue:
            return jsonify(issue.asdict(True))
        else:
            # If no issue found
            return jsonify({"status": "Resource Not Found"}), 404

    # Get a bunch of issues
    query = db.session.query(Issue).order_by(func.random())

    for attr, value in filters.iteritems():
        if 'project' in attr:
            proj_attr = attr.split('_')[1]
            query = query.join(Issue.project).filter(getattr(Project, proj_attr).ilike('%%%s%%' % value))
        elif 'organization' in attr:
            org_attr = attr.split('_')[1]
            query = query.join(Issue.project).join(Project.organization).filter(getattr(Organization, org_attr).ilike('%%%s%%' % value))
        else:
            query = query.filter(getattr(Issue, attr).ilike('%%%s%%' % value))

    response = paged_results(query, int(request.args.get('page', 1)), int(request.args.get('per_page', 10)), querystring)
    return jsonify(response)
Beispiel #16
0
 def sort_columns(self):
     return util.unalias_dict({
         'random': (func.random(), None),
         'id': (db.Post.post_id, self.SORT_DESC),
         'score': (db.Post.score, self.SORT_DESC),
         'tag-count': (db.Post.tag_count, self.SORT_DESC),
         'comment-count': (db.Post.comment_count, self.SORT_DESC),
         'fav-count': (db.Post.favorite_count, self.SORT_DESC),
         'note-count': (db.Post.note_count, self.SORT_DESC),
         'relation-count': (db.Post.relation_count, self.SORT_DESC),
         'feature-count': (db.Post.feature_count, self.SORT_DESC),
         'file-size': (db.Post.file_size, self.SORT_DESC),
         ('image-width', 'width'):
             (db.Post.canvas_width, self.SORT_DESC),
         ('image-height', 'height'):
             (db.Post.canvas_height, self.SORT_DESC),
         ('image-area', 'area'):
             (db.Post.canvas_area, self.SORT_DESC),
         ('creation-date', 'creation-time', 'date', 'time'):
             (db.Post.creation_time, self.SORT_DESC),
         ('last-edit-date', 'last-edit-time', 'edit-date', 'edit-time'):
             (db.Post.last_edit_time, self.SORT_DESC),
         ('comment-date', 'comment-time'):
             (db.Post.last_comment_creation_time, self.SORT_DESC),
         ('fav-date', 'fav-time'):
             (db.Post.last_favorite_time, self.SORT_DESC),
         ('feature-date', 'feature-time'):
             (db.Post.last_feature_time, self.SORT_DESC),
     })
Beispiel #17
0
def category(name):
    random = db.session.query(db.Books).order_by(func.random()).limit(config.RANDOM_BOOKS)
    if name != "all":
        entries = db.session.query(db.Books).filter(db.Books.tags.any(db.Tags.name.like("%" +name + "%" ))).order_by(db.Books.last_modified.desc()).all()
    else:
        entries = db.session.query(db.Books).all()
    return render_template('index.html', random=random, entries=entries, title="Category: %s" % name)
Beispiel #18
0
    def preview(self, article_id):
        article = Article.query.get_or_404(article_id)
        related_articles = Article.query.search(article.keywords). \
            filter(Article.id != article.id).limit(3)

        _base_query = Article.query.public()

        # Tags
        tags = Tag.query.order_by(Tag.views.desc()).limit(10)

        # recommended articles top 5
        recommended_articles = _base_query.filter_by(recommended=True).limit(5)
        popular_articles = _base_query. \
            order_by(Article.views.desc()).limit(5)

        from sqlalchemy.sql.expression import func

        random_articles = _base_query.order_by(func.random()).limit(5)

        return self.render('article.html',
                           article=article,
                           tags=tags,
                           related_articles=related_articles,
                           recommended_articles=recommended_articles,
                           popular_articles=popular_articles,
                           random_articles=random_articles)
Beispiel #19
0
def get_questions(api_key='',method=1):
  ''' Accepts api_key and a paramteter method. Method
      determines the criteria by which the questions
      are generated.Currently only one method is de-
      fined. "1 Random Question Selection"
  '''
  #-- Selects 1000 questions at random
  if method ==1:
    questions = Question.query.order_by(func.random()).limit(100).all()
    #questions = questions[1:100]
    return (questions,1)
  #-- Action corresponding to method 2
  elif method == 2:
  #  pass
    questions = []    
    for c in Category.query.all():
      question_list = c.questions
      random.shuffle(question_list)
      if len(question_list) > 20 :
        question_list = question_list[0:20]
      for q in question_list:
        if q.question not in questions:
          questions.append(q.question)
    return (questions,2)
  #-- Action corresponding to method 3 etc,

  elif method == 3:
    pass

  else:
    pass
Beispiel #20
0
def index(page=1):
    _base_query = Article.query.public()
    # Latest 10 articles
    template_name = 'index.html' if page == 1 else 'includes/items.html'
    all_articles = _base_query.order_by(Article.created_at.desc()).\
        paginate(page, Article.PER_PAGE, False).items

    # Tags
    tags = Tag.query.order_by(Tag.views.desc()).all()

    slides = _base_query.filter_by(slider=True).order_by(
        Article.created_at.desc()).limit(5)

    # recommended articles top 5
    recommended_articles = _base_query.filter_by(recommended=True).limit(9)
    popular_articles = _base_query.\
        order_by(Article.views.desc()).limit(9)

    from sqlalchemy.sql.expression import func
    random_articles = _base_query.order_by(func.random()).limit(9)

    return render_template(template_name,
                           all_articles=all_articles,
                           recommended_articles=recommended_articles,
                           popular_articles=popular_articles,
                           random_articles=random_articles,
                           slides=slides,
                           tags=tags,
                           page=page)
Beispiel #21
0
def madlib():
	m = Madlib.query.order_by( func.random() ).first()

	regex = re.compile( r"\{\{(.+?)\}\}" )
	blanks = regex.findall( m.text )

	return render_template( 'madlib.html', madlib=m, blanks=blanks )
Beispiel #22
0
def sorting(request):
    
    session=DBSession()

    if request.method == "GET":

    
        #length_table=session.query(func.count(Item.id)).scalar()
        #randoms=random.sample(range(1,length_table+1),2)
        #first=session.query(Item).order_by(Item.id).offset(random).first()
        #second=session.query(Item).order_by(Item.id).offset(random)
        #query1=session.query(Item).filter_by(id=randoms[0]+1)
        #results = session.query(Item).filter(Item.id.in_(randoms)).all()
        results = session.query(Item).order_by(func.random()).limit(2).all()
        #item1=query1.one()
        #query2=session.query(Item).filter_by(id=randoms[1]+1)
        #item2=query2.one()
        id1=results[0].id
        id2=results[1].id
        name1=results[0].name
        name2=results[1].name
        data1=results[0].data
        disp_data1="%0.2f" % (data1-5)
        data2=results[1].data
        disp_data2="%0.2f" % (data2-5)
        url1=results[0].url
        url2=results[1].url
        dist=(data2-data1)/400
        corr1=decimal.Decimal(math.exp(-((data1-10)**2)/3))
        corr2=decimal.Decimal(math.exp(-((data2-10)**2)/3))
        return {'disp_data1':disp_data1,'disp_data2':disp_data2, 'dist':dist,
        'id1':id1,'id2':id2,'results':results,
        'name1':name1,'name2':name2, 'data1':data1,'data2':data2, 'url1':url1,'url2':url2}
    if request.method == "POST":
        post_data=request.POST
        #output=post_data.get('myradio')
        key1=request.params['id1']
        key2=request.params['id2']
        #dist=float(request.params['dist'])
        data1=decimal.Decimal(request.params['data1'])
        data2=decimal.Decimal(request.params['data2'])
        dist=data2-data1
        corr1=decimal.Decimal(math.exp(-((data1-10)**2)/5))
        corr2=decimal.Decimal(math.exp(-((data2-10)**2)/5))
        randoms=[key1,key2]
        #results = session.query(Item).filter(Item.id.in_(randoms)).all()
        result1= session.query(Item).filter(Item.id==key1).one()
        result2= session.query(Item).filter(Item.id==key2).one()
        x=3
        print dist
        if request.params["form"] == "form1":
            result1.data=result1.data+(1-(1/(1+10**dist)))*corr1*x
            result2.data=result2.data+(0-(1/(1+10**(-1*dist))))*corr2*x
            return HTTPFound(location=request.route_url('sorting'))    
        if request.params["form"] == "form2":
            result1.data=result1.data+(0-(1/(1+10**dist)))*corr1*x
            result2.data=result2.data+(1-(1/(1+10**(-1*dist))))*corr2*x
            return HTTPFound(location=request.route_url('sorting'))  
    return {'results':results, 'randoms':randoms}
Beispiel #23
0
 def get(self):
     session = Session()
     messages = list(session.query(Message).order_by(func.random()).limit(100))
     messages.append(Message(content='Hello, World!'))
     messages.sort(key=lambda m: m.content)
     response = loader.load('template.html').generate(messages=messages)
     session.close()
     self.write(response)
Beispiel #24
0
def find_participants(n=2):
    bots = list(db.query(Bot).order_by(func.random()).limit(n))

    if len(bots) != n:
        raise LookupError('Not enough bots found in database')

    logging.info('Letting %s fight', bots)
    return bots
Beispiel #25
0
def search():
    term = request.args.get("query")
    if term:
        random = db.session.query(db.Books).order_by(func.random()).limit(config.RANDOM_BOOKS)
        entries = db.session.query(db.Books).filter(db.or_(db.Books.tags.any(db.Tags.name.like("%"+term+"%")),db.Books.series.any(db.Series.name.like("%"+term+"%")),db.Books.authors.any(db.Authors.name.like("%"+term+"%")),db.Books.title.like("%"+term+"%"))).all()
        return render_template('search.html', searchterm=term, entries=entries)
    else:
        return render_template('search.html', searchterm="")
Beispiel #26
0
def index():
    landing_image = ImageLink.query.get(Config.query.first().landing_image_id)
    sponsors = Sponsor.query.order_by(func.random()).limit(3).all()
    front_page = {
        'projects': [i.serialize for i in Project.query
                     .order_by(func.random()).limit(2)],
        'events': [i.content for i in Event.query.all()],
        'sticky': [i.serialize for i in Post.query.filter_by(sticky=True)
                   .order_by(Post.date.desc())],
        'recent': [i.serialize for i in Post.query.filter_by(sticky=False)
                   .order_by(Post.date.desc()).limit(10)]
    }

    return render_template('index.html',
                           landing_image=landing_image.link,
                           sponsors=sponsors,
                           front_page=front_page)
Beispiel #27
0
def get_solve_task():
    sess = db.Session()
    task_id = request.args.get('task')
    if task_id:
        task = sess.query(db.OpenTask).filter(db.OpenTask.id == task_id).first()
    else:
        task = sess.query(db.OpenTask).filter(db.OpenTask.solved == False).order_by(func.random()).limit(1).first()
    user_id = session.get("user_id") or ""
    return render_template("solve_task.html", task=task, user_id=user_id)
Beispiel #28
0
 def get_comments_for_training(self, limit=None):
     # Using 'subreddit' as placeholder for username - should be changed
     comments = (db.query(Comment)
         .filter_by(author=self.subreddit)
         .order_by(func.random())
     )
     valid_comments = [comment for comment in comments
         if self.should_include_comment(comment)]
     return valid_comments
Beispiel #29
0
def index(page):
    random = db.session.query(db.Books).order_by(func.random()).limit(config.RANDOM_BOOKS)
    if page == 1:
        entries = db.session.query(db.Books).order_by(db.Books.last_modified.desc()).limit(config.NEWEST_BOOKS)
    else:
        off = int(int(config.NEWEST_BOOKS) * (page - 1))
        entries = db.session.query(db.Books).order_by(db.Books.last_modified.desc()).offset(off).limit(config.NEWEST_BOOKS)
    pagination = Pagination(page, config.NEWEST_BOOKS, len(db.session.query(db.Books).all()))
    return render_template('index.html', random=random, entries=entries, pagination=pagination, title="Latest Books")
Beispiel #30
0
 def get_comments_for_training(self, limit=None):
     comments = (db.query(Comment)
         .filter_by(subreddit=self.subreddit)
         .order_by(func.random())
         .limit(Settings["max corpus size"])
     )
     valid_comments = [comment for comment in comments
         if self.should_include_comment(comment)]
     return valid_comments
Beispiel #31
0
    def __init__(self, full_game=False, double_jeopardy=False):
        self.categories = {}
        self.round = Round.query.filter_by(name="Jeopardy!").first()
        self.full_game = full_game
        self.double_jeopardy = double_jeopardy
        self.unanswered_questions = 30
        first_question_value = 200

        # Set to double jeopardy accordingly
        if double_jeopardy:
            self.round = Round.query.filter_by(name="Double Jeopardy!").first()
            first_question_value = 400

        while len(self.categories) < 6:
            # Find a random category in the chosen round that hasn't been chosen already, check to ensure this category has 5 clues
            category = None
            while category is None or category in self.categories:
                category = Category.query.filter_by(
                    round_id=self.round.id).order_by(func.random()).first()

                if Clue.query.filter_by(round_id=self.round.id,
                                        category_id=category.id).count() < 5:
                    category = None

            # Get category clues; break out of loop early (e.g < 5 categories) if we can't find all 5 clue values for category
            self.categories[category.name] = {}
            cur_value = first_question_value
            while len(self.categories[category.name]) < 5:
                clue = Clue.query.filter_by(
                    round_id=self.round.id,
                    category_id=category.id,
                    value_id=Value.query.filter_by(
                        value=cur_value).first().id).first()
                if clue is None:
                    break

                # Create dictionary of clue data
                self.categories[category.name][clue.value.value] = {
                    "id": clue.id,
                    "round": clue.round.name,
                    "category": clue.category.name,
                    "value": clue.value.value,
                    "question": clue.question,
                    "answered": False,
                    "answer": clue.answer,
                    "air_date": clue.air_date.air_date
                }
                cur_value += first_question_value

            # Ensure we got all 5 clues; if not, delete category and we need to start over
            if len(self.categories[category.name]) < 5:
                del self.categories[category.name]
    def setup():
        def find_sentence(word):
            if len(word.sentence) < 3:
                url = "https://twinword-word-graph-dictionary.p.rapidapi.com/example/"
                querystring = {"entry": word.word}
                headers = {
                    'x-rapidapi-host':
                    "twinword-word-graph-dictionary.p.rapidapi.com",
                    'x-rapidapi-key': os.getenv('RAPID_API_KEY')
                }
                response = requests.request("GET",
                                            url,
                                            headers=headers,
                                            params=querystring)
                raw_sentence_response = response.json()

                while True:
                    index_choice = random.choice(
                        range(len(raw_sentence_response["example"])))
                    sentence_response = raw_sentence_response["example"][
                        index_choice]
                    if Sentence.query.filter_by(
                            example=sentence_response).count() == 0:
                        break

                sentence = Sentence(example=sentence_response,
                                    from_api=True,
                                    word_id=word.id)
                sentence.save()

                return sentence.example

            else:
                return random.choice(word.sentence).example

        if not request.data:
            return make_response(jsonify(error="Missing token."), 400)

        token = str(request.json.get('token', ''))
        user = User.query.filter_by(token=token)

        if user.count() > 0:
            words = Word.query.order_by(func.random()).limit(64)
            random_words = []

            for word in words:
                sentence = find_sentence(word)
                random_words.append({"word": word.word, "sentence": sentence})

            return jsonify(random_words)
        else:
            return make_response(jsonify(error="User not found."), 404)
Beispiel #33
0
 def sort_columns(self):
     return {
         'random': (func.random(), None),
         'user': (db.User.name, self.SORT_ASC),
         'author': (db.User.name, self.SORT_ASC),
         'post': (db.Comment.post_id, self.SORT_DESC),
         'creation-date': (db.Comment.creation_time, self.SORT_DESC),
         'creation-time': (db.Comment.creation_time, self.SORT_DESC),
         'last-edit-date': (db.Comment.last_edit_time, self.SORT_DESC),
         'last-edit-time': (db.Comment.last_edit_time, self.SORT_DESC),
         'edit-date': (db.Comment.last_edit_time, self.SORT_DESC),
         'edit-time': (db.Comment.last_edit_time, self.SORT_DESC),
     }
Beispiel #34
0
    def get_quiz_next_question():

        body = request.get_json()
        previous_questions = body.get('previous_questions', None)
        quiz_category = body.get('quiz_category', None)

        if previous_questions is None or quiz_category is None:
            abort(400)

        try:
            quiz_category_id = int(quiz_category["id"])
        except (KeyError, ValueError):
            abort(400)

        if (not isinstance(previous_questions, list) and all(
                isinstance(previous_question, int)
                for previous_question in previous_questions)):
            abort(400)

        if len(previous_questions) > 0:
            if quiz_category_id is 0:
                next_question = (Question.query.filter(
                    ~Question.id.in_(previous_questions)).order_by(
                        func.random()).first_or_404())
            else:
                next_question = (Question.query.filter(
                    Question.category == quiz_category_id,
                    ~Question.id.in_(previous_questions)).order_by(
                        func.random()).first_or_404())
        else:
            if quiz_category_id is 0:
                next_question = (Question.query.order_by(
                    func.random()).first_or_404())
            else:
                next_question = (Question.query.filter(
                    Question.category == quiz_category_id).order_by(
                        func.random()).first_or_404())

        return jsonify({"success": True, "question": next_question.format()})
Beispiel #35
0
def all_tutors_view():
    tutors = Tutor.query.order_by(func.random()).all()
    form = SortTutorsForm()

    if form.validate_on_submit():
        if form.select_sort.data == "rating":
            tutors = Tutor.query.order_by(Tutor.rating.desc()).all()
        elif form.select_sort.data == "price_desc":
            tutors = Tutor.query.order_by(Tutor.price.desc()).all()
        elif form.select_sort.data == "price_asc":
            tutors = Tutor.query.order_by(Tutor.price).all()

    return render_template("all.html", tutors=tutors, form=form)
Beispiel #36
0
def category(name):
    random = db.session.query(db.Books).order_by(func.random()).limit(
        config.RANDOM_BOOKS)
    if name != "all":
        entries = db.session.query(db.Books).filter(
            db.Books.tags.any(db.Tags.name.like("%" + name + "%"))).order_by(
                db.Books.last_modified.desc()).all()
    else:
        entries = db.session.query(db.Books).all()
    return render_template('index.html',
                           random=random,
                           entries=entries,
                           title="Category: %s" % name)
Beispiel #37
0
def viewCommunity():
    users = User.query.order_by(func.random()).limit(20).all()
    user_icons = []
    for user in users:
        user_icon = user.user_icon
        if user_icon:
            user_icons.append(b64encode(user_icon).decode('utf-8'))
        else:
            user_icons.append(None)
    teams = Team.query.order_by(func.random()).limit(20).all()
    team_icons = []
    team_chorusbattles = []
    for team in teams:
        team_logo = team.team_logo
        if team_logo:
            team_icons.append(b64encode(team_logo).decode('utf-8'))
        else:
            team_icons.append(None)
        team_chorusbattles.append(ChorusBattle.query.filter_by(id=team.chorusbattle).first().name)
    print(users, teams)
    return render_template('community.html', users=users, user_icons=user_icons, teams=teams, team_chorusbattles=team_chorusbattles, \
        team_icons=team_icons, icon=getUserIcon((session['username'] if 'username' in session else None)))
Beispiel #38
0
def random_dinger():
    """Returns a random home run
    """

    play = Play.query.order_by(func.random())

    team = request.args.get('team')
    if team is not None:
        play = play.filter(Play.batter_team == team)

    play = play.first()

    return JsonResponse(serialize_play(play))
Beispiel #39
0
 def get_quiz_questions():
     previous_questions = request.json.get('previous_questions')
     quiz_category = request.json.get('quiz_category')
     if quiz_category is None:
         return abort(404)
     category_id = Question.query.filter(
       Question.category == category_id,
       Question.id.in_(previous_questions)) if category_id else \
       Question.query.filter(Question.id.in_(previous_questions))
     question = questions.order_by(func.random()).first()
     if not question:
         return jsonify({})
     return jsonify({'question': question.format()})
 def test_delete_question_valid_id(self):
     test_id = Question.query.order_by(func.random()).first().id
     total_before = len(Question.query.all())
     response = self.client().delete('/questions/{}'.format(test_id))
     data = json.loads(response.data)
     total_after = len(Question.query.all())
     # check response
     self.assertEqual(response.status_code, 200)
     self.assertEqual(data['success'], True)
     # check response body
     self.assertEqual(data['deleted'], test_id)
     # check database changes
     self.assertEqual(total_before - 1, total_after)
Beispiel #41
0
def index():
    categories = db.session.query(CategoryModel).all()
    cat_meals_dict = {}

    # формируем список их 3х товаров по каждой из категорий
    for category in categories:
        meals = db.session.query(MealModel) \
            .filter(MealModel.category == category) \
            .order_by(func.random()) \
            .limit(3) \
            .all()
        cat_meals_dict[category] = meals
    return render_template('main.html', meals=cat_meals_dict, session=session)
Beispiel #42
0
    def get_three_reviews(restaurant_id):
        """
        Given the restaurant_di return three random reviews
        """
        reviews = (
            db.session.query(Review)
            .filter_by(restaurant_id=restaurant_id)
            .order_by(func.random())
            .limit(3)
            .all()
        )

        return reviews
Beispiel #43
0
def home_view(request):
    """View for home route."""
    session = request.dbsession
    real_tweet = session.query(Tweet).order_by(func.random()).first()
    fake_tweet = gen_tweet()
    if request.method == "POST" and request.POST:
        new_entry = FakeTweet(faketweet=request.POST['fakeTweet'],
                              tweeted=False,
                              shown=1,
                              chosen=1)
        request.dbsession.add(new_entry)
        return {}
    return {'page': 'Home', 'real': real_tweet.tweet, 'fake': fake_tweet}
Beispiel #44
0
def add_word(word_list, n):
    if not word_list:
        word = db.session.query(models.UpperWords).order_by(
            func.random()).first().word  #postgre
    elif len(word_list) <= n:
        word = get_word(word_list, len(word_list))
    else:
        word = get_word(word_list, n)
    if word:
        word_list.append(word)
        return True
    else:
        return False
Beispiel #45
0
    def category_menu(self):
        """Display categories for the user

        Returns:
            str: Return a list of choices 
        """
        q = session.query(Category.category_name).order_by(
            func.random()).limit(6).all()
        print(Fore.GREEN + "\n------ Catégories ------\n")
        for n, category_name in enumerate(q):
            print(f"{n} - {category_name}")
        choice = input("Choissisez une option:")
        return self.main_menu
Beispiel #46
0
 def _gallery_orderby(model_name, capture=db.model_name(db.Gallery)):
     return {
         ItemSort.GalleryRandom.value: (func.random(), ),
         ItemSort.GalleryTitle.value: (db.Title.name, ),
         ItemSort.GalleryArtist.value: (db.ArtistName.name, ),
         ItemSort.GalleryDate.value: (db.Gallery.timestamp, ),
         ItemSort.GalleryPublished.value: (db.Gallery.pub_date, ),
         ItemSort.GalleryRead.value: (db.Gallery.last_read, ),
         ItemSort.GalleryUpdated.value: (db.Gallery.last_updated, ),
         ItemSort.GalleryRating.value: (db.Gallery.rating, ),
         ItemSort.GalleryReadCount.value: (db.Gallery.times_read, ),
         ItemSort.GalleryPageCount.value: (db.func.count(db.Page.id), ),
     }
Beispiel #47
0
def random_food():
    food = Foods.query.filter_by(food_type="main_course").order_by(
        func.random()).first()

    obj = dict()
    obj['id'] = food.id
    obj['food_id'] = food.food_id
    obj['food_type'] = food.food_type
    obj['food_name'] = food.food_name
    obj['food_image'] = food.food_image
    obj['ingredients'] = food.ingredients
    obj['recipe'] = food.recipe
    return jsonify({"result": obj})
Beispiel #48
0
def get_random():
    limit = request.args.get('limit')
    try:
        limit = int(limit)
    except Exception:
        limit = 100
    query = db.session.query(Staff).filter(Staff.type == 0).order_by(
        func.random()).limit(limit)
    temp = []
    for s in query:
        temp.append(s.to_json())
    res = ResponseMsg(temp)
    return res.json_body()
Beispiel #49
0
 def quizzes():
     body = request.get_json()
     app.logger.info(body)
     prev = [data for data in body.get('previous_questions')]
     app.logger.info(prev)
     if body.get('quiz_category') is None:
         abort(400)
     elif body.get('quiz_category').get('id') == 0:
         next_ques = Question.query.filter(
             Question.id.notin_(prev)).order_by(func.random()).first()
     else:
         next_ques = Question.query.filter(
             Question.category == body['quiz_category']['id'],
             Question.id.notin_(prev)).order_by(func.random()).first()
     if len(prev) == 0 and next_ques is None:
         abort(400)
     return jsonify({
         'success':
         True,
         'question':
         None if next_ques is None else next_ques.format()
     })
Beispiel #50
0
def group():
    users = []
    if current_user.is_authenticated:
        posts = current_user.followed_posts().all()
        tempUsers = User.query.filter(User.id != current_user.id).order_by(
            func.random()).all()
        for tempUser in tempUsers:
            if not current_user.is_following(tempUser) and len(users) <= 2:
                users.append(tempUser)
        return render_template('group/groups.html',
                               posts=posts,
                               users=users,
                               active='group')
    def random(self):
        while self.running:
            if len(self.queue) > 0:
                time.sleep(1)
                continue

            random_blog = self.db.query(Blog).filter(
                or_(Blog.updated != Blog.last_crawl_update,
                    Blog.last_crawl_update == None)).order_by(
                        func.random()).limit(1).scalar()

            self.log(random_blog.name, random_blog.total_posts)
            self.archive(random_blog)
Beispiel #52
0
def get_random_user(method):
    """
        Pick random user from db acording to some rules
        
        Pick first that is true
        1. If main user never scraped, then scrape it
        2. If main user to long since scraped, then scrape it
        3. If user with degree priority high enough to be fully scraped never was scraped, then scrape it
        4. If user with degree priority high enough to be fully scraped is to long since updated, then scrape it
        5. if user never scraped, then scrape it
        6. If user to old since update, then scrape it
        
        todo:
            remove or keep rule 5 and 6? 
        
        args:
            method (str): friendship|user|tweet. Used to pick which last updated field to check
    """
    users = None
    if method == "friendship":
        users = _get_random_user(
            "friendships_last_updated",
            user_main_delta=twitter_config.FRIENDSHIP_USER_MAIN_DELTA,
            user_full_delta=twitter_config.FRIENDSHIP_USER_FULL_DELTA)
    elif method == "user":
        users = _get_random_user(
            "last_updated",
            user_main_delta=twitter_config.USER_MAIN_DELTA,
            user_full_delta=twitter_config.USER_FULL_DELTA,
            user_delta=twitter_config.USER_DELTA)
    elif method == "tweet":
        users = _get_random_user(
            "tweets_last_updated",
            user_main_delta=twitter_config.TWEET_USER_MAIN_DELTA,
            user_full_delta=twitter_config.TWEET_USER_FULL_DELTA)

    if not users:
        return None
    if not users.first():
        return None

    #This should shuffle the list retrieved for different type of db. Not tested on all
    #Might also become to slow when db gets large, not tested.
    if twitter_config.DATABASE == twitter_const.MYSQL:
        users = users.order_by(func.rand())
    elif twitter_config.DATABASE == twitter_const.POSTGRESSQL or twitter_config.DATABASE == twitter_const.SQLITE:
        users = users.order_by(func.random())
    elif twitter_config.DATABASE == twitter_const.ORACLE:
        users = users.order_by('dbms_random.value')

    return users.first()
Beispiel #53
0
    def play_quiz():
        error = 422

        previous_questions = request.json.get('previous_questions', None)
        quiz_category = request.json.get('quiz_category', None)

        try:
            # retrieve category_id from quiz_category dictionary
            category = quiz_category.get('id')

            prevques = []
            for question in previous_questions:
                prevques.append(question)
        except:
            abort(400)

        try:
            # frontend sets value of 'ALL' categories to 'click'
            if category == 0:
                next_question = Question.query.filter(
                    ~Question.id.in_(prevques)).order_by(
                        func.random()).first()
            else:
                next_question = Question.query.filter(
                    Question.category == category).filter(
                        ~Question.id.in_(prevques)).order_by(
                            func.random()).first()

            if not next_question:
                error = 404
                abort()
            else:
                return jsonify({
                    'success': True,
                    'question': next_question.format()
                })
        except:
            abort(error)
Beispiel #54
0
def get_orgs_issues(organization_name, labels=None):
    ''' A clean url to get an organizations issues
    '''
    # Get one named organization.
    organization = Organization.query.filter_by(name=raw_name(organization_name)).first()
    if not organization:
        return "Organization not found", 404

    # Get that organization's projects
    projects = Project.query.filter_by(organization_name=organization.name).all()
    project_ids = [project.id for project in projects]

    if labels:
        # Get all issues belonging to these projects
        query = Issue.query.filter(Issue.project_id.in_(project_ids))

        # Create a labels list by comma separating the argument
        labels = [label.strip() for label in labels.split(',')]

        # Create the filter for each label
        labels = [Label.name.ilike(format_ilike_term(label)) for label in labels]

        # Create the base query object by joining on Issue.labels
        query = query.join(Issue.labels)

        # Filter for issues with each individual label
        label_queries = [query.filter(L) for L in labels]

        # Intersect filters to find issues with all labels
        query = query.intersect(*label_queries).order_by(func.random())

    else:
        # Get all issues belonging to these projects
        query = Issue.query.filter(Issue.project_id.in_(project_ids)).order_by(func.random())

    filters, querystring = get_query_params(request.args)
    response = paged_results(query=query, include_args=dict(include_project=True, include_labels=True), page=int(request.args.get('page', 1)), per_page=int(request.args.get('per_page', 10)), querystring=querystring)
    return jsonify(response)
Beispiel #55
0
def create_fake_order(discounts):
    user = User.query.order_by(func.random()).first()
    address = create_fake_address()
    status = random.choice(list(OrderStatusKinds)).value
    order_data = {
        "user_id": user.id,
        "shipping_address": address.full_address,
        "status": status,
        "token": str(uuid4()),
    }
    shipping_method = ShippingMethod.query.order_by(func.random()).first()
    order_data.update({
        "shipping_method_name": shipping_method.title,
        "shipping_method_id": shipping_method.id,
        "shipping_price_net": shipping_method.price,
    })

    order = Order.create(**order_data)
    lines = create_order_lines(order, discounts, random.randrange(1, 5))
    order.total_net = sum([line.get_total() for line in lines])
    order.save()
    create_payment(order)
    return order
Beispiel #56
0
 async def read(self, ids, fields=Available):
     if ids['id'] == 'random':
         provider_id = ids['provider_id']
         account = self.get_account(provider_id)
         kw = dict(account_id=account.id,
                   account_provider_id=account.provider_id,
                   provider_id=provider_id)
         self.policy.grant_query(account, self.__model__, kw)
         ids = dict(provider_id=provider_id)
         query = await self.query(ids, kw)
         random = query.order_by(func.random()).first()
         if random:
             ids['id'] = random.id
     return await super().read(ids, fields=fields)
Beispiel #57
0
def _random_story(message=''):
    story = Story.query.filter(Story.author_id != current_user.id).filter_by(
        published=1).order_by(func.random()).first()
    if story is None:
        message = 'Ooops.. No random story for you!'
        rolls_outcome = []
    else:
        rolls_outcome = json.loads(story.rolls_outcome)
    return render_template("story.html",
                           message=message,
                           story=story,
                           url="/story/",
                           current_user=current_user,
                           rolls_outcome=rolls_outcome)
Beispiel #58
0
def fill_indexpage(page, database, db_filter, order, *join):
    if current_user.show_detail_random():
        randm = db.session.query(db.Books).filter(common_filters())\
            .order_by(func.random()).limit(config.config_random_books)
    else:
        randm = false()
    off = int(int(config.config_books_per_page) * (page - 1))
    pagination = Pagination(page, config.config_books_per_page,
                            len(db.session.query(database).filter(db_filter).filter(common_filters()).all()))
    entries = db.session.query(database).join(*join, isouter=True).filter(db_filter).filter(common_filters()).\
        order_by(*order).offset(off).limit(config.config_books_per_page).all()
    for book in entries:
        book = order_authors(book)
    return entries, randm, pagination
Beispiel #59
0
    def getRandom(self, limit=1):
        '''
            Return a list of rows taken randomly.
            Works only on SQLite.

            :param int limit: Limit
            :return: List of non persistent entities
            :rtype: list of entities.Common
        '''
        '''return self._session.query(self._persistent_entity)
                                .order_by(func.random())
                                .limit(limit).all()
        '''
        return self._getBy(order=func.random(), limit=limit)
Beispiel #60
0
def search():
    term = request.args.get("query")
    if term:
        random = db.session.query(db.Books).order_by(func.random()).limit(
            config.RANDOM_BOOKS)
        entries = db.session.query(db.Books).filter(
            db.or_(
                db.Books.tags.any(db.Tags.name.like("%" + term + "%")),
                db.Books.series.any(db.Series.name.like("%" + term + "%")),
                db.Books.authors.any(db.Authors.name.like("%" + term + "%")),
                db.Books.title.like("%" + term + "%"))).all()
        return render_template('search.html', searchterm=term, entries=entries)
    else:
        return render_template('search.html', searchterm="")