def main(): print('Advent of Code 2015') highest_score = 0 with open('input.txt', 'r') as f: ingredients = parse_ingredients(f.readlines()) for perm in itertools.permutations(range(0, MAX_SPOONS), len(ingredients)): if sum(perm) == MAX_SPOONS: new_recipe = Recipe(ingredients, perm) score = new_recipe.get_score() calorie_count = new_recipe.get_calories() if calorie_count != CALORIES: continue if highest_score < score: print('recipe score: {}, calorie count: {}'.format( score, calorie_count)) print(new_recipe) highest_score = score print(highest_score)
class BookTest(unittest.TestCase): mozzarella = Recipe('mozzarella_sticks', 3, 20, ['mozzarella', 'sticks'], "", "starter") nugget = Recipe('nugget', 4, 65, ['chicken', 'bread'], "", "starter") omelette = Recipe('omelette au fromage', 2, 10, ['eggs', 'cheese', 'pepper'], "", "lunch") fondant = Recipe('fondant', 4, 30, ['eggs', 'chocolate', 'butter'], "", "dessert") creation = datetime.datetime(2019, 4, 13, 00, 00, 00) last = datetime.datetime(2019, 5, 27, 00, 00, 00) recipe_list = { 'starter': { mozzarella, nugget, }, 'lunch': { omelette, }, 'dessert': { fondant, } } test_book = Book("Text Book", last, creation, recipe_list) def test_get_recipe_by_type_method(self): gibberish_type = "blabla" integer_type = 123 with self.assertRaises(SystemExit): self.test_book.get_recipes_by_type(gibberish_type) self.test_book.get_recipes_by_type(integer_type) def test_get_recipe_by_name_method(self): non_existing_name = "blabla" int_name = 123 empty_name = "" with self.assertRaises(SystemExit): self.test_book.get_recipes_by_type(non_existing_name) self.test_book.get_recipes_by_type(int_name) self.test_book.get_recipes_by_type(empty_name) def test_add_recipe_method(self): non_recipe_object = "blabla" with self.assertRaises(SystemExit): self.test_book.add_recipe(non_recipe_object) def test_add_recipe_does_the_adding(self): recipe_to_add = Recipe('pasta', 1, 9, ['pasta', 'water'], "", 'lunch') self.test_book.add_recipe(recipe_to_add) type_of_added_recipe = recipe_to_add.recipe_type self.assertIn(recipe_to_add, self.test_book.recipes_list[type_of_added_recipe]) def test_add_recipe_method_update_time(self): recipe_to_add = Recipe('cheesecake', 5, 45, ['cheese', 'cake'], "", 'dessert') last_update1 = self.test_book.last_update self.test_book.add_recipe(recipe_to_add) self.test_book.print_content_recipe_list() last_update2 = self.test_book.last_update self.assertNotEqual(last_update1, last_update2)
def main(): parser = argparse.ArgumentParser( prog='plexlibrary', description=("This utility creates or maintains a Plex library " "based on a configuration recipe."), usage='%(prog)s [options] [<recipe>]', ) parser.add_argument('recipe', nargs='?', help='Create a library using this recipe') parser.add_argument( '-l', '--list-recipes', action='store_true', help='list available recipes') parser.add_argument( '-s', '--sort-only', action='store_true', help='only sort the library') if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() if args.list_recipes: list_recipes() sys.exit(0) if args.recipe not in recipes.get_recipes(): print("Error: No such recipe") list_recipes() sys.exit(1) r = Recipe(args.recipe) r.run(args.sort_only) print("Done!")
def make_request(params): '''Make a request to the Web API using the baseurl and params Parameters ---------- params: dict A dictionary of param:value pairs Returns ------- list the data returned from making the request in the form of a list ''' search_url = BASE_URL + "?q=" + params["q"] +\ "&app_id=" + API_ID + "&app_key=" + API_KEY +\ f"&cuisineType={params['cuisineType']}" response = requests.get(search_url).json() cache_list = [] for recipe_json in response['hits']: recipe = Recipe(recipe_json) cache_list.append(recipe.to_json()) return cache_list
def hint(self): """ Provides a hint about finding the root cause of this recipe """ print('Giving hint for recipe') Recipe._auth_cluster() external_ip_command = "kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}'" ip, error = Recipe._run_command(external_ip_command) ip = ip.decode("utf-8").replace("'", '') if not ip: print('No external IP found.') logging.error('No external IP found.') exit(1) print( 'Visit the external IP of the demo application to see if there are any visible changes: http://{}' .format(ip)) get_project_command = "gcloud config list --format value(core.project)" project_id, error = Recipe._run_command(get_project_command) project_id = project_id.decode("utf-8").replace('"', '') if not project_id: print('No project ID found.') logging.error('No project ID found.') exit(1) print( 'Use Monitoring Dashboards to see metrics associated with each service: https://console.cloud.google.com/monitoring/dashboards?project={}' .format(project_id)) print( 'Note: It may take up to 5 minutes for monitoring metrics to be updated' )
def test_recipe_as_selectable_from_yaml(self): """A recipe can be used as a selectable for a shelf created from yaml""" recipe = (Recipe( shelf=census_shelf, session=self.session).metrics("pop2000").dimensions("state")) yaml = """ pop: kind: Metric field: value: pop2000 aggregation: avg """ recipe_shelf = Shelf.from_yaml(yaml, recipe) r = Recipe(shelf=recipe_shelf, session=self.session).metrics("pop") assert (r.to_sql() == """SELECT avg(anon_1.pop2000) AS pop FROM (SELECT census.state AS state, sum(census.pop2000) AS pop2000 FROM census GROUP BY state) AS anon_1""") assert r.dataset.tsv == """pop\r\n3147355.0\r\n"""
def get(self): recname = "Fried Chicken" rec = Recipe(id=recname, name=recname, totalprice=8.50, totaltime=0.5, healthrating=2, notes="Don't cook on high heat!") rec_key = rec.put() ingred = Ingredient(parent=rec.key, id="Chicken", name="Chicken", price=2.50) ingred.put() ingred1 = Ingredient(parent=rec.key, id="Flour", name="Flour", price=0.10) ingred1.put() ##key = ndb.Key("Recipe", "Fried Chicken") ##key.delete() self.response.write("Data filled!")
def test_possible_recipes(shopkeeper): assert shopkeeper.possible_recipes() \ == {Recipe(quantity=1, name='Bandages', ingredient1='Linen Cloth', ingredient2='Linen Cloth'), Recipe(quantity=1, name='Fire Rag', ingredient1='Linen Cloth', ingredient2='Thick Oil'), Recipe(quantity=3, name='Bullet', ingredient1='Iron Scrap', ingredient2='Thick Oil')}
def parse(self, filename): recipe = Recipe() with open(filename, 'r') as filehandle: self.throwAwayHeaderLine(filehandle) reader = csv.reader(filehandle, dialect=dsv.DsvDialect) for line in reader: recipe.appendStep(self.parseline(line)) return recipe
def test_recipe_class_methods(self): self.assertItemsEqual( Recipe.all(), [recipe_1, recipe_2, recipe_3, recipe_4, recipe_5, recipe_6]) self.assertItemsEqual(Recipe.top_three(), [recipe_1, recipe_2, recipe_3]) self.assertItemsEqual(Recipe.bottom_three(), [recipe_4, recipe_2, recipe_3])
def getDirectionsFromRecipeWorks(): file = open("exrecipe.json", "r") data = json.loads(file.read()) recipe = Recipe(data) directions = Recipe.preprocessDirections(data['Directions']) assert recipe.getCurrentDirection() == directions[0]
def verify_broken_cause(self): """ Displays a multiple choice quiz to the user about the cause of the breakage and prompts the user for an answer """ prompt = 'What caused the breakage?' choices = ['failed connections to other services', 'high memory usage', 'high latency', 'dropped requests'] answer = 'high latency' Recipe._generate_multiple_choice(prompt, choices, answer)
def moveCursorRecipeWorks(): file = open("exrecipe.json", "r") data = json.loads(file.read()) recipe = Recipe(data) directions = Recipe.preprocessDirections(data['Directions']) assert recipe.goForward() == directions[1] assert recipe.goBack() == directions[0]
def test_recipe_name(self): """ Testing if assigning an incorrect name to a recipe raises a system exit""" empty_name = "" integer_name = 123 with self.assertRaises(SystemExit): recette = Recipe(empty_name, self.cook_level, self.cook_time, self.ingredient, self.descr, self.rcp_type) with self.assertRaises(SystemExit): recette_2 = Recipe(integer_name, self.cook_level, self.cook_time, self.ingredient, self.descr, self.rcp_type)
def verify_broken_service(self): """ Displays a multiple choice quiz to the user about which service broke and prompts the user for an answer """ prompt = 'Which service has a breakage?' choices = ['email service', 'frontend service', 'ad service', 'recommendation service', 'currency service'] answer = 'frontend service' Recipe._generate_multiple_choice(prompt, choices, answer)
def test_recipe_cook_level(self): """ Testing if assigning wrong cook level to a recipe raises a system exit""" off_range = 6 negative_range = -3 with self.assertRaises(SystemExit): recette = Recipe(self.name, off_range, self.cook_time, self.ingredient, self.descr, self.rcp_type) with self.assertRaises(SystemExit): recette_2 = Recipe(self.name, negative_range, self.cook_time, self.ingredient, self.descr, self.rcp_type)
def break_service(self): """ Rolls back the working version of the given service and deploys the broken version of the given service """ print("Deploying broken service...") Recipe._auth_cluster() self.deploy_state(True) print("Done") logging.info('Deployed broken service')
def test_field_with_add_float(self): yaml = """ addage: kind: Metric field: 'age + 1.24' """ shelf = Shelf.from_validated_yaml(yaml, MyTable) recipe = Recipe(shelf=shelf, session=self.session).metrics("addage") assert (" ".join(recipe.to_sql().split()) == "SELECT sum(foo.age + 1.24) AS addage FROM foo")
def restore_service(self): """ Rolls back the broken version of the given service and deploys the working version of the given service """ print('Deploying working service...') Recipe._auth_cluster() self._deploy_state(False) print('Done') logging.info('Deployed working service')
def parse(self, response): # Information from header includes title, author, cook time, difficulty, servings # and nutritional information header = response.xpath('//div[contains(@class, "recipe-header")]') recipe_title = header.xpath('h1[contains(@class, "recipe-header__title")]/text()') attrib = header.xpath('//div[contains(@class, "recipe-header__chef")]/span/a/text()') img = header.xpath('//img[contains(@itemprop, "image")]/@src') description = header.xpath('//div[contains(@class, "recipe-header__description")]//text()').get() time = { "prep": { 'hrs': header.xpath('//span[contains(@class, "recipe-details__cooking-time-prep")]/' 'span[contains(@class, "hrs")]/text()').get(), 'mins': header.xpath('//span[contains(@class, "recipe-details__cooking-time-prep")]/' 'span[contains(@class, "mins")]/text()').get(), }, "cook": { 'hrs': header.xpath('//span[contains(@class, "recipe-details__cooking-time-cook")]/' 'span[contains(@class, "hrs")]/text()').get(), 'mins': header.xpath('//span[contains(@class, "recipe-details__cooking-time-cook")]/' 'span[contains(@class, "mins")]/text()').get(), } } difficulty = header.xpath('//section[contains(@class, "recipe-details__item--skill-level")]' '/span[contains(@class, "recipe-details__text")]/text()').get() servings = header.xpath('//section[contains(@class, "recipe-details__item--servings")]' '/span[contains(@class, "recipe-details__text")]/text()').get() # Here we gather available nutritional info and build the Nutrition object nutrition_list = header.xpath('//ul[contains(@class, "nutrition")]') kcal = nutrition_list.xpath('//span[contains(@itemprop, "calories")]/text()').get() fat = nutrition_list.xpath('//span[contains(@itemprop, "fatContent")]/text()').get() sat_fats = nutrition_list.xpath('//span[contains(@itemprop, "saturatedFatContent")]/text()').get() carbs = nutrition_list.xpath('//span[contains(@itemprop, "carbohydrateContent")]/text()').get() sugars = nutrition_list.xpath('//span[contains(@itemprop, "sugarContent")]/text()').get() fibre = nutrition_list.xpath('//span[contains(@itemprop, "fiberContent")]/text()').get() protein = nutrition_list.xpath('//span[contains(@itemprop, "proteinContent")]/text()').get() salt = nutrition_list.xpath('//span[contains(@itemprop, "sodiumContent")]/text()').get() nutrition_object = Nutrition(kcal, fat, sat_fats, carbs, sugars, fibre, protein, salt) # Information from the details section includes ingredients and method details = response.xpath('//div[contains(@class, "responsive-tabs")]') # The full text of the ingredients will be in the content attribute of the li tag ingredients = details.xpath('section[contains(@id, "recipe-ingredients")]//' 'div[contains(@class, "ingredients-list__content")]/ul/li/@content') # TODO Check for final method step, sometimes the beeb offers a suggestion with a link to another recipe method = details.xpath('section[contains(@id, "recipe-method")]//' 'div[contains(@class, "method")]/ol/li/p/text()') recipe_object = Recipe(recipe_title.get(), attrib.get(), description, nutrition_object, ingredients.getall(), method.getall(), time, difficulty, servings, img.get()) # self, name, author, nutrition, ingredients, method return recipe_object.to_dict() pass
def add_cake(): """ create and print a cake recipe, checks if it works with empty recipes """ ingredients = ["chocolate", "flour", "sugar"] cake = Recipe("Cake", 2, 11, ingredients, "it's good", "dessert") new_dic = { "name": cake.name, "cooking_lvl": cake.cooking_lvl, "cooking_time": cake.cooking_time, "ingredients": cake.ingredients, "description": cake.description, "recipe_type": cake.recipe_type } ingredients = ["ice", "cream", "sugar"] icecream = Recipe("Ice-cream", 8, 11, ingredients, "it's good", "dessert") new_dic2 = { "name": icecream.name, "cooking_lvl": icecream.cooking_lvl, "cooking_time": icecream.cooking_time, "ingredients": icecream.ingredients, "description": icecream.description, "recipe_type": icecream.recipe_type } ingredients = ["vegetable", "cream"] soup = Recipe("Soup", 4, 15, ingredients, "it's good", "starter") new_dic3 = { "name": soup.name, "cooking_lvl": soup.cooking_lvl, "cooking_time": soup.cooking_time, "ingredients": soup.ingredients, "description": soup.description, "recipe_type": soup.recipe_type } ingredients = ["eggs", "salt"] omelet = Recipe("Omelet", 1, 5, ingredients, "it's good", "lunch") new_dic4 = { "name": omelet.name, "cooking_lvl": omelet.cooking_lvl, "cooking_time": omelet.cooking_time, "ingredients": omelet.ingredients, "description": omelet.description, "recipe_type": omelet.recipe_type } book = Book("Cookbook", datetime.datetime.today(), datetime.datetime.today()) # [cake.name] name of new entry book.recipes_list[cake.recipe_type][cake.name] = new_dic book.recipes_list[icecream.recipe_type][icecream.name] = new_dic2 book.recipes_list[soup.recipe_type][soup.name] = new_dic3 book.recipes_list[omelet.recipe_type][omelet.name] = new_dic4 return book
def main(): gateau = Recipe("Gateau", 2, 35, ['egg', 'foul'], 'dessert') tarte = Recipe("tarte", 2, 20, ['egg', 'lol'], 'dessert', "C'est une tarte aux fraises") cookbook = Book('cookbook') cookbook.add_recipe(gateau) cookbook.add_recipe(tarte) cookbook.get_recipe_by_name('Gateau') recipes = cookbook.get_recipe_by_types('dessert') for recipe in recipes: print(recipe)
def addRecipe(self, name): newRecipe = Recipe(name) newRecipe.name = name print("Add an ingredient and press enter. If finished type in '---' and enter") ingredient = "" while ingredient != "---": ingredient = input() if ingredient != "---": newRecipe.addIngredient(ingredient) self.recipes[newRecipe.name] = newRecipe
def test_delete(s3): Recipe(name="nachos", instructions="Melt cheese on chips").save() response = s3.list_objects_v2(Bucket=S3_BUCKET) assert len(response["Contents"]) == 1 assert response["Contents"][0]["Key"] == "nachos" Recipe.delete("nachos") # Data in S3 is gone after deleting the recipe response = s3.list_objects_v2(Bucket=S3_BUCKET) assert "Contents" not in response.keys()
def get_recipe_by_name(self, name): """Print a recipe with the name `name` and return the instance""" if name and isinstance(name, str) == True: for recipe in self.recipes_list: if recipe.name == name: Recipe.str(recipe) return (recipe) print( "The recipe name You are looking for doesn't exist in this list!" ) else: print("Please enter proper stringi name to search for!")
def test_cast(self): yaml = """ intage: kind: Metric field: value: age as: integer """ shelf = Shelf.from_validated_yaml(yaml, MyTable) recipe = Recipe(shelf=shelf, session=self.session).metrics("intage") assert (" ".join(recipe.to_sql().split()) == "SELECT CAST(sum(foo.age) AS INTEGER) AS intage FROM foo")
def verify_broken_cause(self): """ Displays a multiple choice quiz to the user about the cause of the breakage and prompts the user for an answer """ prompt = 'What was the cause of the break?' choices = [ 'high latency', 'internal service errors', 'failed connection to other services', 'memory quota exceeded' ] answer = 'internal service errors' Recipe._generate_multiple_choice(prompt, choices, answer)
def get(self): user_id = self.session.get('user_id') print user_id print 'ooooooooooooo' save_cache = Save_cache.get_by_id(DEFAULT_Save_Cache_NAME) if not save_cache: save_cache = Save_cache(id=DEFAULT_Save_Cache_NAME) user = User.get_by_id(user_id) my_recipes_list = [] recipe_query = Recipe.query(Recipe.author == user_id) my_recipes = recipe_query.fetch() for recipe in my_recipes: print recipe recipe_dict = {'photo':'http://placehold.it/700x400', 'name':recipe.name, 'tags':recipe.tags, 'id':str(recipe.key.id()), } if len(recipe.photos)>0: recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key) my_recipes_list.append(recipe_dict) favorite_recipes_list = [] for recipe_id in user.favorite_recipes: recipe = Recipe.get_by_id(long(recipe_id)) recipe_dict = {'photo':'http://placehold.it/700x400', 'name':recipe.name, 'tags':recipe.tags, 'id':str(recipe.key.id()), } if len(recipe.photos)>0: recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key) favorite_recipes_list.append(recipe_dict) wish_recipes_list = [] for recipe_id in user.wish_recipes: recipe = Recipe.get_by_id(long(recipe_id)) recipe_dict = {'photo':'http://placehold.it/700x400', 'name':recipe.name, 'tags':recipe.tags, 'id':str(recipe.key.id()), } if len(recipe.photos)>0: recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key) wish_recipes_list.append(recipe_dict) template = JINJA_ENVIRONMENT.get_template('template/recipebox_page.html') template_values = { 'my_recipes':my_recipes_list, 'favorite_recipes':favorite_recipes_list, 'wish_recipes':wish_recipes_list, 'keywords':json.dumps(save_cache.save_cache), } self.response.write(template.render(template_values))
def get_recipes_by_types(self, recipe_type): """Get all recipe names for a given recipe_type """ if recipe_type and isinstance(recipe_type, str) == True and recipe_type in [ "starter", "lunch", "dessert" ]: for recipe in self.recipes_list: if recipe.recipe_type == recipe_type: Recipe.str(recipe) else: print( "Please enter a proper string recipe_type in ['starter', 'lunch', 'dessert']" )
def test_coalesce(self): yaml = """ defaultage: kind: Metric field: value: age default: 0.1 """ shelf = Shelf.from_validated_yaml(yaml, MyTable) recipe = Recipe(shelf=shelf, session=self.session).metrics("defaultage") assert (" ".join(recipe.to_sql().split()) == "SELECT coalesce(sum(foo.age), 0.1) AS defaultage FROM foo")
def test_wtd_avg(self): yaml = """ divider: kind: Metric field: age*age divide_by: age """ shelf = Shelf.from_validated_yaml(yaml, MyTable) recipe = Recipe(shelf=shelf, session=self.session).metrics("divider") assert (" ".join(recipe.to_sql().split()) == "SELECT CAST(sum(foo.age * foo.age) AS FLOAT) / " "(coalesce(CAST(sum(foo.age) AS FLOAT), 0.0) + 1e-09) " "AS divider FROM foo")
def get(self): recipe_id = self.request.get('recipe_id') recipe = Recipe.get_by_id(long(recipe_id)) save_cache = Save_cache.get_by_id(DEFAULT_Save_Cache_NAME) if not save_cache: save_cache = Save_cache(id=DEFAULT_Save_Cache_NAME) photo_urls = [] for i in xrange(len(recipe.photos)): photo_urls.append(images.get_serving_url(recipe.photos[0].blob_key)) user = User.get_by_id(self.session.get('user_id')) template = JINJA_ENVIRONMENT.get_template('template/edit_page.html') template_values = { 'recipe_id':recipe_id, 'recipe_name':recipe.name, 'photo_urls':photo_urls, 'author':user.user_name, 'description':recipe.description, 'ingredients':recipe.ingredients, 'directions':recipe.directions, 'estimate_time':recipe.estimate_time.strftime('%H:%M'), 'portion':recipe.portion, 'tags':json.dumps(recipe.tags), 'keywords':json.dumps(save_cache.save_cache), } self.response.write(template.render(template_values))
def post(self): user = User.get_by_id(self.request.get('user_id')) shoppingList = [] if self.request.get("DeleteItem")!="": DeleteItem = self.request.get("DeleteItem") delete_item_list = DeleteItem.split(',') for i in xrange(len(user.shopping_list)): if str(i) not in delete_item_list: shoppingList.append(user.shopping_list[i]) for recipe_id in user.tmp_recipes: recipe = Recipe.get_by_id(long(recipe_id)) isInRecipe = False for ingredient in recipe.ingredients: if ingredient in shoppingList: isInRecipe = True if not isInRecipe: user.tmp_recipes.remove(recipe_id) user.shopping_list = shoppingList user.put() time.sleep(0.5) self.redirect('/shoppingpage')
def add_pics(rep, paths, process, recipe=None): """ Add pictures to repository. Arguments: rep -- Add pictures to this repository. paths -- Paths of the pictures to be added (check if path exists). process -- Boolean flag if added pictures should be processed. recipe -- Recipe to use for picture processing. """ for path in paths: if not os.path.exists(path): log.warning("File not found: '%s'. Skipping it." % path) pics = [Picture(path) for path in paths if os.path.exists(path)] rep.index.add(pics) if process: log.info("Processing pictures.") if not recipe: # set up pipeline process_recipe = \ Recipe.fromString(rep.config['recipes.default']) pl = Pipeline('Pipeline1', process_recipe, path=rep.connector.url.path) for pic in pics: pl.put(pic) pl.start() # start processing threads pl.join() # wait until threads exit log.info("Saving index to file.") with rep.connector.connected(): rep.save_index_to_disk() return rep
def start_load(self): """Loads a list from a file. :return: null """ # Request filename. line_y, line_x = util.center_start(self._list_height-2, self._list_width-2, 1, 16) self._list_display.addstr(line_y+4, 1, ' '*(self._list_width-2)) self._list_display.addstr(line_y+4, line_x, "Enter filename: ") self._list_display.refresh() # Get filename curses.echo() filename = self._list_display.getstr().decode(encoding="utf-8") filename = 'shopping_lists/data/' + filename curses.noecho() # Try to load list, and recursively call start_command if the file isn't loaded. try: new_list = Recipe.create_from_file(filename) # Add ingredients to the shopping list. new_list.add_to(self._shopping_list) # Alert user that list was updated.. line_y, line_x = util.center_start(self._list_height-2, self._list_width-2, 1, len(filename)+13) self._list_display.addstr(line_y+5, line_x, "{} fully loaded".format(filename)) self._list_display.refresh() except (FileNotFoundError, IsADirectoryError): # Alert user that file was not found. line_y, line_x = util.center_start(self._list_height-2, self._list_width-2, 1, 13) self._list_display.addstr(line_y+5, line_x, "File not found.") self._list_display.refresh() # Retry getting a command self.start_shopping_list()
def __init__(self, console_height, console_width): """Create a main screen. :param console_height: the height of the console :param console_width: the width of the console :return: null """ # List should be two smaller in each direction because of surrounding border. self._list_height, self._list_width = console_height-2, console_width-2 # Center the window based on the size of the console. display_start_y, display_start_x = util.center_start(console_height, console_width, self._list_height, self._list_width) # Initialize a Recipe to serve as a shopping list. self._shopping_list = Recipe() # Create window that will act as main visual. self._list_display = curses.newwin(self._list_height, self._list_width, display_start_y, display_start_x) # Add visual detail to window. self._list_display.bkgd(' ', curses.color_pair(1)) util.color_box(self._list_display, 0, 0, self._list_height-1, self._list_width-1, 3) # Initializes help window for use in pause(). help_height, help_width = 12, 50 help_y, help_x = util.center_start(console_height, console_width, help_height, help_width) self.help_window = curses.newwin(help_height, help_width, help_y, help_x)
def get(self): user = User.get_by_id(self.session.get('user_id')) print self.session.get('user_id') print user.shopping_list print type(user.shopping_list) save_cache = Save_cache.get_by_id(DEFAULT_Save_Cache_NAME) if not save_cache: save_cache = Save_cache(id=DEFAULT_Save_Cache_NAME) shopping_dict = [] for item in user.shopping_list: item_dict = {'todoText':item, 'done':False} shopping_dict.append(item_dict) tmp_recipes_list = [] for recipe_id in user.tmp_recipes: recipe = Recipe.get_by_id(long(recipe_id)) recipe_dict = {'photo':'http://placehold.it/700x400', 'name':recipe.name, 'tags':recipe.tags, 'id':str(recipe.key.id()), } if len(recipe.photos)>0: recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key) tmp_recipes_list.append(recipe_dict) template = JINJA_ENVIRONMENT.get_template('template/shopping_page.html') template_values = { 'shopping_dict':json.dumps(shopping_dict), 'tmp_recipes':tmp_recipes_list, 'keywords':json.dumps(save_cache.save_cache), } self.response.write(template.render(template_values))
def recipe_interface(): with sqlite3.connect('db/food.db') as c: while True: #start by getting the url for the recipe url = raw_input('What recipe would you like to work on today?\n') if(url.find("allrecipes.com/") == -1): print("Please put in a url from allrecipes.com") continue else: #print out the original recipe raw_recipe = download.download_recipe(url) recipe = Recipe.parse(c, raw_recipe) print('\nHere is the original recipe:\n') print(recipe.pretty()) # Then ask what transformation to do while True: print('What would you like to do with your recipe?') print('1 = Make Vegetarian') print('2 = Make NOT Vegetarian') print('3 = Change cuisine style') print('4 = Make healthy') x = raw_input() if x in trans_choices.keys(): new_recipe = trans_choices[x](recipe) break else: print('Please pick a number corresponding to one of the available options') print("Here's your new recipe!") print(new_recipe.pretty())
def post(self): recipe_id = self.request.get('recipe_id') recipe = Recipe.get_by_id(long(recipe_id)) if self.request.get('comment')!="": user = User.get_by_id(self.session.get('user_id')) comment = Comment(author=user.user_id,comment_text=self.request.get('comment')) recipe.comments.append(comment) recipe.put() time.sleep(1) self.redirect('viewpage?recipe_id='+str(recipe_id))
def loadRecipe(self, recipeTitle): recipePath = os.path.join(self.recipeDataBasePath, recipeTitle + ".json") try: f = open(recipePath, "r") data = json.load(f) f.close() r = Recipe.fromDictionary(data) return r except IOError: print "no such file"
def findBest(recipes = [], *args): # Set placeholder best score at 0 best = Recipe(None, None, None) best.setScore(0) # For each recipe in the given list, compare the score with the current best # If the recipe is better, make it the new best # If they are the same, randomly either make the new recipe the best or leave the current one for recipe in recipes: if recipe.score > best.score: best = recipe if recipe.score == best.score: coin = randint(0, 1) if coin == 0: best = recipe else: pass # Return the best recipe return best
def main(): with open('chili.pkl') as f: with sqlite3.connect('db/food.db') as db: raw_recipe = pkl.load(f) recipe = Recipe.parse(db, raw_recipe) for d in recipe.directions: print d.tagged print 'NEXT\n' veg = recipe.veggitize() for d in veg.directions: print d.tagged print veg.pretty()
def scrapeRecipe(title): """ Scrape the page for the recipe with the given title. Return a recipe parsed from that page. """ #print title #test entity = urlopen(RECIPE_URL % title).read() #entity = urlopen(RECIPE_TEST).read() soup = BeautifulSoup(entity) #print soup.prettify() #test use details = soup.find(class_='detail-section greydotted ingredients') recipe = Recipe() # Get title recipe.title = title.replace("-"," ")#details.find(id='itemTitle').text # Get ingredients and amounts, save them to seperate array. initIngredients(recipe, details.find(id='zoneIngredients')) # Get prep, cook, and total times. initTime(recipe, details) # Get cooking directions recipe.directions = initDirections(details.find(class_='directions')) #print recipe.__dict__ #test return recipe
def add_recipe(self, filename): """Load a recipe and add it to the shopping list. :param filename: the recipe (located in saved_recipes) to be loaded :return: null """ # Add the directory name to the filename. filename = 'saved_recipes/' + filename new_recipe = Recipe.create_from_file(filename) # Add ingredients to the shopping list. new_recipe.add_to(self._shopping_list) # Alert user that list was updated. self._list_display.addstr(self._list_height-2, 1, "{} fully loaded".format(filename)) self._list_display.refresh()
def post(self): user = User.get_by_id(self.session.get('user_id')) if self.request.get("newItem")!="": newItem = self.request.get("newItem") user.shopping_list.append(newItem) user.put() time.sleep(0.5) elif self.request.get("shoppingList")!="": shoppingList = [ item["todoText"] for item in json.loads(self.request.get("shoppingList"))] user.shopping_list = shoppingList for recipe_id in user.tmp_recipes: recipe = Recipe.get_by_id(long(recipe_id)) isInRecipe = False for ingredient in recipe.ingredients: if ingredient in user.shopping_list: isInRecipe = True if not isInRecipe: user.tmp_recipes.remove(recipe_id) user.put() time.sleep(0.5) self.redirect('/shoppingpage')
def post(self): upload = self.get_uploads()[0] recipe_id = self.request.get('recipe_id') recipe = Recipe.get_by_id(long(recipe_id)) # # user_id = self.session.get('user_id') author_comments = self.request.get('author_comments') user_id = self.request.get('user_id') user = User.get_by_id(user_id) #img = images.resize(img, 200, 200) # if len(upload) >0: # recipe.photos.append(Photo( # blob_key = upload[0].key(), # filename= upload[0].filename, # )) recipe.put() history = History() history.recipe_name = recipe.name history.author_comments = author_comments history.FromAndroid = True history.recipe_id = str(recipe.key.id()) history.tags = recipe.tags history.recipe_author= user.user_name history.recipe_description= recipe.description history.recipe_authorID = user_id history.photos.append(Photo( blob_key = upload.key(), filename= "hi", )) # if len(upload) >0: # history.photos.append(Photo( # # blob_key = upload[0].key(), # # filename= upload[0].filename, # blob_key = upload.key(), # filename= "hi", # )) history.put() time.sleep(1)
def get(self): recipe_id = self.request.get('recipe_id') ingredient_idx = int(self.request.get('ingredient_idx'))-1 if self.request.get('add') == 'true': isAdd = True else: isAdd = False user_id = self.session.get('user_id') recipe = Recipe.get_by_id(long(recipe_id)) user = User.get_by_id(self.session.get('user_id')) if ingredient_idx < 0: if isAdd: if recipe_id not in user.tmp_recipes: user.tmp_recipes.append(recipe_id) for ingredient in recipe.ingredients: if ingredient not in user.shopping_list: user.shopping_list.append(ingredient) else: for ingredient in recipe.ingredients: user.shopping_list.remove(ingredient) if recipe_id in user.tmp_recipes: user.tmp_recipes.remove(recipe_id) else: if isAdd: if recipe_id not in user.tmp_recipes: user.tmp_recipes.append(recipe_id) if recipe.ingredients[ingredient_idx] not in user.shopping_list: user.shopping_list.append(recipe.ingredients[ingredient_idx]) else: user.shopping_list.remove(recipe.ingredients[ingredient_idx]) isInRecipe = False for ingredient in recipe.ingredients: if ingredient in user.shopping_list: isInRecipe = True if not isInRecipe: user.tmp_recipes.remove(recipe_id) user.put() time.sleep(0.5) self.redirect('viewpage?recipe_id='+str(recipe_id))
def post(self): recipe_authorID = self.request.get('recipe_authorID') recipe_id = self.request.get('recipe_id') FromAndroid = self.request.get('FromAndroid') if int(FromAndroid)==0: recipe = Recipe.get_by_id(long(recipe_id)) if self.request.get('comment')!="": user = User.get_by_id(self.session.get('user_id')) comment = Comment(author=user.user_id,comment_text=self.request.get('comment')) recipe.comments.append(comment) recipe.put() time.sleep(1) else: history_query = History.query(History.recipe_id ==recipe_id, History.recipe_authorID==recipe_authorID) recipe_query_all= history_query.fetch() if self.request.get('comment')!="": user = User.get_by_id(self.session.get('user_id')) comment = Comment(author=user.user_id,comment_text=self.request.get('comment')) recipe_query_all[0].comments.append(comment) recipe_query_all[0].put() time.sleep(1) self.redirect('/timeline')
def loadRecipe(self, recipeTitle): recipePath = os.path.join(self.dataBasePath, recipeTitle + ".json") print "recipe path==--=", recipePath try: f = open(recipePath, "r") data = json.load(f) f.close() print print print data print print r = Recipe.fromDictionary(data) print "HERE IS THE RECIPE" theRecipeString = r.writeToReadableString() print theRecipeString return theRecipeString except IOError: print "no such file"
def setUp(self): """ Set up some defaults, and create an instance of the recipe, with enough mock buildout config to get by """ self.download_dir = tempfile.mkdtemp() self.eggs_directory = tempfile.mkdtemp() self.destination = os.path.join(tempfile.mkdtemp(), "INSTALLED") self.download_url = "http://localhost/~tomwardill/FlashMediaServer4_x64.tar.gz" # create the recipe, with some mock/temporary buildout config parameters self.recipe = Recipe( { "buildout": { "download-cache": self.download_dir, "eggs-directory": self.eggs_directory, "develop-eggs-directory": tempfile.mkdtemp(), "bin-directory": tempfile.mkdtemp(), "parts-directory": tempfile.mkdtemp(), "python": "python", }, "python": {"executable": "usr/bin/python"}, }, "test-recipe", {"download_url": self.download_url, "recipe": "isotoma.recipe.fms"}, )
def getRecipe(self): recipe = Recipe() recipe.parsePage(self.lxml_data, self.id) return recipe
def parse(self, html): recipe = Recipe() soup = BeautifulSoup(html, "html.parser") links = soup.find_all('a', attrs={'class': 'y-image'}) urls = [] for link in links: urls.append(link['href']) try: recipe.set('recipe_id', soup.find('div', attrs={'class': 'recipe'}).find('meta', attrs={'itemprop': 'url'})['content'].split('/')[-1]) except: print 'no recipe_id' pass # print recipe.get('recipe_id') try: recipe.set('recipe_name', soup.find('h1', attrs={'itemprop': 'name'}).text) except: print 'no recipe_name' pass # print recipe.get('recipe_name') try: recipe.set('image', soup.find('div', attrs={'style': re.compile('^background-image')})['style'].split('\'')[-2]) except: print 'no image' pass # print recipe.get('image') try: source_info = soup.find('span', attrs={'id': 'source-name'}) recipe.set('source_name', source_info.find('a').text.strip()) recipe.set('source_UID', source_info.find('a')['href'].split('/')[-1]) except: print 'no source' pass # print recipe.get('source_name') # print recipe.get('source_UID') try: user_info = soup.find('span', attrs={'class': 'added-by'}) recipe.set('nickname', user_info.find('a').text.strip()) recipe.set('username', user_info.find('a')['href'].split('/')[-1]) except: print 'no user' pass # print recipe.get('nickname') # print recipe.get('username') try: recipe.set('yums', soup.find('span', attrs={'class': 'count'})['data-count']) except: print 'no yums' pass # print recipe.get('yums') try: total_time = soup.find('li', attrs={'class': 'time-data'}).find('span', attrs={'class':'bd'}).text recipe.set('total_time', int(total_time)) except: recipe.set('total_time', None) # print recipe.get('total_time') try: amountf_re = re.compile("(\d*)\s*(\d)/(\d+)([^\d]*)") ingredient_list = [] ingredients = soup.find('div', attrs={'id': 'recipe-ingredients'}).find_all('li', attrs={'itemprop': 'ingredients'}) for ingredient in ingredients: if not ingredient.find('span', attrs={'class': 'amount'}).find('span', attrs={'class':'fraction'}): amount_unit = ingredient.find('span', attrs={'class': 'amount'}).text.strip() if not amount_unit: amount = None unit = None else: amount_unit = amount_unit.split(' ') if len(amount_unit) == 1: amount = amount_unit[0] unit = None else: amount = amount_unit[0] unit = amount_unit[1] else: m = amountf_re.match(ingredient.find('span', attrs={'class': 'amount'}).text) if m: if m.group(1): amount = int(m.group(1)) + float(m.group(2)) / float(m.group(3)) else: amount = float(m.group(2)) / float(m.group(3)) unit = m.group(4).strip() if not unit: unit = None content = ingredient.find('strong', attrs={'class': 'name'}).text.strip() ingredient_list.append((amount, unit, content)) recipe.set('ingredients', ingredient_list) except: print 'no ingredient' pass # print recipe.get('ingredients') try: recipe.set('rating', soup.find('span', attrs={'class': 'recipe-rating-text'}).text.split(' ')[0][1:]) except: print 'no rating' pass # print recipe.get('rating') try: review_list = [] reviews = soup.find('div', attrs={'id': 'reviews-list'}).find_all('div', attrs={'class': 'star-line'}) text_lines = soup.find('div', attrs={'id': 'reviews-list'}).find_all('div', attrs={'class': 'text-line'}) for i in range(0, len(reviews)): reviewer_nickname = reviews[i].find('a', attrs={'class': 'review-user-name'}).text reviewer_username = reviews[i].find('a', attrs={'class': 'review-user-name'})['href'].split('/')[2] review_stars = len(reviews[i].find('span', attrs={'class': 'stars'}).find_all('span', attrs={'class': re.compile('full')})) texts = text_lines[i].text.strip() review_list.append((reviewer_nickname, reviewer_username, review_stars, texts)) recipe.set('reviews', review_list) except: print 'no review' pass # print recipe.get('reviews') try: recipe.set('calories', int(soup.find('table', attrs={'class': 'calories'}).find_all('span', attrs={'class': 'calories'})[0].text)) except: recipe.set('calories', None) # print recipe.get('calories') try: recipe.set('calories_from_fat', int(soup.find('table', attrs={'class': 'calories'}).find_all('span', attrs={'class': 'calories'})[1].text)) except: recipe.set('calories_from_fat', None) # print recipe.get('calories_from_fat') mg = re.compile("[^\.\d]*([\.\d]+)\s*mg") g = re.compile("[^\.\d]*([\.\d]+)\s*g") try: nutrient_list = [] nutrients = soup.find('table', attrs={'class': 'nutrients'}).find_all('tr') for nutrient in nutrients: content = nutrient.text.split('\n')[0].strip() amount = nutrient.text.split('\n')[1].strip() if mg.match(amount): amount = mg.match(amount).group(1) elif g.match(amount): amount = int(float(g.match(amount).group(1)) * 1000) else: amount = None percentage = nutrient.text.split('\n')[-3].strip() if percentage: percentage = percentage[0:-1] else: percentage = None nutrient_list.append((content, amount, percentage)) content = soup.find('div', attrs={'class': 'protein'}).text.split('\n')[1] amount = soup.find('div', attrs={'class': 'protein'}).text.split('\n')[2] if mg.match(amount): amount = mg.match(amount).group(1) elif g.match(amount): amount = int(float(g.match(amount).group(1)) * 1000) else: amount = None percentage = None nutrient_list.append((content, amount, percentage)) nutrients = soup.find_all('table', attrs={'class': 'nutrients'}, limit=2)[1].find_all('tr') for nutrient in nutrients: content = nutrient.text.split('\n')[0] amount = None percentage = nutrient.text.split('\n')[3].strip() if percentage: percentage = percentage[0:-1] nutrient_list.append((content, amount, percentage)) recipe.set('nutrients', nutrient_list) except: print 'no calorie content' pass # print recipe.get('nutrients') try: taste_list = [] tastes = soup.find('div', attrs={'class': 'taste'}).find_all('div', attrs={'class': 'ninja-level'}) for taste in tastes: taste_list.append(taste['style'].split(':')[-1][0:-1]) recipe.set('tastes', taste_list) except: print 'no flavor' pass # print recipe.ge('tastes') try: tag_list = [] tags = soup.find('div', attrs={'class': 'recipe-tags'}).find_all('a') for tag in tags: tag_list.append(tag.text) recipe.set('tags', tag_list) except: print 'no tag' pass # print recipe.get('tags') self.recipe = recipe return urls
def create_recipe(end_product, material_names, quantity_types, tool_types, tool_type_default, ending_tools): """if not tools.has_word_type(end_product, [tools.WORD_TYPE_NOUN]): end_product_nounified = tools.nounify_first_result(end_product, "") if len(end_product_nounified) > 0 and end_product_nounified != end_product and end_product_nounified not in material_names: print("Nounified end product " + end_product + " => " + end_product_nounified) end_product = end_product_nounified """ r = Recipe(end_product, ending_tools) for material_name in random.sample(material_names, min(4, len(material_names))): material_word_type = tools.find_most_common_word_type(material_name) # Unknown and length 12? Probably truncated, let's skip it. if material_word_type == tools.WORD_TYPE_UNKNOWN and len(material_name) == 12: continue if not tools.DEBUG_SKIP_WORD_ANALYSIS and material_word_type != tools.WORD_TYPE_NOUN and not tools.has_word_type(material_name, [tools.WORD_TYPE_NOUN]): material_name_nounified = tools.nounify_first_result(material_name, "") if len(material_name_nounified) > 0 and material_name_nounified != end_product and material_name_nounified not in material_names: print("Nounified material " + material_name + " => " + material_name_nounified) material_name = material_name_nounified material_word_type = tools.find_most_common_word_type(material_name) if material_word_type == tools.WORD_TYPE_ADJECTIVE: material_name = "being " + material_name if material_word_type in quantity_types: quantity_type = random.choice(quantity_types[material_word_type]) amount = quantity_type.random_amount() r.add_material(Material(material_name, amount, quantity_type)) tool_types = tool_types.copy() tool_count = random.randint(2, len(tool_types)) # for tool_type in random.sample(tool_types, min(2, len(tool_types))): while len(r.tools) < tool_count: tool_type = tools.random_weighted_choice(tool_types, lambda t: t.chance_value) tool_types.remove(tool_type) tool = Tool(tool_type) # if not any(tool.equals(other_tool) for other_tool in r.tools): r.add_tool(tool) r.add_tool(Tool(tool_type_default)) r.finish() print("=======================") print() r.print() return r
def task3_task4(): recipe = Recipe() recipe.read_file("./data/recipe-data.txt") print(recipe)
def task1(): recipe = Recipe() recipe.test()
def handleLeftMouseClick(self, xy): for button in self.buttonGroup.sprites(): if button.getRect().collidepoint(xy): ## stupid organization leads to hacky solutions... # in groceryList viewer, the writeToDesktop button must be stored in the main # class. So thats whats going on here, we call writeToDesktop # in the scrollable window and grab the grocery list there and send that to # dbm to write it to desktop if button.getIdentity() == "writeToDesktop": theString = self.windowGroup.sprites()[0].writeToDesktop() #print #print #print theString self.dbm.writeStringToDesktop(self.windowGroup.sprites()[0].writeToDesktop(), "Grocery List") self.state = "menu" self.stateChanged = True #print "got here!" return ## we want to store the state of the stuff people are looking at # whether that is a grocery list they have increased or recipes they have added to cart # we call the "grabState()" method of the scrollableWindow to get the information #### keep in mind, this is the previous state # so if self.state == "browseAll" it means we are coming from browseAll state # to the menu if self.state == "browseAll": ## this one is tricky. We need to store a list of toggled rows, and then # if the user goes back to the viewAllBrowser we need to call "updateState()" # with this list, to ensure those buttons are toggled to reflect that they are # still in the groceryList # keep in mind this is a list of the names of the recipes that are already added # so we will need to search for them in "updateState()" allWindows = self.windowGroup.sprites() if allWindows: self.toggledRecipeNames = allWindows[0].grabState() elif self.state == "viewGroceryList": ## this one is simple, we just grabState() and store the returns in self.groceryList # all the changes the user has made will be in the new list # and new changes will happen to that list allWindows = self.windowGroup.sprites() if allWindows: self.groceryList.empty() self.groceryList.addIngredientList(allWindows[0].grabState()) self.state = button.getIdentity() self.stateChanged = True command = None if self.state == "browseAll" or self.state == "deleteRecipe": for scrollableWindow in self.windowGroup.sprites(): if scrollableWindow.getRect().collidepoint(xy): command = scrollableWindow.isClicked(xy) break if not command == None: ## command is a string, meaning there is a change of state # from the button press #print "command recieved!" #print " ", command if isinstance(command, str): self.state = command self.stateChanged = True #print "this thing" else: if len(command) == 2: #print "entered here" #print "command[0]:", command[0] if command[0] == "expand": recipeInfo = self.dbm.loadRecipe(command[1]).toReadableString() scrollableWindow.addTextBlock(command[1], recipeInfo) elif command[0] == "addToGroceryList": self.groceryList.addRecipe(self.dbm.loadRecipe(command[1])) elif command[0] == "removeFromGroceryList": self.groceryList.removeRecipe(self.dbm.loadRecipe(command[1])) elif command[0] == "writeToDesktop": #print "got into this" self.dbm.writeRecipeToDesktop(command[1]) if command[0] == "delete": #print "got here" self.dbm.deleteRecipe(command[1]) elif self.state == "menu" or self.state=="prestart": for sprite in self.buttonGroup.sprites(): if sprite.rect.collidepoint(xy): parseID = sprite.getIdentity().split() # no extra info, just an ID for the new state # if this is not true there is something wrong if len(parseID) == 1: spriteID = parseID[0] if not spriteID == self.state: self.state = spriteID self.stateChanged = True else: raise GUIError("button gives too much data") elif self.state == "addRecipe": for recipeReciever in self.windowGroup.sprites(): recipeData = recipeReciever.isClicked(xy) if not recipeData == None: #for k in recipeData.keys(): #print k, recipeData[k] self.dbm.addRecipeToDataBase(Recipe.fromDictionary(recipeData)) self.state = "menu" self.stateChanged = True elif self.state == "viewGroceryList": for scrollableWindow in self.windowGroup.sprites(): command = scrollableWindow.isClicked(xy) elif self.state == "search": ## search has 2 states, the first is a text box where the user # enters what the search ingredient is # the second the window where the results are displayed # we determine which state by what is in self.windowGroup.sprites() # a TextBox is the first state, a ScrollableWindow is the second for sprite in self.windowGroup.sprites(): pass#command = sprite.isClicked
def main(): xml_cntrl = xml_handler("cook_book_data.xml") recipe_name = raw_input("Enter recipe name: ") wine_suggestion = raw_input("Enter wine info: ") general_info = raw_input("Enter general info: ") ingredient_list = [] instructions = [] keys = [] ingredient = raw_input("Enter ingredient name: ") while ingredient != "done": quantity = raw_input("Enter quantity: ") full_string = raw_input("Enter full string: ") ingredient_list.append(Ingredient(ingredient, quantity, full_string)) ingredient = raw_input("Enter ingredient name: ") instruction = raw_input("Enter instruction: ") while instruction != "done": new_instruction = Instruction_step() new_instruction.set_instruction(instruction) instructions.append(new_instruction) instruction = raw_input("Enter instruction: ") key = raw_input("Enter key to success: ") while key != "done": keys.append(Paragraph(key)) key = raw_input("Enter key to success: ") new_recipe = Recipe( recipe_name ) new_recipe.set_wine_suggestion(wine_suggestion) new_recipe.set_general_info(general_info) for ingredient in ingredient_list: new_recipe.add_ingredient(ingredient) for instr in instructions: new_recipe.add_instruction(instr) for key in keys: new_recipe.add_key_to_success(key) xml_cntrl.append_recipe(new_recipe)
def load_recipe( self, recipe_name ): recipe_node = None for node in self.xml_root.findall("Recipe"): if node.attrib["recipe_name"] == recipe_name: recipe_node = node break; if recipe_node == None: return ( False, None ) new_recipe = Recipe( recipe_name ) new_recipe.set_wine_suggestion( recipe_node.find("Wine_suggestion") ) new_recipe.set_general_info( recipe_node.find("General_info")) for ingredient in recipe_node.find("Ingredients").findall("ingredient"): ingr_name = ingredient.attrib["name"] ingr_quantity = ingredient.attrib["quantity"] ingr_full_string = ingredient.attrib["full_string"] new_recipe.add_ingredient( Ingredient(ingr_name, ingr_quantity, ingr_full_string )) for instruction in recipe_node.find("Instructions").findall("instruction"): instruction_step = Instruction_step() instruction_step.set_instruction( instruction.attrib["instruction_txt"]) new_recipe.add_instruction(instruction_step) for key in recipe_node.find("Keys_to_success").findall("key"): new_recipe.add_key_to_success(Paragraph(key.attrib["key_txt"])) return (True, new_recipe)
def task5(): recipe = Recipe() recipe.read_file_id("./data/recipe-data.txt") print(recipe)