def get_by_date_and_hour(cls, date, begin_hour, end_hour): schedules = [] query = {'$and': [{'date': date}, {'begin_meeting': begin_hour}]} # query = {'$and': [{'date': date}, # {'$or': [{'$gt': {'begin_meeting': end_hour}}, {'$st': {'end_meeting': begin_hour}}]}]} data = Database.find('schedules', query) if data is not None: for sched in data: schedules.append(cls(**sched)) return schedules
def from_user_topic(username): return [ post for post in Database.find(collection='Bids', query=({ 'transactions.username': username }, { 'transactions': True })) ]
def get_by_room_and_date_and_hour(cls, _id, date, begin_hour, end_hour): schedules = [] query = {'$and': [{'date': date}, {'room_id': _id}]} data = Database.find('schedules', query) if data is not None: for schedule in data: if int(schedule.end_meeting) <= int(end_hour) and int( schedule.begin_meeting) >= int(begin_hour): schedules.append(cls(**schedule)) return schedules
def from_all_ads(): #yesterday = date.today() - timedelta(2) yesterday = date.today() yesterday = yesterday.strftime('%d-%m-%y') return [ post for post in Database.find(collection='ecom', query=({ "created_date": yesterday })) ]
def find_by_author_id(cls, author_id): blogs = Database.find(collection="blogs", query={"author_id": author_id}) print(author_id) print(blogs) print([cls(**blog) for blog in blogs]) return [ cls(**blog) for blog in blogs ] # list_comprehention -> returns blog(Object) that need to be **unpacking
def all(cls: Type[T]) -> List[T]: """ give a list of item objects cls is the current class, cls is equal to Item class **item is passing four arguments:_id, url, tag, query, because the parameters has the same as the keys in json """ # pymongo cursor, find return a cursor, can iterate by for loop elements_from_db = Database.find(cls.collection, {}) # iterate the items_from_db so the item is each of the dicts in that cursor # return [Item(_id=item['_id'], url=item['url']) for item in items_from_db], given a list of item objects return [cls(**elem) for elem in elements_from_db]
def all(cls: Type[T]) -> List[T]: """ This method loads all objects found in a given database collection :return: List of all elements in a given database collection """ elements_from_db = Database.find(cls.collection, {}) ## cls.collection - Warning because collection is not defined in Model class ## This is ok because child classes will have cls.collection defined ## Above definition collection: str resolves warnings return [cls(**elem) for elem in elements_from_db]
def asset(): if request.cookies.get('login_email') is not None: email = request.cookies.get('login_email') data = Database.find_one(userconstants.COLLECTION, {'email': email}) blogs = Database.find("blogs", {'email': email}) return render_template('userblog.html', author=data['firstname'], lastname=data['lastname'], email=request.form['email'], blogs=blogs, date=datetime.datetime.utcnow())
def get_by_room_and_date(cls, _id, date): """ :return: list of schedule's object that represent the schedule in the given room_id on the given date """ schedules = [] query = {'$and': [{'date': date}, {'room_id': _id}]} data = Database.find('schedules', query) if data is not None: for sched in data: schedules.append(cls(**sched)) return schedules
def checkpassword(password): data = Database.find(UserConstants.COLLECTION, {"password": password}) for datas in data: hash_password = utils.check_hash_password(password, datas['password']) if hash_password: return True else: return False else: return False
def get_facilities(company): """ :param company: :return: List of company's facilities """ facility_dict = Database.find('facilities', {'company': company}) facilities = [] for facility in facility_dict: facility = facility['facility'] facilities.append(facility) return facilities
def find_many_by(cls: Type[T], attribute: str, value: str) -> List[T]: """ This method finds all records in the database matching a supplied attribute / value :param collection: Uses collection specified in the child class :param attribute: The key we want to search on :param value: The value we want to find :return: The records found """ return [ cls(**elem) for elem in Database.find(cls.collection, {attribute: value}) ]
def isBlog(titleBlog=None): condition = False; if titleBlog is not None: data = Database.find("blogs", {"title":titleBlog}) for item in data: if item['title'] == titleBlog: condition = True return condition else: return condition else: return 0
def find_needing_update(cls, minutes_since_update=AlertConstants.ALERT_TIMEOUT): last_updated_limit = datetime.datetime.utcnow() - datetime.timedelta( minutes=minutes_since_update) return [ cls(**elem) for elem in Database.find(AlertConstants.COLLECTION, { "last_checked": { "$lte": last_updated_limit }, "active": True }) ]
def get_by_room(cls, room_id): """ :param room_id: :return: list of schedule's object that represent the schedule in the given room_id """ schedules = [] data = Database.find('schedules', {'room_id': room_id}) if data is not None: for sched in data: schedules.append(cls(**sched)) return schedules
def get_by_facility(cls, company, facility): data = Database.find( 'rooms', {'$and': [{ 'company': company }, { 'facility': facility }]}) rooms = [] if data is not None: for room in data: rooms.append(cls(**room)) return rooms
def find_by_facility(cls, company, facility): orders = [] data = Database.find( 'orders', {'$and': [{ 'company': company }, { 'facility': facility }]}) if data is not None: for order in data: orders.append(cls(**order)) return orders
def find_oddities(cls: Type[T]) ->List[T]: elements_from_db = Database.find(cls.collection, {}) elements = [cls(**elem) for elem in elements_from_db] result = [] for element in elements: if not element.ResultStatus == 'Succeeded': if not element.org == 'AS786 Jisc Services Limited': long, latt = element.loc distance = (long - 50.3755) /(latt - 4.1427) distance = math.sqrt(distance*distance) if distance > 0.1: result.append(element) return result
def find_needing_update( cls, minutes_since_last_update=AlertConstants.ALERT_TIMEOUT): last_updated_limit = datetime.datetime.utcnow() - datetime.timedelta( minutes=0) alertss = [ cls(**elm) for elm in Database.find(AlertConstants.COLLECTION, {"last_checked": { "$lte": last_updated_limit }}) ] print(alertss) return alertss
def find_needing_update(cls, minutes_since_update: int) -> List["Alert"]: last_updated_limit = datetime.datetime.utcnow() - datetime.timedelta( minutes=minutes_since_update) return [ cls(**elem) for elem in Database.find( cls.collection, { "last_checked": { "$lte": last_updated_limit }, "active": True }, ) ]
def rest_map_template(city): df, df1 = [], [] col1 = Database.DATABASE['rest_rec'] col1.drop() for food in Database.find(collection='Resturants', query={}): food1 = Database.find(collection='Resturants', query={}) df = pd.DataFrame(list(food1)) for cols in Database.find('Rest_rating', {}).limit(1): food2 = Database.find('Rest_rating', {}) df1 = pd.DataFrame(list(food2)) rating_count = pd.DataFrame( df1, columns=['rest_id', 'no_of_rating', 'avg_rating']) rating_count = rating_count.sort_values('no_of_rating', ascending=False) rating_count1 = rating_count['rest_id'][:10] rating_count1 = rating_count1.values.tolist() rating = pd.DataFrame( df1.groupby('rest_id')['no_of_rating', 'avg_rating'].mean()) print(rating) rating.sort_values('no_of_rating', ascending=False) rating_pivot = pd.pivot_table(data=df1, values='user_rating', index='user_id', columns='rest_id') oneman = rating_pivot[rating_count1[1]] similar_to = rating_pivot.corrwith(oneman) corr_oneman = pd.DataFrame(similar_to, columns=['PearsonR']) oneman_sum = corr_oneman.join(rating) oneman_sum1 = oneman_sum.sort_values('PearsonR', ascending=False) oneman_sum2 = oneman_sum1.index.values.tolist() place_coor = pd.DataFrame(oneman_sum2, index=np.arange(393), columns=['rest_id']) sumarry = pd.merge(place_coor, df, on='rest_id') places = sumarry[:10] record = places.to_dict('records') Database.insert('rest_rec', record) foods = [p for p in Database.find(collection='rest_rec', query={})] #sumarry = json.loads(sumarry[:10].to_json()).values() #places=[i for i in sum1] #places = Place.from_city_place(city) place = Database.find("Resturants", {'City': city}) df2 = pd.DataFrame(list(place)) m = folium.Map(location=[15.6, 74.6], tiles="OpenStreetMap", zoom_start=10) for i in range(len(df2)): icon_url = 'https://cdn1.iconfinder.com/data/icons/maps-locations-2/96/Geo2-Number-512.png' icon = folium.features.CustomIcon(icon_url, icon_size=(28, 30)) popup = folium.Popup(df2.iloc[i]['Location'], parse_html=True) folium.Marker([df2.iloc[i]['lat'], df2.iloc[i]['lon']], popup=popup, icon=icon).add_to(m) m.save('templates/map.html') return render_template('rest_map.html', foods=foods, username=session['username'], picture=session['picture'])
def get_num_employees_facility(company_id, facility_id=None): if facility_id is None: query = {'company': company_id} else: query = { '$and': [{ 'facility': facility_id }, { 'company': company_id }] } emps = Database.find('users', query) if emps is None: return return emps.count(True)
def get_by_email_and_date_and_hour(cls, email, date, begin_hour, end_hour): ###need to change the queary schedules = [] # query = {'$and': [{'date': date} , {'email': email}, {'$gt': {'begin_meeting': begin_hour}}]} query = {'$and': [{'date': date}, {'email': email}]} # query = {'$and': [{'date': date}, {'email':email}, {'begin_meeting': begin_hour}, {'end_meeting': end_hour}]} # query = {'$and': [{'date': date}, {'email': email}, # {'$or': [{'$gt': {'begin_meeting': end_hour}}, {'$st': {'end_meeting': begin_hour}}]}]} data = Database.find('schedules', query) if data is not None: for sched in data: if cls.check_time_interval(sched, begin_hour, end_hour) == True: schedules.append(cls(**sched)) return schedules
def all(cls) -> List[Model]: """ Finds and returns all the models corresponding to the model's collection. Returns ------- List[Model] The list of all the models of the model's collection. """ logger.debug("all...") elements_from_db = Database.find(cls.collection, {}) logger.debug(f"elements_from_db: {elements_from_db}") elements = [cls(**elem) for elem in elements_from_db] logger.debug(f"elements: {elements}") return elements
def get_num_rooms_facility(company_id, facility_id=None): if facility_id is None: query = {'company': company_id} # print "Here" else: query = { '$and': [{ 'facility': facility_id }, { 'company': company_id }] } # print query rooms = Database.find('rooms', query) if rooms is None: return return rooms.count(True)
def login_admin(): # renders the overview page email = request.form['email'] password = request.form['password'] if Admin.is_login_valid(email, password): # is True Admin.login(email) session['email'] = email else: session['email'] = "no email" return "ADMIN NOT FOUND, PLEASE CHECK YOUR CREDENTIALS, OR CONTACT SERVER ADMINISTRATOR" # collection = 'students' students = Database.find(collection='students', query={}) # return "HELLO" return render_template("overview_page.html", email=session['email'], students=students)
def find_by_user_email_and_date_and_time(cls, user_email, date, beign, end): orders = [] intersection = { '$or': [{ '$and': [{ 'start_time': { '$not': { '$gte': end } } }, { 'end_time': { '$gte': end } }] }, { '$and': [{ 'start_time': { '$not': { '$gte': beign } } }, { 'end_time': { '$gt': beign } }] }] } query = { '$and': [{ 'date': date }, { 'user_email': user_email }, intersection] } data = Database.find('orders', query) for order in data: orders.append(cls(**order)) return orders
def find_by_date_and_time_facility(cls, date, beign, end, facility): orders = [] intersection = { '$or': [{ '$and': [{ 'start_time': { '$not': { '$gte': end } } }, { 'end_time': { '$gte': end } }] }, { '$and': [{ 'start_time': { '$not': { '$gte': beign } } }, { 'end_time': { '$gt': beign } }] }] } query = { '$and': [{ 'date': date }, { 'facility': facility }, intersection] } data = Database.find('orders', query) for order in data: orders.append(cls(**order)) return orders
def get_friends(user_email): """ :param user_email: :return: List of user_email's friends """ friends_dict = Database.find('friends', { '$or': [{ 'user_email_1': user_email }, { 'user_email_2': user_email }] }) friends = [] for friend in friends_dict: user1 = friend['user_email_1'] user2 = friend['user_email_2'] friend = user1 if user1 != user_email else user2 friends.append(friend) return friends
class Video(object): def __init__(self, account, title='None', link='None', image='None', time='None'): self.account = account self.title = title self.link = link self.image = image self.time = time self.database = Database('localhost:27017', 'videos') def save_to_db(self): print("save_to_db") self.database.insert(collection='video', data=self.json()) def fine_video(self, account): result = self.database.find(collection='video', data={'account': account}) return result def delete_video(self, account, link): self.database.remove(collection='video', data={ 'account': account, 'link': link }) def json(self): return { 'account': self.account, 'title': self.title, 'link': self.link, 'image': self.image, 'time': self.time }
def from_blog(id): return [post for post in Database.find(collection='posts', query={'blog_id': id})]
def from_blog(blogId): return [post for post in Database.find(collection='posts', query={'blogId': blogId})]
def find_by_author_id(cls, authorId): ''' find by author id ''' blogs = Database.find("blogs", {'authorId': authorId}) return [cls(**blog) for blog in blogs]
def from_blog(id): return [post for post in Database.find(collection="posts", query={"blog_id": id})]
def find_by_author_id(cls, author_id): blogs = Database.find(collection='blogs', query={'author_id': author_id}) return [cls(**blog) for blog in blogs]