Here are the examples of the python api sqlalchemy.func.random taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4 Examples
3
View Complete Implementation : request.py
Copyright MIT License
Author : flask-dashboard
Copyright MIT License
Author : flask-dashboard
def get_latencies_sample(db_session, endpoint_id, interval, sample_size=500):
criterion = create_time_based_sample_criterion(interval.start_date(), interval.end_date())
dialect = db_session.bind.dialect.name
if dialect in ['sqlite', 'mysql']:
order_by = func.random() if dialect == 'sqlite' else func.rand()
items = db_session.query(Request.duration) \
.filter(Request.endpoint_id == endpoint_id, *criterion) \
.order_by(order_by) \
.limit(sample_size) \
.all()
durations = [item.duration for item in items]
return durations
else:
return get_latencies_in_timeframe(db_session, endpoint_id, interval.start_date(), interval.end_date())
0
View Complete Implementation : experiment.py
Copyright MIT License
Author : interactiveaudiolab
Copyright MIT License
Author : interactiveaudiolab
def astign_conditions(participant, limit_to_condition_ids=None):
"""
astign experimental conditions for a participant's trial.
Parameters
----------
participant : caqe.models.Participant
limit_to_condition_ids : list, optional
List of integer ids.
Returns
-------
condition_ids : list of int
"""
# Ideal astignment in our scenario:
# If the participant pasted the listening test:
# astign a participant the first condition (in order of index) that has
# A) not been astigned to them before
# B) has not received the required number of ratings by people that have pasted the listening test
# If the participant has not pasted the listening test:
# Same as above. This may give us a bit more ratings from lower condition indices for people that have not pasted
# the listening test, but I think that is ok.
# construct our subqueries
# conditions which have the required number of trials with hearing_test pasted participants
conditions = get_available_conditions(limit_to_condition_ids)
# the conditions the participant has already done
participant_conditions = db.session.query(Trial.condition_id).join(Participant). \
filter(Participant.id == participant.id).subquery()
conditions = conditions.filter(Condition.id.notin_(participant_conditions))
# find which group has the most conditions for this participant
if app.config['TEST_CONDITION_GROUP_ORDER_RANDOMIZED']:
group_id = db.session.query(Condition.group_id).filter(Condition.id.in_([c.id for c in conditions.all()])). \
group_by(Condition.group_id). \
order_by(func.random()).first()[0]
else:
group_id = db.session.query(Condition.group_id).filter(Condition.id.in_([c.id for c in conditions.all()])). \
group_by(Condition.group_id). \
order_by(func.count(Condition.group_id).desc()).first()[0]
condition_group_ids = [group_id,]
# limit to one group
conditions = conditions.filter(Condition.group_id == group_id).order_by(Condition.id).all()
if conditions is None or len(conditions) == 0:
logger.info('No hits left for %r' % participant)
return None
if app.config['LIMIT_SUBJECT_TO_ONE_TASK_TYPE']:
previous_trial = participant.trials.first()
try:
if previous_trial.condition.test_id != conditions[0].test_id:
# If the participant is supposed to be limited to one task type, and we are out of all task of that type
logger.info('Subject limited to ont task type. No hits left for %r' % participant)
return None
except AttributeError:
# no previous trials
past
if app.config['TEST_CONDITION_ORDER_RANDOMIZED']: # i.e. randomize the condition order within a test
# determine what test we are on
current_test_id = conditions[0].test_id
# randomize the order of the conditions within that test
condition_ids = [c.id for c in conditions if c.test_id == current_test_id]
random.shuffle(condition_ids)
condition_ids = condition_ids[:app.config['CONDITIONS_PER_EVALUATION']]
# if there are not enough conditions left from this test, add more from the next.
if len(condition_ids) < app.config['CONDITIONS_PER_EVALUATION']:
more_cids = [c.id for c in conditions if c.test_id == current_test_id + 1]
random.shuffle(more_cids)
condition_ids += more_cids[:(app.config['CONDITIONS_PER_EVALUATION'] - len(condition_ids))]
else:
condition_ids = [c.id for c in conditions[:app.config['CONDITIONS_PER_EVALUATION']]]
logger.info('Participant %r astigned conditions: %r in groups: %r' % (participant,
condition_ids,
condition_group_ids))
return condition_ids, condition_group_ids
0
View Complete Implementation : tag.py
Copyright MIT License
Author : Nukesor
Copyright MIT License
Author : Nukesor
def handle_next(session, bot, chat, tg_chat, user):
"""Handle the /next call or the 'next' button click."""
# We are tagging a whole sticker set. Skip the current sticker
if chat.tag_mode == TagMode.STICKER_SET:
# Check there is a next sticker
stickers = chat.current_sticker.sticker_set.stickers
for index, sticker in enumerate(stickers):
if sticker == chat.current_sticker and index + 1 < len(stickers):
# We found the next sticker. Send the messages and return
chat.current_sticker = stickers[index + 1]
send_tag_messages(chat, tg_chat, user)
return
# There are no stickers left, reset the chat and send success message.
chat.current_sticker.sticker_set.completely_tagged = True
send_tagged_count_message(session, bot, user, chat)
tg_chat.send_message('The full sticker set is now tagged.',
reply_markup=get_main_keyboard(user))
chat.cancel(bot)
# Find a random sticker with no changes
elif chat.tag_mode == TagMode.RANDOM:
base_query = session.query(Sticker) \
.outerjoin(Sticker.changes) \
.join(Sticker.sticker_set) \
.filter(Change.id.is_(None)) \
.filter(StickerSet.international.is_(False)) \
.filter(StickerSet.banned.is_(False)) \
.filter(StickerSet.nsfw.is_(False)) \
.filter(StickerSet.furry.is_(False)) \
# Let the users tag the deluxe sticker set first.
# If there are no more deluxe sets, just tag another random sticker.
# Remove the favoring of deluxe stickers until the deluxe pool is bigger again.
# sticker = base_query.filter(StickerSet.deluxe.is_(True)) \
# .order_by(func.random()) \
# .limit(1) \
# .one_or_none()
# if sticker is None:
sticker = base_query \
.order_by(func.random()) \
.limit(1) \
.one_or_none()
# No stickers for tagging left :)
if not sticker:
call_tg_func(tg_chat, 'send_message',
['It looks like all stickers are already tagged :).'],
{'reply_markup': get_main_keyboard(user)})
chat.cancel(bot)
return
# Found a sticker. Send the messages
chat.current_sticker = sticker
send_tag_messages(chat, tg_chat, user, send_set_info=True)
0
View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : spectria
Copyright GNU Affero General Public License v3.0
Author : spectria
@view_config(
route_name="settings_theme_previews", renderer="settings_theme_previews.jinja2"
)
def get_settings_theme_previews(request: Request) -> dict:
"""Generate the theme preview page."""
# get the generic/unknown user and a random group to display on the example posts
fake_user = request.query(User).filter(User.user_id == -1).one()
group = request.query(Group).order_by(func.random()).limit(1).one()
fake_link_topic = Topic.create_link_topic(
group, fake_user, "Example Link Topic", "https://tildes.net/"
)
fake_text_topic = Topic.create_text_topic(
group, fake_user, "Example Text Topic", "No real text"
)
fake_text_topic.content_metadata = {
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
fake_topics = [fake_link_topic, fake_text_topic]
# manually add other necessary attributes to the fake topics
for fake_topic in fake_topics:
fake_topic.topic_id = sys.maxsize
fake_topic.tags = ["tag one", "tag two"]
fake_topic.num_comments = 123
fake_topic.num_votes = 12
fake_topic.created_time = utc_now() - timedelta(hours=12)
# create a fake top-level comment that appears to be written by the user
markdown = (
"This is what a regular comment written by yourself would look like.\n\n"
"It has **formatting** and a [link](https://tildes.net)."
)
fake_top_comment = Comment(fake_link_topic, request.user, markdown)
fake_top_comment.comment_id = sys.maxsize
fake_top_comment.created_time = utc_now() - timedelta(hours=12, minutes=30)
child_comments_markdown = [
(
"This reply has received an Exemplary label. It also has a blockquote:\n\n"
"> Hello World!"
),
(
"This is a reply written by the topic's OP with a code block in it:\n\n"
"```js\n"
"function foo() {\n"
" ['1', '2', '3'].map(parseInt);\n"
"}\n"
"```"
),
(
"This reply is new and has the *Mark New Comments* stripe on its left "
"(even if you don't have that feature enabled)."
),
]
fake_comments = [fake_top_comment]
# vary the ID and created_time on each fake comment so CommentTree works properly
current_comment_id = fake_top_comment.comment_id
current_created_time = fake_top_comment.created_time
for markdown in child_comments_markdown:
current_comment_id -= 1
current_created_time += timedelta(minutes=5)
fake_comment = Comment(
fake_link_topic, fake_user, markdown, parent_comment=fake_top_comment
)
fake_comment.comment_id = current_comment_id
fake_comment.created_time = current_created_time
fake_comment.parent_comment_id = fake_top_comment.comment_id
fake_comments.append(fake_comment)
# add other necessary attributes to all of the fake comments
for fake_comment in fake_comments:
fake_comment.num_votes = 0
fake_tree = CommentTree(
fake_comments, CommentTreeSortOption.RELEVANCE, request.user
)
# add a fake Exemplary label to the first child comment
fake_comments[1].labels = [
CommentLabel(fake_comments[1], fake_user, CommentLabelOption.EXEMPLARY, 1.0)
]
# the comment to mark as new is the last one, so set a visit time just before it
fake_last_visit_time = fake_comments[-1].created_time - timedelta(minutes=1)
return {
"theme_options": THEME_OPTIONS,
"fake_topics": fake_topics,
"fake_comment_tree": fake_tree,
"last_visit": fake_last_visit_time,
}