Cheddar | #Architecture | Click's Hexagonal Domain Driven Architecture

 by   travel-cloud Java Updated: 9 months ago - Current License: Apache-2.0

Download this library from

Build Applications

kandi X-RAY | Cheddar REVIEW AND RATINGS

Click's Hexagonal Domain Driven Architecture

kandi-support
Support

  • Cheddar has a low active ecosystem.
  • It has 92 star(s) with 50 fork(s).
  • It had no major release in the last 12 months.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • Cheddar has no issues reported.

security
Security

  • Cheddar has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

license
License

  • Cheddar is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.

build
Reuse

  • Cheddar releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
Top functions reviewed by kandi - BETA

kandi has reviewed Cheddar and discovered the below as its top functions. This is intended to give you an instant insight into Cheddar implemented functionality, and help decide if they suit your requirements.

  • Compute the marshaller .
  • Generate scan spec .
  • Checks if a property matches a given condition .
  • Creates all the unique constraint indexes .
  • Send metric .
  • Entry point for the SLF application .
  • Cache the domain endpoints .
  • Get the credit card check digit .
  • Creates a DynamoDB condition .
  • Scan resources for Jaxrs annotations .

Cheddar Key Features

Click's Hexagonal Domain Driven Architecture

Cheddar examples and code snippets

  • Python - Item Price Web Scraping for Target
  • How to render an Array in ReactJS?
  • Having trouble finishing this python code
  • XSLT Select multiple attribute with the same name
  • Display items with different properties ReactJS
  • How can I persist enum type field, with Hibernate?
  • Iterate through list of lists and remove unwanted strings
  • WhiteLabel Error page with no error message in sts console
  • Logs complaining "extensions/v1beta1 Ingress is deprecated"
  • change values for each object with a button

Python - Item Price Web Scraping for Target

price_css_locator = 'div[data-test=product-price]'
price_xpath_locator = '//div[@data-test="product-price"]'
soup.select('div[data-test="product-price"]')
price = soup.select('div[data-test="product-price"]').text
print(price)
-----------------------
price_css_locator = 'div[data-test=product-price]'
price_xpath_locator = '//div[@data-test="product-price"]'
soup.select('div[data-test="product-price"]')
price = soup.select('div[data-test="product-price"]').text
print(price)
-----------------------
price_css_locator = 'div[data-test=product-price]'
price_xpath_locator = '//div[@data-test="product-price"]'
soup.select('div[data-test="product-price"]')
price = soup.select('div[data-test="product-price"]').text
print(price)
-----------------------
price_css_locator = 'div[data-test=product-price]'
price_xpath_locator = '//div[@data-test="product-price"]'
soup.select('div[data-test="product-price"]')
price = soup.select('div[data-test="product-price"]').text
print(price)
-----------------------
price = soup.find("div",class_= "web-migration-tof__PriceFontSize-sc-14z8sos-14 elGGzp")
print(price.text)
-----------------------
from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')

# If you don't want to open a browser, comment out the line above and uncomment below
#options = webdriver.ChromeOptions()
#options.add_argument('headless')
#driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe', options=options)

url = "https://www.target.com/p/ruffles-cheddar-38-sour-cream-potato-chips-2-5oz/-/A-14930847#lnk=sametab"
driver.get(url)
r = driver.page_source
soup = BeautifulSoup(r, "lxml")

price = soup.find("div",class_= "web-migration-tof__PriceFontSize-sc-14z8sos-14 elGGzp")
print(price.text)
$1.99
-----------------------
from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')

# If you don't want to open a browser, comment out the line above and uncomment below
#options = webdriver.ChromeOptions()
#options.add_argument('headless')
#driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe', options=options)

url = "https://www.target.com/p/ruffles-cheddar-38-sour-cream-potato-chips-2-5oz/-/A-14930847#lnk=sametab"
driver.get(url)
r = driver.page_source
soup = BeautifulSoup(r, "lxml")

price = soup.find("div",class_= "web-migration-tof__PriceFontSize-sc-14z8sos-14 elGGzp")
print(price.text)
$1.99

How to render an Array in ReactJS?

const MealItems = (props) => (
  <div className="col-md-4">
    <div className="item-add">
      <div className="product_header">
        <div className="product_name">
          <span className="item-heading">{props.name}</span>
        </div>
      </div>
      <div className="product_price">
        <span className="item-price">
          {props.price}
          <span> $</span>
        </span>
      </div>
      <div className="product_description">{props.description} </div>
    </div>
  </div>
);

const Card = () => {
  return (
    <div>
      <ul>
        {DUMMY_MEALS.map((meal) => (
          <MealItems
            key={meal.id}
            id={meal.id}
            name={meal.name}
            description={meal.description}
            price={meal.price}
          />
        ))}
      </ul>
    </div>
  );
};

export default Card;

Having trouble finishing this python code

print(receipt)
print(f'total cost {total_cost}')
chosenToppings = []
while True:
    toppingCount = int(input('How many toppings would you like?: '))
    if toppingCount <= 3:
        for i in range(1,toppingCount+1):
            top = 1
            while top in [1,2,3]:
                top = int(input('Enter choice 1-3: '))
                chosenToppings.append(top)
                break
        break
    else:print('Enter a number less than three please')
-----------------------
print(receipt)
print(f'total cost {total_cost}')
chosenToppings = []
while True:
    toppingCount = int(input('How many toppings would you like?: '))
    if toppingCount <= 3:
        for i in range(1,toppingCount+1):
            top = 1
            while top in [1,2,3]:
                top = int(input('Enter choice 1-3: '))
                chosenToppings.append(top)
                break
        break
    else:print('Enter a number less than three please')

XSLT Select multiple attribute with the same name

<ul>
  <xsl:for-each select="nutrition_info">
    <xsl:for-each select="ingredient">
      <li><xsl:value-of select="."/></li>
    </xsl:for-each>
  </xsl:for-each>
</ul>
-----------------------
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  >

  <xsl:template match="/">
    <html>
      <body>
        <h2>
          <center>Menu</center>
        </h2>
        <table border="1">
          <thead>
            <tr>
              <th>Name</th>
              <th>Description</th>
              <th>Type</th>
              <th>Ingredients</th>
              <th>dietary restrictions</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
            <xsl:apply-templates select="Menu/dish"/>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  
  <xsl:template match="dish">
    <tr>
      <td>
        <xsl:value-of select="general_info/name"/>
      </td>
      <td>
        <xsl:value-of select="general_info/description"/>
      </td>
      <td>
        <xsl:value-of select="general_info/type"/>
      </td>
      <td>
        <xsl:apply-templates select="nutrition_info"/>
      </td>
      <td>
        <xsl:value-of select="nutrition_info/dietary_restrictions"/>
      </td>
      <td>
        <xsl:value-of select="price"/>
      </td>
    </tr>
    
  </xsl:template>

  <xsl:template match="nutrition_info">
    <ul>
      <xsl:apply-templates select="ingredient"/>
    </ul>
  </xsl:template>
  
  <xsl:template match="ingredient">
    <li>
      <xsl:value-of select="."/>
    </li>
  </xsl:template>

</xsl:stylesheet>

Display items with different properties ReactJS

  {menuItems
        .filter((v) => v.category === "burger")
        .map(({ id, title, price, image, title, description }) => {
          return (
            <li key={id}>
              <h4>{title}</h4>
              <span>{price}</span>
              <img src={image} alt={title} />
              <p>{description}</p>
              <button type="submit" onClick={() => addToCart(id)}>
                Add to cart
              </button>
            </li>
          );
        })}
-----------------------
const categoryBurger = menuItems.filter((item) => item.category === "burger");

const categoryCrepe = menuItems.filter((item) => item.category === "crepe");

-----------------------
{menuItems.map(menuItem => {
    return (
    
    )
})}

How can I persist enum type field, with Hibernate?

@Enumerated(EnumType.STRING)
private final Type type;

Iterate through list of lists and remove unwanted strings

newlist  = [i for i in oldlist if unwanted_string not in i]
item_list = ["BigCar", "SmallCar", "BigHouse", "SmallHouse"]
unwanted_string = "Big"
[i for i in item_list if not unwanted_string in i]
['SmallCar', 'SmallHouse']
-----------------------
newlist  = [i for i in oldlist if unwanted_string not in i]
item_list = ["BigCar", "SmallCar", "BigHouse", "SmallHouse"]
unwanted_string = "Big"
[i for i in item_list if not unwanted_string in i]
['SmallCar', 'SmallHouse']
-----------------------
newlist  = [i for i in oldlist if unwanted_string not in i]
item_list = ["BigCar", "SmallCar", "BigHouse", "SmallHouse"]
unwanted_string = "Big"
[i for i in item_list if not unwanted_string in i]
['SmallCar', 'SmallHouse']
-----------------------
full_list = []
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = s.replace(old, new)
    full_list.append(s.rstrip())  # .rstrip() removes trailing spaces if exist
import re

full_list = []
replace_rules = {
    r'\s*(finely|chopped|grated)': '',
    r'(\s*)tbsp': r'\1grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = re.sub(old, new, s, re.IGNORECASE)
    full_list.append(s)
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
result_list = []
for l in full_list:
    temp_list = []
    for w in l:
        if w.lower() in replace_rules:
            if replace_rules[w.lower()]:
                temp_list.append(replace_rules[w.lower()])
        else:
            temp_list.append(w)
    result_list.append(temp_list)
filter_list = {'finely', 'chopped', 'grated'}  # words to ignore
replace_rules = {'tbsp': 'grams'}              # words to replace
result_list = [[replace_rules.get(w.lower(), w) for w in l if w.lower() not in filter_list] for l in full_list]
-----------------------
full_list = []
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = s.replace(old, new)
    full_list.append(s.rstrip())  # .rstrip() removes trailing spaces if exist
import re

full_list = []
replace_rules = {
    r'\s*(finely|chopped|grated)': '',
    r'(\s*)tbsp': r'\1grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = re.sub(old, new, s, re.IGNORECASE)
    full_list.append(s)
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
result_list = []
for l in full_list:
    temp_list = []
    for w in l:
        if w.lower() in replace_rules:
            if replace_rules[w.lower()]:
                temp_list.append(replace_rules[w.lower()])
        else:
            temp_list.append(w)
    result_list.append(temp_list)
filter_list = {'finely', 'chopped', 'grated'}  # words to ignore
replace_rules = {'tbsp': 'grams'}              # words to replace
result_list = [[replace_rules.get(w.lower(), w) for w in l if w.lower() not in filter_list] for l in full_list]
-----------------------
full_list = []
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = s.replace(old, new)
    full_list.append(s.rstrip())  # .rstrip() removes trailing spaces if exist
import re

full_list = []
replace_rules = {
    r'\s*(finely|chopped|grated)': '',
    r'(\s*)tbsp': r'\1grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = re.sub(old, new, s, re.IGNORECASE)
    full_list.append(s)
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
result_list = []
for l in full_list:
    temp_list = []
    for w in l:
        if w.lower() in replace_rules:
            if replace_rules[w.lower()]:
                temp_list.append(replace_rules[w.lower()])
        else:
            temp_list.append(w)
    result_list.append(temp_list)
filter_list = {'finely', 'chopped', 'grated'}  # words to ignore
replace_rules = {'tbsp': 'grams'}              # words to replace
result_list = [[replace_rules.get(w.lower(), w) for w in l if w.lower() not in filter_list] for l in full_list]
-----------------------
full_list = []
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = s.replace(old, new)
    full_list.append(s.rstrip())  # .rstrip() removes trailing spaces if exist
import re

full_list = []
replace_rules = {
    r'\s*(finely|chopped|grated)': '',
    r'(\s*)tbsp': r'\1grams'
}
for s in ingrediant_list:
    for old, new in replace_rules.items():
        s = re.sub(old, new, s, re.IGNORECASE)
    full_list.append(s)
replace_rules = {
    'finely': '',
    'chopped': '',
    'grated': '',
    'tbsp': 'grams'
}
result_list = []
for l in full_list:
    temp_list = []
    for w in l:
        if w.lower() in replace_rules:
            if replace_rules[w.lower()]:
                temp_list.append(replace_rules[w.lower()])
        else:
            temp_list.append(w)
    result_list.append(temp_list)
filter_list = {'finely', 'chopped', 'grated'}  # words to ignore
replace_rules = {'tbsp': 'grams'}              # words to replace
result_list = [[replace_rules.get(w.lower(), w) for w in l if w.lower() not in filter_list] for l in full_list]

WhiteLabel Error page with no error message in sts console

@GetMapping  
    public String showDesignForm(Model model) {   
        List<Ingredient> ingredients = Arrays.asList(new Ingredient("FLTO", "Flour Tortilla", Ingredient.Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Ingredient.Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Ingredient.Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Ingredient.Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatoes", Ingredient.Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Ingredient.Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Ingredient.Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Ingredient.Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Ingredient.Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Ingredient.Type.SAUCE));
        Type[] types = Ingredient.Type.values();
            for (Type type : types) {
                model.addAttribute(type.toString().toLowerCase(), 
                filterByType(ingredients, type));    
                }    
        model.addAttribute("tacodesign", new Taco());    
        // Set the template name to the appropriate value
        // Generally speaking, it should match a file name in the
        // templates directory, without the extension
        return "TacoHome";  
  }

Logs complaining &quot;extensions/v1beta1 Ingress is deprecated&quot;

@microk8s:~$ kubectl describe ing
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress

change values for each object with a button

<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
<span id="amountNumber_' + ${match.foodId} + '">
<button onclick="add(amountNumber_' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById(id);
    console.log(amountNum.innerText)
}
<li>Protein: <span id="protein_' + ${match.foodId} +'>${match.Protein}</span> g</li>
<button onclick="add(' + ${match.foodId} + ')" id="add">+</button>
function add(id) {
{
    const amountNum = document.getElementById("amountNumber_' + ${match.foodId} +'");
    console.log(amountNum.innerText)

    var span = document.getElementById("protein_' + ${match.foodId} +'");
    span.innerText += parseFloat(span.innerText) 
}
-----------------------
    const outputHtml = matches => {
        if (matches.length > 0) {
            const lookUpItem = matches.map((match, index) => `
            <div class="foodInfo">
                    <h4 id="title">${match.foodDesc}</h4>
                    <small><span class="foodDetails">
                        <li>Protein: ${match.Protein} g</li>
                        <li>Calories: ${match.Calories} cals</li>
                        <li>Total Fat: ${match.Fat} g</li>
                        <li><button onclick="minus('amountNumber_${index}')" id="minus_${index}">-</button>
                            <span id="amount">Amount: <span id="amountNumber_${index}">${match.amount1}</span> / ${match.msreDesc1} </span>
                            <button onclick="add('amountNumber_${index}')" id="add_${index}">+</button> </li>
                        <button onclick="submit()" id="submit">Add to Diary</button>
                    </span></small>
            </div>
            `
    ).join('');
            itemList.innerHTML = lookUpItem;
        }
    }
    
    

function add(el) {

    amountNum = parseInt(document.getElementById(el)) + 1;

    document.getElementById(el).innerText = amountNum;

    console.log(amountNum.innerText)
}

COMMUNITY DISCUSSIONS

Top Trending Discussions on Cheddar
  • Python - Item Price Web Scraping for Target
  • How to render an Array in ReactJS?
  • Having trouble finishing this python code
  • XSLT Select multiple attribute with the same name
  • Spring validator does not detect errors
  • Display items with different properties ReactJS
  • How can I persist enum type field, with Hibernate?
  • Iterate through list of lists and remove unwanted strings
  • WhiteLabel Error page with no error message in sts console
  • Logs complaining &quot;extensions/v1beta1 Ingress is deprecated&quot;
Top Trending Discussions on Cheddar

QUESTION

Python - Item Price Web Scraping for Target

Asked 2021-Jun-09 at 14:09

I'm trying to get any item's price from Target website. I did some examples for this website using selenium and Redsky API but now I tried to wrote bs4 code below:

import requests
from bs4 import BeautifulSoup

url = "https://www.target.com/p/ruffles-cheddar-38-sour-cream-potato-chips-2-5oz/-/A-14930847#lnk=sametab"
r= requests.get(url)
soup = BeautifulSoup(r.content, "lxml")

price = soup.find("div",class_= "web-migration-tof__PriceFontSize-sc-14z8sos-14 elGGzp")
print(price)

But it returns me None .

I tried soup.find("div",{'class': "web-migration-tof__PriceFontSize-sc-14z8sos-14 elGGzp"})

What am I missing?

I can accept any selenium code or Redsky API code but my priority is bs4

ANSWER

Answered 2021-Jun-09 at 10:13

You are simply using wrong locator.
Try this

price_css_locator = 'div[data-test=product-price]'

or in XPath style

price_xpath_locator = '//div[@data-test="product-price"]'

With bs4 it should be something like this:

soup.select('div[data-test="product-price"]')

to get the element get you just need to add .text

price = soup.select('div[data-test="product-price"]').text
print(price)

Source https://stackoverflow.com/questions/67901743

QUESTION

How to render an Array in ReactJS?

Asked 2021-May-26 at 20:10

I know there is a lot wrong, I need someone to help me out and fix/explain this. I'm trying to make a food ordering app and I need to render an array of objects. ps. I'm new to ReactJS and this is my first job with it.

Here is the error code I get: [The screenshot is at the end of the page][1] I need to render these objects in a component so I could export it to my main app. I hope there is someone out there to help me out.

import './css/foa-navigation.css';

const DUMMY_MEALS = [
    {
      id: 'm1',
      name: 'Triple B',
      description: 'Triple B burger for extreme meat lovers to feel the taste of 480 g (160 g x 3) charcoal grilled gourmet meat with melted cheese, lettuce and sauce in 4.5" ban.',
      price: 75,
    },
    {
      id: 'm2',
      name: 'Pina Colada',
      description: 'Charcoal grilled gourmet beef patty with pineapple, bacon, white cheese & pina colada sauce.',
      price: 44,
    },
    {
      id: 'm3',
      name: 'Mushroom Burger',
      description: 'Charcoal grilled gourmet beef patty with homemade pickles, mayo, Cheddar cheese, fresh mushrooms & rich homemade mushroom sauce',
      price: 44,
    },
    {
      id: 'm4',
      name: 'Mexican Burger',
      description: 'Charcoal grilled gourmet beef patty with homemade pickles, mayo, jalapeno, Emmental cheese & Mexican sauce.',
      price: 44,
    },
    {
      id: 'm5',
      name: 'Lads 70’s B',
      description: 'Charcoal grilled gourmet beef patty, homemade pickles, fresh mushrooms, grilled onions, egg, Cheddar & mozzarella cheese.',
      price: 44,
    },
    {
      id: 'm6',
      name: 'Hot Dog',
      description: '-',
      price: 28,
    },
    {
      id: 'm7',
      name: 'Double B',
      description: 'Double taste for meat lovers! 320 g (160 g x 2) of charcoal grilled patty with double cheese, lettuce and sauce in 4.5" ban.',
      price: 55,
    },
    {
      id: 'm8',
      name: 'Classic Burger',
      description: 'Charcoal grilled gourmet beef patty with iceberg lettuce, tomatoes, homemade pickles, onions, Cheddar cheese & chef’s sauce.',
      price: 39,
    },
    {
      id: 'm9',
      name: 'Big Lads',
      description: 'Charcoal grilled gourmet beef patty with iceberg lettuce, tomatoes, onions, mango, avocado, bacon, beetroot, mayo & white cheese.',
      price: 55,
    },
  ];

  const Card = () => {
    const mealsList = DUMMY_MEALS.map((meal) => (
      <MealItems
        key={meal.id}
        id={meal.id}
        name={meal.name}
        description={meal.description}
        price={meal.price}
      />
    ));
  
const MealItems = (props) => {
    <div className="col-md-4">
                <div className="item-add">
                  <div className="product_header">
                    <div className="product_name">
                      <span className="item-heading">{props.name}</span>
                    </div>
                  </div>
                  <div className="product_price">
                    <span className="item-price">
                    {props.price}<span> $</span>
                    </span>
                  </div>
                  <div className="product_description">
                  {props.description}{" "}
                  </div>
                </div>
              </div>

}
return (
      <div>
        <ul>{mealsList}</ul>
      </div>
  );
}
export default Card;```


  [1]: https://i.stack.imgur.com/g95BF.png
  [2]: https://i.stack.imgur.com/vZMR3.png

ANSWER

Answered 2021-May-26 at 14:29

If you are up for a refactor then i would suggest you to refactor the component as below . I would still prefer the MealItems to be in a separate file of its own.

const MealItems = (props) => (
  <div className="col-md-4">
    <div className="item-add">
      <div className="product_header">
        <div className="product_name">
          <span className="item-heading">{props.name}</span>
        </div>
      </div>
      <div className="product_price">
        <span className="item-price">
          {props.price}
          <span> $</span>
        </span>
      </div>
      <div className="product_description">{props.description} </div>
    </div>
  </div>
);

const Card = () => {
  return (
    <div>
      <ul>
        {DUMMY_MEALS.map((meal) => (
          <MealItems
            key={meal.id}
            id={meal.id}
            name={meal.name}
            description={meal.description}
            price={meal.price}
          />
        ))}
      </ul>
    </div>
  );
};

export default Card;

Source https://stackoverflow.com/questions/67706719

QUESTION

Having trouble finishing this python code

Asked 2021-Apr-26 at 22:12

I need help finishing this code. I cant figure out how to get a total dollar amount. Can anyone help with this? At the end I want it to have a detailed receipt with a total $amount. I can get it to print the receipt but I can figure out how to get a total. I just recently starting writing code so please do not judge me lol.

receipt = ""

print("Pizza size choices: ")
print("1 - small ($5)")
print("2 - medium ($7)")
print("3 - large ($10)")
size_choice = int(input("Your choice: "))

while size_choice < 1 or size_choice > 3:
    size_choice = int(input("Not a valid choice: "))

total_cost = 0

if size_choice == 1:
    total_cost += 5
    receipt += "Size: Small ($5)"
elif size_choice == 2:
    total_cost += 7
    receipt += "Size: Medium ($7)"
elif size_choice == 3:
    total_cost += 10
    receipt += "Size: Large ($10)"

receipt += "\n"

print("Pizza crust options: ")
print("1 - thin ($1)")
print("2 - very thin ($1.5)")
print("3 - thick ($2)")
crust_choice = int(input("Your choice: "))

while crust_choice < 1 or crust_choice > 3:
    crust_choice = int(input("Not a valid choice: "))


if crust_choice == 1:
    total_cost += 1
    receipt += "Crust: thin ($1)"
elif crust_choice ==2:
    total_cost += 1.5
    receipt += "Crust: very thin ($1.5)"
elif crust_choice == 3:
    total_cost += 2
    receipt += "Crust: thick ($2)"

receipt += "\n"

print("Pizza sauce options: ")
print("1 - Marinara ($0.50")
print("2 - Ranch ($0.75)")
sauce_choice = int(input("Your choice: "))

while sauce_choice < 1 or sauce_choice > 2:
    sauce_choice = int(input("Not a valid choice: "))


if sauce_choice == 1:
    total_cost += 0.5
    receipt += ("Sauce: Marinara ($0.50)")
elif sauce_choice == 2:
    total_cost += 0.75
    receipt += ("Sauce: Ranch ($0.75)")

receipt += "\n"

print("Cheese options: ")
print("1 - Mozzarella ($0.50")
print("2 - Cheddar ($0.50")
print("3 - Provolone ($0.50)")
cheese_choice = int(input("Your choice: "))

while cheese_choice < 1 or cheese_choice > 3:
    cheese_choice = int(input("Not a valid choice: "))

if cheese_choice == 1:
    total_cost += 0.5
    receipt += ("Cheese: Mozzarella ($0.50)")
elif cheese_choice == 2:
    total_cost += 0.5
    receipt += ("Cheese: Cheddar ($0.50)")
elif cheese_choice ==3:
    total_cost += 0.5
    receipt += ("Cheese: Provolone ($0.50)")

receipt += "\n" 

print("Topping options (Select up to 3): ")
print("1 - Mushrooms")
print("2 - Peppers")
print("3 - Olives")
print("4 - Onions")
print("5 - Pineapple")
print("6 - Spinach")
topping_choice = int(input("Your choice/choices are: "))

while topping_choice < 1 or topping_choice > 6:
    topping_choice = int(input("Not a valid choice: "))

if topping_choice == 1: 
    receipt += ("Mushrooms")
if topping_choice == 2: 
    receipt += ("Peppers")
if topping_choice == 3: 
    receipt += ("Olives")
if topping_choice == 4: 
    receipt += ("Onions")
if topping_choice == 5: 
    receipt += ("Pineapple")
if topping_choice == 6: 
    receipt += ("Spinach")

receipt += "\n"

print(receipt)

ANSWER

Answered 2021-Apr-26 at 22:12

At the end of your script because you are already keeping track of the total cost just print the variable total_cost. #Note: This should go at the end of the script

print(receipt)
print(f'total cost {total_cost}')

Edit Out of the kindness of my heart OP, I have created a basic idea of what you could do to accomplish your goal of giving three topping choices. The below code asks user for a number of topping choices. Then asks them which toppings they want. It's basic, i'd like you OP to clean it up and put it in the respectable place.

chosenToppings = []
while True:
    toppingCount = int(input('How many toppings would you like?: '))
    if toppingCount <= 3:
        for i in range(1,toppingCount+1):
            top = 1
            while top in [1,2,3]:
                top = int(input('Enter choice 1-3: '))
                chosenToppings.append(top)
                break
        break
    else:print('Enter a number less than three please')

Source https://stackoverflow.com/questions/67274011

QUESTION

XSLT Select multiple attribute with the same name

Asked 2021-Apr-08 at 21:11

Good morning, I am new to XLS and I trying to display a XML containing 'Menu' items . But each dish contain many ingredient tags , and I can't manage to display them in a list in my table . This is my XML:

<Menu>
    <dish Id='001'>
        <general_info>
            <name>Margharita</name>
            <description>Mozzarela slices, tomatoes, basil and extra olive oil</description>
            <type>Pizza</type>
        </general_info>

        <nutrition_info>
            <ingredient>Mozzarela</ingredient>
            <ingredient>tomatoes</ingredient>
            <ingredient>basil</ingredient>
            <ingredient>olive oil</ingredient>
            <ingredient>flour</ingredient>
            <dietary_restrictions>Allergic to Gluten</dietary_restrictions>
        </nutrition_info>

        <price>RS300</price>
    </dish>

    <dish Id='002'>
        <general_info>
            <name>Chicken Burger</name>
            <description>Chicken regular Hamburger</description>
            <type>Burger</type>
        </general_info>

        <nutrition_info>
            <ingredient>bread</ingredient>
            <ingredient>chicken</ingredient>
            <ingredient>tomato</ingredient>
            <ingredient>cheddar</ingredient>
            <ingredient>onions</ingredient>
            <ingredient>lettuce</ingredient>
            <dietary_restrictions></dietary_restrictions>
        </nutrition_info>

        <price>RS290</price>
    </dish>
</Menu>

And this is my XSL

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
    <body>
      <h2><center>Menu</center></h2>
          <table border="1">
              <tr bgcolor="orange">
                  <th>Name</th>
                  <th>Description</th>
                  <th>Type</th>
                  <th>Ingredients</th>
                  <th>dietary restrictions</th>
                  <th>Price</th>
              </tr>

              <xsl:for-each select="Menu/dish">
              <tr>
                  <td><xsl:value-of select="general_info/name"/></td>
                  <td><xsl:value-of select="general_info/description"/></td>
                  <td><xsl:value-of select="general_info/type"/></td>
                  <td>
                    <ul>
                      <xsl:for-each select="Menu/dish/nutrition_info">
                      <li><xsl:value-of select="ingredient"/></li>
                      </xsl:for-each>
                    </ul>
                  </td>
                  <td><xsl:value-of select="nutrition_info/dietary_restrictions"/></td>
                  <td><xsl:value-of select="price"/></td>
              </tr>
              </xsl:for-each>
          </table>
    </body>
  </html>
</xsl:template>

</xsl:stylesheet>

And i'm trying to achieve something like this:

Name      | Description | TYPE | Ingredients | dietary restrictions | Price
Margharita|.............|Pizza |list of items|......................|......
etc

Note that each dish may have a different number of ingredient attributes.

ANSWER

Answered 2021-Mar-26 at 07:31

you need to use relative path

<ul>
  <xsl:for-each select="nutrition_info">
    <xsl:for-each select="ingredient">
      <li><xsl:value-of select="."/></li>
    </xsl:for-each>
  </xsl:for-each>
</ul>

Source https://stackoverflow.com/questions/66812361

QUESTION

Spring validator does not detect errors

Asked 2021-Apr-07 at 09:02

This code is creating a hmtl form where you can select some chekcboxes and design a Taco. I am trying to perform model fields validation but it is not working. This code for example is supposed to return an error if the input field box of the name is empty or if no checkboxes are selected at all. The error variable in the controller though never catches any errors. What could possibly be happening. This code a copy paste example from the Spring in Action book so I'm not sure why it's not working.

Model

@Data
public class Taco {

 @NotNull
 @Size(min=5, message = "Name must be at least 5 characters long")
 private String name;
 @Size(min=1, message = "You must choose at least 1 ingredient")
 private List<String> ingredients;
}

Controller

@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController {

@GetMapping
public String showDesignFromModel(Model model){
    List<Ingredient> ingredients = Arrays.asList(
            new Ingredient("FLTO","Flour Tortilla", WRAP),
            new Ingredient("COTO","Corn Tortilla", WRAP),
            new Ingredient("GRBF","Ground Beef", PROTEIN),
            new Ingredient("CARN","Carnitas", PROTEIN),
            new Ingredient("TMTP","Diced Tomatoes", VEGGIES),
            new Ingredient("LETC","Lettuce", VEGGIES),
            new Ingredient("CHED","Cheddar", CHEESE),
            new Ingredient("JACK","Monterrey Jack", CHEESE),
            new Ingredient("SLSA","Salsa", SAUCE),
            new Ingredient("SRCR","Sour Cream", SAUCE)
    );


    Type[] types = Ingredient.Type.values();
    for (Type type : types){
        model.addAttribute(type.toString().toLowerCase(),
                ingredients.stream()
                        .filter(e -> e.getType() == type)
                        .collect(Collectors.toList()));

    }
    model.addAttribute("design",new Taco());
    return "design";
}

@PostMapping
public String processDesign(@Valid Taco design , Errors errors){
    if(errors.hasErrors()){
        System.out.println("Many errors " + errors);
        return "design";
    }
    System.out.println("Process design: " + design);
    System.out.println("No errors " + errors);
    log.info("Process design: " + design);
    return "redirect:/orders/current";
}
}

View

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:th="http://www.thymeleaf.org">

<head>
   <title>Taco Cloud</title>
   <link rel="stylesheet" th:href="@{/styles.css}" />
</head>

<body>
<h1>Design your taco!</h1>
<img th:src="@{/images/TacoCloud.png}" alt="Taco Cloud Logo"/>
<form method="POST" th:object="${design}">
    <div class="grid">
        <div class="ingredient-group" id="wraps">
           <h3>Designate your wrap:</h3>
           <div th:each="ingredient : ${wrap}">
               <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
               <span th:text="${ingredient.name}">INGREDIENT</span><br/>
           </div>
        </div>
        <div class="ingredient-group" id="proteins">
            <h3>Pick your protein:</h3>
            <div th:each="ingredient : ${protein}">
                <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                <span th:text="${ingredient.name}">INGREDIENT</span><br/>
            </div>
        </div>
        <div class="ingredient-group" id="cheeses">
            <h3>Choose your cheese:</h3>
            <div th:each="ingredient : ${cheese}">
                <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                <span th:text="${ingredient.name}">INGREDIENT</span><br/>
            </div>
        </div>
        <div class="ingredient-group" id="veggies">
            <h3>Determine your veggies:</h3>
            <div th:each="ingredient : ${veggies}">
                <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                <span th:text="${ingredient.name}">INGREDIENT</span><br/>
            </div>
        </div>
        <div class="ingredient-group" id="sauces">
            <h3>Select your sauce:</h3>
            <div th:each="ingredient : ${sauce}">
                <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                <span th:text="${ingredient.name}">INGREDIENT</span><br/>
            </div>
        </div>
    </div>
    <div>
        <h3>Name your taco creation:</h3>
        <input type="text" th:field="*{name}"/>
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Error</span>
        <br/>
        <button>Submit your taco</button>
    </div>
</form>
</body>


</html>

ANSWER

Answered 2021-Apr-07 at 09:02

When validation isn't working there is generally one thing that isn't right. There is no implementation for the javax.validation API on the classpath. Only adding a dependency to the validation-api from javax.validation will do nothing as that is only the API not an actual implementation.

You will need to add an implementation, like hibernate-validator, as well.

Now in earlier versions of Spring Boot (prior to 2.3) the validation was automatically included when adding spring-boot-starter-web as a dependency. However in newer version (2.3+) this has been removed. You now need to explicitly include the spring-boot-starter-validation starter dependency. This includes the API and an implementation.

That being said it could also be that instead of the Java Validation API you have the Jakarta Validation API on the classpath as well as an implementation of that (like hibernate-validator version 7 or up). The Jakarata Validation API (or most of the JakartaEE APIs) aren't support (yet) by Spring or Spring Boot. So even if you have that on your classpath it won't work, you need the Java Validation API one.

Source https://stackoverflow.com/questions/66972086

QUESTION

Display items with different properties ReactJS

Asked 2021-Apr-01 at 11:45

I have data

const menuItems = [
    { "id": "1", "category": "burger", "image": cranberryBurger, "title": "Cranberry", 
    "description": '100% Beef, Camembert, cranberry sauce, red onion, arugula, lamb`s lettuce', 
    "price": '5$'},
    { "id": "2", "category": "burger", "image": italianTaste, "title": "Italian taste", 
    "description": '100% Beef, mascarpone, black olives, dried tomatoes, red onion, arugula, iceberg lettuce', "price": '4$'},
    { "id": "3", "category": "burger", "image": mushroomBurger, "title": "Mushroom", 
    "description": '100% beef, mushrooms in sour cream, red onion, arugula, cheddar, iceberg lettuce', "price": '4$'},
    { "id": "4", "category": "burger", "image": seasonalBurger, "title": "Seasonal", 
    "description": '100% beef, tomato sauce, asparagus, red onion, iceberg lettuce, lamb`s lettuce', "price": '5$'},
    { "id": "5", "category": "burger", "image": vegeBurger, "title": "Vege", 
    "description": 'Halloumi cheese, red onion, beetroot marinated in honey, homemade sauce, sunflower sprouts, lamb`s lettuce', "price": '5$'},
    { "id": "6", "category": "crepe", "image": baconCrepe, "title": "Bacon", 
    "description": 'Mozzarella, grilled chicken, fried bacon, fresh tomatoes, BBQ sauce, spinach, arugula', "price": '5$'},
    { "id": "7", "category": "crepe", "image": fourCheeseCrepe, "title": "4 cheese", 
    "description": 'Mozzarella, gorgonzola, camembert, parmesan, white sauce, arugula', "price": '5$'},
    { "id": "8", "category": "crepe", "image": nutellaCrepe, "title": "Nutella", 
    "description": 'Nutella, Oreo bisquits, strawberries', "price": '5$'},
    { "id": "9", "category": "crepe", "image": salmonCrepe, "title": "Salmon", 
    "description": 'Philadelphia cheese, fresh salmon, avocado, fresh cucumber', "price": '5$'},
    { "id": "10", "category": "crepe", "image": vegeSalad, "title": "Vege salad", 
    "description": 'Beetroot marinated in honey, Halloumi cheese, pomegranate seeds, lamb`s lettuce, cashew nuts', "price": '5$'},
    { "id": "11", "category": "crepe", "image": coleslowSalad, "title": "Coleslow salad", 
    "description": 'Cabbage, lime juice, mayonnaise, lemongrass, coriander', "price": '5$'}
]

There is one property called "category" which has different value - either "burger" or "crepe". I want to pass "category": "burger" to one tab panel and "category": "crepe" to another tab panel.

<TabPanel>
        <div className="burgers">
          <ul> 
          {menuItems.map(menuItem => (
            <li key={menuItem.id}>
            <h4>{menuItem.title}</h4>
            <span>{menuItem.price}</span>
            <img src={menuItem.image} alt={menuItem.title} />
            <p>{menuItem.description}</p>
            <button type="submit" onClick={() => addToCart(menuItem)}>Add to cart</button>
            </li>
            ))}
          </ul>
        </div>
      </TabPanel>

I tried to check if menu item category matches "burger"

{menuItems.map(menuItem => (
         if (menuItem.category === "burger") {
           return <li key={menuItem.id}>
            <h4>{menuItem.title}</h4>
            <span>{menuItem.price}</span>
            <img src={menuItem.image} alt={menuItem.title} />
            <p>{menuItem.description}</p>
            <button type="submit" onClick={() => addToCart(menuItem)}>Add to cart</button>
            </li>
}
            ))}

It's not working. What am I missing or doing wrong?

ANSWER

Answered 2021-Apr-01 at 11:30
  1. use .filter()
  2. use destructuring
  3. add to cart only 'id' of product
  {menuItems
        .filter((v) => v.category === "burger")
        .map(({ id, title, price, image, title, description }) => {
          return (
            <li key={id}>
              <h4>{title}</h4>
              <span>{price}</span>
              <img src={image} alt={title} />
              <p>{description}</p>
              <button type="submit" onClick={() => addToCart(id)}>
                Add to cart
              </button>
            </li>
          );
        })}

Source https://stackoverflow.com/questions/66903535

QUESTION

How can I persist enum type field, with Hibernate?

Asked 2021-Mar-14 at 14:51

I have the following code

Repo

package my.taco.data;

import my.taco.models.Ingredient;
import org.springframework.data.repository.CrudRepository;

public interface  IngredientRepository extends CrudRepository <Ingredient,String> {
}

Controller

package my.taco.web;


import my.taco.data.IngredientRepository;
import my.taco.data.TacoRepository;
import my.taco.models.Ingredient;
import my.taco.models.Ingredient.Type;
import my.taco.models.Order;
import my.taco.models.Taco;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignTacoController {

    private final IngredientRepository ingredientRepo;
    private TacoRepository designRepo;

    @Autowired
    public DesignTacoController(IngredientRepository ingredientRepo,TacoRepository designRepo){
        this.ingredientRepo=ingredientRepo;
        this.designRepo=designRepo;
    }

    @ModelAttribute(name="order")
    public Order order(){
        return new Order();
    }

    @ModelAttribute(name = "design")
    public Taco taco(){
        return new Taco();
    }

    @GetMapping
    public String showDesignForm(Model model){
        List<Ingredient> ingredients= new ArrayList<>();
        ingredientRepo.findAll().forEach(i->ingredients.add(i));
        Type[] types=Ingredient.Type.values();
        for(Type type: types){
           model.addAttribute(type.toString().toLowerCase(),filterByType(ingredients,type));
        }
        return "design";
    }


    @PostMapping
    public String processDesign(@Valid Taco design, Errors errors,@ModelAttribute Order order){
        if(errors.hasErrors()){
            return "design";
        }
        Taco saved=designRepo.save(design);
        order.addDesign(saved);

        return "redirect:/orders/current";
    }

    private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type){

        return ingredients.stream()
                .filter(x->x.getType().equals(type))
                .collect(Collectors.toList());
    }
}

Domain

package my.taco.models;


import lombok.*;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@RequiredArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE,force = true)
@Entity
public class Ingredient {
    @Id
    private final String id;
    private final String name;
    private final Type type;

    public enum Type{
        WRAP,PROTEIN,VEGGIES,CHEESE,SAUCE
    }
}

View

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" lang="pl">
<head>
    <meta charset="utf-8">
    <title>Aplikacja Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}"/>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <h1>Przygotuj własne taco</h1>
    <img th:src="@{/images/TacoCloud.png}" class="img-thumbnail">

    <form method="POST" th:object="${design}">
        <div class="grid">
            <div class="ingredient-group" id="wraps">
                <h3>Wybierz rodzaj mąki:</h3>
                <div th:each="ingredient: ${wrap}">
                    <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                    <span th:text="${ingredient.name}">SKŁADNIK</span>
                </div>
            </div>
            <div class="ingredient-group" id="proteins">
                <h3>Wybierz mięso:</h3>
                <div th:each="ingredient : ${protein}">
                    <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                    <span th:text="${ingredient.name}">SKŁADNIK</span>
                </div>
            </div>
            <div class="ingredient-group" id="cheeses">
                <h3>Wybierz sery:</h3>
                <div th:each="ingredient: ${cheese}">
                    <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                    <span th:text="${ingredient.name}">SKŁADNIK</span>
                </div>
            </div>
            <div class="ingredient-group" id="veggies">
                <h3>Wybierz warzywa</h3>
                <div th:each="ingredient: ${veggies}">
                    <input name="ingredients" type="checkbox" th:value="${ingredient.id}"/>
                    <span th:text="${ingredient.name}">SKŁADNIK</span>
                </div>
                <div class="ingredient-group" id="sauces">
                    <h3>Wybierz sosy</h3>
                    <div th:each="ingredient: ${sauce}">
                        <input type="checkbox" th:value="${ingredient.id}"/>
                        <span th:text="${ingredient.name}">SKŁADNIK</span>
                    </div>
                </div>
            </div>
            <h3>Nadaj nazwę przygotowanemu taco:</h3>
            <button>Wyślij swoje zamówienie</button>
        </div>
    </form>
</div>
</body>
</html>

When i go to /design i have the following error

Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.

Sun Mar 14 00:28:34 CET 2021 There was an unexpected error
(type=Internal Server Error, status=500). could not execute query; SQL
[select ingredient0_.id as id1_0_, ingredient0_.name as name2_0_,
ingredient0_.type as type3_0_ from ingredient ingredient0_]; nested
exception is org.hibernate.exception.DataException: could not execute
query org.springframework.dao.DataIntegrityViolationException: could
not execute query; SQL [select ingredient0_.id as id1_0_,
ingredient0_.name as name2_0_, ingredient0_.type as type3_0_ from
ingredient ingredient0_]; nested exception is
org.hibernate.exception.DataException: could not execute query    
  at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:280)
  at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
  at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
  at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
  at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
  at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
  at com.sun.proxy.$Proxy96.findAll(Unknown Source)   
  at my.taco.web.DesignTacoController.showDesignForm(DesignTacoController.java:49)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.base/java.lang.reflect.Method.invoke(Method.java:564)   
  at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
  at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
  at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
  at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)     
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)     
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346)
  at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
  at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
  at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684)
  at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.base/java.lang.Thread.run(Thread.java:832) 
Caused by:
org.hibernate.exception.DataException: could not execute query    
  at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
  at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
  at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
  at org.hibernate.loader.Loader.doList(Loader.java:2852)     
  at org.hibernate.loader.Loader.doList(Loader.java:2831)  at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2663)    at org.hibernate.loader.Loader.list(Loader.java:2658)    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)   at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400)
  at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
  at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414)   
  at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1625)
  at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1593)
  at org.hibernate.query.Query.getResultList(Query.java:165)  
  at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:76)
  at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:356)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)   
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.base/java.lang.reflect.Method.invoke(Method.java:564)   
  at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
  at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
  at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
  at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:524)
  at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)
  at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:531)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:156)
  at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
  at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
  ... 58 more 
Caused by: org.h2.jdbc.JdbcSQLDataException: Błądkonwersji danych "WRAP" Data conversion error converting "WRAP" [22018-200]   
  at org.h2.message.DbException.getJdbcSQLException(DbException.java:457)
  at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
  at org.h2.message.DbException.get(DbException.java:194)     
  at org.h2.value.Value.convertTo(Value.java:875)  at org.h2.value.Value.convertTo(Value.java:737)  at org.h2.value.Value.getInt(Value.java:623)     at org.h2.jdbc.JdbcResultSet.getInt(JdbcResultSet.java:352)  at com.zaxxer.hikari.pool.HikariProxyResultSet.getInt(HikariProxyResultSet.java)
  at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$2.doExtract(IntegerTypeDescriptor.java:62)
  at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
  at org.hibernate.metamodel.model.convert.internal.OrdinalEnumValueConverter.readValue(OrdinalEnumValueConverter.java:66)
  at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:250)   
  at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:119)    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:91)     at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3135)
  at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1869)
  at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1797)
  at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1770)
  at org.hibernate.loader.Loader.getRow(Loader.java:1622)     at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:740)  at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1039)    at org.hibernate.loader.Loader.processResultSet(Loader.java:990)     at org.hibernate.loader.Loader.doQuery(Loader.java:959)  at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
  at org.hibernate.loader.Loader.doList(Loader.java:2849)     ... 89 more
Caused by: java.lang.NumberFormatException: For input string: "WRAP"
  at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
  at java.base/java.lang.Integer.parseInt(Integer.java:652)   at java.base/java.lang.Integer.parseInt(Integer.java:770)    at org.h2.value.Value.convertToInt(Value.java:982)   at org.h2.value.Value.convertTo(Value.java:806)  ... 110 more

Idk what`s wrong

schema.sql

create table if not exists Ingredient (id varchar(4) not null,
name varchar(40) not null, type varchar(10) not null);

data.sql

> delete from Taco_Order_Tacos; delete from Taco_Ingredients; delete
> from Taco; delete from Taco_Order;
> 
> delete from Ingredient;
> 
> insert into Ingredient (id, name, type)
>                 values ('FLTO', 'Flour Tortilla', 'WRAP'); insert into Ingredient (id, name, type)
>                 values ('COTO', 'Corn Tortilla', 'WRAP'); insert into Ingredient (id, name, type)
>                 values ('GRBF', 'Ground Beef', 'PROTEIN'); insert into Ingredient (id, name, type)
>                 values ('CARN', 'Carnitas', 'PROTEIN'); insert into Ingredient (id, name, type)
>                 values ('TMTO', 'Diced Tomatoes', 'VEGGIES'); insert into Ingredient (id, name, type)
>                 values ('LETC', 'Lettuce', 'VEGGIES'); insert into Ingredient (id, name, type)
>                 values ('CHED', 'Cheddar', 'CHEESE'); insert into Ingredient (id, name, type)
>                 values ('JACK', 'Monterrey Jack', 'CHEESE'); insert into Ingredient (id, name, type)
>                 values ('SLSA', 'Salsa', 'SAUCE'); insert into Ingredient (id, name, type)
>                 values ('SRCR', 'Sour Cream', 'SAUCE');

Added data and schema for more details about problem. type is varchar type so idk why i have number exception i dont have any number in my table

ANSWER

Answered 2021-Mar-14 at 14:51

You should add @Enumerated(EnumType.STRING) on your type field, like:

@Enumerated(EnumType.STRING)
private final Type type;

This will allow persisting Enum field, as a string, in the corresponding varchar column.

Ingredient table's type column is of a varchar type, and enum needs to be represented as a String, in order to get mapped to that column.

Source https://stackoverflow.com/questions/66619611

QUESTION

Iterate through list of lists and remove unwanted strings

Asked 2021-Mar-04 at 12:25

I'm having a play about and I've scraped a ingredient list from a website. I now have a list of lists.

ingrediant_list = []

for ingrediant in soup.select('.wprm-recipe-ingredient'):
    ingrediant_list.append(ingrediant.text)

full_list = []

for item in ingrediant_list:
    full_list.append(item.split())

This is my code that generates the list of lists. First I get the ingredients from the website and throw them into ingrediants_list; then I split each string into a separate list generating a list of lists under full_list

My list is as follows:

[['400', 'g', '5%', 'Fat', 'Minced', 'Beef'], ['1', 'large', 'Onion', 'finely', 'chopped'], ['3', 'cloves', 'Garlic', 'finely', 'grated'], ['5', 'Mushrooms', 'sliced'], ['1', 'large', 'Carrot', 'finely', 'chopped'], ['1', 'stick', 'Celery', 'finely', 'chopped'], ['1', 'Red', 'Pepper', 'finely', 'chopped'], ['2', 'tins', 'Chopped', 'Tomatoes'], ['1', 'tbsp', 'Tomato', 'Puree'], ['1', 'tbsp', 'Mixed', 'Italian', 'Herbs'], ['1', 'tbsp', 'Balsamic', 'Vinegar'], ['1', 'Red', 'Wine', 'Stock', 'Pot'], ['250', 'ml', 'Beef', 'Stock', 'make', 'using', '1-2', 'beef', 'stock', 'cubes'], ['dash', "Henderson's", 'Relish/Worcestershire', 'Sauce'], ['Low', 'Calorie', 'Cooking', 'Spray'], ['200', 'g', 'Dried', 'Pasta', 'use', 'whichever', 'shape', 'you', 'prefer'], ['80', 'g', 'Reduced', 'Fat', 'Cheddar', 'Cheese']]

How can I iterate through this list of lists removing strings like 'finely', 'chopped' and 'grated', replace the 'tbsp' with 'grams', and then create another list similar to 'ingrediants_list' with none of stuff I didn't want?

ANSWER

Answered 2021-Mar-04 at 11:23
newlist  = [i for i in oldlist if unwanted_string not in i]

I'll expand with an example

item_list = ["BigCar", "SmallCar", "BigHouse", "SmallHouse"]
unwanted_string = "Big"
[i for i in item_list if not unwanted_string in i]

Result:

['SmallCar', 'SmallHouse']

Source https://stackoverflow.com/questions/66473910

QUESTION

WhiteLabel Error page with no error message in sts console

Asked 2021-Feb-16 at 13:16

I am in the first steps of making a basic app following the book Spring in action, fifth edition. But right now I am seeing the following error message in browser, and no logs are printed in console. Below are the code:

Controller method:

@Controller
@RequestMapping("/design")
public class DesignTacoController {
    @GetMapping  
    public String showDesignForm(Model model) {   
        List<Ingredient> ingredients = Arrays.asList(new Ingredient("FLTO", "Flour Tortilla", Ingredient.Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Ingredient.Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Ingredient.Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Ingredient.Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatoes", Ingredient.Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Ingredient.Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Ingredient.Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Ingredient.Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Ingredient.Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Ingredient.Type.SAUCE));
        Type[] types = Ingredient.Type.values();
            for (Type type : types) {
                model.addAttribute(type.toString().toLowerCase(), 
                filterByType(ingredients, type));    
                }    
        model.addAttribute("tacodesign", new Taco());    
        return "tacodesign";  
        }

    private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
        return ingredients.stream().filter(x -> x.getType().equals(type)).collect(Collectors.toList());  
        }
    
    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("templates/");
        //resolver.setSuffix(".html");
        return resolver;
    }

Model:

package com.example.demo.taco.model;

import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class Ingredient {
    private String id;
    private String name;
    private Type type;

    public static enum Type {
        WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
    }

    public Ingredient(String id, String name, Type type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Type getType() {
        return type;
    }
}

View(using thymeleaf):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:th="http://www.thymeleaf.org" 
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Taco Cloud</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
    <h1>Design your taco!</h1>
    <img th:src="@{/images/TacoCloud.png}" />
    <form method="POST" th:object="${tacodesign}">
        <div class="grid">
            <div class="ingredient-group" id="wraps">
                <h3>Designate your wrap:</h3>
                <div th:each="ingredient : ${wrap}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span
                        th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="proteins">
                <h3>Pick your protein:</h3>
                <div th:each="ingredient : ${protein}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span
                        th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="cheeses">
                <h3>Choose your cheese:</h3>
                <div th:each="ingredient : ${cheese}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span
                        th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="veggies">
                <h3>Determine your veggies:</h3>
                <div th:each="ingredient : ${veggies}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span
                        th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
            <div class="ingredient-group" id="sauces">
                <h3>Select your sauce:</h3>
                <div th:each="ingredient : ${sauce}">
                    <input name="ingredients" type="checkbox"
                        th:value="${ingredient.id}" /> <span
                        th:text="${ingredient.name}">INGREDIENT</span><br />
                </div>
            </div>
        </div>
        <div>
            <h3>Name your taco creation:</h3>
            <input type="text" th:field="*{name}" /><br/>
            <button>Submit your taco</button>
        </div>
    </form>
</body>
</html>

SpringBootStarter:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TacoCloudApplication {

    public static void main(String[] args) {
        SpringApplication.run(TacoCloudApplication.class, args);
    }

}

Below is the screenshot of folder structure:

Screenshot of folder structure

Screenshot of the error:

Screenshot of the error

I took some inputs from the below links and it did help me to remove the old errors, but now i am stuck with this one. Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers How to avoid the "Circular view path" exception with Spring MVC test

ANSWER

Answered 2021-Jan-14 at 23:57

The problem is that you need to provide the right template as the return value of the showDesignForm in your controller.

Please, return TacoHome instead of tacodesign:

@GetMapping  
    public String showDesignForm(Model model) {   
        List<Ingredient> ingredients = Arrays.asList(new Ingredient("FLTO", "Flour Tortilla", Ingredient.Type.WRAP),
                new Ingredient("COTO", "Corn Tortilla", Ingredient.Type.WRAP),
                new Ingredient("GRBF", "Ground Beef", Ingredient.Type.PROTEIN),
                new Ingredient("CARN", "Carnitas", Ingredient.Type.PROTEIN),
                new Ingredient("TMTO", "Diced Tomatoes", Ingredient.Type.VEGGIES),
                new Ingredient("LETC", "Lettuce", Ingredient.Type.VEGGIES),
                new Ingredient("CHED", "Cheddar", Ingredient.Type.CHEESE),
                new Ingredient("JACK", "Monterrey Jack", Ingredient.Type.CHEESE),
                new Ingredient("SLSA", "Salsa", Ingredient.Type.SAUCE),
                new Ingredient("SRCR", "Sour Cream", Ingredient.Type.SAUCE));
        Type[] types = Ingredient.Type.values();
            for (Type type : types) {
                model.addAttribute(type.toString().toLowerCase(), 
                filterByType(ingredients, type));    
                }    
        model.addAttribute("tacodesign", new Taco());    
        // Set the template name to the appropriate value
        // Generally speaking, it should match a file name in the
        // templates directory, without the extension
        return "TacoHome";  
  }

Source https://stackoverflow.com/questions/65728082

QUESTION

Logs complaining &quot;extensions/v1beta1 Ingress is deprecated&quot;

Asked 2021-Feb-15 at 12:15

Very new to Kubernetes.

I'm adding an Ingres as follows:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: cheddar
spec:
  rules:
  - host: cheddar.213.215.191.78.nip.io
    http:
      paths:
      - backend:
          service:
            name: cheddar
            port:
              number: 80
        path: /
        pathType: ImplementationSpecific

but the logs complain:

W0205 15:14:07.482439       1 warnings.go:67] extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
time="2021-02-05T15:14:07Z" level=info msg="Updated ingress status" namespace=default ingress=cheddar
W0205 15:18:19.104225       1 warnings.go:67] networking.k8s.io/v1beta1 IngressClass is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 IngressClassList

Why? What's the correct yaml to use? I'm currently on microk8s 1.20

ANSWER

Answered 2021-Feb-15 at 12:15

I have analyzed you issue and came to the following conclusions:

  1. The Ingress will work and these Warnings you see are just to inform you about the available api versioning. You don't have to worry about this. I've seen the same Warnings:

@microk8s:~$ kubectl describe ing
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
  1. As for the "why" this is happening even when you use apiVersion: networking.k8s.io/v1, I have found the following explanation:

This is working as expected. When you create an ingress object, it can be read via any version (the server handles converting into the requested version). kubectl get ingress is an ambiguous request, since it does not indicate what version is desired to be read.

When an ambiguous request is made, kubectl searches the discovery docs returned by the server to find the first group/version that contains the specified resource.

For compatibility reasons, extensions/v1beta1 has historically been preferred over all other api versions. Now that ingress is the only resource remaining in that group, and is deprecated and has a GA replacement, 1.20 will drop it in priority so that kubectl get ingress would read from networking.k8s.io/v1, but a 1.19 server will still follow the historical priority.

If you want to read a specific version, you can qualify the get request (like kubectl get ingresses.v1.networking.k8s.io ...) or can pass in a manifest file to request the same version specified in the file (kubectl get -f ing.yaml -o yaml)

Long story short: despite the fact of using the proper apiVersion, the deprecated one is still being seen as the the default one and thus generating the Warning you experience.

I also see that changes are still being made recently so I assume that it is still being worked on.

Source https://stackoverflow.com/questions/66080909

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL Cheddar

You can use Cheddar like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Cheddar component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement Cheddar faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi