def generateReservation(collectionId, idSpectateur, idGame, date, heure, email): reservation = Reservation(collectionId, idSpectateur, idGame, date + ' ' + heure, email) reservation.toString() newReservation_id = addReservationToSQL(reservation) return newReservation_id
def reset_DB(): conn = get_connection() Reservation.drop_table(conn) Client.drop_table(conn) Room.drop_table(conn) Hotel.drop_table(conn) Country.drop_table(conn) Country.reset_table(conn) Hotel.reset_table(conn) Room.reset_table(conn) Client.reset_table(conn) Reservation.reset_table(conn)
def make_reservation(): customer = ask_name() destination = select_destination() print(f"Your randomly selected destination is: {destination.city}") while True: try: vehicle = select_vehicle() print(f"You've selected a {vehicle.vtype}") if vehicle.vtype == 'bicycle': vehicle.cycle() elif vehicle.vtype == 'car': vehicle.drive() elif vehicle.vtype == 'boat': vehicle.sail() elif vehicle.vtype == 'hovercraft': vehicle.drive() vehicle.sail() elif vehicle.vtype == 'train': vehicle.ride() elif vehicle.vtype == 'airplane': vehicle.fly() except: print("Please try again") else: break price = vehicle.km_cost * destination.distance reservation = Reservation(customer.name, destination.city, destination.distance, vehicle.vtype, price) write_to_file(reservation) pickle_to_file(reservation) return reservation
def add_reservation(self, username, projection_id, row, col): session.add( Reservation(username=username, projection_id=projection_id, row=row, col=col)) session.commit()
def get_Reservation(User) : cur.execute=(""" SELECT * FROM EnsReservation WHERE user_id = ? """, (Reservation.get_user_id())) result = cur.fetchall() for ReservationCur in result : ReservationCur = Reservation(ReservationCur[0],ReservationCur[1],ReservationCur[2],ReservationCur[3],ReservationCur[4],ReservationCur[5],ReservationCur[6])
def test_take_reservationC(self): name = "Carla's" genre = "Diner" max_seats = 5 open_t = 6 close_t = 15 restaurant = Restaurant(name, genre, max_seats, open_t, close_t) customer = Customer("George", "(802)555-5555") res1 = Reservation(customer, 12, 2) res2 = Reservation(customer, 12, 3) restaurant.take_reservation(res1) restaurant.take_reservation(res2) self.assertEqual(restaurant.seats_available, 0)
def supprimer_Reservation(Reservation): #Supprime une reservation try: cur.execute=(""" DELETE FROM EnsReservation WHERE Reservation_id = ?""", (Reservation.get_user_id())) conn.commit() except: print "Erreur lors de la suppression de la Reservation"
def getReservation(self, sessionId, reservationId): self.__db = Database() self.__sessionId = sessionId if self.__db.connect(): #check session id and get user id auth = AuthenticationManager() if auth.isSessionIdCorrect(self.__sessionId): self.__userId = auth.getUser().getUserId() sql = 'SELECT `username`, `status` FROM `user` WHERE `user_id` = "'+str(self.__userId)+'";' self.__db.execute(sql) u = self.__db.getCursor().fetchone() username = u[0] status = u[1] if str(status).lower() == 'admin': sql = 'SELECT `reservation_id`, `title`, `description`, `start`, `end`, `image_type`, `type` FROM `reservation` WHERE `reservation_id`="'+str(reservationId)+'";' self.__db.execute(sql) data = self.__db.getCursor().fetchone() r = Reservation(data) r.setOwner(username) r.setReservationsSite() status = r.getReservationsSite()[0].getStatus() return r return None
def getReservations(self, sessionId = None, userId = None, ended = None): if sessionId == None and userId == None: return None self.__db = Database() self.__sessionId = sessionId self.__reservations = [] if self.__db.connect(): try: if userId == None: #check session id and get user id auth = AuthenticationManager() if auth.isSessionIdCorrect(self.__sessionId): self.__userId = auth.getUser().getUserId() else: self.__userId = userId if self.__userId != None: sql = 'SELECT `username` FROM `user` WHERE `user_id`="'+str(self.__userId)+'";' self.__db.execute(sql) username = self.__db.getCursor().fetchone()[0] self.__db.lock({'reservation':'READ'}) sql = 'SELECT `reservation_id`, `title`, `description`, `start`, `end`, `image_type`, `type` FROM `reservation` WHERE `user_id`="'+str(self.__userId)+'";' self.__db.execute(sql) data = self.__db.getCursor().fetchall() currentTime = NOW for d in data: end = d[4] diff = currentTime - end r = Reservation(d) r.setOwner(username) r.setReservationsSite() status = r.getReservationsSite()[0].getStatus() if ended == None: #for pcc self.__reservations.append(r) elif ended: #history (already ended) if diff >= timedelta(hours=0) or status == 'cancel': self.__reservations.append(r) else: #see reservations which havn't ended if diff < timedelta(hours=0) and status != 'cancel': self.__reservations.append(r) self.__db.unlock() finally: self.__db.close() return self.__reservations
def read_reservations(): r = open('reservations.txt', 'r+') reservations = [] for rline in r.readlines(): rparts = rline.strip().split(',') reserved_room = Reservation(int(rparts[0]), datetime.strptime(rparts[1], '%d.%m.%Y'), rparts[2]) reservations.append(reserved_room) r.close() return reservations
def getRoomReservations(self): self.conn.execute_query('SELECT * FROM Edu_RoomReservations') reservations = {} for row in self.conn: reservation = Reservation(row['RoomID'], row['DayID'], row['StartID'], row['EndID']) reservations[row['RoomID']] = [] reservations[row['RoomID']].append(reservation) self._reservations = reservations return reservations
def createReservation(self, roomType, familyName, guestsNumber, arrival, departure): ''' Validates and creates a reservation. ''' reservation = Reservation(None, None, familyName, guestsNumber, arrival, departure) self._validateReservation(roomType, reservation) return self._repository.createReservation(roomType, reservation)
def make_reservation(self, name, number_of_tickets): self.show_movies() choosen_movie_id = input("Choose a movie>") self.show_movie_projections(choosen_movie_id) choosen_projection_id = input("Choose a projection>") free_slots_for_choosen_projection = self.free_slots_for_projection( choosen_projection_id) if free_slots_for_choosen_projection < number_of_tickets: print("Not enought tickets for this projection, only {} available". format(free_slots_for_choosen_projection)) return print("Available seats (marked with a dot):") reset_hall() self.fill_hall_for_projection(choosen_projection_id) pprint(hall) checked_tickets = 0 seats = [] while checked_tickets != number_of_tickets: seat_row = int( input("Choose seat{}(row)>".format(checked_tickets + 1))) seat_col = int( input("Choose seat{}(col)>".format(checked_tickets + 1))) if self.is_position_free([seat_row, seat_col]): seats.append([seat_row, seat_col]) checked_tickets += 1 else: print("This seat is already taken! or it's outside the hall!") choosen_movie_name = session.query( Movie.name).filter(Movie.id == choosen_movie_id).one() choosen_movie_date = session.query( Projection.date).filter(Projection.id == choosen_movie_id).one() choosen_movie_time = session.query( Projection.time).filter(Projection.id == choosen_movie_id).one() choosen_projection_type = session.query(Projection.type).filter( Projection.id == choosen_projection_id).one() print("This is your reservation:") print("Movie: ", choosen_movie_name) print("Date and Time: {}:{} - ({})".format(choosen_movie_date, choosen_movie_time, choosen_projection_type)) print("Seats: ", ) for seat in seats: print("row:{}, col:{}".format(seat[0], seat[1]), ) is_finalized = input("Confirm - type 'finalize'>") if is_finalized == 'finalize': for seat in seats: session.add( Reservation(username=name, projection_id=choosen_projection_id, row=seat[0], col=seat[1])) session.commit()
def add(self, table, date, time, customer_id, num_people, petitions, type, ID=None): super().add( Reservation(table, date, time, customer_id, num_people, petitions, type, ID))
def loadGuestsDict(): guests = json.loads(open('./Guests.json').read()) currentGuests = {} for guest in guests: currentRes = Reservation(guest['reservation']['roomNumber'], \ guest['reservation']['startTimestamp'], \ guest['reservation']['endTimestamp']) newGuest = Guest(guest['id'], \ guest['firstName'], \ guest['lastName'], \ currentRes) currentGuests.update({newGuest.id: newGuest}) return currentGuests
def test_has_seatsA(self): name = "Carla's" genre = "Diner" max_seats = 5 open_t = 6 close_t = 15 restaurant = Restaurant(name, genre, max_seats, open_t, close_t) customer = Customer("George", "(802)555-5555") res1 = Reservation(customer, 12, 2) restaurant.take_reservation(res1) self.assertEqual(restaurant.has_seats(3), True)
def _loadReservations(self, fileName): ''' Loads from '<fileName>' the reservations ''' with open(fileName, "r") as file: data = file.read().strip("\n").split("\n") reservations = {} for current in data: parameters = current.split(",") ID = parameters[0].strip(" ") roomNumber = int(parameters[1].strip(" ")) familyName = parameters[2].strip(" ") guestsNumber = int(parameters[3].strip(" ")) arrival = datetime.datetime.strptime(parameters[4].strip(" ") + ".2018", "%d.%m.%Y") departure = datetime.datetime.strptime(parameters[5].strip(" ") + ".2018", "%d.%m.%Y") reservations[ID] = Reservation(ID, roomNumber, familyName, guestsNumber, arrival, departure) return reservations
def availableRooms(self, arrival, departure): ''' Returns a list of the available rooms for the given interval. ''' matching = [] matching.extend(self._rooms[1]) matching.extend(self._rooms[2]) matching.extend(self._rooms[4]) supposed = Reservation(None, None, None, None, arrival, departure) for reservation in self._reservations.values(): if reservation.roomNumber in matching: if self._datesOverlap(reservation, supposed): matching.remove(reservation.roomNumber) if matching == []: raise RepoError("No available rooms of this type.") matching.sort() return matching
def monthlyReport(self): ''' Returns a list of the months sorted in descending order by the number of the reservation days. ''' monthDays = [] for month in range(1,13): monthDays.append([month, 0]) start = datetime.datetime (year = 2018, month = month, day = 1) end = datetime.datetime(year = 2018, month = month, day = monthrange(2018, month)[1]) supposed = Reservation(None, None, None, None, start, end) for reservation in self._reservations.values(): if self._datesOverlap(reservation, supposed): relativeStart = reservation.arrival relativeEnd = reservation.departure if relativeStart < start: relativeStart = start if relativeEnd > end: relativeEnd = end monthDays[month-1][1] += (relativeEnd-relativeStart).days monthDays.sort(key= lambda element: element[1], reverse=True) results = [] for element in monthDays: results.append( str(month_name[element[0]]) + ": " + str(element[1]) ) return results
def register_event(self, event): event_id = ReservationManager.generate_uuid() self.reservation_map[event_id] = Reservation(event) return event_id
def initSlice(s1): rs, L, BW, B, PW, LX, LY, BLX, BLY = Reservation.generateConfigToSlice( ) K1 = s1 # number of users of slice1 Dc = 0.1 * np.ones((1, K1)) # delay constraint of slice1 #location matrix of the users of the slice in the LXxLY area #location matrix of the users in the x axis of the AXxAY area ULX1 = np.random.randint( 0, LX, (1, K1) ) #LX is x axis, we multiply the result by LX to update the value have value upto the value of the coordinates. #location matrix of the users in the y axis of the AXxAY area ULY1 = np.random.randint( 0, LY, (1, K1) ) #LY is y axis, we multiply the result by LY to update the value have value upto the value of the coordinates. #distance matrix of the users to the base stations DKB1 = np.zeros((K1, B)) for k in range(0, K1): for b in range(0, B): x1 = np.array([ULX1[0, k], ULY1[0, k]]) x2 = np.array([BLX[0, b], BLY[0, b]]) dist = np.linalg.norm(x1 - x2) DKB1[k, b] = max( dist, 1) # distane between BS and user, assume minimum 1m. # arrival rate of users ar = 80 + np.random.randint(0, 40, (1, K1)) # power multiply by channel gain(received power) pg = np.zeros((K1, B)) for i in range(0, K1): # users for j in range(0, B): # base stations ''' the Channel Gain is equivalent to the inverse of sum of the losses. linear division is subtraction in decibels.(if it was division in linear, it will be subtraction in decibel becuase of logarithm) the randn with deviation of 8 is for shadowing. the randi is for antena gain ''' pg[i, j] = PW[j] - ( 34 + 40 * np.log10(DKB1[i, j]) + 8 * np.random.randn() ) # received at the user from base station, in other words transmitted power times channel gain #Achievable data rate of users on each base station R = np.zeros((K1, B)) for i in range(0, K1): for j in range(0, B): R[i, j] = BW * np.log2(1 + ( np.power(10, pg[i, j] / 10) / (sum(np.power(10, pg[i, :] / 10)) - np.power(10, pg[i, j] / 10) + np.power(10, rs / 10)))) #normalized achiecable datarate of users on each base station rt = R / L # do all the code below iteratively at every specified time #virtual resouce #create the deep Q network #DQNd() du = 0 ru = 0 # out side the iteration # todo # dqn1 = DQNd() # dqn1.createNN() P1 = np.zeros((1, B)) v = np.zeros((1, B)) a1 = 0 d1 = -1 return rt, Dc, ar, P1, du, ru
def removeSliceFromResourceTable(s1): if s1 != 0: reser = Reservation(s1, 0) reser.deleteSlice() else: print('undefined number of parameters')
def makeResourceManagement(self, RL): P1 = self.P11 (K1a, B) = np.array(self.rt).shape a1 = 0 if self.ii <= 0: #we use ii=0 to differenciate whether the resource managment is form DQN or NVS and Netshare. bcz only DQN uses the neural network but the other algoriths does not need the neural network print( 'this will not be used for training becuase it is from NVS or NetShare' ) v = self.v elif self.ii == 1: # initially user random action or use the whole reservation # becuase you have not state information and allocation a1 = 1 #randi([-9 10],1,1)/10 v = BS.update_AL_pro(np.zeros((1, B)), self.RE1, P1, a1) Reservation.UpdateUnusedResource(self.s1, v, np.array( [0])) # send resource update to the base stations elif self.ii > 1: # use the neural network for dynamic resource management a1 = RL.choose_action([ sum(self.AL1 * P1), sum(self.du) / K1a, sum(self.ru) / K1a, sum(self.RE1 * P1) ]) v = BS.update_AL_pro(self.AL1, self.RE1, P1, a1) Reservation.UpdateUnusedResource(self.s1, v, np.array( [0])) # send resource update to the base stations if np.sum( v ) == 0: # if resource for the slice is 0, the allocation to users is also 0 d1 = -1 * np.ones((1, np.array(self.rt).shape[0])) r1 = np.zeros(np.array(self.rt).shape[0], 1) else: # ADMM rrr = self.rt y = Delay_ADMM_Alloc.ADMM_Alloc(v, self.ar, self.rt, self.Dc) rt = rrr yR = y * rt # sum rate of users r1 = np.sum(yR, axis=1) # delay of the users d1 = -1 * np.ones((1, K1a)) for i in range(0, K1a): d1[0, i] = 1 / (r1[i] - self.ar[0, i]) delay = d1 #show the delay min_max_D = [ min(d1), max(d1) ] # show the minimum delay and the maximum delay out of all the users of the slice #calculate new resource utilization and QoS utility of next state #cululate delay utility for delay 100 ms upper bound dd = d1 * 1000 #change to ms ndu = np.zeros((1, K1a)) nru = np.zeros((1, K1a)) for uk1 in range(0, K1a): if dd[0, uk1] < 0 or dd[0, uk1] > self.Dc[0, uk1] * 1000: ndu[0, uk1] = 0 nru[0, uk1] = 0 else: ndu[0, uk1] = -0.5 * np.tanh(0.06 * (dd[0, uk1] - 70)) + 0.5 nru[0, uk1] = min(1, (self.ar[0, uk1] + 1 / self.Dc[0, uk1]) / r1[uk1]) du = ndu ru = nru return P1, du, ru, v, a1, d1
def initial_VR2(rtV, Q, rtV2, Q2): print('filtering feasiblity of user demands, removes if not feasible...\n') #initial virtual resource allocation of the slice in the base stations _, un = Reservation.getUnusedResourceAndNumOfSlices() [K, B] = np.array(rtV).shape [K2, B2] = np.array(rtV2).shape qyu = np.zeros((K, B)) for i in range(0, K): for j in range(0, B): qyu[i, j] = Q[0, i] / rtV[ i, j] # how much fractions is required by the users in each bs assuming single user base station associations qyu2 = np.zeros((K2, B2)) for i in range(0, K2): for j in range(0, B2): qyu2[i, j] = Q2[0, i] / rtV2[ i, j] # how much fractions is required by the users in each bs assuming single user base station associations #calculate the resource requitement of the slice in the BSs assumig every user is admitted sequencially as they come to the nearest BS VR = np.zeros((1, B)) VR2 = np.zeros((1, B2)) accepF = np.zeros((1, K)) #how much percent of the user is accepted copyr = rtV accepF2 = np.zeros((1, K2)) #how much percent of the user is accepted copyr2 = rtV2 wh = 0 while wh <= K * B + K2 * B2: maxr1 = copyr.max() # the smallest user bs distance combination maxr2 = copyr2.max( ) # the smallest user bs distance combination for i=1:1:K if maxr1 > maxr2: maxr = maxr1 for i in range(0, K): for m in range(0, B): if copyr[i, m] == maxr and ( accepF[0, i] + 1 ) != 2: # plus one is used to ignore very small fraction if un[0, m] >= qyu[i, m] * (1 - accepF[0, i]) and qyu[ i, m] > 0 and un[0, m] > 0: VR[0, m] = VR[0, m] + qyu[i, m] * (1 - accepF[0, i]) un[0, m] = un[0, m] - qyu[i, m] * (1 - accepF[0, i]) accepF[0, i] = 1 elif un[0, m] < qyu[i, m] * (1 - accepF[0, i]) and qyu[ i, m] > 0 and un[0, m] > 0: VR[0, m] = VR[0, m] + un[0, m] un[0, m] = 0 accepF[0, i] = accepF[ 0, i] + un[0, m] / (qyu[i, m] * (1 - accepF[0, i])) copyr[i, m] = 0 else: maxr = maxr2 for i in range(0, K2): for m in range(0, B2): if copyr2[i, m] == maxr and ( accepF2[0, i] + 1 ) != 2: # plus one is used to ignore very small fraction if un[0, m] >= qyu2[i, m] * (1 - accepF2[0, i]) and qyu2[ i, m] > 0 and un[0, m] > 0: VR2[0, m] = VR2[0, m] + qyu2[i, m] * (1 - accepF2[0, i]) un[0, m] = un[0, m] - qyu2[i, m] * (1 - accepF2[0, i]) accepF2[0, i] = 1 elif un[0, m] < qyu2[i, m] * (1 - accepF2[0, i]) and qyu2[ i, m] > 0 and un[0, m] > 0: VR2[0, m] = VR2[0, m] + un[0, m] un[0, m] = 0 accepF2[0, i] = accepF2[ 0, i] + un[0, m] / (qyu2[i, m] * (1 - accepF2[0, i])) copyr2[i, m] = 0 if (copyr.max() == 0 and copyr2.max() == 0) or (accepF.min() == 1 and accepF2.min() == 1): break wh = wh + 1 accept = np.floor(accepF) accept2 = np.floor(accepF2) if np.sum(accept ) >= 1: # check if there is at leasst one user fully accepted S, _ = Reservation.getUnusedResourceAndNumOfSlices() res = S + 1 V = VR RQ = np.zeros((1, B)) Reservation.initialization(res, np.zeros((1, B)), RQ) else: res = 0 # reject the slice. no enouph resource V = np.zeros((1, B)) if np.sum(accept2 ) >= 1: # check if there is at leasst one user fully accepted S, _ = Reservation.getUnusedResourceAndNumOfSlices() res2 = S + 1 V2 = VR2 RQ2 = np.zeros((1, B)) Reservation.initialization(res2, np.zeros((1, B)), RQ2) else: res2 = 0 # reject the slice. no enouph resource V2 = np.zeros((1, B)) return res, V, accept, res2, V2, accept2
def reservations(): return render_template('reservations.html', hotel_list=Reservation.find_room(conn))
from datetime import date, time from Reservation import Location, Reservation reservation = Reservation({ 'location': Location.HL15, 'username': '', 'password': '' }) reservation.book(date(2019, 8, 21), 5, time(hour=14, minute=30), time(hour=2))
def run(): RL1 = DQNd( n_actions=20, n_features=4, # number of observation(state) learning_rate=0.01, e_greedy=0.4, replace_target_iter=300, memory_size=10000, batch_size=1000, e_greedy_increment=None, reward_decay=0.9) RL2 = DQNd( n_actions=20, n_features=4, # number of observation(state) learning_rate=0.01, e_greedy=0.4, replace_target_iter=300, memory_size=10000, batch_size=1000, e_greedy_increment=None, reward_decay=0.9) for T in range(0, 100000): ''' s1r a vector of achievable data rate of users of slice1 s1Q is a vector of minimum QoS requirements of users of slice1 s1ar is a vector of arrival rates of users of slice1, a vector of priorities of the base stations to slice1 du is a vector of delay utilities of uses of slice1, ru is a vector of resource utilizations of users of slice1. (the same goes for slice2) ''' max_users = np.random.randint(10, 600) # generate random users s1r, s1Q, s1ar, P1, du, ru = Slice1.initSlice( max_users ) # generating random users and and creating the network for slice1 RL1.learn() s2r, s2Q, s2ar, P2, rtu, rsu = Slice2.initSlice(max_users) RL2.learn() #checking feasile users [S1, V, accept, S2, V2, accept2] = initial_VR2(s1r, s1ar + 1 / s1Q, s2r, s2Q) # filter users that cant be satisfied # S1 is ID of slice 1, v is a vector of fractions that is occupied in # the checking but not used here, accept is a vector showing whether # the corresponding users are accepted or not 1 means accepted 0 means # not accepted, THE SAME GOES FOR SLCIE2 if S1 > 0 and S2 > 0: # removing the users that are not in range [K1, B] = np.array(s1r).shape tr = np.zeros((K1, B)) for k in range(0, K1): for b in range(0, B): tr[k, b] = s1r[k, b] * accept[ 0, k] # if accept(1,k)=1 the users rate is saved, else it is set to zero rt = tr rt = rt[~(rt == 0).all(1)] # remove the users with zero rate Dc = s1Q * accept # if user not accepted set its delay constraint to zero for removing Dc = np.delete( Dc, np.argwhere(np.all(Dc[..., :] == 0, axis=0)), axis=1 ) #Dc=Dc[0,any(Dc,1)]# removing the delay constrained of the users removed above ar = s1ar * accept # remove the arrival rate of the removed users ar = np.delete(ar, np.argwhere(np.all(ar[..., :] == 0, axis=0)), axis=1) #ar=ar[0,any(ar,1)] K1a = np.array(rt).shape[0] # accepted users of k1 print('#d of #d users of slice1 accepted\n', K1a, K1) [K2, B] = np.array(s2r).shape tr2 = np.zeros((K2, B)) # the same steps for slice2 for k in range(0, K2): for b in range(0, B): tr2[k, b] = s2r[k, b] * accept2[0, k] rt2 = tr2 rt2 = rt2[~(rt2 == 0).all(1)] Rc = s2Q * accept2 Rc = np.delete(Rc, np.argwhere(np.all(Rc[..., :] == 0, axis=0)), axis=1) # Rc=Rc(1, any(Rc,1)) ar2 = s2ar * accept2 ar2 = np.delete(ar2, np.argwhere(np.all(ar2[..., :] == 0, axis=0)), axis=1) #ar2=ar2(1,any(ar2,1)) K2a = np.array(rt2).shape[0] # accepted users of k1 print('#d of #d users of slice2 accepted\n', K2a, K2) cng1 = 0 cng2 = 0 # to calculate the resource requirements and priorities of the slice1 Pu1 = np.zeros( (K1a, B) ) # minimum data link requirement of each user in each base station for u in range(0, K1a): Pu1[u, :] = (ar[0, u] + 1 / Dc[0, u]) * ( rt[u, :] / sum(rt[u, :])) #equation12 and 13 Puu1 = np.sum(Pu1, axis=0) #求矩阵列和 P1 = np.zeros((1, B)) for bp2 in range(0, B): P1[0, bp2] = Puu1[bp2] / sum( Puu1 ) # priority or importance of the base stations to slice1 Reservation.UpdateUnusedResource( S1, np.zeros((1, B)), Puu1 ) # minimim resource requirement os the slice1 on the base stations d1 = -1 # if resource is zero delay must be initialized out of the delay range for convenience of calculating utility cdu = 0 # current delay utility initialization cru = 0 # current resource utilization of slice1 # to calculate the resource requirements and priorities of the slice2 Pu2 = np.zeros( (K2a, B) ) # minimum resource requirement of each user of slice2 in each base station for u in range(0, K2a): Pu2[u, :] = (Rc[0, u]) * (rt2[u, :] / sum(rt2[u, :]) ) #equation12 and 13 Puu2 = np.sum(Pu2, axis=0) #求矩阵列和 P2 = np.zeros((1, B)) for bp2 in range(0, B): P2[0, bp2] = Puu2[bp2] / sum( Puu2 ) # priority or importance of the base stations to slice2 Reservation.UpdateUnusedResource( S2, np.zeros((1, B)), Puu2 ) # minimim resource requirement os the slice2 on the base stations r2 = 0 # data rate of slice2 crtu = 0 # current rate utility of slice2 crsu = 0 # current resource utilizatin of slice2 xtrn = np.random.randint( 4, 10) # to decide at how many time intervals to train for ii in range(0, 50): # V and V2 are useless here _, _, AL1, RE1 = Reservation.sendCurrAllocAndReservOfSlice( 1 ) # request allocation and reservation of slice 1 from all base stations _, _, AL2, RE2 = Reservation.sendCurrAllocAndReservOfSlice( 2) #............slice2.... P1, du, ru, v, a1, d1 = Slice1( S1, V, P1, ii, rt, Dc, ar, cdu, cru, cng1, AL1, RE1).makeResourceManagement( ) # MAKE AUTONOMOUS RESOURCE MANAGEMENT IN SLICE1 P2, rtu, rsu, v2, a2, r2 = Slice2( S2, V2, P2, ii, rt2, Rc, ar2, crtu, crsu, cng2, AL2, RE2).makeResourceManagement( ) # MAKE AUTOMOUS RESOURCE MANAGEMET IN SLICE2 # P1 avector importance of the base stations to slice1, # du delay utility vector of the users of slice1, # ru resource utility vector of the users of slice1, v the resource updated by the action in # slice1, a1 the action of slice1, # d1 the delay vector for users of slice1, s1 is ID of slice1, V is use less here, # ii is the current iteration of slicing time, # rt is the data rate matrix for all users of slice one in all base stations, # Dc is delay constraint of slice1, # ar is arrival rate of slic1, cdu is currrent delay utility, # cru is current resouce utility, # AL1 is the previous resource allocation vector of slice1, # RE1 is the current resource reservation vector of slice1 in all base stations. # the same goes for slice2... # r2 is the rate vector of the users of slice2 K1a = np.array(rt).shape[0] K2a = np.array(rt2).shape[0] if ii > 1: # if the iteration is not initial calculate the reward functions and call the DQN for trdaining, and increament the number of users at an interval of three iterations trn = 0 #if a condition to trian IS ACTIVATED TRAIN THE ANN if np.mod(ii, xtrn) == 0: trn = 1 #calculate reward of slice1 rw1 = ( sum(du[0, 0:K1a]) / K1a + 9. * sum(ru[0, 0:K1a]) / K1a ) / 10 # priority is given to the resource utility than the qos utility #calculate the current state tuple of slice 1 cs1 = [ sum(AL1 * P1), sum(cdu) / K1a, sum(cru) / K1a, sum(RE1 * P1) ] RL1.store_transition( cs1, a1, rw1, trn) # send the tuple to reply memory of #slice 1 for training #calculate reward of slice2 rw2 = ( sum(rtu[0, 0:K2a]) / K2a + 9. * sum(rsu[0, 0:K2a]) / K2a ) / 10 # priority is given to the resource utility than qos utility #calculate the current state tuple of slice 1 cs2 = [ sum(AL2 * P2), sum(crtu) / K2a, sum(crsu) / K2a, sum(RE2 * P2) ] RL2.store_transition( cs2, a2, rw2, trn) # send the tuple to reply memory of #slice 2 for training #copy the next states crtu = rtu crsu = rsu else: # save the calculated QOS utilities and resource utilizations # as current states cdu = du cru = ru crtu = rtu crsu = rsu cng1 = 0 cng2 = 0 else: print('one or both of the slices not accepted') Slice1.removeSliceFromResourceTable( S1) # remove slice 1 from resource table Slice2.removeSliceFromResourceTable( S2) # remove slice2 from resource table
def Reservation_to_table(Reservation): # Reservation -> List ReservationTable=(Reservation.get_Reservation_id(),Reservation.get_user_id(),Reservation.get_Jeu_id(),Reservation.get_Exemplaire_id(),Reservation.get_date_Reservation()) return ReservationTable
"The room is already reserved at that day. Try another date (DD.MM.YYYY): " ) else: break except: reserve_date = input( "Please enter valid date format (DD.MM.YYYY): ") reserve_guest = input("What is the guest's name: ") while True: if reserve_guest == "" or len(reserve_guest) < 2: reserve_date = input("Please type a valid name: ") else: reservations.append( Reservation( reserve_room_number, datetime.strptime(reserve_date, '%d.%m.%Y'), reserve_guest)) write_reservations(reservations) print('Room reserved successfully\n\n') break #show unoccupied rooms elif val == "3": unocc_date = input("Which date would you like to see? : ") while True: try: unocc_date = datetime.strptime(unocc_date, '%d.%m.%Y') for room in rooms: reserved = False for reservation in reservations:
def Ajouter_Reservation(Reservation): #Ajouter_Reservation : Reservation x Utilisateur x EnsReservation -> EnsReservation if (not(Reservation_EnCours(User))): try: cur.execute=(""" INSERT INTO EnsReservation(Reservation_id, Jeu_id, user_id, Exemplaire_id, date_Reservation) VALUES(?, ?, ?, ?, ?) """, (Reservation.get_Reservation_id(), Reservation.get_Jeu_id(), Reservation.get_user_id(), Extension.get_date_Reservation() )) conn.commit() print(" Reservation ajoutée !") except: print ("Erreur lors de l'ajout d'une reservation") else: print ("Une reservation est deja en cours " )
def make_reservation(self, restaurant, time, party_size): res = Reservation(self, time, party_size) restaurant.take_reservation(res) return res
def Reservation_EnCours(User) : cur.execute=(""" SELECT user_id FROM EnsReservation WHERE user_id = ? """, (Reservation.get_user_id())) result=cur.fetchone() return result != None
def reserve(self, patron_id): self.reservation = Reservation(patron_id, self.qr_code)