Example #1
0
    def createRestaurants(self):
        #10 Rests
        fullRestaurants = []

        fullRestaurants.append(
            Restaurant(RestaurantFeed[0], [FoodType.Indian.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[1], [FoodType.Chinese.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[2], [FoodType.Mexican.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[3], [FoodType.Italian.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[4], [FoodType.American.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[5],
                       [FoodType.Mexican.name, FoodType.Italian.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[6],
                       [FoodType.Chinese.name, FoodType.Italian.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[7],
                       [FoodType.Indian.name, FoodType.Chinese.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[8],
                       [FoodType.Chinese.name, FoodType.American.name]))
        fullRestaurants.append(
            Restaurant(RestaurantFeed[9],
                       [FoodType.Chinese.name, FoodType.Mexican.name]))
        return fullRestaurants
Example #2
0
def main(access_port, no_clients, timeout,ft=0, r = 0):
    # logger for the main
    logger = logging.getLogger('Token Ring')

    first_entity = 0
    if r == 1:
        first_entity = ft
    # initial node (Restaurant)
    restaurant_node = Restaurant(5000 + first_entity,4,3)
    restaurant_node.start()
    
    # Clerk
    clerk_node = Clerk(5000 + first_entity,4,3)
    clerk_node.start()

    # Chef
    chef_node_1 = Chef(5000 + first_entity, 4,3)
    #chef_node_2 = Chef(5000 + first_entity, 5, 3, 5004, 4)

    chef_node_1.start()
    #chef_node_2.start()
    
    # Waiter
    waiter_node=Waiter(5000 + first_entity, 4, 3)
    waiter_node.start()
Example #3
0
class RestaurantSimulation(object):

    def __init__(self):

        tableDefinition = [[5, 2], [1, 4]]
        
        self.restaurant = Restaurant(tableDefinition)


    def simulate(self):

        id = 1
        while(True):
            #randomly add new party 
            if id < 10 and random.random() < 0.3:
                peopleCount = random.randint(MIN_PEOPLE_COUNT, MAX_PEOPLE_COUNT)
                party = Party(peopleCount, id)
                id += 1     
                self.restaurant.waitingParties.append(party)
            self.restaurant.timeUpdate()
            time.sleep(1)
            if id == 10 and len(self.restaurant.waitingParties) == 0 and len(self.restaurant.eatingParties) == 0:
                return
            #Visualization
                            
    def addToLine(self):
        return True
Example #4
0
    def test_get_restaurantsA(self):
        restaurant1 = Restaurant("Friendly's", "American", 20, 10, 20)
        restaurant2 = Restaurant("Denny's", "Diner", 15, 7, 1)

        restaurantsInArea = RestaurantsInArea([restaurant1, restaurant2])

        assert restaurantsInArea.get_restaurants() == [
            restaurant1, restaurant2
        ], "get_restaurants test failed"
Example #5
0
    def test_find_restaurant_genreB(self):
        restaurant1 = Restaurant("Friendly's", "Diner", 20, 10, 20)
        restaurant2 = Restaurant("Denny's", "Diner", 15, 7, 1)
        restaurant3 = Restaurant("Sabai Sabai", "Thai", 203, 11, 22)

        restaurantsInArea = RestaurantsInArea(
            [restaurant1, restaurant2, restaurant3])

        assert restaurantsInArea.find_restaurant_genre(
            "Mexican") == [], "find_restaurant_genre test failed"
Example #6
0
    def test_find_restaurant_nameB(self):
        restaurant1 = Restaurant("Friendly's", "American", 20, 10, 20)
        restaurant2 = Restaurant("Denny's", "Diner", 15, 7, 1)
        restaurant3 = Restaurant("Sabai Sabai", "Thai", 203, 11, 22)

        restaurantsInArea = RestaurantsInArea(
            [restaurant1, restaurant2, restaurant3])

        assert restaurantsInArea.find_restaurant_name(
            "Smorgasbord") == False, "find_restaurant_name test failed"
Example #7
0
    def test_add_restaurantA(self):
        restaurant1 = Restaurant("Friendly's", "American", 20, 10, 20)
        restaurant2 = Restaurant("Denny's", "Diner", 15, 7, 1)
        restaurant3 = Restaurant("Sabai Sabai", "Thai", 203, 11, 22)

        restaurantsInArea = RestaurantsInArea([restaurant1, restaurant2])

        restaurantsInArea.add_restaurant(restaurant3)
        assert restaurantsInArea.get_restaurants(
        )[2] == restaurant3, "add_restaurant test failed"
Example #8
0
def add_restaurant(rest_dict, rest_name, rest_id, msg):
    restaurant = Restaurant(name=rest_name, id=rest_id)
    timestamp_str = msg['ts']
    timestamp_int = int(float(timestamp_str))

    if rest_dict.__contains__(restaurant):
        rest_dict[restaurant].add_time(timestamp_int)
    else:
        restaurant.add_time(timestamp_int)
        rest_dict[restaurant] = restaurant
Example #9
0
    def test_has_seatsB(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")

        self.assertEqual(restaurant.has_seats(50), False)
Example #10
0
def restaurant():

    while True:

        ship_restaurant = input('''Elija el restaurante de un barco:

        1. Agregar al Menu
        2. Eliminar del Menu
        3. Modificar el Menu
        4. Agregar al Menu de Combos
        5. Eliminar del Menu de Combos
        6. Buscar Producto por Nombre 
        7. Buscar Combos por Nombre 
        8. Regresar a la pantalla principal
        
        Ingrese la opcion de su preferencia >>> ''')
        print()

        rest = Restaurant(ship_restaurant)

        if ship_restaurant == '1' or ship_restaurant == '2' or ship_restaurant == '3':
            rest.menu_op123()
        elif ship_restaurant == '4' or ship_restaurant == '5':
            rest.combo_op45()
        elif ship_restaurant == '6' or ship_restaurant == '7':
            rest.search67()
        else:
            break
    def setUp(self):
        self.server_obj = Server("Lisa", False)
        #create table object to test functionality
        self.table_obj = Table(6, "W", True)
        self.table_obj2 = Table(4, "N", True)
        #Create customer object ti test Functionality
        self.customer_obj = Customer("Jim", 6, "B", True, False, False)
        self.customer_obj2 = Customer("Joe", 4, "W", True, False, False)


        self.restaurant1 = Restaurant()
        self.restaurant2 = Restaurant()

        self.seating1 = Seating(self.server_obj, self.customer_obj, self.table_obj, 'W')
        self.seating2 = Seating(self.server_obj, self.customer_obj2, self.table_obj2, 'N')
Example #12
0
    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)
Example #13
0
def main(ip, port):
    logger = logging.getLogger('Drive-through')

    logger.info('Setup ZMQ')
    context = zmq.Context()
    restaurant = Restaurant()

    # frontend for clients (socket type Router)
    frontend = context.socket(zmq.ROUTER)
    frontend.bind("tcp://{}:{}".format(ip, port))

    # backend for workers (socket type Dealer)
    backend = context.socket(zmq.DEALER)
    backend.bind("inproc://backend")

    # Setup workers
    workers = []
    for i in range(4):
        # each worker is a different thread
        worker = Worker(context, i, "inproc://backend", restaurant)
        worker.start()
        workers.append(worker)

    # Setup proxy
    # This device (already implemented in ZMQ) connects the backend with the frontend
    zmq.proxy(frontend, backend)

    # join all the workers
    for w in workers:
        w.join()

    # close all the connections
    frontend.close()
    backend.close()
    context.term()
Example #14
0
def handle_message(event):
    global sum, orderRequest, pushRequest, ordering, orderCalled, wait4input
    message = ''
    msg = event.message.text

    if wait4input == True:
        if 'c' == msg:
            ordering = False
            wait4input = False
            quitMessage = '結束點單,總價為:  ' + str(sum) + ' 元'
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=quitMessage))
            sum = 0
            orderRequest.clear()
        else:
            splStr = msg.split(' ')
            if len(splStr) == 3:
                items = splStr[0] + splStr[2]
                sum = sum + int(splStr[1]) * int(splStr[2])
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text='收到'))
            else:
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text='格式錯誤,請再試一次'))
        return

    if ordering == True:
        if time.time() - orderCalled > 600:
            ordering = False
            wait4input = False
        elif msg in restaurantName:
            orderRequest.append(
                Restaurant(event.source.user_id, jdata,
                           restaurantName.index(msg)))
            pushRequest.append(orderRequest[-1])
            getOrder(line_bot_api, event.reply_token, msg)
            wait4input = True
            return

    if 'RELOAD' == msg:
        loadGAS(jdata['Gas']['Get'][0]['baseExcel'])
        loadShop(jdata['Gas']['Get'][1]['baseExcel'])
    elif '點餐' in msg:
        message = order()
        ordering = True
        orderCalled = time.time()
    elif msg in reactDict:
        message = TextSendMessage(text=reactDict.get(msg))
    elif 'setKey;' in msg:
        splitStr = msg.split(';')
        if len(splitStr) == 3:
            payload = {
                'DATE': time.strftime("%Y-%m-%d", time.localtime()),
                'NAME': splitStr[1],
                'VALUE': splitStr[2]
            }
            sendDataToGoogleSheet(jdata['Gas']['Get'][0]['baseExcel'], payload)
    # 回復訊息
    if message != '':
        line_bot_api.reply_message(event.reply_token, message)
Example #15
0
    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 test_check_availability_is_avail_bad(self):
     server1 = Server("Lisa", False)
     server2 = Server("Bob", False)
     server3 = Server("Joe", False)
     server4 = Server("Kate", False)
     server5 = Server("John", False)
     servers = [server1, server2, server3, server4, server5]
     table1 = Table(4, "W", True)
     table2 = Table(10, "B", True)
     table3 = Table(4, "N", True)
     table4 = Table(4, "N", True)
     table5 = Table(2, "W", True)
     table6 = Table(6, "N", True)
     table7 = Table(3, "O", True)
     table8 = Table(2, "N", True)
     table9 = Table(12, "O", True)
     table10 = Table(2, "N", True)
     tables = [table1, table2, table3, table4, table5, table6, table7, table8, table9, table10]
     restaurant1 = Restaurant(servers, tables)
     self.assertTrue(restaurant1.check_availability_bad(self.customer_obj))
Example #17
0
 def simulateOnce(self, tableDefinition):
     restaurant = Restaurant(tableDefinition)
     restaurant.sittingMethod = self.sittingMethod
     id = 1
     timer = 0
     while(timer < 180):
         #randomly add new party
         # this simulates rush hours of the getting a new party every minute 
         if random.random() < 1:              
             peopleCount = self.getRandomPartyCount()
             party = Party(peopleCount, id)
             id += 1                     
             restaurant.waitingParties.append(party)
         timer += 1
         
         # Please uncomment for animation of the simulation 
         #V.plotRestaurant(restaurant)
         restaurant.timeUpdate()
                    
     return restaurant
Example #18
0
def search_restaurants(URL, KEY_ID, freeword, hit_per_page=3):
    response = requests.get(URL,
                            params={
                                "keyid": KEY_ID,
                                "freeword": freeword,
                                "hit_per_page": hit_per_page
                            })
    rests = response.json()["rest"]
    for rest in rests:
        yield Restaurant(name=rest["name"],
                         url=rest["url"],
                         access=rest["access"])
Example #19
0
    def test_make_reservation(self):
        name = "Brian"
        phone_number = "(802)555-1234"

        customer = Customer(name, phone_number)

        restaurant = Restaurant("Tapas", "mexican", 7, 11, 17)

        res = customer.make_reservation(restaurant, 15, 7)
        self.assertEqual(res.customer.name, "Brian")
        self.assertEqual(res.time, 15)
        self.assertEqual(res.party_size, 7)
Example #20
0
def convert_input_to_restaurant(line):
    '''
    Parse the Yelp input data to create a Restaurant object.
    '''
    m = line.strip().split("|")
    name = m[0]
    latitude = float(m[1])
    longitude = float(m[2])
    address = m[3].split('+')  # creates a list of the address lines
    url = m[4]
    restaurant_type = m[5]
    reviews = []
    for r in m[6:]:
        reviews.append(int(r))
    return Restaurant(name, latitude, longitude, address, url, \
                          restaurant_type, reviews )
    def __init__(self, FEL):

        self.restaurants = {
            'a': Restaurant(),
            'b': Restaurant(),
            'c': Restaurant(),
            'd': Restaurant(),
            'e': Restaurant(),
            'f': Restaurant(),
            'g': Restaurant(),
            'drinks': Restaurant(availability=2)
        }
        self.be4 = deque()
        self.pay = Pay(num_of_checkout_lines=8)
        self.FEL = FEL
        self.poisson_mean = 4
        self.be4_capacity = 50
        self.customers = []

        self.debug = 1
Example #22
0
def main():

    restaurant = Restaurant()
    waiter = Receptionist()
    chef = Chef()
    clerk = Employee()

    restaurant.start()
    waiter.start()
    chef.start()
    clerk.start()

    restaurant.join()
    waiter.join()
    chef.join()
    clerk.join()

    return 0
Example #23
0
def main():

    restaurant = Restaurant()
    waiter = Waiter()
    chef = Chef()
    recep = Receptionist()

    restaurant.start()
    waiter.start()
    chef.start()
    recep.start()

    restaurant.join()
    waiter.join()
    chef.join()
    recep.join()

    return 0
def main():

    restaurant = Restaurant()
    waiter = Waiter()
    chef = Chef()
    clerk = Clerk()

    restaurant.start()
    waiter.start()
    chef.start()
    clerk.start()

    restaurant.join()
    waiter.join()
    chef.join()
    clerk.join()

    return 0
def main():

    restaurant = Restaurant(ringSize=4)
    waiter = Waiter(ringSize=4)
    chef = Chef(ringSize=4)
    clerk = Clerk(ringSize=4)

    restaurant.start()
    waiter.start()
    chef.start()
    clerk.start()

    restaurant.join()
    waiter.join()
    chef.join()
    clerk.join()

    return 0
def main():

    restaurant = Restaurant()
    waiter = Waiter()
    chef = Chef()
    clerk = Clerk()

    # O start vai a cada entidade e vai inciar uma thread
    restaurant.start()
    waiter.start()
    chef.start()
    clerk.start()

    restaurant.join()
    waiter.join()
    chef.join()
    clerk.join()

    return 0
def main():
    print("Welcome to the NYC Restaurant Generator!")
    print(
        "Let's find a restaurant in New York City that is perfectly matched to your tastes."
    )

    user = User(
        "", 0, "", "", ""
    )  # Initialize a user object. The attributes will be updated once the
    # user inputs their information
    newUserInput = input("Are you a (1) new user or (2) returning user? ")
    while newUserInput.isdigit() == False:
        print("Please enter 1 or 2.")
        newUserInput = input("Are you a (1) new user or (2) returning user? ")
    while int(newUserInput) != 1 and int(newUserInput) != 2:
        print("Please enter 1 or 2.")
        newUserInput = input("Are you a (1) new user or (2) returning user? ")

    if int(newUserInput) == 1:  # User is a new user
        # Call the corresponding functions in the user class to obtain user preferences:
        usernameInput = User.getUserName(user)
        zipInput = User.getUserZip(user)
        genreInput = User.getUserGenre(user)
        priceInput = User.getPriceRange(user)
        featureInput = User.getFavQuality(user)

        # Write user preferences to the CSV File
        User.writeFile(user, usernameInput.lower(), zipInput,
                       genreInput.lower(), priceInput, featureInput)

        # Update the object attributes to user's preferences
        User.updateUser(user, usernameInput)

    elif int(newUserInput) == 2:  # User is a returning user
        returningUserName = input("Please enter your username: "******"Your username is not currently in our database. Please try again."
            )
            returningUserName = input("Please enter your username: "******"user_data.csv", index_col="username")
        userRowIndex = data.loc[returningUserName.lower()]
        userList = userRowIndex.tolist()

        print("Welcome back,", returningUserName.title())
        print("Here is your current profile: ")
        print("Username:"******"Zip Code:", str(userList[0]))
        print("Preferred Restaurant Type:", userList[1].title())
        print("Price Range:", userList[2])
        print("Preferred Feature:", userList[3])

        editInput = input("\nWould you like to edit your profile? (Y/N): ")

        while editInput.lower() != "y" and editInput.lower() != "n":
            print("Invalid input. Please enter Y or N.")
            editInput = input("Would you like to edit your profile? (Y/N): ")

        if editInput.lower() == "y":  # User wants to edit their information
            editContinue = True

            while editContinue == True:
                User.editUserInfo(
                    user, returningUserName
                )  # Run the function to correct ONE aspect of their profile
                User.updateUser(
                    user, returningUserName
                )  # Update attribute information in the User class
                print("Here is your updated profile: ")
                print(user)

                continueInput = input(
                    "Would you like to edit another feature? (Y/N) ")
                while continueInput.lower() != "y" and continueInput.lower(
                ) != "n":
                    print("Invalid input. Please enter Y or N.")
                    continueInput = input(
                        "Would you like to edit another feature? (Y/N) ")
                if continueInput.lower(
                ) == "n":  # user does not want to edit anything else
                    editContinue = False
                elif continueInput.lower(
                ) == "y":  # user wants to edit something else
                    editContinue = True

    continueChoice = True
    while continueChoice == True:
        # Generate the restaurant recommendation using functions in the Restaurant class
        restaurant = Restaurant(
            "", "", "", "", ""
        )  # Initialize the restaurant variable, which will be updated once
        # a restaurant is generated for the user.
        print(
            "\nWould you like a (1) randomly generated restaurant, or (2) a restaurant based off your preferences?"
        )
        randomRestaurantInput = input("> ")
        while randomRestaurantInput.isdigit() == False:
            print("Invalid input. Please enter 1 or 2.")
            print(
                "\nWould you like a (1) randomly generated restaurant, or (2) a restaurant based off your preferences?"
            )
            randomRestaurantInput = input("> ")
        while int(randomRestaurantInput) != 1 and int(
                randomRestaurantInput) != 2:
            print("Invalid input. Please enter 1 or 2.")
            print(
                "\nWould you like a (1) randomly generated restaurant, or (2) a restaurant based off your preferences?"
            )

        if int(randomRestaurantInput
               ) == 1:  # user wants a randomly generated restaurant
            # Randomly generate a restaurant name:
            restaurantName = Restaurant.generateRandomRestaurant(restaurant)

            # Using the restaurant name, retrieve the rest of the restaurant's information from the data
            Restaurant.getRestaurant(restaurant, restaurantName)

        elif int(
                randomRestaurantInput
        ) == 2:  # user wants a restaurant generated based on their preferences
            restaurantName = Restaurant.generateRecommendation(
                restaurant, user.zip_code, user.restaurant_type,
                user.price_range, user.preferred_feature)
            Restaurant.getRestaurant(restaurant, restaurantName)

        # Re-formats the restaurant description so it is not printed in one long line of code:
        Restaurant.getFormattedDesc(restaurant, restaurant.description)
        print("Here is your restaurant recommendation:")
        print(restaurant)

        continueInput = input(
            "\nWould you like to generate another recommendation? (Y/N): ")
        while continueInput.lower() != "y" and continueInput.lower() != "n":
            print("Invalid input. Please enter Y or N.")
            continueInput = input(
                "\nWould you like to generate another recommendation? (Y/N): ")
        if continueInput.lower() == "n":
            continueChoice = False

    print("\nThanks for using the NYC Restaurant Generator. Happy eating!")
Example #28
0
def main(number_nodes):
    # logger for the main
    logger = logging.getLogger('Restaurant')

    # list with all the nodes
    ring = []

    # socket
    tsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    tsocket.settimeout(3)

    # create Restaurant
    restaurant = Restaurant()
    restaurant.start()
    ring.append(restaurant)
    logger.info(restaurant)

    # create Cook
    cook = Cook()
    cook.start()
    ring.append(cook)
    logger.info(cook)

    # create Receptionist
    receptionist = Receptionist()
    receptionist.start()
    ring.append(receptionist)
    logger.info(receptionist)

    # create Employee
    employee = Employee()
    employee.start()
    ring.append(employee)
    logger.info(employee)

    #     # Await for DHT to get stable
    #     time.sleep(5)

    #     # Print the ring order for debug
    #     msg = { 'method' : 'PRINT_RING' }
    #     tsocket.sendto(pickle.dumps(msg), ('localhost', 5000))

    #     # Start building the table from the root node
    #     msg = { 'method' : 'NODE_DISCOVERY', 'args' : { 'table' : {} , 'rounds' : 0 } }
    #     tsocket.sendto(pickle.dumps(msg), ('localhost', 5000))

    #     # Await for DHT to get stable
    #     time.sleep(5)

    #     # Print the ring order for debug
    #     msg = { 'method' : 'PRINT_TABLE' }
    #     tsocket.sendto(pickle.dumps(msg), ('localhost', 5000))

    time.sleep(5)

    subprocess.run(['python3', 'client.py'], check=True)
    subprocess.run(['python3', 'client.py'], check=True)

    for node in ring:
        node.join()

    return 0
Example #29
0
from Restaurant import Restaurant

rest = Restaurant("billy joes", "ribs")

rest.open_restaurant()
Example #30
0
 def fetchMenuForRestaurant(self, restaurantID):
     restaurantObject = Restaurant(restaurantID, self.authorizationToken)
     data = restaurantObject.getMenuAndOtherRestaurantDetails()
     self.listMenuForSelectedRestaurant(data)
Example #31
0
def getReply(message):
    message = message.lower().strip()
    answer = ""

    if " " in message:
        msg_list = message.split(" ")

        curr_str = ""
        for i in range(len(msg_list) - 1):
            curr_str += msg_list[i] + "+"

        curr_str += "restaurants"
        max_num_returns = msg_list[-1]
        js_ = requests.get(
            "https://maps.googleapis.com/maps/api/place/textsearch/json?query="
            + curr_str + "&radius=5000&key=" + key).json()

        parse = []
        rate = {}
        rate_val = {}
        avg_rank = {}

        for restaurant in js_['results']:

            try:
                rating = restaurant['rating']
                open_ = restaurant['opening_hours']['open_now']
                name = restaurant['name']
                user_ratings_count = restaurant['user_ratings_total']

                if rating and name and user_ratings_count and int(
                        user_ratings_count):
                    curr = Restaurant(name, rating, user_ratings_count, open_)
                    parse.append(curr)

                if curr not in rate.keys():
                    rate[curr] = user_ratings_count

                if curr not in rate_val.keys():
                    rate_val[curr] = rating

            except:
                continue

        if rate and rate_val:
            sorted_rate = {
                k: v
                for k, v in sorted(
                    rate.items(), key=lambda item: item[1], reverse=True)
            }
            sorted_rate_val = {
                k: v
                for k, v in sorted(
                    rate_val.items(), key=lambda item: item[1], reverse=True)
            }

            max = len(list(sorted_rate.keys()))
            for score in range(len(list(sorted_rate.keys()))):
                avg_rank[list(sorted_rate.keys())[score]] = (max - score) / 4

            for rating in range(len(list(sorted_rate_val.keys()))):
                avg_rank[list(
                    sorted_rate_val.keys())[rating]] += (max - rating) / 2

            sorted_avg_rank = sorted(avg_rank.items(),
                                     key=lambda x: x[1],
                                     reverse=True)

            answer = ""
            for i in range(int(max_num_returns)):
                if i == len(sorted_avg_rank):
                    answer += '... (exceeded max results)'
                    break
                answer += str(i + 1) + ". "
                answer += str(sorted_avg_rank[i][0])
                answer += '\n\n'

    else:
        answer = "Please use the format: '[CITY] [STATE ABBREV] [MAX # RESULTS]' for example: 'Hanover NH 5'"

    if len(answer) > 1500:
        answer = answer[0:1500] + "..."

    return answer
from Restaurant import Restaurant


class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name, cuisine):
        super().__init__(restaurant_name, cuisine)
        self.flavour = []

    def describe_flavors(self, flavour):
        self.flavour = flavour
        print("Flavors are: " + str(self.flavour))


restaurant1 = Restaurant('chawla chicken', 'tangdi')

restaurant1.describe_restaurant()
restaurant1.customer_number()
restaurant1.set_number_served(20)
restaurant1.set_number_served(100)
restaurant1.customer_number()
restaurant1.increment_customer(10)
restaurant1.customer_number()

iceCreamStand = IceCreamStand('ice cream stand', 'ice cream')
iceCreamStand.describe_restaurant()
flav = ['choco', 'kicki', 'vanila']
iceCreamStand.describe_flavors(flav[::-1])



Example #33
0
    def __init__(self):

        tableDefinition = [[5, 2], [1, 4]]
        
        self.restaurant = Restaurant(tableDefinition)
Example #34
0
def main():
    address_old = 'localhost'
    port_old = 27017

    address_new = '192.168.6.254'
    port_new = 37017

    print("convert label type data")
    LabelType.insert_label_type(address_new, port_new)
    
    print("convert area data")
    Area.insert_area(address_old, port_old, address_new, port_new)

    print("convert label data")
    Label.convert_label(address_old, port_old, address_new, port_new)

    # 城市表 依赖新导入的Label表,需保证City前导入Label
    print("convert city data")
    City.convert_city(address_old, port_old, address_new, port_new)

    print("convert weather data")
    Weather.convert_weather(address_old, port_old, address_new, port_new,
                            Weather.collection_old, Weather.collection_new, Weather.params_map)
    
    # 特别注意  weather_history 表依赖于当前的 weather 表
    print("create weather_history data")
    WeatherHistory.create_weather_history(address_new, port_new, address_new, port_new,
                            WeatherHistory.collection_old, WeatherHistory.collection_new, WeatherHistory.params_map)

    print("convert pgc data")
    Pgc.convert_pgc(address_old, port_old, address_new, port_new)

    print("convert label data")
    Label.convert_label(address_old, port_old, address_new, port_new)

    print("convert attraction data")
    Attraction.convert_attraction(address_old, port_old, address_new, port_new,
                                  Attraction.collection_old, Attraction.collection_new, Attraction.params_map)

    print("convert restaurant data")
    Restaurant.convert_restaurant(address_old, port_old, address_new, port_new,
                                  Restaurant.collection_old, Restaurant.collection_new, Restaurant.params_map)

    print("convert shopping data")
    Shopping.convert_shopping(address_old, port_old, address_new, port_new,
                              Shopping.collection_old, Shopping.collection_new, Shopping.params_map)

    print("convert activity data")
    Activity.convert_activity(address_old, port_old, address_new, port_new,
                              Activity.collection_old, Activity.collection_new, Activity.params_map)

    print("convert recommendBynamic data")
#    RecommendDynamic.convert_recommendDynamic(address_old, port_old, address_new, port_new,RecommendDynamic.collection_old, 
#                               RecommendDynamic.collection_new, RecommendDynamic.params_map)

    print("convert plan data")
    Plan.convert_plan(address_old, port_old, address_new, port_new,
                      Plan.collection_old, Plan.collection_new, Plan.params_map)
    
    
    print("convert brand data")
    Brand.convert_brand(address_old, port_old, address_new, port_new,
                              Brand.collection_old, Brand.collection_new, Brand.params_map)
    print("OK")