问:
How would I go about Creating a ShoppingCart inside of an Ecommerce Website (using Eclipse and MongoDB)
Lately, I have been working on an ecommerce website. So far, I have a basic POJO called "Product" which is supposed to represent each individual product for sale. I also have a ProductController, which performs the basic CRUD operations.

I have been wanting to create a ShoppingCart, and for each Product, there needs to be an option to add the Product to the ShoppingCart (the option is shown when you open a specific page of a product). The user should also be able to open the ShoppingCart and see the products inside.

I am having trouble though because I am not sure how to go about creating this. Am I supposed to create a separate ShoppingCart POJO that contains an arraylist of Products? Or am I supposed to keep the arraylist of products inside of the Product POJO? Or do I need to do something else entirely?

Here is my code so far, which does not work because Eclipse is saying that "the dependencies of some of the beans in the application context form a cycle":

ProductController.java

```<code>package com.ecommerce.website.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.ListCrudRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.repository.ProductRepository;

/**This is the product controller class. It has different mappings as well as the methods that allow
 * the user to perform the different CRUD operations with regard to the products. */
@Controller
public class ProductController {

    //Creating ProductRepository object and injecting dependency using @Autowired
    @Autowired
    ProductRepository productRepository;

    //This method maps for /product endpoint. It gathers the products from the database and displays them via product.html
    //@model The model being passed in to hold the products from database
    //return product.html page
    @RequestMapping("/product")
    public String product(Model model) {

        //Find all products from database, and put them in model, and the name of this model is "products"
        //html page will use "products" to display/modify the model
        model.addAttribute("products", productRepository.findAll());

        //Display html page
        return "product";
    }

    //This method maps for /create endpoint. It shows the "create product" html page
    //@model The model being passed in to hold the products from database
    //return create.html page
    @RequestMapping("/create")
    public String create(Model model) {

        //Display html page
        return "create";
    }

    //This method maps for /save endpoint. It allows the user to save a product from the create.html page
    //prodName's (and the other variables passed in) value is captured from html page using @RequestParam
    //return show.html page that shows the product and its information
    @RequestMapping("/save")
    public String save(@RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {

        //Create new product object, and enter information into the product's fields; values are what is passed in using @RequestParam
        Product product = new Product();
        product.setProdName(prodName);
        product.setProdDesc(prodDesc);
        product.setProdPrice(prodPrice);
        product.setProdImage(prodImage);

        //Save the product
        productRepository.save(product);

        //Return to show.html to show the created product
        return "redirect:/show/" + product.getId();
    }

    //This method maps for /show/{id} endpoint.
    //id that is given the value of {id} from the URL via @Pathvariable
    //@model The model being passed in to hold the product from database
    //return show.html page
    @RequestMapping("/show/{id}")
    public String show(@PathVariable String id, Model model) {

        //Find product from database that has the id that is being searched for, and put it in model, and the name of this model is "product"
        //html page will use "product" to display/modify the model
        model.addAttribute("product", productRepository.findById(id).get());

        //Display html page
        return "show";
    }

    //This method maps for /delete endpoint. It uses the id to find the product that needs to be deleted and deletes it
    //id's value is captured from html page using @RequestParam
    //return product.html page
    @RequestMapping("/delete")
    public String delete(@RequestParam String id) {

        //Search for the product and delete it
        Optional<Product> product = productRepository.findById(id);
        productRepository.delete(product.get());

        //Redirected back to product list page
        return "redirect:/product";
    }

    //This method maps for /edit/{id} endpoint.
    //id that is given the value of {id} from the URL via @Pathvariable
    //@model The model being passed in to hold the product from database
    //return edit.html page
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable String id, Model model) {

        //Find product from database that has the id that is being searched for, put it in model, and the name of this model is "product"
        //html page will use "product" to display/modify the model
        model.addAttribute("product", productRepository.findById(id).get());

        //Display html page
        return "edit";
    }

    //This method maps for /update endpoint.
    //id's (and the other variables passed in) value is captured from html page using @RequestParam
    //return show.html that shows the product and its information
    @RequestMapping("/update")
    public String update(@RequestParam String id, @RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {

        //Search for the product
        Optional<Product> product = productRepository.findById(id);

        //Updating the product's fields; new values are what is passed in using @RequestParam
        product.get().setProdName(prodName);
        product.get().setProdDesc(prodDesc);
        product.get().setProdPrice(prodPrice);
        product.get().setProdImage(prodImage);

        //Saving the product
        productRepository.save(product.get());

        //Redirecting to show.html page that shows the updated product and its information
        return "redirect:/show/" + product.get().getId();
    }

}
</code>```

ShoppingCartController.java

```<code>package com.ecommerce.website.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;
import com.ecommerce.website.repository.ShoppingCartRepository;

@Controller
public class ShoppingCartController {

    //Inject dependency
    @Autowired
    ShoppingCartRepository shoppingCartRepository;

    //Creating productRepository and shoppingCart objects
    CrudRepository<Product, String> productRepository;
    ShoppingCart shoppingCart = new ShoppingCart();

    @RequestMapping("/showShoppingCart")
    public String showShoppingCart(Model model) {

        //Getting the arraylist of products inside of the shoppingCartRepository
        model.addAttribute("shoppingcart", shoppingCartRepository.showShoppingCartProducts());

        //Return page showing shoppingcart.html
        return "shoppingcart";
    }

    @RequestMapping("/addToShoppingCart/{id}")
    public String addToShoppingCart(@PathVariable String id) {

        //ShoppingCart object
        ShoppingCart shoppingCart = new ShoppingCart();

        //Find product from database that has the id that is being searched for
        Optional<Product> productToBeAdded = productRepository.findById(id);

        //Add the product to the shoppingCart
        shoppingCart.addProductToShoppingCart(productToBeAdded);

        //Saving the shoppingCart to the shoppingCartRepository
        shoppingCartRepository.save(shoppingCart);

        //Stay on the same page
        return null;

    }

}
</code>```

Product.java

```<code>package com.ecommerce.website.model;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;

/**This is the product POJO class. It connects to the products collection in MongoDB. It also has different
 * properties that vary depending on the product. Additionally, it contains getter and setter methods. */
@Document(collection = "products")
public class Product {

    //Fields (@Id used to mark primary key)
    @Id
    String id;

//    @NotBlank
    @Max(value=10, message="must be less than or equal to 10")
    String prodName;

//  @NotBlank
    String prodDesc;

    @Min((long) 5d)
    Double prodPrice;
    String prodImage;

    //Constructors, getters, and setters
    public Product() {
    }

    public Product(String id, @Max(value = 10, message = "must be less than or equal to 10") String prodName,
            String prodDesc, @Min(5) Double prodPrice, String prodImage, ArrayList<Optional<Product>> productsInShoppingCart,
            int shoppingCartCount, double shoppingCartTotalPrice) {
        super();
        this.id = id;
        this.prodName = prodName;
        this.prodDesc = prodDesc;
        this.prodPrice = prodPrice;
        this.prodImage = prodImage;

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getProdName() {
        return prodName;
    }

    public void setProdName(String prodName) {
        this.prodName = prodName;
    }

    public String getProdDesc() {
        return prodDesc;
    }

    public void setProdDesc(String prodDesc) {
        this.prodDesc = prodDesc;
    }

    public Double getProdPrice() {
        return prodPrice;
    }

    public void setProdPrice(Double prodPrice) {
        this.prodPrice = prodPrice;
    }

    public String getProdImage() {
        return prodImage;
    }

    public void setProdImage(String prodImage) {
        this.prodImage = prodImage;
    }

}
</code>```

ShoppingCart.java

```<code>package com.ecommerce.website.model;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="shoppingcarts")
public class ShoppingCart {

    //Primary key to represent shopping cart
    @Id
    String shoppingCartId;

    //Arraylist to hold products
    ArrayList<Optional<Product>> shoppingCartItems;

    //Variables to display the number of products and the total price of the products in the cart
    int shoppingCartCount;
    double shoppingCartTotalPrice;

    //Constructors
    public ShoppingCart() {
    }

    public ShoppingCart(String shoppingCartId, ArrayList<Optional<Product>> shoppingCartItems, int shoppingCartCount,
            double shoppingCartTotalPrice) {
        this.shoppingCartId = shoppingCartId;
        this.shoppingCartItems = shoppingCartItems;
        this.shoppingCartCount = shoppingCartCount;
        this.shoppingCartTotalPrice = shoppingCartTotalPrice;
    }

    //Method to add a product to shoppingCartItems
    public void addProductToShoppingCart(Optional<Product> product) {
        shoppingCartItems.add(product);
    }

    //Method to return products inside of shoppingCartItems
    public ArrayList<Optional<Product>> getShoppingCartItems() {
        return shoppingCartItems;
    }

    //Getters and setters
    public String getShoppingCartId() {
        return shoppingCartId;
    }

    public void setShoppingCartId(String shoppingCartId) {
        this.shoppingCartId = shoppingCartId;
    }

    public void setShoppingCartItems(ArrayList<Optional<Product>> shoppingCartItems) {
        this.shoppingCartItems = shoppingCartItems;
    }

    public int getShoppingCartCount() {
        return shoppingCartCount;
    }

    public void setShoppingCartCount(int shoppingCartCount) {
        this.shoppingCartCount = shoppingCartCount;
    }

    public double getShoppingCartTotalPrice() {
        return shoppingCartTotalPrice;
    }

    public void setShoppingCartTotalPrice(double shoppingCartTotalPrice) {
        this.shoppingCartTotalPrice = shoppingCartTotalPrice;
    }

}
</code>```

ProductRepository.java

```<code>package com.ecommerce.website.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Product;

/**This is the product repository. This is what connects the project model/POJO to the database. Also, the\
 * interface extends from the MongoRepository so that the latter has access to the CRUD functionalities */
public interface ProductRepository extends MongoRepository<Product, String> {

}
</code>```

ShoppingCartRepository.java

```<code>package com.ecommerce.website.repository;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;

public interface ShoppingCartRepository extends MongoRepository<ShoppingCart, String> {

    //Method to show products inside of shopping cart
    public ArrayList<Optional<Product>> showShoppingCartProducts();

}
</code>```

ShoppingCartRepositoryImpl.java

```<code>package com.ecommerce.website.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;

public class ShoppingCartRepositoryImpl implements ShoppingCartRepository {

    //Inject dependency
    @Autowired
    ShoppingCartRepository shoppingCartRepository;

    //shoppingCart object
    ShoppingCart shoppingCart;

    //Method to show products inside of shopping cart
    @Override
    public ArrayList<Optional<Product>> showShoppingCartProducts() {

        return shoppingCart.getShoppingCartItems();

    }

    @Override
    public <S extends ShoppingCart> S insert(S entity) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> insert(Iterable<S> entities) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> findAll(Example<S> example) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> findAll(Example<S> example, Sort sort) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> saveAll(Iterable<S> entities) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<ShoppingCart> findAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<ShoppingCart> findAllById(Iterable<String> ids) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> S save(S entity) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Optional<ShoppingCart> findById(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean existsById(String id) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public long count() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void deleteById(String id) {
        // TODO Auto-generated method stub

    }

    @Override
    public void delete(ShoppingCart entity) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAllById(Iterable<? extends String> ids) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAll(Iterable<? extends ShoppingCart> entities) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAll() {
        // TODO Auto-generated method stub

    }

    @Override
    public List<ShoppingCart> findAll(Sort sort) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Page<ShoppingCart> findAll(Pageable pageable) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> Optional<S> findOne(Example<S> example) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> Page<S> findAll(Example<S> example, Pageable pageable) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> long count(Example<S> example) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public <S extends ShoppingCart> boolean exists(Example<S> example) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public <S extends ShoppingCart, R> R findBy(Example<S> example,
            Function<FetchableFluentQuery<S>, R> queryFunction) {
        // TODO Auto-generated method stub
        return null;
    }

}
</code>```

show.html (page to show each product)

```<code><!DOCTYPE HTML>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="default">
    <head>
        <title>Show Product</title>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">

                <!-- Link that maps to /product, which takes the user to product.html -->
                <h3>
                    <a href="/product" class="btn btn-primary"><span class="glyphicon glyphicon-list"></span>Product List</a>

                </h3>

                <!-- Text showing the product name, image, description, and price (uses the model from /show to access this information) -->
                <h2 th:text="${product.prodName}"></h2>
                <h2><img th:src="${product.prodImage}" width="200" /></h2>
                <dl class="list">
                    <dt>Product Description</dt>
                    <dd th:text="${product.prodDesc}"></dd>
                    <dt>Product Price</dt>
                    <dd th:text="${product.prodPrice}"></dd>
                </dl>

                <!-- Mapping to the /delete endpoint -->
                <form action="/delete">

                    <!-- Input that contains name="id" so that the endpoint can capture it using @RequestParam -->
                    <input type="hidden" name="id" th:value="${product.id}" />

                    <!-- Buttons: first deletes the product; second maps to the /edit endpoint, which takes the user to edit.html
                         for whichever product the product.id is for (id is appended to the URL, which is how the /show endpoint
                         is able to access it -->
                    <h2><input type="submit" class="btn btn-danger" value="Delete" onclick="return confirm('Are you sure?');" />
                        <a th:href="@{'/edit/' + ${product.id}}" class="btn btn-warning">Edit</a></h2>
                </form>

                <!-- Mapping to the /delete endpoint -->
                <form action="/addToShoppingCart/{id}">

                    <!-- Input that contains name="id" so that the endpoint can capture it using @RequestParam -->
                    <h2><input type="hidden" name="id" th:value="${product.id}" />
                        <a th:href="@{'/addToShoppingCart/' + ${product.id}}" class="btn btn-warning">Add to Cart</a></h2>

                </form>
            </div>
        </div>
    </body>
</html>
</code>```

shoppingcart.html (to show the shopping cart of items)

```<code><!DOCTYPE HTML>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="default">
    <head>
        <title>Shopping Cart</title>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">

                <!-- Link that maps to /create, which takes the user to create.html -->
                <h3>
                    <a href="/create" class="btn btn-primary"><span class="glyphicon glyphicon-plus-sign"></span>Create Product</a>
                </h3>

                <h2>Shopping Cart</h2>

                <div class="table-responsive">

                    <!-- Table to show the user all the products from the database -->
                    <table class="table" id="product-table">

                        <!-- Table headers -->
                        <thead>
                            <tr>
                                <th>Product Name</th>
                                <th>Product Desc</th>
                                <th>Product Price</th>
                            </tr>
                        </thead>
                        <tbody>

                            <!-- Looping through each product in "products" from /product endpoint -->
                            <tr th:each="product : ${shoppingcart}">

                                <!-- For each product, make its name a link that maps to /show endpoint, which takes the user to show.html
                                     for whichever product the product.id is for (id is appended to the URL, which is how the /show endpoint
                                     is able to access it -->
                                <td><a th:text="${product.prodName}" th:href="@{'/show/' + ${product.id}}"></a></td>
                                <td th:text="${product.prodDesc}"></td>
                                <td th:text="${product.prodPrice}"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

At first, I tried creating an arraylist called ShoppingCart inside of my Product POJO, and then putting that arraylist inside of a model so that it can be displayed in the shoppingcart.html page, but that did not work. Then, I tried creating a separate ShoppingCart POJO, but so far, that has not worked for me.

Body:
Lately, I have been working on an ecommerce website. So far, I have a basic POJO called "Product" which is supposed to represent each individual product for sale. I also have a ProductController, which performs the basic CRUD operations.

I have been wanting to create a ShoppingCart, and for each Product, there needs to be an option to add the Product to the ShoppingCart (the option is shown when you open a specific page of a product). The user should also be able to open the ShoppingCart and see the products inside.

I am having trouble though because I am not sure how to go about creating this. Am I supposed to create a separate ShoppingCart POJO that contains an arraylist of Products? Or am I supposed to keep the arraylist of products inside of the Product POJO? Or do I need to do something else entirely?

Here is my code so far, which does not work because Eclipse is saying that "the dependencies of some of the beans in the application context form a cycle":

ProductController.java

package com.ecommerce.website.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.ListCrudRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.repository.ProductRepository;

/**This is the product controller class. It has different mappings as well as the methods that allow
 * the user to perform the different CRUD operations with regard to the products. */
@Controller
public class ProductController {

    //Creating ProductRepository object and injecting dependency using @Autowired
    @Autowired
    ProductRepository productRepository;

    //This method maps for /product endpoint. It gathers the products from the database and displays them via product.html
    //@model The model being passed in to hold the products from database
    //return product.html page
    @RequestMapping("/product")
    public String product(Model model) {

        //Find all products from database, and put them in model, and the name of this model is "products"
        //html page will use "products" to display/modify the model
        model.addAttribute("products", productRepository.findAll());

        //Display html page
        return "product";
    }

    //This method maps for /create endpoint. It shows the "create product" html page
    //@model The model being passed in to hold the products from database
    //return create.html page
    @RequestMapping("/create")
    public String create(Model model) {

        //Display html page
        return "create";
    }

    //This method maps for /save endpoint. It allows the user to save a product from the create.html page
    //prodName's (and the other variables passed in) value is captured from html page using @RequestParam
    //return show.html page that shows the product and its information
    @RequestMapping("/save")
    public String save(@RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {

        //Create new product object, and enter information into the product's fields; values are what is passed in using @RequestParam
        Product product = new Product();
        product.setProdName(prodName);
        product.setProdDesc(prodDesc);
        product.setProdPrice(prodPrice);
        product.setProdImage(prodImage);

        //Save the product
        productRepository.save(product);

        //Return to show.html to show the created product
        return "redirect:/show/" + product.getId();
    }

    //This method maps for /show/{id} endpoint.
    //id that is given the value of {id} from the URL via @Pathvariable
    //@model The model being passed in to hold the product from database
    //return show.html page
    @RequestMapping("/show/{id}")
    public String show(@PathVariable String id, Model model) {

        //Find product from database that has the id that is being searched for, and put it in model, and the name of this model is "product"
        //html page will use "product" to display/modify the model
        model.addAttribute("product", productRepository.findById(id).get());

        //Display html page
        return "show";
    }

    //This method maps for /delete endpoint. It uses the id to find the product that needs to be deleted and deletes it
    //id's value is captured from html page using @RequestParam
    //return product.html page
    @RequestMapping("/delete")
    public String delete(@RequestParam String id) {

        //Search for the product and delete it
        Optional<Product> product = productRepository.findById(id);
        productRepository.delete(product.get());

        //Redirected back to product list page
        return "redirect:/product";
    }

    //This method maps for /edit/{id} endpoint.
    //id that is given the value of {id} from the URL via @Pathvariable
    //@model The model being passed in to hold the product from database
    //return edit.html page
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable String id, Model model) {

        //Find product from database that has the id that is being searched for, put it in model, and the name of this model is "product"
        //html page will use "product" to display/modify the model
        model.addAttribute("product", productRepository.findById(id).get());

        //Display html page
        return "edit";
    }

    //This method maps for /update endpoint.
    //id's (and the other variables passed in) value is captured from html page using @RequestParam
    //return show.html that shows the product and its information
    @RequestMapping("/update")
    public String update(@RequestParam String id, @RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {

        //Search for the product
        Optional<Product> product = productRepository.findById(id);

        //Updating the product's fields; new values are what is passed in using @RequestParam
        product.get().setProdName(prodName);
        product.get().setProdDesc(prodDesc);
        product.get().setProdPrice(prodPrice);
        product.get().setProdImage(prodImage);

        //Saving the product
        productRepository.save(product.get());

        //Redirecting to show.html page that shows the updated product and its information
        return "redirect:/show/" + product.get().getId();
    }

}

ShoppingCartController.java

package com.ecommerce.website.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;
import com.ecommerce.website.repository.ShoppingCartRepository;

@Controller
public class ShoppingCartController {

    //Inject dependency
    @Autowired
    ShoppingCartRepository shoppingCartRepository;

    //Creating productRepository and shoppingCart objects
    CrudRepository<Product, String> productRepository;
    ShoppingCart shoppingCart = new ShoppingCart();

    @RequestMapping("/showShoppingCart")
    public String showShoppingCart(Model model) {

        //Getting the arraylist of products inside of the shoppingCartRepository
        model.addAttribute("shoppingcart", shoppingCartRepository.showShoppingCartProducts());

        //Return page showing shoppingcart.html
        return "shoppingcart";
    }

    @RequestMapping("/addToShoppingCart/{id}")
    public String addToShoppingCart(@PathVariable String id) {

        //ShoppingCart object
        ShoppingCart shoppingCart = new ShoppingCart();

        //Find product from database that has the id that is being searched for
        Optional<Product> productToBeAdded = productRepository.findById(id);

        //Add the product to the shoppingCart
        shoppingCart.addProductToShoppingCart(productToBeAdded);

        //Saving the shoppingCart to the shoppingCartRepository
        shoppingCartRepository.save(shoppingCart);

        //Stay on the same page
        return null;

    }

}

Product.java

package com.ecommerce.website.model;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;

/**This is the product POJO class. It connects to the products collection in MongoDB. It also has different
 * properties that vary depending on the product. Additionally, it contains getter and setter methods. */
@Document(collection = "products")
public class Product {

    //Fields (@Id used to mark primary key)
    @Id
    String id;

//    @NotBlank
    @Max(value=10, message="must be less than or equal to 10")
    String prodName;

//  @NotBlank
    String prodDesc;

    @Min((long) 5d)
    Double prodPrice;
    String prodImage;

    //Constructors, getters, and setters
    public Product() {
    }

    public Product(String id, @Max(value = 10, message = "must be less than or equal to 10") String prodName,
            String prodDesc, @Min(5) Double prodPrice, String prodImage, ArrayList<Optional<Product>> productsInShoppingCart,
            int shoppingCartCount, double shoppingCartTotalPrice) {
        super();
        this.id = id;
        this.prodName = prodName;
        this.prodDesc = prodDesc;
        this.prodPrice = prodPrice;
        this.prodImage = prodImage;

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getProdName() {
        return prodName;
    }

    public void setProdName(String prodName) {
        this.prodName = prodName;
    }

    public String getProdDesc() {
        return prodDesc;
    }

    public void setProdDesc(String prodDesc) {
        this.prodDesc = prodDesc;
    }

    public Double getProdPrice() {
        return prodPrice;
    }

    public void setProdPrice(Double prodPrice) {
        this.prodPrice = prodPrice;
    }

    public String getProdImage() {
        return prodImage;
    }

    public void setProdImage(String prodImage) {
        this.prodImage = prodImage;
    }

}

ShoppingCart.java

package com.ecommerce.website.model;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="shoppingcarts")
public class ShoppingCart {

    //Primary key to represent shopping cart
    @Id
    String shoppingCartId;

    //Arraylist to hold products
    ArrayList<Optional<Product>> shoppingCartItems;

    //Variables to display the number of products and the total price of the products in the cart
    int shoppingCartCount;
    double shoppingCartTotalPrice;

    //Constructors
    public ShoppingCart() {
    }

    public ShoppingCart(String shoppingCartId, ArrayList<Optional<Product>> shoppingCartItems, int shoppingCartCount,
            double shoppingCartTotalPrice) {
        this.shoppingCartId = shoppingCartId;
        this.shoppingCartItems = shoppingCartItems;
        this.shoppingCartCount = shoppingCartCount;
        this.shoppingCartTotalPrice = shoppingCartTotalPrice;
    }

    //Method to add a product to shoppingCartItems
    public void addProductToShoppingCart(Optional<Product> product) {
        shoppingCartItems.add(product);
    }

    //Method to return products inside of shoppingCartItems
    public ArrayList<Optional<Product>> getShoppingCartItems() {
        return shoppingCartItems;
    }

    //Getters and setters
    public String getShoppingCartId() {
        return shoppingCartId;
    }

    public void setShoppingCartId(String shoppingCartId) {
        this.shoppingCartId = shoppingCartId;
    }

    public void setShoppingCartItems(ArrayList<Optional<Product>> shoppingCartItems) {
        this.shoppingCartItems = shoppingCartItems;
    }

    public int getShoppingCartCount() {
        return shoppingCartCount;
    }

    public void setShoppingCartCount(int shoppingCartCount) {
        this.shoppingCartCount = shoppingCartCount;
    }

    public double getShoppingCartTotalPrice() {
        return shoppingCartTotalPrice;
    }

    public void setShoppingCartTotalPrice(double shoppingCartTotalPrice) {
        this.shoppingCartTotalPrice = shoppingCartTotalPrice;
    }

}

ProductRepository.java

package com.ecommerce.website.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Product;

/**This is the product repository. This is what connects the project model/POJO to the database. Also, the\
 * interface extends from the MongoRepository so that the latter has access to the CRUD functionalities */
public interface ProductRepository extends MongoRepository<Product, String> {

}

ShoppingCartRepository.java

package com.ecommerce.website.repository;

import java.util.ArrayList;
import java.util.Optional;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;

public interface ShoppingCartRepository extends MongoRepository<ShoppingCart, String> {

    //Method to show products inside of shopping cart
    public ArrayList<Optional<Product>> showShoppingCartProducts();

}

ShoppingCartRepositoryImpl.java

package com.ecommerce.website.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;

import com.ecommerce.website.model.Product;
import com.ecommerce.website.model.ShoppingCart;

public class ShoppingCartRepositoryImpl implements ShoppingCartRepository {

    //Inject dependency
    @Autowired
    ShoppingCartRepository shoppingCartRepository;

    //shoppingCart object
    ShoppingCart shoppingCart;

    //Method to show products inside of shopping cart
    @Override
    public ArrayList<Optional<Product>> showShoppingCartProducts() {

        return shoppingCart.getShoppingCartItems();

    }

    @Override
    public <S extends ShoppingCart> S insert(S entity) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> insert(Iterable<S> entities) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> findAll(Example<S> example) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> findAll(Example<S> example, Sort sort) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> List<S> saveAll(Iterable<S> entities) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<ShoppingCart> findAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<ShoppingCart> findAllById(Iterable<String> ids) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> S save(S entity) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Optional<ShoppingCart> findById(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean existsById(String id) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public long count() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void deleteById(String id) {
        // TODO Auto-generated method stub

    }

    @Override
    public void delete(ShoppingCart entity) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAllById(Iterable<? extends String> ids) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAll(Iterable<? extends ShoppingCart> entities) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAll() {
        // TODO Auto-generated method stub

    }

    @Override
    public List<ShoppingCart> findAll(Sort sort) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Page<ShoppingCart> findAll(Pageable pageable) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> Optional<S> findOne(Example<S> example) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> Page<S> findAll(Example<S> example, Pageable pageable) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <S extends ShoppingCart> long count(Example<S> example) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public <S extends ShoppingCart> boolean exists(Example<S> example) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public <S extends ShoppingCart, R> R findBy(Example<S> example,
            Function<FetchableFluentQuery<S>, R> queryFunction) {
        // TODO Auto-generated method stub
        return null;
    }

}

show.html (page to show each product)

<!DOCTYPE HTML>

        <title>Show Product</title>

                    Product List

Product Description

Product Price

                <form action="/delete">

                    <input type="hidden" name="id" th:value="${product.id}" />

<input type="submit" class="btn btn-danger" value="Delete" onclick="return confirm('Are you sure?');" />
                        Edit

                </form>

                <form action="/addToShoppingCart/{id}">

<input type="hidden" name="id" th:value="${product.id}" />
                        Add to Cart

                </form>

shoppingcart.html (to show the shopping cart of items)

<!DOCTYPE HTML>

        <title>Shopping Cart</title>

                    Create Product

Shopping Cart

                                Product Name
                                Product Desc
                                Product Price

At first, I tried creating an arraylist called ShoppingCart inside of my Product POJO, and then putting that arraylist inside of a model so that it can be displayed in the shoppingcart.html page, but that did not work. Then, I tried creating a separate ShoppingCart POJO, but so far, that has not worked for me.


来源: stackexchange

问:
Database Not Initializing with the Name in the URI String
I spin up my docker mongodb database locally:

version: "3.8"
services:
  mongodb:
    image: mongo:latest
    container_name: mongodb
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: name
    ports:
      - 27017:27017
    volumes:
      - mongodbdata:/data/db
volumes:
  mongodbdata:```
</div>
</div>
</p>
<p>I create my connection string with "name" as the initial database:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>MONGO_URI = "mongodb://root:password@localhost:27017/name"</code>```

I connect to my database:

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    mongoose.set("strictQuery", false);
    const conn = await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

module.exports = connectDB;```

Authentication Failed:

What am I doing wrong? It connects fine when I remove "name" from the connection string, but I need that name to initialize my database name. Without adding "name," the database name initializes to "test."

The flagged question more had to do with the "authentication failed" being the issue, but mine was that it wasn't initializing with the correct name which so happened to give a random authentication failed error. Completely different questions which requires a unique answer. I found the solution myself and it wasn't in the "related" post but the question was closed and now I can't answer my own question...

ContentLicense: CC BY-SA 4.0

Body:
I spin up my docker mongodb database locally:

version: "3.8"
services:
  mongodb:
    image: mongo:latest
    container_name: mongodb
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: name
    ports:
      - 27017:27017
    volumes:
      - mongodbdata:/data/db
volumes:
  mongodbdata:

I create my connection string with "name" as the initial database:

MONGO_URI = "mongodb://root:password@localhost:27017/name"

I connect to my database:

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    mongoose.set("strictQuery", false);
    const conn = await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

module.exports = connectDB;

Authentication Failed:

What am I doing wrong? It connects fine when I remove "name" from the connection string, but I need that name to initialize my database name. Without adding "name," the database name initializes to "test."

The flagged question more had to do with the "authentication failed" being the issue, but mine was that it wasn't initializing with the correct name which so happened to give a random authentication failed error. Completely different questions which requires a unique answer. I found the solution myself and it wasn't in the "related" post but the question was closed and now I can't answer my own question...


问:
Insert unique timestamp to sql server using spring batch chunk step
I have a table that stores current timestamp as a unique identifier. The format is “yyyy-MM-dd HH:mm:ss.SSSSSS”. Unfortunately with chunk oriented steps I’m seeing duplicate insert errors as multiple items gets the same timestamp. Please advise how can I handle this use case. I’m not in a position to change the Table definition to use any other unique identifiers.

I’ve tried to set the timestamp using the itemProcessor as it was failing originally when set at itemWriter. But results were same.

Also tested by introducing a sleep of 1 ns(Thread.Sleep(0,1)) but that made the spring batch job terribly slow. A sample job with 200K records that took under 2minutes was taking about 10-11 minutes after Thread.Sleep


问:
Creating a non-Attacking Queens game that is supposed to print out all 92 solutions of 8 queens on a chess board that cannot attack eachother
I made the 8x8 chess board and have a lot of the code done, but for some reason it only print out one solution, does anyone know why this may be and how I can fix it?

```<code>public class NonAttackingQueens {
    private int[][] board;
    private int solutionCount = 0;
    private boolean solutionFound = false;

    public NonAttackingQueens() {
        board = new int[8][8];
    }

    public boolean canPlace(int x, int y) {
        // Check if a queen is already placed at position (x, y)
        if (board[x][y] == 1) {
            return false;
        }

        // Check horizontal positions
        for (int i = 0; i < 8; i++) {
            if (board[x][i] == 1) {
                return false;
            }
        }

        // Check vertical positions
        for (int i = 0; i < 8; i++) {
            if (board[i][y] == 1) {
                return false;
            }
        }

        // Check diagonal positions
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == 1 && (Math.abs(i - x) == Math.abs(j - y))) {
                    return false;
                }
            }
        }

        return true;
    }

public void solve() {
    // Check if the solutionCount has reached 92
    if (solutionCount == 92) {
        return;
    }

    // Check if all 8 queens have been placed
    int queensPlaced = 0;
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if (board[i][j] == 1) {
                queensPlaced++;
            }
        }
    }
    if (queensPlaced == 8) {
        // All positions have been checked, so we have found a solution
        solutionCount++;
        System.out.println("Solution " + solutionCount + ":");
        print();
        return;
    }

    // Try to place a queen at each position on the board
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if (canPlace(i, j)) {
                // Place a queen at position (i, j) and try to solve the rest of the board
                board[i][j] = 1;
                solve();
                // Backtrack: remove the queen from position (i, j) and try the next position
                board[i][j] = 0;
            }
        }
    }
}

    public void print() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == 1) {
                    System.out.print(" X");
                } else {
                    System.out.print(" O");
                }
            }
            System.out.println();
        }
        System.out.println("---------------");
    }
}
</code>```

I'm doing this in blueJ, so I tried to run the void solve(); method and it runs, but it only prints out the first of 92 solutions 92 times. It should print out all 92 different solutions.

Body:
I made the 8x8 chess board and have a lot of the code done, but for some reason it only print out one solution, does anyone know why this may be and how I can fix it?

public class NonAttackingQueens {
    private int[][] board;
    private int solutionCount = 0;
    private boolean solutionFound = false;

    public NonAttackingQueens() {
        board = new int[8][8];
    }

    public boolean canPlace(int x, int y) {
        // Check if a queen is already placed at position (x, y)
        if (board[x][y] == 1) {
            return false;
        }

        // Check horizontal positions
        for (int i = 0; i < 8; i++) {
            if (board[x][i] == 1) {
                return false;
            }
        }

        // Check vertical positions
        for (int i = 0; i < 8; i++) {
            if (board[i][y] == 1) {
                return false;
            }
        }

        // Check diagonal positions
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == 1 && (Math.abs(i - x) == Math.abs(j - y))) {
                    return false;
                }
            }
        }

        return true;
    }

public void solve() {
    // Check if the solutionCount has reached 92
    if (solutionCount == 92) {
        return;
    }

    // Check if all 8 queens have been placed
    int queensPlaced = 0;
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if (board[i][j] == 1) {
                queensPlaced++;
            }
        }
    }
    if (queensPlaced == 8) {
        // All positions have been checked, so we have found a solution
        solutionCount++;
        System.out.println("Solution " + solutionCount + ":");
        print();
        return;
    }

    // Try to place a queen at each position on the board
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            if (canPlace(i, j)) {
                // Place a queen at position (i, j) and try to solve the rest of the board
                board[i][j] = 1;
                solve();
                // Backtrack: remove the queen from position (i, j) and try the next position
                board[i][j] = 0;
            }
        }
    }
}

    public void print() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == 1) {
                    System.out.print(" X");
                } else {
                    System.out.print(" O");
                }
            }
            System.out.println();
        }
        System.out.println("---------------");
    }
}

I'm doing this in blueJ, so I tried to run the void solve(); method and it runs, but it only prints out the first of 92 solutions 92 times. It should print out all 92 different solutions.


问:
is this binary tree function postorder or preorder?
My understanding is that in binary tree, the preorder traversal visits the root node first, then traverses the left subtree, and finally traverses the right subtree. The postorder traversal visits the left subtree, then the right subtree, and finally the root node.

In the final of my class this asks if this the function f() is preorder or postorder.

template
int f(treeNode* t)
{
   int n=0, leftValue, rightValue;
   if (t != NULL) {
      if (t->leftChild != NULL || t->rightChild != NULL)
         n++;
      leftValue = f(t->leftChild);
      rightValue = f(t->rightChild);
      return n + leftValue + rightValue;
   } else
      return 0;
}
```
<p>Doesn't this travel the down the left tree, the the right tree before processing anything? So it should be postorder shouldn't it?</p>
<p>Similar to how this function to delete the nodes in a binary tree:</p>
<pre class="lang-cpp prettyprint-override"><code>clear(Node* curr) {
   if (!curr)
      return;

   clear(curr->left);
   clear(curr->right);
   delete curr;
}
</code>```

Body:
My understanding is that in binary tree, the preorder traversal visits the root node first, then traverses the left subtree, and finally traverses the right subtree. The postorder traversal visits the left subtree, then the right subtree, and finally the root node.

In the final of my class this asks if this the function f() is preorder or postorder.

template
int f(treeNode* t)
{
   int n=0, leftValue, rightValue;
   if (t != NULL) {
      if (t->leftChild != NULL || t->rightChild != NULL)
         n++;
      leftValue = f(t->leftChild);
      rightValue = f(t->rightChild);
      return n + leftValue + rightValue;
   } else
      return 0;
}

Doesn't this travel the down the left tree, the the right tree before processing anything? So it should be postorder shouldn't it?

Similar to how this function to delete the nodes in a binary tree:

clear(Node* curr) {
   if (!curr)
      return;

   clear(curr->left);
   clear(curr->right);
   delete curr;
}


问:
JavaScript: how to perform a movement and rotation of an object like in RTS game?

The problem is follow:

when the object has a positive angle and if negative angle is clicked - it follows logic and makes a counterclockwise rotation instead of clockwise rotation like it requires and vice versa. It doesn`t look like rotation of a unit in RTS games. How to fix it?

`

```<code>var object = document.createElement("div");
object.style.backgroundColor = "red";
object.style.width = "50px";
object.style.height = "50px";
object.style.position = "absolute";
object.style.transition = "transform 3s";
document.body.appendChild(object);

function action(event){
        mousePosition = {
            x : event.clientX - (object.offsetWidth/2),
            y : event.clientY - (object.offsetHeight/2)
        };
        let unitBoundingRect = object.getBoundingClientRect();
        let unitCenter = {
        x: unitBoundingRect.left + unitBoundingRect.width/2,
        y: unitBoundingRect.top + unitBoundingRect.height/2
        }
        let angle = Math.atan2(event.pageX - unitCenter.x, - (event.pageY - unitCenter.y))*(180 /   Math.PI);

        object.style.transform = "translate(" + mousePosition.x + "px," + mousePosition.y + "px) rotate(" + angle + "deg)";
        object.innerText = Math.floor(angle);
}
window.addEventListener("click",action,false);
</code>```

`

Body:
The problem is follow:

when the object has a positive angle and if negative angle is clicked - it follows logic and makes a counterclockwise rotation instead of clockwise rotation like it requires and vice versa. It doesn`t look like rotation of a unit in RTS games. How to fix it?

`

var object = document.createElement("div");
object.style.backgroundColor = "red";
object.style.width = "50px";
object.style.height = "50px";
object.style.position = "absolute";
object.style.transition = "transform 3s";
document.body.appendChild(object);

function action(event){
        mousePosition = {
            x : event.clientX - (object.offsetWidth/2),
            y : event.clientY - (object.offsetHeight/2)
        };
        let unitBoundingRect = object.getBoundingClientRect();
        let unitCenter = {
        x: unitBoundingRect.left + unitBoundingRect.width/2,
        y: unitBoundingRect.top + unitBoundingRect.height/2
        }
        let angle = Math.atan2(event.pageX - unitCenter.x, - (event.pageY - unitCenter.y))*(180 /   Math.PI);

        object.style.transform = "translate(" + mousePosition.x + "px," + mousePosition.y + "px) rotate(" + angle + "deg)";
        object.innerText = Math.floor(angle);
}
window.addEventListener("click",action,false);

`


问:
Matrices multiplication
[I don't understand why z4][4] = ... (in the imange)
I want to code a program that can make matrices multiplication but when I run my code with two 2x2 matrices, my output z[1][1], z[1][2], z[2][1] is the same that I expected (value), only z[2][2] is printed with its address. I have tried with bigger matrices, my bug happened with more entry. Can someone help me.</p>
```<code>#include <stdio.h>
int main() {
    const int m,n,k;
    scanf("%d %d %d",&m,&n,&k);  // size of 3 matrices
    int a[m][n];
    int b[n][k];
    int z[m][k];
    int i,j,e,r,v,x,c;
    for (i=1;i<=m;i++){                            // declare matrix a
        for (j=1;j<=n;j++){
            scanf("%d",&a[i][j]);
        }

    }
    for (e=1;e<=n;e++){                             // declare matrix b
        for(r=1;r<=k;r++){
            scanf("%d",&b[e][r]);
        }
    }
    for (c=1;c<=m;c++){                              // multipication of a and b
        for (v=1;v<=k;v++){
            for (x=1;x<=n;x++){
                z[c][v]+=a[c][x]*b[x][v];
            }
            printf("%d ",z[c][v]);
            x=1;
        }
        v=1;
        printf("\n");
    }
    return 0;
}
</code>```

Title: Matrices multiplication

Body:
[I don't understand why z4][4] = ... (in the imange)
I want to code a program that can make matrices multiplication but when I run my code with two 2x2 matrices, my output z[1][1], z[1][2], z[2][1] is the same that I expected (value), only z[2][2] is printed with its address. I have tried with bigger matrices, my bug happened with more entry. Can someone help me.

#include <stdio.h>
int main() {
    const int m,n,k;
    scanf("%d %d %d",&m,&n,&k);  // size of 3 matrices
    int a[m][n];
    int b[n][k];
    int z[m][k];
    int i,j,e,r,v,x,c;
    for (i=1;i<=m;i++){                            // declare matrix a
        for (j=1;j<=n;j++){
            scanf("%d",&a[i][j]);
        }

    }
    for (e=1;e<=n;e++){                             // declare matrix b
        for(r=1;r<=k;r++){
            scanf("%d",&b[e][r]);
        }
    }
    for (c=1;c<=m;c++){                              // multipication of a and b
        for (v=1;v<=k;v++){
            for (x=1;x<=n;x++){
                z[c][v]+=a[c][x]*b[x][v];
            }
            printf("%d ",z[c][v]);
            x=1;
        }
        v=1;
        printf("\n");
    }
    return 0;
}


问:
dotnet.exe .NET Host from commandLine
When I run my webapi project in VSCode, it is hosted in  dotnet.exe .NET Host. Often the process is left open after closing VSCode. It it possible to communicate with it using commandLine?</p>

Title: dotnet.exe .NET Host from commandLine