问:
I'm getting a 400 error when I try to create a new Item on my model that is referenced to another model, am i missing data to send to the backend?
I'm creating a full stack MERN stack app, my front end is getting passed down the categories prop which is the model that i'm referencing to create a new Item, which is the model i'm trying to create on.

I'm getting a 400 error when I use the form to add new data. I'm new to the MERN stack so i'm not sure what exactly I'm missing when I send the data to my server. I'm guessing the issue is in my controller function, I just can not figure out how to add that reference on when I send the request to my server. Any help would be greatly appreciated

Error when I add an item, console logged the productData

Form component for adding Item

```<code>
export default function AddProductForm({addProduct, categories}) {
    const [newProduct, setNewProduct] = useState({
      name: "",
      images: [],
      category: {categories},
      price: 0,
      description: ""
    });

    function handleChange (evt) {
      setNewProduct({...newProduct, [evt.target.name]: evt.target.value });
    }

    async function handleAddProduct(evt) {
        evt.preventDefault();
        addProduct(newProduct);
        setNewProduct({
            name: "",
            images: [],
            category: {categories},
            price: 0,
            description: ""
          });
      }

    return (
      <>
        <h1>Add New Product</h1>
        <form onSubmit={handleAddProduct}>
        <label>Name</label>
          <input
              name="name"
              type="text"
              value={newProduct.name}
              onChange={handleChange}
              required
          />
        <label>images</label>
          <input
              name="images"
              type="text"
              value={newProduct.images}
              onChange={handleChange}
              required
          />
        <label>category</label>
          <select
              name="category"
              value={newProduct.category}
              onChange={handleChange}>
            {categories.map ((cat, idx) => (
              <option key={idx} value={cat}>{cat}</option>
            ))}
          </select>
        <label>Price</label>
          <input
              name="price"
              type="number"
              value={newProduct.price}
              onChange={handleChange}
              required
          />
        <label>Description</label>
          <input
              name="description"
              type="text"
              value={newProduct.description}
              onChange={handleChange}
              required
          />
          <button type="submit">Add Product</button>
        </form>
      </>
    );
  }
</code>```

Page where Form component lives

```<code>

export default function AdminPage({categories}) {
    const [allProducts, setAllProducts] = useState([]);
    const [allOrders, setAllOrders] = useState([]);

    useEffect(function() {
        async function getProducts() {
          const items = await itemsAPI.getAll();
          setAllProducts(items);
        }
        getProducts();

        async function getOrders() {
            const orders = await ordersAPI.getAllActiveOrders();
            setAllOrders(orders)
        }
        getOrders();
      }, []);

    async function updateOrder(orderData){
        console.log(orderData)
        const updatedOrder = await ordersAPI.updateOrder(orderData);
        setAllOrders([...allOrders, updatedOrder]);
    }

    async function addProduct(productData) {
        console.log(productData)
        const newProduct = await itemsAPI.createItem(productData);
        setAllProducts([...allProducts, newProduct]);
    }

    async function deleteProduct(itemId) {
        const products = await itemsAPI.removeItem(itemId);
        setAllProducts(products);
        window.location.reload(false);
    }

    return (
        <div className="admin-page">
            <h1>Admin Page</h1>
            <h2>All Available Products </h2>
            <div className="admin-products">
                {allProducts.map((product, idx) => (
                    <div key={idx}>{product.name}<br></br>
                        <img src={`${product.images[0]}`} alt=""/><br></br>
                        {/* <button>Edit</button> */}
                        <button onClick={() => deleteProduct(product._id)}>Delete Item</button>
                    </div>
                ))}
            </div>
            <AddProductForm addProduct={addProduct} categories={categories} />
            <h1>ACTIVE ORDERS</h1>
            <div className="orders">
                {allOrders.map((order, idx) => (
                        <div key={idx} className="order-info">
                            Order ID: {order.orderId}<br></br>
                            Ordered on: {new Date(order.updatedAt).toLocaleDateString()}<br></br>
                            Order Total: ${order.orderTotal}
                            {order.shipment.map((info, idx) => (
                                <div key={idx} className="shipment-info">
                                    <h3>Ship to:</h3>
                                    <p>
                                        {info.name}<br></br>
                                        {info.address}<br></br>
                                        {info.city},
                                        {info.state}
                                        {info.zip}
                                    </p>
                                </div>
                            ))}
                            <UpdateOrderForm updateOrder={updateOrder}/>
                        </div>
                    ))}
            </div>
        </div>
    );
}

</code>```

Item model (what I'm trying to create a new instance of)

```<code>
const Schema = require('mongoose').Schema;

const itemSchema = new Schema({
    name: { type: String, required: true },
    images: [{ type: String, required: true }],
    category: {type: Schema.Types.ObjectId, ref: 'Category'},
    price: { type: Number, required: true },
    description: { type: String }
  }, {
    timestamps: true
  });

  module.exports = itemSchema;

</code>```

category model (referenced model)

```<code>
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const categorySchema = new Schema({
  name: { type: String, required: true },
  sortOrder: Number
}, {
  timestamps: true
});

module.exports = mongoose.model('Category', categorySchema);

</code>```

controller for creating item

```<code>
async function create(req, res) {
  try {
    const item = await Item.create(req.body);
    res.json(item);
  } catch (err) {
    res.status(400).json(err);
  }
}

</code>```

api call to route

```<code>

export async function createItem(productData) {
  return sendRequest(`${BASE_URL}/new`, 'POST', productData)
}

</code>```

Body:
I'm creating a full stack MERN stack app, my front end is getting passed down the categories prop which is the model that i'm referencing to create a new Item, which is the model i'm trying to create on.

I'm getting a 400 error when I use the form to add new data. I'm new to the MERN stack so i'm not sure what exactly I'm missing when I send the data to my server. I'm guessing the issue is in my controller function, I just can not figure out how to add that reference on when I send the request to my server. Any help would be greatly appreciated

Error when I add an item, console logged the productData

Form component for adding Item

export default function AddProductForm({addProduct, categories}) {
    const [newProduct, setNewProduct] = useState({
      name: "",
      images: [],
      category: {categories},
      price: 0,
      description: ""
    });

    function handleChange (evt) {
      setNewProduct({...newProduct, [evt.target.name]: evt.target.value });
    }

    async function handleAddProduct(evt) {
        evt.preventDefault();
        addProduct(newProduct);
        setNewProduct({
            name: "",
            images: [],
            category: {categories},
            price: 0,
            description: ""
          });
      }

    return (
      <>

Add New Product

        <form onSubmit={handleAddProduct}>
        Name
          <input
              name="name"
              type="text"
              value={newProduct.name}
              onChange={handleChange}
              required
          />
        images
          <input
              name="images"
              type="text"
              value={newProduct.images}
              onChange={handleChange}
              required
          />
        category
          <select
              name="category"
              value={newProduct.category}
              onChange={handleChange}>
            {categories.map ((cat, idx) => (
              <option key={idx} value={cat}>{cat}</option>
            ))}
          </select>
        Price
          <input
              name="price"
              type="number"
              value={newProduct.price}
              onChange={handleChange}
              required
          />
        Description
          <input
              name="description"
              type="text"
              value={newProduct.description}
              onChange={handleChange}
              required
          />
          <button type="submit">Add Product</button>
        </form>
      </>
    );
  }

Page where Form component lives

export default function AdminPage({categories}) {
    const [allProducts, setAllProducts] = useState([]);
    const [allOrders, setAllOrders] = useState([]);

    useEffect(function() {
        async function getProducts() {
          const items = await itemsAPI.getAll();
          setAllProducts(items);
        }
        getProducts();

        async function getOrders() {
            const orders = await ordersAPI.getAllActiveOrders();
            setAllOrders(orders)
        }
        getOrders();
      }, []);

    async function updateOrder(orderData){
        console.log(orderData)
        const updatedOrder = await ordersAPI.updateOrder(orderData);
        setAllOrders([...allOrders, updatedOrder]);
    }

    async function addProduct(productData) {
        console.log(productData)
        const newProduct = await itemsAPI.createItem(productData);
        setAllProducts([...allProducts, newProduct]);
    }

    async function deleteProduct(itemId) {
        const products = await itemsAPI.removeItem(itemId);
        setAllProducts(products);
        window.location.reload(false);
    }

    return (

Admin Page

All Available Products

                {allProducts.map((product, idx) => (

{product.name}

                        <img src={`${product.images[0]}`} alt=""/>

                        {/* <button>Edit</button> */}
                        <button onClick={() => deleteProduct(product._id)}>Delete Item</button>

                ))}

            <AddProductForm addProduct={addProduct} categories={categories} />

ACTIVE ORDERS

                {allOrders.map((order, idx) => (

                            Order ID: {order.orderId}

                            Ordered on: {new Date(order.updatedAt).toLocaleDateString()}

                            Order Total: ${order.orderTotal}
                            {order.shipment.map((info, idx) => (

Ship to:

                                        {info.name}

                                        {info.address}

                                        {info.city},
                                        {info.state}
                                        {info.zip}

                            ))}
                            <UpdateOrderForm updateOrder={updateOrder}/>

                    ))}

    );
}

Item model (what I'm trying to create a new instance of)

const Schema = require('mongoose').Schema;

const itemSchema = new Schema({
    name: { type: String, required: true },
    images: [{ type: String, required: true }],
    category: {type: Schema.Types.ObjectId, ref: 'Category'},
    price: { type: Number, required: true },
    description: { type: String }
  }, {
    timestamps: true
  });

  module.exports = itemSchema;

category model (referenced model)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const categorySchema = new Schema({
  name: { type: String, required: true },
  sortOrder: Number
}, {
  timestamps: true
});

module.exports = mongoose.model('Category', categorySchema);

controller for creating item

async function create(req, res) {
  try {
    const item = await Item.create(req.body);
    res.json(item);
  } catch (err) {
    res.status(400).json(err);
  }
}

api call to route

export async function createItem(productData) {
  return sendRequest(`${BASE_URL}/new`, 'POST', productData)
}


来源: stackexchange

问:
How can I remove the section "Last modified" from an embeded Google drive folder?
I am trying to embed a Google drive folder in a wordpress site, but I only need it to display the document title. Currently it shows both, the title and the date last modified.

I am using this code:

```<code><iframe src="https://drive.google.com/embeddedfolderview?id=MY_FOLDERS_ID#list" style="width:100%; height:250px; border:0;"></iframe>
</code>```

and as a result I get this:
Result

The thing is that the "Last modified" column hides parts of the title and I really need the full titles to be displayed.

I've been searching for something that would improve this, but I could not find any solutions.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to embed a Google drive folder in a wordpress site, but I only need it to display the document title. Currently it shows both, the title and the date last modified.

I am using this code:

and as a result I get this:
Result

The thing is that the "Last modified" column hides parts of the title and I really need the full titles to be displayed.

I've been searching for something that would improve this, but I could not find any solutions.


问:
RMarkdown | ggsave is producing different results in different devices
I created an RMarkdown file to create 4 charts and save them on my desktop. I'm using ggsave and have forced the DPI to 280 so that the output images look good.

The issue I'm having is that when the script is run on my colleague's computer, the charts in the output look all over the place.
Here is an example of the output

I even tried several DPIs to see if we needed a specific DPI for that computer, but the output didn't change. It looks the same.

What can be causing that? Something in the settings?


问:
Is there a way to have lambdas server files?
I really would like to use lambda functions opposed to an ec2 instance to host my website. However, I cannot figure out how to serve files (such as js files, html files, css files, images, etc.) as a response to a GET request.

Basically, I want the lambda function to serve the the html, client side js, and css when they visit the API Gateway URL

In testing with localhost (without using lambda functions) this would be my code to serve the html file on request (very basic for demonstration)

const http = require('http');
const fs = require('fs');

const httpServer = http.createServer((req,res) => {

    fs.readFile(/index.html, null, (err, data) => {
        if(err){
            res.writeHead(404);
            res.write('File not found')
        }else{
            res.write(data)
        }
        res.end();
    })

})
httpServer.listen(3000);```

I understand that lambda functions are stateless, so the part I'm concerned about in the code above is the fs.readFile(). Where do you store files with lambda functions? And how to you call fs.readFile() on these files and return the data as a response?

Body:
I really would like to use lambda functions opposed to an ec2 instance to host my website. However, I cannot figure out how to serve files (such as js files, html files, css files, images, etc.) as a response to a GET request.

Basically, I want the lambda function to serve the the html, client side js, and css when they visit the API Gateway URL

In testing with localhost (without using lambda functions) this would be my code to serve the html file on request (very basic for demonstration)

const http = require('http');
const fs = require('fs');

const httpServer = http.createServer((req,res) => {

    fs.readFile(/index.html, null, (err, data) => {
        if(err){
            res.writeHead(404);
            res.write('File not found')
        }else{
            res.write(data)
        }
        res.end();
    })

})
httpServer.listen(3000);

I understand that lambda functions are stateless, so the part I'm concerned about in the code above is the fs.readFile(). Where do you store files with lambda functions? And how to you call fs.readFile() on these files and return the data as a response?


问:
Diffrent filtering applied for request from browser and from curl or webclient
Project is in initial phase, so you could see some „bad things” like public actuator endpoint, but it does not interfere with main issue.

I have two rest controllers:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/a")
@RequiredArgsConstructor
class AController {
    @GetMapping("/")
    @CrossOrigin(origins = "*")
    @PreAuthorize("hasAnyRole('ROLE_User')")
    public Collection<AProjection> getAThing(@RequestHeader("Authorization") String auth) {
      // do something
    }
}

// and
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/b")
@RequiredArgsConstructor
class BController {
    @GetMapping("/")
    @CrossOrigin(origins = "*")
    @PreAuthorize("hasAnyRole('ROLE_User')")
    public Collection<BProjection> getBThing() {
      // do something
    }
}
```
<p>They are the same from a spring security point of view. Just different paths.</p>
<p>Now I prepare security configuration:</p>
<pre class="lang-java prettyprint-override"><code>public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenFilter authenticationJwtTokenFilter, AuthEntryPointJwt unauthorizedHandler) throws Exception {
    http.csrf().disable().cors().and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeHttpRequests()
            .requestMatchers("/auth/**").permitAll()
            .requestMatchers("/actuator/**").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "authorization", "content-type", "x-auth-token"));
    configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
</code>```

Issue symptoms

When I call AController from react app I get HTTP200 and everything is OK. The same situation is when I call it from cUrl or IntetlliJ WebClient. But…

When I call BController from react app I get HTTP401 Unauthorized, but when I use cUrl or WebClient I get HTTP200.

Few request:

Call from IntelliJ WebClient for AController

```<code>GET http://localhost:28080/a
Host: localhost:28080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.…
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
</code>```

Call from IntelliJ WebClient for BController

```<code>GET http://localhost:28080/b
Host: localhost:28080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.…
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
</code>```

Both was copied from browser.

React call:

```<code>const get = (resource: string): Promise<any> =>
    axios
        .get(`http://localhost:28080/${resource}`, {
            headers: authHeader() as AxiosRequestHeaders,
        })
        .then(response => response.data as string)
        .catch(err => {
            console.log(err);
            return "";
        });
</code>```

What I have discovered during debugging

I started debugging of code and I discovered one strange thing.

One of a filters in chain is SecurityContextHolderFilter. When I call AController this filter is applied only once. Before I add user to security context, SecurityContextHolder.getContext().getAuthentication() return null. After that, my security filter is applied where I call SecurityContextHolder.getContext().setAuthentication(authentication). But when I call BController from react app SecurityContextHolderFilter is applied twice. That does not happen when I use cUrl or WebClient. On that case, application happen only once.

It looks like I have two requests when I use browser…

Another observation, when I use browser

First application works with RequestFacade object as request.
Second works with FirewalledFacade object as request.

Questions

What is the rule that decide to change of request?

Why?

I know that second question is not so precise, but I give up and have no idea what happen there.

Edit

About new request – that because after failed auth we are redirected to /error.

Body:
Project is in initial phase, so you could see some „bad things” like public actuator endpoint, but it does not interfere with main issue.

I have two rest controllers:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/a")
@RequiredArgsConstructor
class AController {
    @GetMapping("/")
    @CrossOrigin(origins = "*")
    @PreAuthorize("hasAnyRole('ROLE_User')")
    public Collection<AProjection> getAThing(@RequestHeader("Authorization") String auth) {
      // do something
    }
}

// and
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/b")
@RequiredArgsConstructor
class BController {
    @GetMapping("/")
    @CrossOrigin(origins = "*")
    @PreAuthorize("hasAnyRole('ROLE_User')")
    public Collection<BProjection> getBThing() {
      // do something
    }
}

They are the same from a spring security point of view. Just different paths.

Now I prepare security configuration:

public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenFilter authenticationJwtTokenFilter, AuthEntryPointJwt unauthorizedHandler) throws Exception {
    http.csrf().disable().cors().and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeHttpRequests()
            .requestMatchers("/auth/**").permitAll()
            .requestMatchers("/actuator/**").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "authorization", "content-type", "x-auth-token"));
    configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Issue symptoms

When I call AController from react app I get HTTP200 and everything is OK. The same situation is when I call it from cUrl or IntetlliJ WebClient. But…

When I call BController from react app I get HTTP401 Unauthorized, but when I use cUrl or WebClient I get HTTP200.

Few request:

Call from IntelliJ WebClient for AController

GET http://localhost:28080/a
Host: localhost:28080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.…
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

Call from IntelliJ WebClient for BController

GET http://localhost:28080/b
Host: localhost:28080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0
Accept: application/json, text/plain, */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.…
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

Both was copied from browser.

React call:

const get = (resource: string): Promise<any> =>
    axios
        .get(`http://localhost:28080/${resource}`, {
            headers: authHeader() as AxiosRequestHeaders,
        })
        .then(response => response.data as string)
        .catch(err => {
            console.log(err);
            return "";
        });

What I have discovered during debugging

I started debugging of code and I discovered one strange thing.

One of a filters in chain is SecurityContextHolderFilter. When I call AController this filter is applied only once. Before I add user to security context, SecurityContextHolder.getContext().getAuthentication() return null. After that, my security filter is applied where I call SecurityContextHolder.getContext().setAuthentication(authentication). But when I call BController from react app SecurityContextHolderFilter is applied twice. That does not happen when I use cUrl or WebClient. On that case, application happen only once.

It looks like I have two requests when I use browser…

Another observation, when I use browser

First application works with RequestFacade object as request.
Second works with FirewalledFacade object as request.

Questions

What is the rule that decide to change of request?

Why?

I know that second question is not so precise, but I give up and have no idea what happen there.

Edit

About new request – that because after failed auth we are redirected to /error.


问:
Laravel: ErrorException Undefined variable: REQUEST http://127.0.0.1:8000/insert
what I'm trying to do is to insert data to database, but its not working, i get this error
:ErrorException Undefined variable: REQUEST http://127.0.0.1:8000/insert

and these are my code
Controler

```<code>    public function insert(Request $request)
{
    $deceased_infos = new deceased_info();
    $deceased_infos  ->lastname = $REQUEST->input('dlastname');
    $deceased_infos  ->firstname = $REQUEST->input('dfirstname');
    $deceased_infos  ->middlename = $REQUEST->input('dmiddlename');
    $deceased_infos->save();

    return redirect('/resident')->with('status', "Inserted!!!");

}
</code>```

View

```<code><div class="modal-body">
        <form action="{{url('insert')}}" id="deceasedform" method="POST"  class="modal-input">
           {{ csrf_field() }}
           <input type="hidden" name="resident_id" id="resident_id">
           <div class="row">
               <div class="col-sm-6">......
</code>```

Route

```<code>Route::post('insert',  [ResidentInfoController::class, 'insert']);
</code>```

Body:
what I'm trying to do is to insert data to database, but its not working, i get this error
:ErrorException Undefined variable: REQUEST http://127.0.0.1:8000/insert

and these are my code
Controler

    public function insert(Request $request)
{
    $deceased_infos = new deceased_info();
    $deceased_infos  ->lastname = $REQUEST->input('dlastname');
    $deceased_infos  ->firstname = $REQUEST->input('dfirstname');
    $deceased_infos  ->middlename = $REQUEST->input('dmiddlename');
    $deceased_infos->save();

    return redirect('/resident')->with('status', "Inserted!!!");

}

View

        <form action="{{url('insert')}}" id="deceasedform" method="POST"  class="modal-input">
           {{ csrf_field() }}
           <input type="hidden" name="resident_id" id="resident_id">

......

Route

Route::post('insert',  [ResidentInfoController::class, 'insert']);


问:
react magnetic snap scroll with react-scroll
ive got a component where i try to make some sort of magnetic snap scroll. i know the css usual css way of snap-y, and setting snap behavior to smooth, but the snap is too fast. so i tried on my own to create a component where if the app detects a scroll down or up with the function, and a scroll below

```<code>        const [scrollDir, setScrollDir] = useState("");
    const [index, setIndex] = useState("0")

useEffect(() => {
  const threshold = 0;
  let lastScrollY = window.pageYOffset;
  let ticking = false;

  const updateScrollDir = () => {
    const scrollY = window.pageYOffset;

    if (Math.abs(scrollY - lastScrollY) < threshold) {
      ticking = false;
      return;
    }
    if(scrollY>lastScrollY){
        // setScrollDir("scrolling down")
         scroller.scrollTo('about',{
                duration: 1000,
                delay: 100,
                smooth: 'linear',
            })
    }
    // setScrollDir(scrollY > lastScrollY ? "scrolling down" : "scrolling up");
    lastScrollY = scrollY > 0 ? scrollY : 0;
    ticking = false;
  };

  const onScroll = () => {
    if (!ticking) {
      window.requestAnimationFrame(updateScrollDir);
      ticking = true;
    }
  };

  window.addEventListener("scroll", onScroll);
  console.log(scrollDir);

  return () => window.removeEventListener("scroll", onScroll);
}, [scrollDir]);
</code>```

the magnetic scroll doesnt work, the page goes all jumpy. i could add a global css to make smooth scrolling, but that defeats the purpose of giving easein animation of scrolling. is there a way to work around this?

Body:
ive got a component where i try to make some sort of magnetic snap scroll. i know the css usual css way of snap-y, and setting snap behavior to smooth, but the snap is too fast. so i tried on my own to create a component where if the app detects a scroll down or up with the function, and a scroll below

        const [scrollDir, setScrollDir] = useState("");
    const [index, setIndex] = useState("0")

useEffect(() => {
  const threshold = 0;
  let lastScrollY = window.pageYOffset;
  let ticking = false;

  const updateScrollDir = () => {
    const scrollY = window.pageYOffset;

    if (Math.abs(scrollY - lastScrollY) < threshold) {
      ticking = false;
      return;
    }
    if(scrollY>lastScrollY){
        // setScrollDir("scrolling down")
         scroller.scrollTo('about',{
                duration: 1000,
                delay: 100,
                smooth: 'linear',
            })
    }
    // setScrollDir(scrollY > lastScrollY ? "scrolling down" : "scrolling up");
    lastScrollY = scrollY > 0 ? scrollY : 0;
    ticking = false;
  };

  const onScroll = () => {
    if (!ticking) {
      window.requestAnimationFrame(updateScrollDir);
      ticking = true;
    }
  };

  window.addEventListener("scroll", onScroll);
  console.log(scrollDir);

  return () => window.removeEventListener("scroll", onScroll);
}, [scrollDir]);

the magnetic scroll doesnt work, the page goes all jumpy. i could add a global css to make smooth scrolling, but that defeats the purpose of giving easein animation of scrolling. is there a way to work around this?


问:
What is the best way to add white space between two php include statements
I have something like this code. (I replaced specific words with fake ones.) The end result lacks spaces between and around the output of the includes.

When I add  , it looks good, but is there a better way?

```<code>Word - <?php include($_SERVER['DOCUMENT_ROOT'] . '/fake/path.php'); ?> vs <?php include($_SERVER['DOCUMENT_ROOT'] . '/fake/path2.php'); ?>
</code>```

Result:
Word -pathnamevspathname2

Thanks

Body:
I have something like this code. (I replaced specific words with fake ones.) The end result lacks spaces between and around the output of the includes.

When I add  , it looks good, but is there a better way?

Word - <?php include($_SERVER['DOCUMENT_ROOT'] . '/fake/path.php'); ?> vs <?php include($_SERVER['DOCUMENT_ROOT'] . '/fake/path2.php'); ?>

Result:
Word -pathnamevspathname2

Thanks


问:
Puppeteer Page.$$eval() method returning empty arrays
I'm building a web scraping application with puppeteer. I'm trying to get an array of links to scrape from but it returns an empty array.

```<code>const scraperObject = {
    url: 'https://www.walgreens.com/',
    async scraper(browser){
        let page = await browser.newPage();
        console.log(`Navigating to ${this.url}...`);
        await page.goto(this.url);
        // Wait for the required DOM to be rendered
        await page.waitForSelector('.CA__Featured-categories__full-width');
        // Get the link to all the required links in the featured categories
        let urls = await page.$$eval('.list__contain >  ul#at-hp-rp-featured-ul > li', links => {
            // Extract the links from the data
            links = links.map(el => el.querySelector('li > a').href)
            return links;
        });
</code>```

Whenever I ran this, the console would give me the needed array of links (example below).

```<code>Navigating to https://www.walgreens.com/...
[
'https://www.walgreens.com/seasonal/holiday-gift-shop?ban=dl_dl_FeatCategory_HolidayShop_TEST'
'https://www.walgreens.com/store/c/cough-cold-and-flu/ID=20002873-tier1?ban=dl_dl_FeatCategory_CoughColdFlu_TEST'
'https://www.walgreens.com/store/c/contact-lenses/ID=359432-tier2clense?ban=dl_dl_FeatCategory_ContactLenses_TEST'
]
</code>```

So, from here I had the navigate to one of those urls through the code block below and rerun the same code to go through an array of categories to eventually navigate to the product listings page.

```<code>//Navigate to Household Essentials
        let hEssentials = await browser.newPage();
        await hEssentials.goto(urls[11]);
        // Wait for the required DOM to be rendered
        await page.waitForSelector('.content');
        // Get the link to all the required links in the featured categories
        let shopByNeedUrls = await page.$$eval('div.wag-row > div.wag-col-3 wag-col-md-6 wag-col-sm-6 CA__MT30', links1 => {
            // Extract the links from the data
            links1 = links1.map(el => el.querySelector('div > a').href)
            return links1;
        });

console.log(shopByNeedUrls);
    }

</code>```

However, whenever I run this code through the console, I receive the same navigating message but then I return an empty array(as shown in the example below)

```<code>Navigating to https://www.walgreens.com/...
[]
</code>```

If anyone is able to explain why I'm outputting an empty array, that'd be great. Thank you.

I've attempted to change the parameter of the page.waitForSelector method and the page.$$eval method. However none of them appeared to work and output the same result. In fact, I recieve a timeout error sometimes for the the page.waitForSelector method.

Body:
I'm building a web scraping application with puppeteer. I'm trying to get an array of links to scrape from but it returns an empty array.

const scraperObject = {
    url: 'https://www.walgreens.com/',
    async scraper(browser){
        let page = await browser.newPage();
        console.log(`Navigating to ${this.url}...`);
        await page.goto(this.url);
        // Wait for the required DOM to be rendered
        await page.waitForSelector('.CA__Featured-categories__full-width');
        // Get the link to all the required links in the featured categories
        let urls = await page.$$eval('.list__contain >  ul#at-hp-rp-featured-ul > li', links => {
            // Extract the links from the data
            links = links.map(el => el.querySelector('li > a').href)
            return links;
        });

Whenever I ran this, the console would give me the needed array of links (example below).

Navigating to https://www.walgreens.com/...
[
'https://www.walgreens.com/seasonal/holiday-gift-shop?ban=dl_dl_FeatCategory_HolidayShop_TEST'
'https://www.walgreens.com/store/c/cough-cold-and-flu/ID=20002873-tier1?ban=dl_dl_FeatCategory_CoughColdFlu_TEST'
'https://www.walgreens.com/store/c/contact-lenses/ID=359432-tier2clense?ban=dl_dl_FeatCategory_ContactLenses_TEST'
]

So, from here I had the navigate to one of those urls through the code block below and rerun the same code to go through an array of categories to eventually navigate to the product listings page.

//Navigate to Household Essentials
        let hEssentials = await browser.newPage();
        await hEssentials.goto(urls[11]);
        // Wait for the required DOM to be rendered
        await page.waitForSelector('.content');
        // Get the link to all the required links in the featured categories
        let shopByNeedUrls = await page.$$eval('div.wag-row > div.wag-col-3 wag-col-md-6 wag-col-sm-6 CA__MT30', links1 => {
            // Extract the links from the data
            links1 = links1.map(el => el.querySelector('div > a').href)
            return links1;
        });

console.log(shopByNeedUrls);
    }

However, whenever I run this code through the console, I receive the same navigating message but then I return an empty array(as shown in the example below)

Navigating to https://www.walgreens.com/...
[]

If anyone is able to explain why I'm outputting an empty array, that'd be great. Thank you.

I've attempted to change the parameter of the page.waitForSelector method and the page.$$eval method. However none of them appeared to work and output the same result. In fact, I recieve a timeout error sometimes for the the page.waitForSelector method.


问:
How to append a new attribute in a xml using scala and sbt?
I have a use-case where I need to append an attribute to a complex xml file, I have referred " Add or append new element to XML file in Scala instead of replacing it " which works to a extent but not on the inner childs of the xml.

XML I am working with :

```<code><persons>
    <person id="1">
        <firstname>James</firstname>
        <lastname>Smith</lastname>
        <middlename></middlename>
        <dob_year>1980</dob_year>
        <dob_month>1</dob_month>
        <gender>M</gender>
        <salary currency="Euro">10000</salary>
        <addresses>
            <address>
                <street>123 ABC street</street>
                <city>NewJersy</city
                <state>NJ</state>
            </address>
            <address>
                <street>456 apple street</street>
                <city>newark</city>
                <state>DE</state>
            </address>
        </addresses>
    </person>
    <person id="2">
        <firstname>Michael</firstname>
        <lastname></lastname>
        <middlename>Rose</middlename>
        <dob_year>1990</dob_year>
        <dob_month>6</dob_month>
        <gender>M</gender>
        <salary currency="Dollor">10000</salary>
        <addresses>
            <address>
                <street>4512 main st</street>
                <city>new york</city>
                <state>NY</state>
            </address>
            <address>
                <street>4367 orange st</street>
                <city>sandiago</city>
                <state>CA</state>
            </address>
        </addresses>
    </person>
</persons>
</code>```

I would like to add the value in  that too after state, is it possible ?

Thanks in advance.

Body:
I have a use-case where I need to append an attribute to a complex xml file, I have referred " Add or append new element to XML file in Scala instead of replacing it " which works to a extent but not on the inner childs of the xml.

XML I am working with :

<persons>
    <person id="1">
        <firstname>James</firstname>
        <lastname>Smith</lastname>
        <middlename></middlename>
        <dob_year>1980</dob_year>
        <dob_month>1</dob_month>
        <gender>M</gender>
        <salary currency="Euro">10000</salary>
        <addresses>
            <address>
                <street>123 ABC street</street>
                <city>NewJersy</city
                <state>NJ</state>
            </address>
            <address>
                <street>456 apple street</street>
                <city>newark</city>
                <state>DE</state>
            </address>
        </addresses>
    </person>
    <person id="2">
        <firstname>Michael</firstname>
        <lastname></lastname>
        <middlename>Rose</middlename>
        <dob_year>1990</dob_year>
        <dob_month>6</dob_month>
        <gender>M</gender>
        <salary currency="Dollor">10000</salary>
        <addresses>
            <address>
                <street>4512 main st</street>
                <city>new york</city>
                <state>NY</state>
            </address>
            <address>
                <street>4367 orange st</street>
                <city>sandiago</city>
                <state>CA</state>
            </address>
        </addresses>
    </person>
</persons>

I would like to add the value in  that too after state, is it possible ?

Thanks in advance.


问:
Html: disable all suggestion (copy share search dhe web)
Sometimes on some elements the mobile Android shows a set of 2 blue balloons and if you touch the element, it show a context menu containing paste/share/search the WEB.
. Is it possible to disable this feature on the entire body?</p>


问:
Websocket: Handshake failed due to invalid Upgrade header: null
Could not find a solution to the other posted questions.

Our web socket service is running on HTTP in Kubernetes and we have enabled ELB(Elastic Load balancer). The client is connecting using stomp.js.
The client is calling ELB, ELB redirects the request to the Spring cloud gateway and the gateway is calling the web socket service. All this works fine when everything is running on HTTP.

But after enabling CloudFront on AWS and running UI and ELB on HTTPS, when we try to connect Websocket from HTTPS UI(Client) and only ELB is on HTTPS, it redirects the request to the gateway with HTTP and from there to Web socket service,
We get Handshake failure at the backend and on the browser, we are getting a response with status "Cancelled".

Any idea what could be the reason for the issue.?


问:
How to set up `timesteps_total` in the config in Python API? (RLlib)
I just started playing with RLlib and I wanted to test offline DQN training on a CartPole. Thus, I generated the data as in the tutorial:

rllib train --run=PG --env=CartPole-v1 --config='{"output": "/tmp/cartpole-out", "output_max_file_size": 5000000}' --stop='{"timesteps_total": 100000}'
```
<p>And then run offline the training via</p>
<pre class="lang-bash prettyprint-override"><code>rllib train --run=DQN --env=CartPole-v1 --config='{"input": "/tmp/cartpole-out","explore": false}' --stop='{"timesteps_total": 1000000}'
</code>```

However, now I want to reproduce offline training using Python API and I get a little confused about timesteps_total. I have written the following code:

if __name__ == '__main__':
    config = (
        DQNConfig()
        .environment(env="CartPole-v1")
        .framework("torch")
        .offline_data(input_="/tmp/cartpole-out")
        .exploration(explore=False)
    )

    algo = config.build()
    for _ in tqdm(range(100)):
        algo.train()
```

but I am not sure how timesteps_total  is related to the training loop with the above snippet. I looked inside AlgorithmConfig class, but I found that self.timesteps_per_iteration = DEPRECATED_VALUE. Thus, the question:

How to set up timesteps_total in the config in Python API?

Disclaimer: I asked ChatGPT about that, but it confidently gave me the wrong answer with a detailed explanation.

Body:
I just started playing with RLlib and I wanted to test offline DQN training on a CartPole. Thus, I generated the data as in the tutorial:

rllib train --run=PG --env=CartPole-v1 --config='{"output": "/tmp/cartpole-out", "output_max_file_size": 5000000}' --stop='{"timesteps_total": 100000}'

And then run offline the training via

rllib train --run=DQN --env=CartPole-v1 --config='{"input": "/tmp/cartpole-out","explore": false}' --stop='{"timesteps_total": 1000000}'

However, now I want to reproduce offline training using Python API and I get a little confused about timesteps_total. I have written the following code:

if __name__ == '__main__':
    config = (
        DQNConfig()
        .environment(env="CartPole-v1")
        .framework("torch")
        .offline_data(input_="/tmp/cartpole-out")
        .exploration(explore=False)
    )

    algo = config.build()
    for _ in tqdm(range(100)):
        algo.train()

but I am not sure how timesteps_total  is related to the training loop with the above snippet. I looked inside AlgorithmConfig class, but I found that self.timesteps_per_iteration = DEPRECATED_VALUE. Thus, the question:

How to set up timesteps_total in the config in Python API?

Disclaimer: I asked ChatGPT about that, but it confidently gave me the wrong answer with a detailed explanation.


问:
Mocking SignInResult and set SignInResult.Succeeded
I want to mock SignInResult (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinresult?view=aspnetcore-6.0) for xUnit test. I am trying varius ways to set signinresult.succeeded property using
moq.

```<code>var signInresult = new Mock<SignInResult>();
signInresult.SetupProperty<bool>(p => p.Succeeded,true );

</code>```

but got an exception.
Any suggestion on this? I am using dot net core 6.0

Body:
I want to mock SignInResult (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinresult?view=aspnetcore-6.0) for xUnit test. I am trying varius ways to set signinresult.succeeded property using
moq.

var signInresult = new Mock<SignInResult>();
signInresult.SetupProperty<bool>(p => p.Succeeded,true );

but got an exception.
Any suggestion on this? I am using dot net core 6.0


问:
Chakra UI: <Text> with more than 1 word collpasing into 2 lines instead of remaining 100% of content width
I have an HStack full of Texts and I'd like each to take up exactly 100% of its content. Instead the Texts that have more than 1 word are starting to collapse on itself:

```<code><HStack
  spacing={1}
  overflowX={'scroll'}
  className={'hide-scrollbar'}
>
  {traits.map((t) => (
    <Text flex={1} key={t}>
      {t},
    </Text>
  ))}
  </HStack>
</code>```

Parent is scrollable so even though all 4 won't fit into a single line they should remain 100% each and overflow instead of collpasing.

How can this be achieved?

Body:
I have an HStack full of Texts and I'd like each to take up exactly 100% of its content. Instead the Texts that have more than 1 word are starting to collapse on itself:

<HStack
  spacing={1}
  overflowX={'scroll'}
  className={'hide-scrollbar'}
>
  {traits.map((t) => (
    <Text flex={1} key={t}>
      {t},
    </Text>
  ))}
  </HStack>

Parent is scrollable so even though all 4 won't fit into a single line they should remain 100% each and overflow instead of collpasing.

How can this be achieved?


问:
Get ellipse element by id shadowroot open
I have a card web-component. In each card we have an ellipse element with unique id

All ids are numeric

```<code><div class="card">
  <div class="timmer-mobile ">
    <div class="ellipse" id="timeForCount " data-time="73">
      <svg viewBox="-10 -10 250 120">
        <ellipse id="57" cx="100" cy="50" rx="100" ry="50" ></ellipse>
      </svg>
    </div>
  </div>
</div>
</code>```

Im trying to get the ellipse element id with this code:

```<code>const ellipse = this.shadowRoot.getElementById="ellipse#"+id;
</code>```

Result being ellipse#50

Now the problem is when I try to add to the ellipse a style with this code:

```<code>ellipse.style.strokeDasharray = `0, 1000`;
</code>```

I get error:

```<code>'Uncaught TypeError: Cannot set properties of undefined (setting 'strokeDasharray')'
</code>```

My guess is the selector is not working or the way I'm doing it .

Trying to add that style for each ellipse

```<code>ellipse.style.strokeDasharray = `0, 1000`;
</code>```

Body:
I have a card web-component. In each card we have an ellipse element with unique id

All ids are numeric

      <svg viewBox="-10 -10 250 120">
        <ellipse id="57" cx="100" cy="50" rx="100" ry="50" ></ellipse>
      </svg>

Im trying to get the ellipse element id with this code:

const ellipse = this.shadowRoot.getElementById="ellipse#"+id;

Result being ellipse#50

Now the problem is when I try to add to the ellipse a style with this code:

ellipse.style.strokeDasharray = `0, 1000`;

I get error:

'Uncaught TypeError: Cannot set properties of undefined (setting 'strokeDasharray')'

My guess is the selector is not working or the way I'm doing it .

Trying to add that style for each ellipse

ellipse.style.strokeDasharray = `0, 1000`;


问:
MAUI/MudBlazor/MVVM Toolkit: Observable properties not updating UI
I am experimenting with creating MAUI Blazor app using MudBlazor (v6.0.13) components in an MVVM pattern using Microsoft.CommunityToolkit.Mvvm (v8.0.0) and I am confused by the behavior I am seeing in that the UI is not updating when an observable property is updated.

I eliminated MAUI out of the equation and just created a plain Blazor WASM app and the behavior is the same.  But, now I don't know if this is an issue with the MVVM toolkit, MudBlazor, or just the way I understand how the RelayCommand operates relative to observable objects.   I couldn't find any information on if this is an issue or expected behavior.    Can someone shed some light here?

In the MudBlazor sample app I created, it has two buttons, both run the same function Test which adds an item to the displayed list of items via an ObservableProperty.   One button uses OnClick and runs the function, the other uses Command.

OnClick updates the UI when each item is added, but Command does not, yet the property is Observable.   If you press the Command button several times and then press the OnClick button, it displays the list with both sets of items added.

Index.razor

```<code>@page "/"
@inject ViewModels.TestViewModel vm

<PageTitle>Index</PageTitle>

<MudText Typo="Typo.h3" GutterBottom="true">Hello, world!</MudText>
<MudText Class="mb-8">Welcome to your new app, powered by MudBlazor!</MudText>
<MudAlert Severity="Severity.Normal">You can find documentation and examples on our website here: <MudLink Href="https://mudblazor.com" Typo="Typo.body2" Color="Color.Inherit"><b>www.mudblazor.com</b></MudLink></MudAlert>

<ul>
    @foreach (string item in vm.Items)
    {
        <li>@item</li>
    }
</ul>

<MudButton Command="@vm.RebuildCommand" >Test via Command</MudButton>
<MudButton OnClick="@OnClickRebuild">Test via OnClick</MudButton>

@code {

    public void OnClickRebuild()
    {
        vm.Test("OnClick");
    }
}
</code>```

TestViewModel.cs

```<code>using static MudBlazor.CategoryTypes;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.ComponentModel;

namespace MudBlazorMVVM.ViewModels;

public partial class TestViewModel : ObservableObject
{
//  Doesn't work
//    [ObservableProperty]
//    private List<string> _items = new();

//  Doesn't work
//    public ObservableCollection<string> Items = new();

//  Also doesn't work
    public ObservableCollection<string> Items { get; set; } = new();

    [RelayCommand]
    public async Task Rebuild()
    {
//      Tested on another thread for giggles...doesn't change
//        await Task.Run(() => { Test("RelayCommand"); });

        Test("RelayCommand");
    }

    public void Test(string source)
    {
        Items.Add("Item: " + Items.Count + "  (from " + source + ")");
    }
}
</code>```

Edit

For completeness, below is Program.cs code where TestViewModel singleton was added for DI.

```<code>using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor.Services;
using MudBlazorMVVM;
using MudBlazorMVVM.ViewModels;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddSingleton<TestViewModel>();

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddMudServices();

await builder.Build().RunAsync();
</code>```

Edit #2: Adjusted code to show ObservableCollection use

Body:
I am experimenting with creating MAUI Blazor app using MudBlazor (v6.0.13) components in an MVVM pattern using Microsoft.CommunityToolkit.Mvvm (v8.0.0) and I am confused by the behavior I am seeing in that the UI is not updating when an observable property is updated.

I eliminated MAUI out of the equation and just created a plain Blazor WASM app and the behavior is the same.  But, now I don't know if this is an issue with the MVVM toolkit, MudBlazor, or just the way I understand how the RelayCommand operates relative to observable objects.   I couldn't find any information on if this is an issue or expected behavior.    Can someone shed some light here?

In the MudBlazor sample app I created, it has two buttons, both run the same function Test which adds an item to the displayed list of items via an ObservableProperty.   One button uses OnClick and runs the function, the other uses Command.

OnClick updates the UI when each item is added, but Command does not, yet the property is Observable.   If you press the Command button several times and then press the OnClick button, it displays the list with both sets of items added.

Index.razor

@page "/"
@inject ViewModels.TestViewModel vm

<PageTitle>Index</PageTitle>

<MudText Typo="Typo.h3" GutterBottom="true">Hello, world!</MudText>
<MudText Class="mb-8">Welcome to your new app, powered by MudBlazor!</MudText>
<MudAlert Severity="Severity.Normal">You can find documentation and examples on our website here: <MudLink Href="https://mudblazor.com" Typo="Typo.body2" Color="Color.Inherit">www.mudblazor.com</MudLink></MudAlert>

    @foreach (string item in vm.Items)
    {

@item

    }

<MudButton Command="@vm.RebuildCommand" >Test via Command</MudButton>
<MudButton OnClick="@OnClickRebuild">Test via OnClick</MudButton>

@code {

    public void OnClickRebuild()
    {
        vm.Test("OnClick");
    }
}

TestViewModel.cs

using static MudBlazor.CategoryTypes;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.ComponentModel;

namespace MudBlazorMVVM.ViewModels;

public partial class TestViewModel : ObservableObject
{
//  Doesn't work
//    [ObservableProperty]
//    private List<string> _items = new();

//  Doesn't work
//    public ObservableCollection<string> Items = new();

//  Also doesn't work
    public ObservableCollection<string> Items { get; set; } = new();

    [RelayCommand]
    public async Task Rebuild()
    {
//      Tested on another thread for giggles...doesn't change
//        await Task.Run(() => { Test("RelayCommand"); });

        Test("RelayCommand");
    }

    public void Test(string source)
    {
        Items.Add("Item: " + Items.Count + "  (from " + source + ")");
    }
}

Edit

For completeness, below is Program.cs code where TestViewModel singleton was added for DI.

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor.Services;
using MudBlazorMVVM;
using MudBlazorMVVM.ViewModels;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddSingleton<TestViewModel>();

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddMudServices();

await builder.Build().RunAsync();

Edit #2: Adjusted code to show ObservableCollection use


问:
JAVA GUI drawing objects with buttons in multiple windows
So, i have a question with me code here, i have to make a program that draws objects and sometime fills them by clicking radiobuttons, the other part is that the drawing part had to be done in a second window, so i need to have the radiobuttons in one screen and by clicking them i have to draw objects in different window. I maded up to the part where i declared the buttons and created the 2nd screen, but i dont know how to make when i select the radiobutton to draws in the 2nd screen, can someone help me, im new into JAVA.
`

```<code>
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class ButtonWindow extends JFrame{

        JRadioButton Oval, Line,OutlineColor1,OutlineColor2,OutlineColor3,FillColor1,FillColor2,FillColor3;

        ButtonWindow(){
            JFrame f1=new JFrame();
            this.setTitle("Drawing Objects");
            this.setVisible(true);
            this.setLayout(new FlowLayout());
            this.pack();
            this.setSize(500,500);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            setLayout(new GridLayout(0,1));

              Oval = new JRadioButton("Oval shape ");
              Line = new JRadioButton("Line");
              OutlineColor1 = new JRadioButton("Outline Color: RED");
              OutlineColor2 = new JRadioButton("Outline Color: BLUE");
              OutlineColor3 = new JRadioButton("Outline Color: GREEN");
              FillColor1 = new JRadioButton("Filling Color: RED");
              FillColor2 = new JRadioButton("Filling Color: BLUE");
              FillColor3 = new JRadioButton("Filling Color: GREEN");

             ButtonGroup group1 = new ButtonGroup();
                group1.add(Oval);
                group1.add(Line);

                ButtonGroup group2 = new ButtonGroup();
                group2.add(OutlineColor1);
                group2.add(OutlineColor2);
                group2.add(OutlineColor3);

                ButtonGroup group3 = new ButtonGroup();
                group3.add(FillColor1);
                group3.add(FillColor2);
                group3.add(FillColor3);

             this.add(Oval);
             this.add(Line);
             this.add(OutlineColor1);
             this.add(OutlineColor2);
             this.add(OutlineColor3);
             this.add(FillColor1);
             this.add(FillColor2);
             this.add(FillColor3);
        }
}
</code>```

`

```<code>import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class ObjectWindow extends JFrame implements ActionListener {

    ButtonWindow ButtonWindow;

    ObjectWindow(ButtonWindow bw){
        this.ButtonWindow =bw;
        this.setTitle("Drawing Objects");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());

     this.setSize(1000, 1000);
     this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }

}
</code>```

`

```<code>
import javax.swing.JRadioButton;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.*;

public class main {
    public static void main(String a[]){
        ButtonWindow window = new ButtonWindow();
        new ObjectWindow(window);

    }

}

</code>```
```<code></code>```

Body:
So, i have a question with me code here, i have to make a program that draws objects and sometime fills them by clicking radiobuttons, the other part is that the drawing part had to be done in a second window, so i need to have the radiobuttons in one screen and by clicking them i have to draw objects in different window. I maded up to the part where i declared the buttons and created the 2nd screen, but i dont know how to make when i select the radiobutton to draws in the 2nd screen, can someone help me, im new into JAVA.
`

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class ButtonWindow extends JFrame{

        JRadioButton Oval, Line,OutlineColor1,OutlineColor2,OutlineColor3,FillColor1,FillColor2,FillColor3;

        ButtonWindow(){
            JFrame f1=new JFrame();
            this.setTitle("Drawing Objects");
            this.setVisible(true);
            this.setLayout(new FlowLayout());
            this.pack();
            this.setSize(500,500);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            setLayout(new GridLayout(0,1));

              Oval = new JRadioButton("Oval shape ");
              Line = new JRadioButton("Line");
              OutlineColor1 = new JRadioButton("Outline Color: RED");
              OutlineColor2 = new JRadioButton("Outline Color: BLUE");
              OutlineColor3 = new JRadioButton("Outline Color: GREEN");
              FillColor1 = new JRadioButton("Filling Color: RED");
              FillColor2 = new JRadioButton("Filling Color: BLUE");
              FillColor3 = new JRadioButton("Filling Color: GREEN");

             ButtonGroup group1 = new ButtonGroup();
                group1.add(Oval);
                group1.add(Line);

                ButtonGroup group2 = new ButtonGroup();
                group2.add(OutlineColor1);
                group2.add(OutlineColor2);
                group2.add(OutlineColor3);

                ButtonGroup group3 = new ButtonGroup();
                group3.add(FillColor1);
                group3.add(FillColor2);
                group3.add(FillColor3);

             this.add(Oval);
             this.add(Line);
             this.add(OutlineColor1);
             this.add(OutlineColor2);
             this.add(OutlineColor3);
             this.add(FillColor1);
             this.add(FillColor2);
             this.add(FillColor3);
        }
}

`

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class ObjectWindow extends JFrame implements ActionListener {

    ButtonWindow ButtonWindow;

    ObjectWindow(ButtonWindow bw){
        this.ButtonWindow =bw;
        this.setTitle("Drawing Objects");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());

     this.setSize(1000, 1000);
     this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }

}

`

import javax.swing.JRadioButton;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.*;

public class main {
    public static void main(String a[]){
        ButtonWindow window = new ButtonWindow();
        new ObjectWindow(window);

    }

}


问:
MongoDB collection index with complex query
I have refined an aggregation query over and over, the query itself is returning exactly the correct information however I am receiving lots of Query targeting alerts as  Scanned Objects / Returned has gone above 1000.

I am guessing my collection index's are not suitable.

Any help with the below aggregation pipeline and suitable index's to create would be greatly appreciated!

The below query checks and returns bookings where the start date for any days within a bookings collection fall between the 2 dates.

```<code>// example booking document
{
  status: 1,
  client: ObjectId,
  customer: ObjectId,
  days: [{ start: date }, { startL date }]
}
</code>```

status and client on the below aggregation are optional, this same query is also often executed without those.

```<code>.aggregate([
      {
        "$match": {
          "status": 1,
          "client": "ObjectId"
          "customer": "ObjectId",
          "days": {
            "$elemMatch": {
              "start": {
                "$gte": "2023-02-01T00:00:00.000Z",
                "$lte": "2023-02-28T23:59:59.999Z"
              }
            }
          }
        }
      },
      {
        "$sort": {
          "createdAt": 1
        }
      }
]);
</code>```

I have tried adding a variety of indexes, examining my query using cursor.explain() but all indexes or amends to the above query are not fixing the issue.

Below is a link to the explain output:
https://codebeautify.org/jsonviewer/y229660e2

Body:
I have refined an aggregation query over and over, the query itself is returning exactly the correct information however I am receiving lots of Query targeting alerts as  Scanned Objects / Returned has gone above 1000.

I am guessing my collection index's are not suitable.

Any help with the below aggregation pipeline and suitable index's to create would be greatly appreciated!

The below query checks and returns bookings where the start date for any days within a bookings collection fall between the 2 dates.

// example booking document
{
  status: 1,
  client: ObjectId,
  customer: ObjectId,
  days: [{ start: date }, { startL date }]
}

status and client on the below aggregation are optional, this same query is also often executed without those.

.aggregate([
      {
        "$match": {
          "status": 1,
          "client": "ObjectId"
          "customer": "ObjectId",
          "days": {
            "$elemMatch": {
              "start": {
                "$gte": "2023-02-01T00:00:00.000Z",
                "$lte": "2023-02-28T23:59:59.999Z"
              }
            }
          }
        }
      },
      {
        "$sort": {
          "createdAt": 1
        }
      }
]);

I have tried adding a variety of indexes, examining my query using cursor.explain() but all indexes or amends to the above query are not fixing the issue.

Below is a link to the explain output:
https://codebeautify.org/jsonviewer/y229660e2


问:
How to clean nan in tf.data.Dataset in sequences multivariates inputs for LSTM
I try to feed huge dataset (out of memory) to my lstm model.
I want to make some transformation on my data using the tf.data.Dataset.
I first turn my numpy data to dataset using tf.keras.utils.timeseries_dataset_from_array.
This is an exemple of my data:

6 first columns are a feature, last one is my target and row are timesteps.

I turn my 7 features inputs to sequences of 5 timesteps and want to predict the output of one value using this code:

```<code>input_dataset = tf.keras.utils.timeseries_dataset_from_array(
        data[:,:-1], None, sequence_length=5, sequence_stride=1, shuffle=True, seed=1)

target_dataset = tf.keras.utils.timeseries_dataset_from_array(
        data[:,-1], None, sequence_length=1, sequence_stride=1,
        shuffle=True, seed=1)
</code>```

as you see in my data, sometimes values are missing. What I try is to remove all sequences (input with associated output) with a 'nan' in the input OR output.

I try to adapt an exemple and get this:

```<code>filter_nan = lambda i, j: not tf.reduce_any(tf.math.is_nan(i)) and not tf.math.is_nan(j)
ds = tf.data.Dataset.zip((input_dataset, output_dataset)).filter(filter_nan)
</code>```

but get this error :

```<code>Using a symbolic `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
</code>```

I take a look to @tf.function but it is out of my comprehension for the moment and not sure my innitial trial was correct anyway.

Body:
I try to feed huge dataset (out of memory) to my lstm model.
I want to make some transformation on my data using the tf.data.Dataset.
I first turn my numpy data to dataset using tf.keras.utils.timeseries_dataset_from_array.
This is an exemple of my data:

6 first columns are a feature, last one is my target and row are timesteps.

I turn my 7 features inputs to sequences of 5 timesteps and want to predict the output of one value using this code:

input_dataset = tf.keras.utils.timeseries_dataset_from_array(
        data[:,:-1], None, sequence_length=5, sequence_stride=1, shuffle=True, seed=1)

target_dataset = tf.keras.utils.timeseries_dataset_from_array(
        data[:,-1], None, sequence_length=1, sequence_stride=1,
        shuffle=True, seed=1)

as you see in my data, sometimes values are missing. What I try is to remove all sequences (input with associated output) with a 'nan' in the input OR output.

I try to adapt an exemple and get this:

filter_nan = lambda i, j: not tf.reduce_any(tf.math.is_nan(i)) and not tf.math.is_nan(j)
ds = tf.data.Dataset.zip((input_dataset, output_dataset)).filter(filter_nan)

but get this error :

Using a symbolic `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

I take a look to @tf.function but it is out of my comprehension for the moment and not sure my innitial trial was correct anyway.


问:
Is it possible to search through the results of an array/echo for a specified value in shell/bash?
I currently am trying to write a script that will check if a client is hardwired into an ethernet connection before running a script to rebind to AD. My idea so far has been to list the connected network IPs and go through that to make sure they're connected. Is there a way to search through the text for a set sequence/variable type of thing? I want to check for 10.101. in the beginning of  one of the IPs to see if it has a wifi connection.

This is what I have written so far
`

```<code>n=0
myArray=$(ifconfig -l | xargs -n1 ipconfig getifaddr)

for i in ${myArray[@]}
do
    testString="$i"
    echo $i
    ((n=n+1))
done

 echo ${myArray[0]}

</code>```

`
This echoes all the IPs and counts how many there are.

Body:
I currently am trying to write a script that will check if a client is hardwired into an ethernet connection before running a script to rebind to AD. My idea so far has been to list the connected network IPs and go through that to make sure they're connected. Is there a way to search through the text for a set sequence/variable type of thing? I want to check for 10.101. in the beginning of  one of the IPs to see if it has a wifi connection.

This is what I have written so far
`

n=0
myArray=$(ifconfig -l | xargs -n1 ipconfig getifaddr)

for i in ${myArray[@]}
do
    testString="$i"
    echo $i
    ((n=n+1))
done

 echo ${myArray[0]}

`
This echoes all the IPs and counts how many there are.


问:
Setting up TeamCity on AWS Ec2
I have set up a Server and a BuildAgent on Amazon Ec2. I have configured the build agent to sit in the /home/ec2-user/build-agent directory (will this cause problems due to permissions?)
I then configured the build agent to point to the server through the public dns and port 8111. I have then started the build agent.

I used the Cloud Tab on the TC Web interface to setup the Build Agent on the server. I can see on the build agent host machine that a connection with the server has been established. Yet in the web interface I can see no build agents in either the unauthorized tab or the compatible tabs.

In short I cannot connect a build agent to the server?

Any help or ideas on this one would be greatly appreciated.

many thanks

Dermot

ContentLicense: CC BY-SA 3.0

Title: Setting up TeamCity on AWS Ec2


问:
Raycasts are not detecting objects with assigned layer in unity
I am trying to use raycasts to detect walls with specific layer, but it just doesn't detect anything. I have previously tried using raycasts for detecting ground and it also didn't work.

Code I tried first was:

```<code>    private void CheckForWall()
    {
        wallRight = Physics.Raycast(transform.position, orientation.right, out rightWallhit, wallCheckDistance, whatIsWall);
        wallLeft = Physics.Raycast(transform.position, -orientation.right, out rightWallhit, wallCheckDistance, whatIsWall);
    }
</code>```

with wallCheckDistance being public float set to 0.7 and what is wall being LayerMask whatIsWall set to walls I want to wallrun on. I am sure the problem is detecting since I also have state handler showing different states and wallrunning never comes up. After cranking up the wallCheckDistance to 1.5, I was able to wallrun only on side of one wall out of many.

Body:
I am trying to use raycasts to detect walls with specific layer, but it just doesn't detect anything. I have previously tried using raycasts for detecting ground and it also didn't work.

Code I tried first was:

    private void CheckForWall()
    {
        wallRight = Physics.Raycast(transform.position, orientation.right, out rightWallhit, wallCheckDistance, whatIsWall);
        wallLeft = Physics.Raycast(transform.position, -orientation.right, out rightWallhit, wallCheckDistance, whatIsWall);
    }

with wallCheckDistance being public float set to 0.7 and what is wall being LayerMask whatIsWall set to walls I want to wallrun on. I am sure the problem is detecting since I also have state handler showing different states and wallrunning never comes up. After cranking up the wallCheckDistance to 1.5, I was able to wallrun only on side of one wall out of many.


问:
trouble editting a jquery function that contains onclick and animate
Wanting to remove the decimal places within this current "jquery" function, I read that it is "to.fixed()", i just don't know where to type it in???

```<code>$(document).ready(function() {
  $("#button").click(function() {
    $("#number").animate({value: '250px'});
  })
});
</code>```

link to example: "onclick with animate example"

Body:
Wanting to remove the decimal places within this current "jquery" function, I read that it is "to.fixed()", i just don't know where to type it in???

$(document).ready(function() {
  $("#button").click(function() {
    $("#number").animate({value: '250px'});
  })
});

link to example: "onclick with animate example"


问:
How to begin on making the interactive section of a card game in Java
As my first big project for class, I need to make a card game using android studio. the game would pretty much be the card jitsu mini game from club penguin. I already have Card objects and everything like that, but I'm just stuck on how to begin working on the parts that the player would need to interact with. For example, how do I display a card "physically" on the game screen where it displays on the bottom left side in the players hand? how to interact with it? I'm basically stuck on the displaying and interacting with the cards. As I'm pretty new to programming I don't even really know where to begin with so every bit of help will be appreciated. I've added a picture to emphasize what I'm stuck on.
The draft:

I've tried looking for how to do this on the internet but due to how specific it is I'm having a really hard time finding something useful for what I need.


问:
inView in framer-motion returns false when component is in viewPort in react image slider
Below is my slider component which renders the imageSlider in my app

```<code>const Slider = () => {
    // slider state and images data
    const [currentSlide, setCurrentSlide] = useState(0);
    const { sliderImages, sliderImagesLoading } = useAppContext();

    //framer-motion
    const [ref, inView] = useInView();
    const controls = useAnimation();
    const sliderVariants = {
        visible: { opatcity: 1, transition: { duration: 1 } },
        hidden: { opacity: 0 },
    };
    // autoscroll imageSlider
    let autoScroll = true;
    let myInterval;

    const setNext = () => {
        const sliderLength = sliderImages.length;
        currentSlide < sliderLength - 1 ? setCurrentSlide(currentSlide + 1) : setCurrentSlide(0);
    };

    const setPrev = () => {
        const sliderLength = sliderImages.length;
        currentSlide === 0 ? setCurrentSlide(sliderLength - 1) : setCurrentSlide(currentSlide - 1);
    };

    const auto = () => {
        myInterval = setInterval(setNext, 5000);
    };

    useEffect(() => {
        setCurrentSlide(0);
    }, []);

    useEffect(() => {
        if (autoScroll) {
            auto();
        }
        return () => clearInterval(myInterval);
    }, [currentSlide]);

    useEffect(() => {
        console.log("inview" + inView);  // here inView logs false when component is visible and true when it is invisible
        if (!inView) {
            controls.start("visible");
        }
    }, [controls, inView]);

    return (
        <div className="overflow-hidden w-full h-64 border-violet-800 border-t-4 border-b-4 ">
            <span
                className="absolute mt-20 left-0 bg-white w-12 h-24 flex items-center rounded-tr-md rounded-br-md z-50 "
                onClick={() => setPrev()}
            >
                <BsChevronLeft className="text-4xl  " />
            </span>
            <span
                className="absolute mt-20 right-0 bg-white w-12 h-24 flex items-center rounded-tl-md rounded-bl-md z-50"
                onClick={() => setNext()}
            >
                <BsChevronRight className="text-4xl" />
            </span>
            <div>
                {sliderImages.map((slide, index) => {
                    return (
                        <motion.div
                            key={slide.id}
                            ref={ref}
                            variants={sliderVariants}
                            initial="hidden"
                            animate={controls}
                        >
                            {currentSlide === index && (
                                <img src={slide.images[0]} className={`object-fill w-full`} />
                            )}
                        </motion.div>
                    );
                })}
            </div>
        </div>
    );
};

</code>```

my sliderImages is array of objects in format

```<code>    [{id:"id", name:"proudctname", images:["img1","img2","img3"]},
     {id:"id", name:"proudctname", images:["img1","img2","img3"]}
     {id:"id", name:"proudctname", images:["img1","img2","img3"]}]
</code>```

So suggest some way how to do this. I want to set opacity of div containg the images to 0 initially and when it is in viewport, set opacity to 1 so that it creates a fade in effect.

I tried using useInView which comes from react-intersection-observer. but it is giving incorrect results. When my particular imageSlider comes in viewport it shows false and when it is removed from vp it shows true. It is totally opposite behaviour of expected.

Body:
Below is my slider component which renders the imageSlider in my app

const Slider = () => {
    // slider state and images data
    const [currentSlide, setCurrentSlide] = useState(0);
    const { sliderImages, sliderImagesLoading } = useAppContext();

    //framer-motion
    const [ref, inView] = useInView();
    const controls = useAnimation();
    const sliderVariants = {
        visible: { opatcity: 1, transition: { duration: 1 } },
        hidden: { opacity: 0 },
    };
    // autoscroll imageSlider
    let autoScroll = true;
    let myInterval;

    const setNext = () => {
        const sliderLength = sliderImages.length;
        currentSlide < sliderLength - 1 ? setCurrentSlide(currentSlide + 1) : setCurrentSlide(0);
    };

    const setPrev = () => {
        const sliderLength = sliderImages.length;
        currentSlide === 0 ? setCurrentSlide(sliderLength - 1) : setCurrentSlide(currentSlide - 1);
    };

    const auto = () => {
        myInterval = setInterval(setNext, 5000);
    };

    useEffect(() => {
        setCurrentSlide(0);
    }, []);

    useEffect(() => {
        if (autoScroll) {
            auto();
        }
        return () => clearInterval(myInterval);
    }, [currentSlide]);

    useEffect(() => {
        console.log("inview" + inView);  // here inView logs false when component is visible and true when it is invisible
        if (!inView) {
            controls.start("visible");
        }
    }, [controls, inView]);

    return (

             setPrev()}
            >
                <BsChevronLeft className="text-4xl  " />

             setNext()}
            >
                <BsChevronRight className="text-4xl" />

                {sliderImages.map((slide, index) => {
                    return (
                        <motion.div
                            key={slide.id}
                            ref={ref}
                            variants={sliderVariants}
                            initial="hidden"
                            animate={controls}
                        >
                            {currentSlide === index && (
                                <img src={slide.images[0]} className={`object-fill w-full`} />
                            )}
                        </motion.div>
                    );
                })}

    );
};

my sliderImages is array of objects in format

    [{id:"id", name:"proudctname", images:["img1","img2","img3"]},
     {id:"id", name:"proudctname", images:["img1","img2","img3"]}
     {id:"id", name:"proudctname", images:["img1","img2","img3"]}]

So suggest some way how to do this. I want to set opacity of div containg the images to 0 initially and when it is in viewport, set opacity to 1 so that it creates a fade in effect.

I tried using useInView which comes from react-intersection-observer. but it is giving incorrect results. When my particular imageSlider comes in viewport it shows false and when it is removed from vp it shows true. It is totally opposite behaviour of expected.


问:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: index 0 is out of bounds for axis 0 with size 0
I'm trying to create a simple discord bot, which returns values from a csv file, the bot is working but when the csv result has spaces, for example: "Lua Crimson", it gives an error in the bot and the message does not return.

The bot command is: !score name

the lines of code (I modified it and put it in quotes but it still didn't work):

import pandas as pd
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
from discord.ext.commands import Bot
from discord import Embed

df = pd.read_csv('score.csv')

bot = discord.Client(intents=discord.Intents.default())

@bot.event
async def on_ready():
  print('Bot is ready!')

bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")
@bot.command()
async def score(ctx, name: str):
  row = df.loc[df['Nick'] == name]
  rank = row['Rank'].values[0]
  score = row['Score'].values[0]
  embed = Embed(title='Rank', color=0x00FF00)
  embed.add_field(name='Nome', value=f"{name}")
  embed.add_field(name='Rank', value=f"{rank}")
  embed.add_field(name='Score', value=f"{score}")
  await ctx.send(embed=embed)

  #await ctx.send(f"{name} está no rank {rank} com um score de {score}")

bot.run('Token')
```
<p>this is the error message that appears in the log:</p>
```Traceback (most recent call last):
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: index 0 is out of bounds for axis 0 with size 0
```

Body:
I'm trying to create a simple discord bot, which returns values from a csv file, the bot is working but when the csv result has spaces, for example: "Lua Crimson", it gives an error in the bot and the message does not return.

The bot command is: !score name

the lines of code (I modified it and put it in quotes but it still didn't work):

import pandas as pd
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
from discord.ext.commands import Bot
from discord import Embed

df = pd.read_csv('score.csv')

bot = discord.Client(intents=discord.Intents.default())

@bot.event
async def on_ready():
  print('Bot is ready!')

bot = commands.Bot(intents=discord.Intents.all() , command_prefix= "!")
@bot.command()
async def score(ctx, name: str):
  row = df.loc[df['Nick'] == name]
  rank = row['Rank'].values[0]
  score = row['Score'].values[0]
  embed = Embed(title='Rank', color=0x00FF00)
  embed.add_field(name='Nome', value=f"{name}")
  embed.add_field(name='Rank', value=f"{rank}")
  embed.add_field(name='Score', value=f"{score}")
  await ctx.send(embed=embed)

  #await ctx.send(f"{name} está no rank {rank} com um score de {score}")

bot.run('Token')

this is the error message that appears in the log:

Traceback (most recent call last):
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\rodri\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: index 0 is out of bounds for axis 0 with size 0


问:
Is there any shortcut for focusing on specific repository in VSCode source control side bar
In vscode, I use a multi-root workspace with 40+ different git repositories. I use vscode source control extensively. My current workflow is to scroll through the source control repositories to find the correct repository and click on it. This could be a little time consuming and annoying if there are many repositories and if you context switch often. Is it possible to do this without scrolling?

I am looking for a shortcut where I could type the repo name. Or a setting or an extension that focus on the correct repository based on open file in editor.

I looked through the git shortcuts in vscode but none of them worked.


问:
NodeJS ENOMEM error when reading from a file
I have an application written in Node.js which works fine when running on one server. When I try running it in a Vagrant virtual machine, I get ENOMEM errors when trying to read from files. These files are not particularly big (one of the files triggering the error is 65 kilobytes, for example), and the virtual machine seems to have plenty of memory available. I'm using tmux to have two consoles open, and when I run free -H while the application is running, it reports plenty of free memory:

```<code>               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       183Mi       3.1Gi       0.0Ki       577Mi       3.4Gi
Swap:             0B          0B          0B
</code>```

I've also tried increasing the soft file limits from 1024 to 100_000 in case that was the issue:

```<code>$ ulimit -Sn
100000
</code>```

The code triggering the error looks like this:

```<code>    const nodeFs = require('node-fs');

// ...

            const threadFilename = 'data/threads/' + id;
            nodeFs.readFile(threadFilename, (err, strFileContents) => {
                logger.debug(`nodeFs.readFile returned for thread ${id}`);
                if (err) {
                    logger.error('Failed to read from ' + threadFilename);
                    logger.error(util.inspect(err));
                    return reject(err);
                } else {
                    //...
                }
            });
</code>```

And the error message that gets logged is:

```<code>error:   [thread.js]Failed to read from data/threads/1853055ec62c5069
error:   [thread.js][Error: ENOMEM: not enough memory, open 'data/threads/1853055ec62c5069'] {
  errno: -12,
  code: 'ENOMEM',
  syscall: 'open',
  path: 'data/threads/1853055ec62c5069'
}
</code>```

This error message is repeated like a hundred times, once for each file I'm trying to open. (Note that "threads" here is referring to discussion threads; the program isn't doing anything fancy with multithreading)

If I try to open the node REPL and directly read the file, it works fine:

```<code>Welcome to Node.js v18.12.1.
Type ".help" for more information.
> const nodeFs = require('node-fs')
undefined
> nodeFs.readFile('data/threads/1853087ddbe2300c', (err, str) => { console.log("err", err, "str", str) })
undefined
> err null str <Buffer 7b 22 69 64 22 3a 22 31 38 35 33 30 38 37 64 64 62 65 32 33 30 30 63 22 2c 22 68 69 73 74 6f 72 79 49 64 22 3a 22 33 34 36 36 32 38 38 37 22 2c 22 6d ... 136972 more bytes>
</code>```

I'm looking for advice on how to debug this further.

Body:
I have an application written in Node.js which works fine when running on one server. When I try running it in a Vagrant virtual machine, I get ENOMEM errors when trying to read from files. These files are not particularly big (one of the files triggering the error is 65 kilobytes, for example), and the virtual machine seems to have plenty of memory available. I'm using tmux to have two consoles open, and when I run free -H while the application is running, it reports plenty of free memory:

               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       183Mi       3.1Gi       0.0Ki       577Mi       3.4Gi
Swap:             0B          0B          0B

I've also tried increasing the soft file limits from 1024 to 100_000 in case that was the issue:

$ ulimit -Sn
100000

The code triggering the error looks like this:

    const nodeFs = require('node-fs');

// ...

            const threadFilename = 'data/threads/' + id;
            nodeFs.readFile(threadFilename, (err, strFileContents) => {
                logger.debug(`nodeFs.readFile returned for thread ${id}`);
                if (err) {
                    logger.error('Failed to read from ' + threadFilename);
                    logger.error(util.inspect(err));
                    return reject(err);
                } else {
                    //...
                }
            });

And the error message that gets logged is:

error:   [thread.js]Failed to read from data/threads/1853055ec62c5069
error:   [thread.js][Error: ENOMEM: not enough memory, open 'data/threads/1853055ec62c5069'] {
  errno: -12,
  code: 'ENOMEM',
  syscall: 'open',
  path: 'data/threads/1853055ec62c5069'
}

This error message is repeated like a hundred times, once for each file I'm trying to open. (Note that "threads" here is referring to discussion threads; the program isn't doing anything fancy with multithreading)

If I try to open the node REPL and directly read the file, it works fine:

Welcome to Node.js v18.12.1.
Type ".help" for more information.
> const nodeFs = require('node-fs')
undefined
> nodeFs.readFile('data/threads/1853087ddbe2300c', (err, str) => { console.log("err", err, "str", str) })
undefined
> err null str <Buffer 7b 22 69 64 22 3a 22 31 38 35 33 30 38 37 64 64 62 65 32 33 30 30 63 22 2c 22 68 69 73 74 6f 72 79 49 64 22 3a 22 33 34 36 36 32 38 38 37 22 2c 22 6d ... 136972 more bytes>

I'm looking for advice on how to debug this further.


问:
Download file in memory without saving it on disk Java Spring Boot
I have an external link where the XLS file is stored. I need to download it in memory, without saving it on disk, read information from it and print that info to the console, so I don't need file after that.
The second issue that I've been struggling with - I can't transform that file to some Java Object.
I'm using WebClient from the Spring WebFlux library and don't know to which type I can transform the response. When I try to transform it into ByteArrayInputStream, ByteArrayOutputStream or ByteArrayResource I'm getting an error:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/xml;charset=UTF-8' not supported for bodyType...

When I test an external link with Postman - I can see that it has a header with Content-Type application/vnd.ms-excel

Example with my code below:

```<code>ByteArrayResource xlsResponse = webClientBuilder.build().get()
                .uri(xlsLink)
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.xls")
                .retrieve()
                .bodyToMono(ByteArrayResource.class)
                .block();
</code>```

UPDATE

RestTemplate solved this problem. Just download it into byte array with next lines of code:

 byte[] fileBytes = restTemplate.getForObject(xlsLink, byte[].class);

But I'm still wondering how to do it with WebClient.

Body:
I have an external link where the XLS file is stored. I need to download it in memory, without saving it on disk, read information from it and print that info to the console, so I don't need file after that.
The second issue that I've been struggling with - I can't transform that file to some Java Object.
I'm using WebClient from the Spring WebFlux library and don't know to which type I can transform the response. When I try to transform it into ByteArrayInputStream, ByteArrayOutputStream or ByteArrayResource I'm getting an error:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/xml;charset=UTF-8' not supported for bodyType...

When I test an external link with Postman - I can see that it has a header with Content-Type application/vnd.ms-excel

Example with my code below:

ByteArrayResource xlsResponse = webClientBuilder.build().get()
                .uri(xlsLink)
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.xls")
                .retrieve()
                .bodyToMono(ByteArrayResource.class)
                .block();

UPDATE

RestTemplate solved this problem. Just download it into byte array with next lines of code:

 byte[] fileBytes = restTemplate.getForObject(xlsLink, byte[].class);

But I'm still wondering how to do it with WebClient.