def get_3by3_matrix(entity, user_id, filter_by=None): if filter_by is None: data = entity.query.filter(entity.UserID == user_id).order_by( func.rand()).limit(9).all() else: # if an author is provided data = entity.query.filter((entity.UserID == user_id) & (entity.Author.any( AuthorID=filter_by.AuthorID))).order_by( func.rand()).limit(9).all() return [list(data[i:i + 3]) for i in [0, 3, 6]] if data else None
def get_spectrum_dict_by_inchikey_choose( self, inchikey_list, instrument_type="%", precursor_type="%", include_len_0=True, sample_num=20, ): collision_energy_list = [10, 20, 40, 60, 80] sampling_num_each = int(sample_num / len(collision_energy_list)) spectrum_inchikey_dict = dict() for inchikey in inchikey_list: # print("get spectrum dict one smiles!") spectrum_list = [] for collision_energy in collision_energy_list: # func.rand() : mysql or mariadb query = self.session.query(SpectrumInfo).filter( SpectrumInfo.inchikey == inchikey, SpectrumInfo.instrument_type == instrument_type, SpectrumInfo.prec_type == precursor_type, SpectrumInfo.collision_energy == collision_energy, ) query = query.order_by(func.rand()).limit(sampling_num_each) for record in query.all(): result_spectrum = record.as_spectrum() if len(result_spectrum.peaks) > 4: spectrum_list.append(record.as_spectrum()) if include_len_0: spectrum_inchikey_dict[inchikey] = spectrum_list # spectrum_smiles_dict[smiles].append(spectrum_list) elif include_len_0 is False: if len(spectrum_list) > 0: spectrum_inchikey_dict[inchikey] = spectrum_list # spectrum_smiles_dict[smiles].append(spectrum_list) return spectrum_inchikey_dict
def random_image(db): ''' Returns a random image from the database. This is MySQL-specific at the moment. ''' image = db.query(Image).order_by(func.rand()).first() response.set_header('Content-Type', 'image/%s' % image.filetype) return str(image.data)
def show_restaurants(customer_score, seed_number=1, area=None, rank=None, search_key=None,page=1): """ Show restaurants randomly by seed_number from offset to offset + limit """ cuisine_match = { 'american': ['American','Steak','New American','French-American'], 'french': ['French','French/Italian','French-American','French| Gluten Free'], 'italian': ['Italian','French/Italian'], 'asian': ['Asian','Japanese','Middle Eastern','Chinese','Korean','Indian','Thai'], } rank_match = {'Platinum': 5, 'Gold': 4, 'Silver': 3, 'Bronze': 2, 'Blue': 1} query = Restaurants.query.filter(Restaurants.dinerscode_rank >= 1, Restaurants.dinerscode_rank <= get_maximum_rank(customer_score), Restaurants.is_deleted == 'N') if area and area != 'ALL': query = query.filter(Restaurants.area == area) if rank in rank_match: query = query.filter(Restaurants.dinerscode_rank == rank_match[rank]) if search_key: search_key = search_key.lower() cuisine_lst = cuisine_match[search_key] if search_key in cuisine_match else (search_key,) query = query.filter(or_(Restaurants.restaurant_name.ilike('%{}%'.format(search_key)), Restaurants.cuisine_type.in_(cuisine_lst), Restaurants.cuisine_type.ilike('%{}%'.format(search_key)))) # restaurants = [res for res in restaurants if search_key in res.restaurant_name.lower() or search_key in res.cuisine_type.lower()] query = query.order_by(func.rand(seed_number)).offset(offset).paginate(page, 12) return query
def given_select_random_current_status(context,var): try: q = db.session.query(Current_Status).order_by(func.rand()).limit(1).one() print (q.serialize['message_id']) context.alienvault[var] = q.serialize except NoResultFound: assert None,"No entries in current_local"
def given_select_random_status_message(context, var): try: q = db.session.query(Status_Message).order_by( func.rand()).limit(1).one() context.alienvault[var] = q.serialize except NoResultFound: assert None, "No entries in status_message"
def gettest( self, inchikeylist, instrument_type, precursor_type, collision_energy, sample_num, ): spectrum_inchikey_dict = dict() for inchikey in inchikeylist: temp = [] query = ( self.session.query(SpectrumInfo) .filter( SpectrumInfo.inchikey == inchikey, SpectrumInfo.instrument_type == instrument_type, SpectrumInfo.prec_type == precursor_type, SpectrumInfo.collision_energy == collision_energy, ) .order_by(func.rand()) .limit(int(sample_num / 5)) ) for record in query.all(): temp.append(record.as_spectrum()) spectrum_inchikey_dict[inchikey] = temp return spectrum_inchikey_dict
def authors(): if request.method == 'GET': users = FrontUserModel.query.order_by( FrontUserModel.points.desc()).all() is_focus_id = None if g.front_user: my_focus = FocusModel.query.filter_by( author_id=g.front_user.id).all() is_focus_id = [focus_users.own_user_id for focus_users in my_focus] return render_template('front/all_authors.html', users=users, is_focus_id=is_focus_id) else: users = [] users_obj = FrontUserModel.query.order_by(func.rand()).limit(5) for user in users_obj: users_focus = FocusModel.query.filter_by(own_user_id=user.id).all() is_focus_id = [ focus_users.author_id for focus_users in users_focus ] users.append({ 'user_id': user.id, 'nickname': user.nickname, 'charactors': len_charactors(user.charactors), 'avatar': user.avatar, 'is_focus_id': is_focus_id }) random.shuffle(users) return restful.success(data=users)
def given_select_random_message(context,var_mid): try: db.session.expire_all() q = db.session.query(Status_Message).order_by(func.rand()).limit(1).one().serialize print (q['id']) context.alienvault[var_mid] = q['id'] except NoResultFound: assert None,"No entries in status message"
def getHotReviews(): session = db.session() reviews = session.query(Reviews) \ .order_by(func.rand()) \ .limit(10) res = [] for r in reviews: res.append([r, getMovieById(r.MovieId)]) return res
def index(): process_data() data = [] subbed = Tag.query.filter(Tag.subscribed==1).all() for sub in subbed: for article in sub.articles: if article not in data: data.append(article) data.sort(key=lambda x: x.id, reverse=True) tags = Tag.query.order_by(func.rand()).all() return render_template('index.html', data=data, tags=tags)
def given_gen_monitor_data(context,var_n,var_type): db.session.query(Monitor_Data).delete() # Delete all current_status entries ctypes = var_type.split(",") for x in range (0,int(var_n)): ctype = random.choice (ctypes) assert (ctype in ['net','host','user','sensor','server','system']) == True, "Unknown type '%s'" % ctype entry = Monitor_Data() # Select a entry try: c_id = { 'user': str(uuid.UUID(db.session.query(Users).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'net' : str(uuid.UUID(db.session.query(Net).order_by(func.rand()).limit(1).one().serialize['id'])), 'host': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'sensor': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'system': str(uuid.UUID(db.session.query(System).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'server': str(uuid.UUID(db.session.query(Server).order_by(func.rand()).limit(1).one().serialize['id'])), }.get(ctype) except NoResultFound: assert None,"Can't load a asset of type '%s'" % ctype # We have now the component_id # Select a msg_id entry.component_id = get_bytes_from_uuid (c_id) entry.monitor_id = 1 entry.component_type = "system" sleep(1) entry.data = "{\"msg\": \"Texto de prueba\"}" db.session.begin() db.session.merge(entry) db.session.commit()
def select_products(cls, session, categroy): """Query that retrieves all products whose nutriscore is greater than "B" Args: session (session): allow to send requests to the database categroy (int): category is an integer that matches the id of the category whose products are to be retrieved. Returns: Products: Database Products objects """ result = session.query(Product)\ .filter(Product.category_id == categroy)\ .filter(Product.nutriscore > "b")\ .join(Category).order_by(func.rand()).limit(10).all() return result
def continue_questions(lesson_id): if not session_f.get('user_id'): return redirect(url_for("login")) user_login = True page_name = 'continue_questions' user_id = int(session_f['user_id']) has_access = check_user_access(user_id, lesson_id) if has_access: s = Session() grade = s.query(Lesson.course_id).filter(Lesson.id == lesson_id).first() grade_id = grade[0] question_len = s.query(Question).filter(Question.lesson_id == lesson_id).count() user_enrol = s.query(Enrol_user).filter(Enrol_user.user_id== user_id, Enrol_user.lesson_id == lesson_id).first() if user_enrol.question_ids : user_question_ids = user_enrol.question_ids.split(',') user_question_ids_len = len(user_question_ids) else: user_question_ids = 'na' user_question_ids_len = 0 next_continue_previous_question = 'na' while user_question_ids_len + 1 < question_len: random_question = s.query(Question).order_by(func.rand()).filter(Question.lesson_id == lesson_id).first() if str(random_question.id) not in user_question_ids: next_continue_previous_question = random_question break if next_continue_previous_question == 'na': first_question_id = s.query(Question.id).filter(Question.lesson_id == lesson_id).first() last_question_id = s.query(Question.id).order_by(Question.id.desc()).filter(Question.lesson_id == lesson_id).first() for id in range(int(first_question_id[0]), int(last_question_id[0])): if id not in user_question_ids: next_continue_previous_question = s.query(Question).filter(Question.id == id).first() break next_continue_previous_voice = s.query(Voice).filter(Voice.id == next_continue_previous_question.voice_id).first() next_continue_previous_answer = s.query(Answer).filter(Answer.question_id == next_continue_previous_question.id).first() lesson = s.query(Lesson).filter(Lesson.id == lesson_id).first() question = next_continue_previous_question.text voice = f'{next_continue_previous_voice.path}' question_id = next_continue_previous_question.id answer = next_continue_previous_answer.ans_text lesson_title = lesson.title s.commit() s.close() else: flash('این درس برای شما باز نشده است!','danger') return redirect(url_for("grade")) return render_template('train.html',grade_id = grade_id, question = question, voice = voice, question_id = question_id, answer = answer, lesson_title = lesson_title, lesson_id = lesson_id, page_name = page_name, user_login = user_login)
def when_select_random_asset(context, var_type, var_uuid): # First, select net,host,system,server,user,sensor value = None while value is None: asset = var_type try: value = { 'user': str( uuid.UUID( db.session.query(Users).order_by( func.rand()).limit(1).one().serialize['uuid'])), 'net': str( uuid.UUID( db.session.query(Net).order_by( func.rand()).limit(1).one().serialize['id'])), 'host': str( uuid.UUID( db.session.query(Host).order_by( func.rand()).limit(1).one().serialize['id'])), 'sensor': str( uuid.UUID( db.session.query(Sensor).order_by( func.rand()).limit(1).one().serialize['id'])), 'system': str( uuid.UUID( db.session.query(System).order_by( func.rand()).limit(1).one().serialize['uuid'])), 'server': str( uuid.UUID( db.session.query(Server).order_by( func.rand()).limit(1).one().serialize['id'])), }.get(asset) except NoResultFound: assert None, "No asset of type '%s' in system" % asset # Verify if the hosts is in the current_status q = db.session.query(Current_Status).filter( Current_Status.component_id == get_bytes_from_uuid(value)).all() if len(q) == 0: value = None context.alienvault[var_uuid] = value
def stream_recommendations(): include_users = [u[0] for u in db.session.query(User.id).\ filter(User.username.in_(request.args.getlist("include-user")))] exclude_users = [u[0] for u in db.session.query(User.id).\ filter(User.username.in_(request.args.getlist("exclude-user")))] datetime_start = request.args.get("datetime-start", datetime.min, type=dateutil.parser.parse) datetime_end = request.args.get("datetime-end", datetime.max, type=dateutil.parser.parse) min_scrobbles_count = request.args.get("min-scrobbles-count", 5, type=int) if request.args.get("sort") == "scrobbles-count": order_by = func.count(Scrobble.id).desc() else: order_by = func.rand() limit = request.args.get("limit", 1000, type=int) added = 0 for artist, track in db.session.query(Scrobble.artist, Scrobble.track).\ filter( Scrobble.user_id.in_(include_users), Scrobble.uts >= time.mktime(datetime_start.timetuple()), Scrobble.uts <= time.mktime(datetime_end.timetuple()) ).\ having(func.count(Scrobble.id) >= min_scrobbles_count).\ group_by(Scrobble.artist, Scrobble.track).\ order_by(order_by): if exclude_users: if db.session.query(func.count(Scrobble.id)).\ filter( Scrobble.user_id.in_(exclude_users), Scrobble.artist == artist, Scrobble.track == track ).\ scalar() > 0: continue yield json.dumps({"artist": artist, "track": track}) + b"\n" added += 1 if added >= limit: break
def given_gen_status_message(context,var_n): db.session.query(Current_Status).delete() # Delete all current_status entries total = 0 total_msg = _return_total_status() assert int(var_n) <= total_msg, "We don't have enought messages and asset to generate %d current_status entries " % int(var_n) while total < int(var_n): ctype = random.choice (['net','host','user','sensor','server','system']) entry = Current_Status() try: c_id = { 'user': str(uuid.UUID(db.session.query(Users).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'net' : str(uuid.UUID(db.session.query(Net).order_by(func.rand()).limit(1).one().serialize['id'])), 'host': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'sensor': str(uuid.UUID(db.session.query(Sensor).order_by(func.rand()).limit(1).one().serialize['id'])), 'system': str(uuid.UUID(db.session.query(System).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'server': str(uuid.UUID(db.session.query(Server).order_by(func.rand()).limit(1).one().serialize['id'])), }.get(ctype) except NoResultFound: assert None,"Can't load a asset of type '%s'" % ctype # We have now the component_id # Select a msg_id try: msg_entry = db.session.query(Status_Message).order_by(func.rand()).limit(1).one().serialize except NoResultFound: assert None,"Can't load a message entry" entry.id = get_bytes_from_uuid (str(uuid.uuid1())) entry.message_id = get_bytes_from_uuid(msg_entry['id']) entry.component_id = get_bytes_from_uuid (c_id) entry.component_type = ctype entry.viewed = random.choice([True, False]) entry.additional_info = """{"msg_id": "Random generate message"}""" # check q = db.session.query(Current_Status).filter(and_( Current_Status.message_id == entry.message_id, Current_Status.component_id == entry.component_id)).all() if len(q) > 0: continue db.session.begin() db.session.merge(entry) db.session.commit() total = total + 1
def given_gen_status_message(context,var_n,var_type): db.session.query(Current_Status).delete() # Delete all current_status entries ctypes = var_type.split(",") total = 0 while (total < 100): ctype = random.choice (ctypes) assert (ctype in ['net','host','user','sensor','server','system']) == True, "Unknown type '%s'" % ctype entry = Current_Status() # Select a entry try: c_id = { 'user': str(uuid.UUID(db.session.query(Users).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'net' : str(uuid.UUID(db.session.query(Net).order_by(func.rand()).limit(1).one().serialize['id'])), 'host': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'sensor': str(uuid.UUID(db.session.query(Sensor).order_by(func.rand()).limit(1).one().serialize['id'])), 'system': str(uuid.UUID(db.session.query(System).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'server': str(uuid.UUID(db.session.query(Server).order_by(func.rand()).limit(1).one().serialize['id'])) }.get(ctype) except NoResultFound: assert None,"Can't load a asset of type '%s'" % ctype # We have now the component_id # Select a msg_id try: msg_entry = db.session.query(Status_Message).order_by(func.rand()).limit(1).one().serialize except NoResultFound: assert None,"Can't load a message entry" entry.id = get_bytes_from_uuid (str(uuid.uuid1())) entry.message_id = get_bytes_from_uuid(msg_entry['id']) entry.component_id = get_bytes_from_uuid (c_id) entry.component_type = ctype entry.viewed = False entry.suppressed = False entry.additional_info = """{"id": "Random generate message"}""" db.session.begin() db.session.merge(entry) db.session.commit() total = total + 1
def when_select_random_asset(context, var_uuid): # First, select net,host,system,server,user,sensor l = ['user', 'net', 'host', 'system', 'server', 'sensor'] value = None while value is None: assert l != [], "I can't select any component_to make the call" asset = random.choice(l) try: value = { 'user': str( uuid.UUID( db.session.query(Users).order_by( func.rand()).limit(1).one().serialize['uuid'])), 'net': str( uuid.UUID( db.session.query(Net).order_by( func.rand()).limit(1).one().serialize['id'])), 'host': str( uuid.UUID( db.session.query(Host).order_by( func.rand()).limit(1).one().serialize['id'])), 'sensor': str( uuid.UUID( db.session.query(Sensor).order_by( func.rand()).limit(1).one().serialize['id'])), 'system': str( uuid.UUID( db.session.query(System).order_by( func.rand()).limit(1).one().serialize['uuid'])), 'server': str( uuid.UUID( db.session.query(Server).order_by( func.rand()).limit(1).one().serialize['id'])), }.get(asset) except NoResultFound: l.remove(asset) context.alienvault[var_uuid] = value
def when_select_random_asset (context,var_uuid): # First, select net,host,system,server,user,sensor l = ['user','net','host','system','server','sensor'] value = None while value is None: assert l != [], "I can't select any component_to make the call" asset = random.choice (l) try: value = { 'user': str(uuid.UUID(db.session.query(Users).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'net' : str(uuid.UUID(db.session.query(Net).order_by(func.rand()).limit(1).one().serialize['id'])), 'host': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'sensor': str(uuid.UUID(db.session.query(Sensor).order_by(func.rand()).limit(1).one().serialize['id'])), 'system': str(uuid.UUID(db.session.query(System).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'server': str(uuid.UUID(db.session.query(Server).order_by(func.rand()).limit(1).one().serialize['id'])), }.get(asset) except NoResultFound: l.remove (asset) context.alienvault[var_uuid] = value
def when_select_random_asset (context,var_type,var_uuid): # First, select net,host,system,server,user,sensor value = None while value is None: asset = var_type try: value = { 'user': str(uuid.UUID(db.session.query(Users).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'net' : str(uuid.UUID(db.session.query(Net).order_by(func.rand()).limit(1).one().serialize['id'])), 'host': str(uuid.UUID(db.session.query(Host).order_by(func.rand()).limit(1).one().serialize['id'])), 'sensor': str(uuid.UUID(db.session.query(Sensor).order_by(func.rand()).limit(1).one().serialize['id'])), 'system': str(uuid.UUID(db.session.query(System).order_by(func.rand()).limit(1).one().serialize['uuid'])), 'server': str(uuid.UUID(db.session.query(Server).order_by(func.rand()).limit(1).one().serialize['id'])), }.get(asset) except NoResultFound: assert None,"No asset of type '%s' in system" % asset # Verify if the hosts is in the current_status q = db.session.query(Current_Status).filter(Current_Status.component_id == get_bytes_from_uuid (value)).all() if len(q) == 0: value = None context.alienvault[var_uuid] = value
def quest_by_cat(cls, _cat, _lim): return cls.query.filter_by(category=_cat).order_by( func.rand()).limit(_lim).all()
def api_hello(): quote = db.session.query(Quote).order_by(sql_func.rand()).first() if not quote: return jsonify(message='hello, world') return jsonify(message=quote.message)
def given_select_random_status_message(context,var): try: q = db.session.query(Status_Message).order_by(func.rand()).limit(1).one() context.alienvault[var] = q.serialize except NoResultFound: assert None,"No entries in status_message"
def get_random_quote(user_id): data = Quote.query.filter(Quote.UserID == user_id).order_by( func.rand()).limit(1).first() return data
def new_questions(lesson_id, index = 0): if not session_f.get('user_id'): return redirect(url_for("login")) user_login = True page_name = 'new_questions' user_id = int(session_f['user_id']) has_access = check_user_access(user_id, lesson_id) if has_access: s = Session() grade = s.query(Lesson.course_id).filter(Lesson.id == lesson_id).first() grade_id = grade[0] index = int(index) if index == -1 : all_previous_answer = s.query(User_answer).filter(User_answer.lesson_id == lesson_id, User_answer.user_id == user_id).all() if all_previous_answer: for answer in all_previous_answer: s.delete(answer) s.commit() has_user_enrol = s.query(Enrol_user).filter(Enrol_user.lesson_id == lesson_id, Enrol_user.user_id == user_id).first() if has_user_enrol: s.query(Enrol_user).filter(Enrol_user.lesson_id == lesson_id, Enrol_user.user_id == user_id).update({ Enrol_user.complete_question: 'na' , Enrol_user.question_ids : 'na'}) s.commit() else: enrol_user = Enrol_user(lesson_id = lesson_id, user_id=user_id, complete_question = 'na', question_ids = 'na') s.add(enrol_user) s.commit() user_enrol = s.query(Enrol_user).filter(Enrol_user.lesson_id == lesson_id, Enrol_user.user_id == user_id).first() question_len = s.query(Question).filter(Question.lesson_id == lesson_id).count() if user_enrol.question_ids != 'na' : user_question_ids = user_enrol.question_ids.split(',') user_question_ids_len = len(user_question_ids) else: user_question_ids = [0] user_question_ids_len = 0 next_new_question = 'na' while user_question_ids_len + 1 < question_len: random_question = s.query(Question).order_by(func.rand()).filter(Question.lesson_id == lesson_id).first() if str(random_question.id) not in user_question_ids: next_new_question = random_question break if next_new_question == 'na': first_question_id = s.query(Question.id).filter(Question.lesson_id == lesson_id).first() last_question_id = s.query(Question.id).order_by(Question.id.desc()).filter(Question.lesson_id == lesson_id).first() for id in range(int(first_question_id[0]), int(last_question_id[0])): if id not in user_question_ids: next_new_question = s.query(Question).filter(Question.id == id).first() break next_new_voice = s.query(Voice).filter(Voice.id == next_new_question.voice_id).first() next_new_answer = s.query(Answer).filter(Answer.question_id == next_new_question.id).first() lesson = s.query(Lesson).filter(Lesson.id == lesson_id).first() else: flash('این درس برای شما باز نشده است!','danger') return redirect(url_for("grade")) question = next_new_question.text voice = f'{next_new_voice.path}' question_id = next_new_question.id answer = next_new_answer.ans_text lesson_title = lesson.title s.commit() s.close() return render_template('train.html',grade_id = grade_id, question = question, voice = voice, question_id = question_id, answer = answer, lesson_title = lesson_title, lesson_id = lesson_id, page_name = page_name, base_url = BASE_URL, user_login = user_login)