问:
Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute
I'm using PayPal payment button with my Mern app , i used the typical sandbox accounts of after configuration. the first time it worked perfectly and after that it doesn't want to pay and lighthouse is send me this error

Indicate whether a cookie is intended to be set in a cross-site context by specifying its SameSite attribute
Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being set in a cross-site context. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie:
Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts. Note that only cookies sent over HTTPS may use the Secure attribute.
Specify SameSite=Strict or SameSite=Lax if the cookie should not be set by cross-site requests.

server.js

```<code>import express, { application } from 'express';
import dotenv from 'dotenv';
import colors from 'colors';
import { notFound, errorHandler } from './middleware/errorMiddleware.js';
import connectDB from './config/db.js';
import productRoutes from './routes/productRoutes.js';
import userRoutes from './routes/userRoutes.js';
import orderRoutes from './routes/orderRoutes.js';
import uploadRoutes from './routes/uploadRoutes.js';

dotenv.config();
connectDB();
const app = express();
app.use(express.json());

app.get('/', (req, res) => {
  res.send('API is running..');
});

app.use('/api/products/', productRoutes);
app.use('/api/users/', userRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/upload', uploadRoutes);
app.get('/api/config/paypal', (req, res) => res.send(process.env.PAYPAL_CLIENT_ID));

app.use(notFound);

app.use(errorHandler);

const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`.red.bold));

</code>```

orderScreen.js

```<code>import React, { useState, useEffect } from 'react';
import axios from 'axios';
//import { PayPalScriptProvider, PayPalButtons } from '@paypal/react-paypal-js';
import { PayPalButton } from 'react-paypal-button-v2';

import { useParams, Link, useLocation } from 'react-router-dom';
import { Button, Row, Col, ListGroup, Image, Card } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';

import Loader from '../components/Loader';
import Message from '../components/Message';

import { getOrderDetails, payOrder, deliverOrder } from '../actions/orderActions.js';
import { ORDER_PAY_RESET, ORDER_DELIVER_RESET } from '../constants/orderConstants.js';

const OrderScreen = () => {
  const { id } = useParams();
  const orderId = `${id}`;
  const dispatch = useDispatch();
  const history = useLocation();
  const [sdkReady, setSdkReady] = useState(false);

  const orderDetails = useSelector((state) => state.orderDetails);
  const { order, loading, error } = orderDetails;

  const orderPay = useSelector((state) => state.orderPay);
  const { loading: loadingPay, success: successPay } = orderPay;

  const orderDeliver = useSelector((state) => state.orderDeliver);
  const { loading: loadingDeliver, success: successDeliver } = orderDeliver;

  const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;

  if (!loading) {
    //   Calculate prices
    const addDecimals = (num) => {
      return (Math.round(num * 100) / 100).toFixed(2);
    };
    order.itemsPrice = addDecimals(order.orderItems.reduce((acc, item) => acc + item.price * item.qty, 0));
  }
  useEffect(() => {
    if (!userInfo) {
      history('/login');
    }

    const addPayPalScript = async () => {
      const { data: clientId } = await axios.get('/api/config/paypal');
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}`;
      script.async = true;
      script.onload = () => {
        setSdkReady(true);
      };
      document.body.appendChild(script);
    };

    if (!order || successPay || successDeliver || order._id !== orderId) {
      dispatch({ type: ORDER_PAY_RESET });
      dispatch({ type: ORDER_DELIVER_RESET });
      dispatch(getOrderDetails(orderId));
    } else if (!order.isPaid) {
      if (!window.paypal) {
        addPayPalScript();
      } else {
        setSdkReady(true);
      }
    }
  }, [dispatch, orderId, successPay, history, userInfo, successDeliver, order]);

  const successPaymentHandler = (paymentResult) => {
    console.log(paymentResult);
    dispatch(payOrder(orderId, paymentResult));
  };

  const deliverHandler = () => {
    dispatch(deliverOrder(order));
  };

  return loading ? (
    <Loader />
  ) : error ? (
    <Message variant='danger'>{error}</Message>
  ) : (
    <>
      <h1>Order {order._id}</h1>
      <Row>
        <Col md={8}>
          <ListGroup variant='flush'>
            <ListGroup.Item>
              <h2>Shipping</h2>
              <p>
                <strong>Name: </strong> {order.user.name}
              </p>
              <p>
                <strong>Email: </strong> <a href={`mailto:${order.user.email}`}>{order.user.email}</a>
              </p>
              <p>
                <strong>Address:</strong>
                {order.shippingAddress.address}, {order.shippingAddress.city} {order.shippingAddress.postalCode}, {order.shippingAddress.country}
              </p>
              {order.isDelivered ? <Message variant='success'>Delivered on {order.deliveredAt}</Message> : <Message variant='danger'>Not Delivered</Message>}
            </ListGroup.Item>

            <ListGroup.Item>
              <h2>Payment Method</h2>
              <p>
                <strong>Method: </strong>
                {order.paymentMethod}
              </p>
              {order.isPaid ? <Message variant='success'>Paid on {order.paidAt}</Message> : <Message variant='danger'>Not Paid</Message>}
            </ListGroup.Item>

            <ListGroup.Item>
              <h2>Order Items</h2>
              {order.orderItems.length === 0 ? (
                <Message>Order is empty</Message>
              ) : (
                <ListGroup variant='flush'>
                  {order.orderItems.map((item, index) => (
                    <ListGroup.Item key={index}>
                      <Row>
                        <Col md={1}>
                          <Image src={item.image} alt={item.name} fluid rounded />
                        </Col>
                        <Col>
                          <Link to={`/product/${item.product}`}>{item.name}</Link>
                        </Col>
                        <Col md={4}>
                          {item.qty} x ${item.price} = ${item.qty * item.price}
                        </Col>
                      </Row>
                    </ListGroup.Item>
                  ))}
                </ListGroup>
              )}
            </ListGroup.Item>
          </ListGroup>
        </Col>
        <Col md={4}>
          <Card>
            <ListGroup variant='flush'>
              <ListGroup.Item>
                <h2>Order Summary</h2>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Items</Col>
                  <Col>${order.itemsPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Shipping</Col>
                  <Col>${order.shippingPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Tax</Col>
                  <Col>${order.taxPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Total</Col>
                  <Col>${order.totalPrice}</Col>
                </Row>
              </ListGroup.Item>

              {!order.isPaid && (
                <ListGroup.Item>
                  {loadingPay && <Loader />}
                  {!sdkReady ? <Loader /> : <PayPalButton amount={order.totalPrice} onSuccess={successPaymentHandler} />}
                </ListGroup.Item>
              )}

              {loadingDeliver && <Loader />}
              {userInfo && userInfo.isAdmin && order.isPaid && !order.isDelivered && (
                <ListGroup.Item>
                  <Button type='button' className='btn btn-block' onClick={deliverHandler}>
                    Mark As Delivered
                  </Button>
                </ListGroup.Item>
              )}
            </ListGroup>
          </Card>
        </Col>
      </Row>
    </>
  );
};

export default OrderScreen;

</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Find the best products for the cheapsest prices !" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
      integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Montserrat" rel="stylesheet" />
    <script src="https://www.paypal.com/sdk/js?client-id=AZm6WLwtUgFKRRvQqV6hMDWIw_CmEDavupEI2NdSImpe3oKSYXWjqBN_dfIOgCfdQ7CCDcYFE3-fx5_X"></script>

    <title>Pro Shop</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './store.js';
import './bootstrap.min.css';
import './index.css';
import App from './App.js';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

reportWebVitals();

</code>```

I've tried everything yet nothing seems to fix it. Most answers show that my code is true but the problem is with my browser , I'm using brave I tried chrome and Microsoft edge. still the same.

I am aware that the problem is because the cookies are blocked but i can't figure out how to fix it !

Body:
I'm using PayPal payment button with my Mern app , i used the typical sandbox accounts of after configuration. the first time it worked perfectly and after that it doesn't want to pay and lighthouse is send me this error

Indicate whether a cookie is intended to be set in a cross-site context by specifying its SameSite attribute
Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being set in a cross-site context. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie:
Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts. Note that only cookies sent over HTTPS may use the Secure attribute.
Specify SameSite=Strict or SameSite=Lax if the cookie should not be set by cross-site requests.

server.js

import express, { application } from 'express';
import dotenv from 'dotenv';
import colors from 'colors';
import { notFound, errorHandler } from './middleware/errorMiddleware.js';
import connectDB from './config/db.js';
import productRoutes from './routes/productRoutes.js';
import userRoutes from './routes/userRoutes.js';
import orderRoutes from './routes/orderRoutes.js';
import uploadRoutes from './routes/uploadRoutes.js';

dotenv.config();
connectDB();
const app = express();
app.use(express.json());

app.get('/', (req, res) => {
  res.send('API is running..');
});

app.use('/api/products/', productRoutes);
app.use('/api/users/', userRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/upload', uploadRoutes);
app.get('/api/config/paypal', (req, res) => res.send(process.env.PAYPAL_CLIENT_ID));

app.use(notFound);

app.use(errorHandler);

const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`.red.bold));

orderScreen.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';
//import { PayPalScriptProvider, PayPalButtons } from '@paypal/react-paypal-js';
import { PayPalButton } from 'react-paypal-button-v2';

import { useParams, Link, useLocation } from 'react-router-dom';
import { Button, Row, Col, ListGroup, Image, Card } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';

import Loader from '../components/Loader';
import Message from '../components/Message';

import { getOrderDetails, payOrder, deliverOrder } from '../actions/orderActions.js';
import { ORDER_PAY_RESET, ORDER_DELIVER_RESET } from '../constants/orderConstants.js';

const OrderScreen = () => {
  const { id } = useParams();
  const orderId = `${id}`;
  const dispatch = useDispatch();
  const history = useLocation();
  const [sdkReady, setSdkReady] = useState(false);

  const orderDetails = useSelector((state) => state.orderDetails);
  const { order, loading, error } = orderDetails;

  const orderPay = useSelector((state) => state.orderPay);
  const { loading: loadingPay, success: successPay } = orderPay;

  const orderDeliver = useSelector((state) => state.orderDeliver);
  const { loading: loadingDeliver, success: successDeliver } = orderDeliver;

  const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;

  if (!loading) {
    //   Calculate prices
    const addDecimals = (num) => {
      return (Math.round(num * 100) / 100).toFixed(2);
    };
    order.itemsPrice = addDecimals(order.orderItems.reduce((acc, item) => acc + item.price * item.qty, 0));
  }
  useEffect(() => {
    if (!userInfo) {
      history('/login');
    }

    const addPayPalScript = async () => {
      const { data: clientId } = await axios.get('/api/config/paypal');
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}`;
      script.async = true;
      script.onload = () => {
        setSdkReady(true);
      };
      document.body.appendChild(script);
    };

    if (!order || successPay || successDeliver || order._id !== orderId) {
      dispatch({ type: ORDER_PAY_RESET });
      dispatch({ type: ORDER_DELIVER_RESET });
      dispatch(getOrderDetails(orderId));
    } else if (!order.isPaid) {
      if (!window.paypal) {
        addPayPalScript();
      } else {
        setSdkReady(true);
      }
    }
  }, [dispatch, orderId, successPay, history, userInfo, successDeliver, order]);

  const successPaymentHandler = (paymentResult) => {
    console.log(paymentResult);
    dispatch(payOrder(orderId, paymentResult));
  };

  const deliverHandler = () => {
    dispatch(deliverOrder(order));
  };

  return loading ? (
    <Loader />
  ) : error ? (
    <Message variant='danger'>{error}</Message>
  ) : (
    <>

Order {order._id}

      <Row>
        <Col md={8}>
          <ListGroup variant='flush'>
            <ListGroup.Item>

Shipping

                Name:  {order.user.name}

                Email:  <a href={`mailto:${order.user.email}`}>{order.user.email}

                Address:
                {order.shippingAddress.address}, {order.shippingAddress.city} {order.shippingAddress.postalCode}, {order.shippingAddress.country}

              {order.isDelivered ? <Message variant='success'>Delivered on {order.deliveredAt}</Message> : <Message variant='danger'>Not Delivered</Message>}
            </ListGroup.Item>

            <ListGroup.Item>

Payment Method

                Method:
                {order.paymentMethod}

              {order.isPaid ? <Message variant='success'>Paid on {order.paidAt}</Message> : <Message variant='danger'>Not Paid</Message>}
            </ListGroup.Item>

            <ListGroup.Item>

Order Items

              {order.orderItems.length === 0 ? (
                <Message>Order is empty</Message>
              ) : (
                <ListGroup variant='flush'>
                  {order.orderItems.map((item, index) => (
                    <ListGroup.Item key={index}>
                      <Row>
                        <Col md={1}>
                          <Image src={item.image} alt={item.name} fluid rounded />
                        </Col>
                        <Col>
                          <Link to={`/product/${item.product}`}>{item.name}</Link>
                        </Col>
                        <Col md={4}>
                          {item.qty} x ${item.price} = ${item.qty * item.price}
                        </Col>
                      </Row>
                    </ListGroup.Item>
                  ))}
                </ListGroup>
              )}
            </ListGroup.Item>
          </ListGroup>
        </Col>
        <Col md={4}>
          <Card>
            <ListGroup variant='flush'>
              <ListGroup.Item>

Order Summary

              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Items</Col>
                  <Col>${order.itemsPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Shipping</Col>
                  <Col>${order.shippingPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Tax</Col>
                  <Col>${order.taxPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>Total</Col>
                  <Col>${order.totalPrice}</Col>
                </Row>
              </ListGroup.Item>

              {!order.isPaid && (
                <ListGroup.Item>
                  {loadingPay && <Loader />}
                  {!sdkReady ? <Loader /> : <PayPalButton amount={order.totalPrice} onSuccess={successPaymentHandler} />}
                </ListGroup.Item>
              )}

              {loadingDeliver && <Loader />}
              {userInfo && userInfo.isAdmin && order.isPaid && !order.isDelivered && (
                <ListGroup.Item>
                  <Button type='button' className='btn btn-block' onClick={deliverHandler}>
                    Mark As Delivered
                  </Button>
                </ListGroup.Item>
              )}
            </ListGroup>
          </Card>
        </Col>
      </Row>
    </>
  );
};

export default OrderScreen;

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Find the best products for the cheapsest prices !" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
      integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Montserrat" rel="stylesheet" />

    <title>Pro Shop</title>

    You need to enable JavaScript to run this app.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './store.js';
import './bootstrap.min.css';
import './index.css';
import App from './App.js';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

reportWebVitals();

I've tried everything yet nothing seems to fix it. Most answers show that my code is true but the problem is with my browser , I'm using brave I tried chrome and Microsoft edge. still the same.

I am aware that the problem is because the cookies are blocked but i can't figure out how to fix it !


来源: stackexchange

问:
Cannot see the sheets or plans on my forge viewer Document browser
I am using the following javascript library for the forge viewer (https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.js) and when displaying the same revit file that I can see perfect on Autodesk Viewer with all the documents, I cannot see the sheets or plans in my custom implementation.
You can see the difference here in these 2 screenshots:

ContentLicense: CC BY-SA 4.0


问:
Python Pandas Split to Columns
When using json_normalize, my response contains:

Header 1:
attributes.skin_tone

Value 1: [{'language_tag': 'en_US', 'value': 'All', 'marketplace_id': 'ATVPDKIKX0DER'}]

How do I break the value up so that it only returns the data next to 'value'?

I've tried to split, but it doesn't work

```<code>response = requests.get("https://sellingpartnerapi-na.amazon.com/catalog/2022-04-01/items/B0BGXW5XH1/?marketplaceIds=ATVPDKIKX0DER&includedData=attributes",auth=auth,headers=headers,json=data)
data = response.json()
df = json_normalize(data)
df.to_csv("datatest.csv",index=False)

</code>```

Title: Python Pandas Split to Columns

Body:
When using json_normalize, my response contains:

Header 1:
attributes.skin_tone

Value 1: [{'language_tag': 'en_US', 'value': 'All', 'marketplace_id': 'ATVPDKIKX0DER'}]

How do I break the value up so that it only returns the data next to 'value'?

I've tried to split, but it doesn't work

response = requests.get("https://sellingpartnerapi-na.amazon.com/catalog/2022-04-01/items/B0BGXW5XH1/?marketplaceIds=ATVPDKIKX0DER&includedData=attributes",auth=auth,headers=headers,json=data)
data = response.json()
df = json_normalize(data)
df.to_csv("datatest.csv",index=False)


问:
Why am I getting this error when deploying Blazor WASM App
I have an app that runs fine locally using VS 2022 and SQL Express. When I deploy I need to change to the production database in appsettings.json, which causes this error.

```<code>Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: net_http_message_not_success_statuscode, 500, Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500, Internal Server Error
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__29`1[[BlazorEcommerce.Shared.ServiceResponse`1[[System.Collections.Generic.List`1[[DataServicesTools.Shared.Models.CoreFile, DataServicesTools.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], DataServicesTools.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at DataServicesTools.Client.Services.CoreFileService.CoreFileService.GetCoreFiles()
   at DataServicesTools.Client.Pages.CoreFiles.Index.OnInitializedAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )
</code>```

Connection strings I have tried. I left the password in case there are special characters that need to be escaped.

Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True;User Id=username;Password=M@sterM!nd;

Driver={ODBC Driver 17 for SQL Server};Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True;User Id=username;Password=M@sterM!nd;

This is the connection string that I'm using locally:
Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True

Body:
I have an app that runs fine locally using VS 2022 and SQL Express. When I deploy I need to change to the production database in appsettings.json, which causes this error.

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: net_http_message_not_success_statuscode, 500, Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500, Internal Server Error
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__29`1[[BlazorEcommerce.Shared.ServiceResponse`1[[System.Collections.Generic.List`1[[DataServicesTools.Shared.Models.CoreFile, DataServicesTools.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], DataServicesTools.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at DataServicesTools.Client.Services.CoreFileService.CoreFileService.GetCoreFiles()
   at DataServicesTools.Client.Pages.CoreFiles.Index.OnInitializedAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )

Connection strings I have tried. I left the password in case there are special characters that need to be escaped.

Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True;User Id=username;Password=M@sterM!nd;

Driver={ODBC Driver 17 for SQL Server};Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True;User Id=username;Password=M@sterM!nd;

This is the connection string that I'm using locally:
Server=servername;Database=database;Trusted_Connection=True;TrustServerCertificate=True


问:
react native webview doesn't work on Android - ERR_HTTP_RESPONSE_CODE_FAILURE
I have a react-native app and I am trying to open a webview with a token in query params.
It works fine on iOS, but on Android I am getting this error
I cannot see any other error in the debugger.

My first thought was that the url is too long, because it has approximately 3500 characters, but if I copy the url and paste it in Chrome it opens the page.
I also searched the limits for browsers and it should work even if the url is very long.

Do you have any idea what should be the problem here?


问:
Why Django celery throws me a key error, not sure why?
Not sure why it throws this key error.

My project/celery.py:

```<code>import os
from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

app = Celery('project')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')
</code>```

my project/init.py:

```<code>
from .celery import app as celery_app

__all__ = ('celery_app',)

</code>```

My app/tasks.py

```<code>from celery import shared_task
from celery.schedules import crontab
from project.celery import app

@shared_task
def my_test():

    print('Celery from task says Hi')

app.conf.beat_schedule = {
    'my-task-every-2-minutes': {
        'task': 'my_test',
        'schedule': crontab(minute='*/1'),
    },
}

</code>```

when I run the command: celery -A project beat -l info

I can see the trigger every 1 min there

[2022-12-22 12:38:00,005: INFO/MainProcess] Scheduler: Sending due task my-task-every-2-minutes (celery_app.my_test)

when running celery -A project worker -l info

and triggers sends info I get KeyError: my_test

It seems that it cannot find the task with that key

but from my info everything running fine :

```<code>
 -------------- celery@192.168.1.131 v5.2.7 (dawn-chorus)
--- ***** -----
-- ******* ---- macOS-10.13.6-x86_64-i386-64bit 2022-12-22 12:43:22
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         project:0x10c757610
- ** ---------- .> transport:   redis://localhost:6379//
- ** ---------- .> results:     redis://localhost:6379/
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . project.celery.debug_task
  . user_statistic_status.tasks.my_test

</code>```

Body:
Not sure why it throws this key error.

My project/celery.py:

import os
from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

app = Celery('project')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

my project/init.py:

from .celery import app as celery_app

__all__ = ('celery_app',)

My app/tasks.py

from celery import shared_task
from celery.schedules import crontab
from project.celery import app

@shared_task
def my_test():

    print('Celery from task says Hi')

app.conf.beat_schedule = {
    'my-task-every-2-minutes': {
        'task': 'my_test',
        'schedule': crontab(minute='*/1'),
    },
}

when I run the command: celery -A project beat -l info

I can see the trigger every 1 min there

[2022-12-22 12:38:00,005: INFO/MainProcess] Scheduler: Sending due task my-task-every-2-minutes (celery_app.my_test)

when running celery -A project worker -l info

and triggers sends info I get KeyError: my_test

It seems that it cannot find the task with that key

but from my info everything running fine :

 -------------- celery@192.168.1.131 v5.2.7 (dawn-chorus)
--- ***** -----
-- ******* ---- macOS-10.13.6-x86_64-i386-64bit 2022-12-22 12:43:22
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         project:0x10c757610
- ** ---------- .> transport:   redis://localhost:6379//
- ** ---------- .> results:     redis://localhost:6379/
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . project.celery.debug_task
  . user_statistic_status.tasks.my_test


问:
Dataframe - Column: Date and Time Filter
a Dataframe Datetime column with different non Datetime elements needs to be filtered. i've tried all the tricks in the hat like .dt.strftime, .strptime(time_data, format_data) and etc. but to no help i reach out to you. The screenshots of the different types of elements are shown. its stored under sheet['DateTime'].
my sample code:

```<code>#Time
sheet.loc[sheet['DateTime']=='', 'DateTime' ] = '0  ERROR: Unplausible Fehlerzeit'
sheet.loc[sheet['DateTime']=='0  ERROR: Unplausible Fehlerzeit', ''DateTime'' ] = '%d.%m.%Y %H:%M:%S'
sheet.loc[sheet[''DateTime'']=='-1  ERROR:Unplausible Fehlerzeit', ''DateTime'' ] = '%d.%m.%Y %H:%M:%S'
</code>```

i want just the date and time in format %d.%m.%Y %H:%M:%S

```<code>sheet['DateTime']= sheet['DateTime'].str[-19:]
print(sheet['DateTime'].dtype) #object
sheet['DateTime'] = pd.to_datetime(sheet['DateTime'], format='%d.%m.%Y %H:%M:%S')
sheet = pd.to_datetime(sheet['Date and Time of occurence'])
sheet.sort_values(by='Date and Time of occurence', inplace=True)
</code>```

Body:
a Dataframe Datetime column with different non Datetime elements needs to be filtered. i've tried all the tricks in the hat like .dt.strftime, .strptime(time_data, format_data) and etc. but to no help i reach out to you. The screenshots of the different types of elements are shown. its stored under sheet['DateTime'].
my sample code:

#Time
sheet.loc[sheet['DateTime']=='', 'DateTime' ] = '0  ERROR: Unplausible Fehlerzeit'
sheet.loc[sheet['DateTime']=='0  ERROR: Unplausible Fehlerzeit', ''DateTime'' ] = '%d.%m.%Y %H:%M:%S'
sheet.loc[sheet[''DateTime'']=='-1  ERROR:Unplausible Fehlerzeit', ''DateTime'' ] = '%d.%m.%Y %H:%M:%S'

i want just the date and time in format %d.%m.%Y %H:%M:%S

sheet['DateTime']= sheet['DateTime'].str[-19:]
print(sheet['DateTime'].dtype) #object
sheet['DateTime'] = pd.to_datetime(sheet['DateTime'], format='%d.%m.%Y %H:%M:%S')
sheet = pd.to_datetime(sheet['Date and Time of occurence'])
sheet.sort_values(by='Date and Time of occurence', inplace=True)


问:
How to update encoded existing password in Sql DB using crud repo put mapping- Spring boot application
-->Project-->Springboot-Rolebased authentication-Crud operation-JWT-MySql<--

I need a solution for following issues. Am trying to update the existing user in database through postman API. While registering am able to see all the information stored in sql DB as class defined and with encoded password. Same user am trying to update in DB using "UPDATE" API - crud operation. Details are getting updated except password field. am getting NULL. Please guide me what changes i should make in class.

Example:

Register api (Post-mapping)

name  : test

username: test1

password : password (encoded in DB)

email  : test@test.com
(successfully added in DB)

update api the user : (Put-mapping)

name   : test

username : test1

password :password

email :test123@test.com

(trying to update email. data updated in DB successfully. But password column become "NULL"

I tried BCryptpassword encoder to mask even for update method. getting rawPassword shouldnt be null error

remaining all the API's are working ( like - Get, Post, Delete) only PUT-mapping having issue (password not getting updated)

Please help -- thanks in advance


问:
updating @State variable in swiftUI not cause to reload when using delegate which called from outside
I have this code:

```<code>import SwiftUI

@main
struct MyWatchApp: App {

    @State var myEnum: MyEnum = .first

    var body: some Scene {
        WindowGroup {
            getCorrectView()
        }
    }

    func getCorrectView() -> some View {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.update(.second) // this works
        }

        switch myEnum {
            case .first: return AnyView(Text("First"))
            case .second: return AnyView(Text("Second"))
        }
    }
}
extension MyWatchApp: MyDelegate {
    func update(_ newState: MyEnum) {
        // when this func calls from outside, this print called but view not reloads
        // when this func calls from my getCorrectView, works as expected
        print("state updated")
        myEnum = newState
    }
}
</code>```

My problem is that calling "update" function from other class, calles method, even print() called but view not reloads like when this function called from inside this file.

Body:
I have this code:

import SwiftUI

@main
struct MyWatchApp: App {

    @State var myEnum: MyEnum = .first

    var body: some Scene {
        WindowGroup {
            getCorrectView()
        }
    }

    func getCorrectView() -> some View {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.update(.second) // this works
        }

        switch myEnum {
            case .first: return AnyView(Text("First"))
            case .second: return AnyView(Text("Second"))
        }
    }
}
extension MyWatchApp: MyDelegate {
    func update(_ newState: MyEnum) {
        // when this func calls from outside, this print called but view not reloads
        // when this func calls from my getCorrectView, works as expected
        print("state updated")
        myEnum = newState
    }
}

My problem is that calling "update" function from other class, calles method, even print() called but view not reloads like when this function called from inside this file.


问:
How to export R's RasterLayer to a 3D model?
I have a RasterLayer I'm happy with, but I would like to export it as a 3D model. The contours are non-rectangular, so the upshot is the areas in the bounding box outside the contours are filled with NaN.

What is a good way to export this to some kind of 3D model?

P.S. I'm pretty open on the 3D model format, but ideally STEP file so it can be imported directly into standard CAD packages, such as OnShape.


问:
Stroke width for outlook email
I have a stroke width for emails outside of outlook, but I can't make it thicker for outlook.  Does anyone know how I can fix this code so that a thick border appears for outlook emails?  Thank you!</p>
```<code><div>
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word"
href="mailto" style="height:40px;v-text-anchor:middle;width:400px;" arcsize="100%"
strokecolor="#ec632e"stroke-width="5px" fillcolor="#ffffff">
<w:anchorlock/>
<center style="color:#ec632e;font-family:sans-serif;font-size:13px;font-weight:bold;">
Click here to schedule a meeting</center>
</v:roundrect>
<![endif]-->
<a href="mailto"
style="background-color:#ffffff;border:4px solid #ec632e;
border-radius:40px;color:#ec632e;display:inline-block;font-size:13px;
font-weight:bold;line-height:40px;text-align:center;
text-decoration:none;width:400px;-webkit-text-size-adjust:none;mso-hide:all;">
Click here to schedule a meeting</a>
</div>
</code>```

Title: Stroke width for outlook email

Body:
I have a stroke width for emails outside of outlook, but I can't make it thicker for outlook.  Does anyone know how I can fix this code so that a thick border appears for outlook emails?  Thank you!

Click here to schedule a meeting


问:
Error of Connection Refused when using SignalR and Autofac
If I do not use Autofac, I can connect without issues. But when I use Autofac, I get an error of

java.util.concurrent.ExecutionException: java.net.ConnectException: Connection refused`.

Here is how I setup my SignalR Server:

```<code>public class Program
{
    private static ApplicationSetting mApplicationSetting;
    private static ILoggingOperation mLoggingOperation;
    static void Main(string[] args)
    {
        StartWebHost();
        Console.ReadLine();
    }

    static void StartWebHost()
    {
        using (WebApp.Start("http://10.16.32.52:8085"))
        {
            Console.WriteLine(@"Server running at 10.16.32.52:8085");
        }
    }
}

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired();
        builder.RegisterType<Application>().As<IApplication>();
        builder.RegisterType<CommonActions>().As<ICommonActions>();
        builder.RegisterType<LoggingOperation>().As<ILoggingOperation>();

        var container = builder.Build();
        var resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);

        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR(new HubConfiguration
        {
            Resolver = resolver,
            EnableJSONP = true,
            EnableDetailedErrors = true,
            EnableJavaScriptProxies = true
        });
    }
}
</code>```

My Hub is called ApplicationHub and it is in another class. What can I try next?

Body:
If I do not use Autofac, I can connect without issues. But when I use Autofac, I get an error of

java.util.concurrent.ExecutionException: java.net.ConnectException: Connection refused`.

Here is how I setup my SignalR Server:

public class Program
{
    private static ApplicationSetting mApplicationSetting;
    private static ILoggingOperation mLoggingOperation;
    static void Main(string[] args)
    {
        StartWebHost();
        Console.ReadLine();
    }

    static void StartWebHost()
    {
        using (WebApp.Start("http://10.16.32.52:8085"))
        {
            Console.WriteLine(@"Server running at 10.16.32.52:8085");
        }
    }
}

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired();
        builder.RegisterType<Application>().As<IApplication>();
        builder.RegisterType<CommonActions>().As<ICommonActions>();
        builder.RegisterType<LoggingOperation>().As<ILoggingOperation>();

        var container = builder.Build();
        var resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);

        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR(new HubConfiguration
        {
            Resolver = resolver,
            EnableJSONP = true,
            EnableDetailedErrors = true,
            EnableJavaScriptProxies = true
        });
    }
}

My Hub is called ApplicationHub and it is in another class. What can I try next?


问:
how to use fbFlipper flipper interceptor with HTTPURLConnection
having code uses HttpURLConnectionfor post the remote service.

```<code>    HttpURLConnection connection = null;
    final int CLIENT_SESSION_TTL = 300000;
    try {
        connection = mUrl.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip");
        for (final Map.Entry<String, String> entry : mHeaders.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
        connection.setConnectTimeout(CLIENT_SESSION_TTL);
        final String postBody = getPostBody(messages);

        final OutputStream out = new BufferedOutputStream(connection.getOutputStream());
        out.write(postBody.getBytes());
        out.flush();
        out.close();
        final int responseCode = connection.getResponseCode();
</code>```

How to set a Flipper interceptor to the HttpURLConnection, or is it possible?

Body:
having code uses HttpURLConnectionfor post the remote service.

    HttpURLConnection connection = null;
    final int CLIENT_SESSION_TTL = 300000;
    try {
        connection = mUrl.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip");
        for (final Map.Entry<String, String> entry : mHeaders.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
        connection.setConnectTimeout(CLIENT_SESSION_TTL);
        final String postBody = getPostBody(messages);

        final OutputStream out = new BufferedOutputStream(connection.getOutputStream());
        out.write(postBody.getBytes());
        out.flush();
        out.close();
        final int responseCode = connection.getResponseCode();

How to set a Flipper interceptor to the HttpURLConnection, or is it possible?


问:
Is there any way I can edit my telegram bio using python?
Just like in discord I want telegram to display what song I am currently listening to on Spotify. I know how to access the information about the current song I am listening to using Spotify Api but how can I update that in my telegram bio?

I need a way to automate profile updation in telegram.


问:
Error in running instascrape in jupyter notebook
I am running this code to scrape data from Instagram:

```<code>from instascrape import Location
url = 'https://www.instagram.com/explore/locations/212988663/new-york-new-york/'
new_york = Location(url)
new_york.scrape()
</code>```

But it's throwing me the following error:

```<code>JSONDecodeError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19132/3754258227.py in <module>
      2 url = 'https://www.instagram.com/explore/locations/212988663/new-york-new-york/'
      3 new_york = Location(url)
----> 4 new_york.scrape()
      5

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

Can anyone help me?

Body:
I am running this code to scrape data from Instagram:

from instascrape import Location
url = 'https://www.instagram.com/explore/locations/212988663/new-york-new-york/'
new_york = Location(url)
new_york.scrape()

But it's throwing me the following error:

JSONDecodeError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19132/3754258227.py in <module>
      2 url = 'https://www.instagram.com/explore/locations/212988663/new-york-new-york/'
      3 new_york = Location(url)
----> 4 new_york.scrape()
      5

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Can anyone help me?


问:
createError not working when typing, even though the service call is made
I have a Yup method that I am calling, this checks whether a 10 digit number has been used before. It returns true/false from the service. If it is in use, it should display a validation error on the input box.

It definitely passes into this Yup method and is handled, returning true or false, however the validation doesn't appear, until the input box is blurred (When blurred it calls this method again, however it hits the earlier createError call where the id's are the same and the lastNumber is false)

At the point where the console.log is, if the value is false I would expect it to display the error via createError but it does not.

```<code>let lastNumber:any;
let lastResult:boolean;
Yup.addMethod(Yup.string, "isNumberInUse", function (errorMessage){
  return this.test(`test-number-is-inuse`, errorMessage, function (value, ctx) {
    const { path } = this;

    let digits = value || '';

    let patientId = ctx.parent.id;

    if(patientId === undefined) {
      patientId = '';
    }

    if(digits.length === 0) {
      lastNumber = '';
      lastResult = false;
      return true;
    }

    if(digits.length === 10) {

      if(lastNumber === ctx.parent.number && !lastResult) {
        return this.createError({path, message: errorMessage})
      }

      if(lastResult){
        return true;
      }

     MyService.IsNumberAvailable(digits, patientId.toString())
        .then((response:boolean) => {
          lastNumber = digits;
          lastResult = response;
          console.log(response);
          return (response || this.createError({path, message: errorMessage}));
        })
        .reject(() => {
          return this.createError({path, message: "Unable to check Number usage"});
        });
    }

    lastNumber = '';
    lastResult = false;

    return false;
  });
});
</code>```

Body:
I have a Yup method that I am calling, this checks whether a 10 digit number has been used before. It returns true/false from the service. If it is in use, it should display a validation error on the input box.

It definitely passes into this Yup method and is handled, returning true or false, however the validation doesn't appear, until the input box is blurred (When blurred it calls this method again, however it hits the earlier createError call where the id's are the same and the lastNumber is false)

At the point where the console.log is, if the value is false I would expect it to display the error via createError but it does not.

let lastNumber:any;
let lastResult:boolean;
Yup.addMethod(Yup.string, "isNumberInUse", function (errorMessage){
  return this.test(`test-number-is-inuse`, errorMessage, function (value, ctx) {
    const { path } = this;

    let digits = value || '';

    let patientId = ctx.parent.id;

    if(patientId === undefined) {
      patientId = '';
    }

    if(digits.length === 0) {
      lastNumber = '';
      lastResult = false;
      return true;
    }

    if(digits.length === 10) {

      if(lastNumber === ctx.parent.number && !lastResult) {
        return this.createError({path, message: errorMessage})
      }

      if(lastResult){
        return true;
      }

     MyService.IsNumberAvailable(digits, patientId.toString())
        .then((response:boolean) => {
          lastNumber = digits;
          lastResult = response;
          console.log(response);
          return (response || this.createError({path, message: errorMessage}));
        })
        .reject(() => {
          return this.createError({path, message: "Unable to check Number usage"});
        });
    }

    lastNumber = '';
    lastResult = false;

    return false;
  });
});


问:
Unable to set the default value using mongoose
I am unable to set default object in mongoose. I have created a default object and when I am creating the new document is saves as null instead of object.

Model file code

```<code>const configSchema = new mongoose.Schema<IConfig>(
  {
    driver: {
      type: driverConfigSchema,
      default: defaultDriverSchema, // instead of this object it saves as null
    },
  },
  { timestamps: true }
);

export const defaultDriverSchema: IDriverConfig = {
  vehicle_types: [],
  service_types: [
    { service_name: SERVICE_TYPES.GROSERY, sub_services: [SUB_SERVICES.NORAML_DELIVERY] },
    { service_name: SERVICE_TYPES.FOOD, sub_services: [SUB_SERVICES.NORAML_DELIVERY] },
  ],
};

const driverConfigSchema = new mongoose.Schema<IDriverConfig>(
  {
    vehicle_types: {
      type: [String],
      required: false,
      default: [],
    },
    service_types: {
      type: [serviceTypeDriverConfigSchema],
      required: false,
      default: [],
    },
  },
  { timestamps: true, _id: false }
);
</code>```

Model definition file

```<code>// create a new Interface for the driver
export interface IDriverConfig {
  vehicle_types?: string[];
  service_types?: [IServiceTypeDriverConfig] | [] | IServiceTypeDriverConfig[];
}

// create a new Interface for the driver services
export interface IServiceTypeDriverConfig {
  service_name?: SERVICE_TYPES;
  sub_services?: [SUB_SERVICES] | [];
}

// service types for driver
export enum SERVICE_TYPES {
  GROSERY = "Grosery",
  FOOD = "Food",
}

// sub services for services of driver
export enum SUB_SERVICES {
  NORAML_DELIVERY = "Normal delivery",
}
</code>```

I want to set "driver" attribute as "defaultDriverSchema" default. But when I am creating a new document it saves "driver" as null. I have tried many things but still it is not working

I tried directly assigning object to default thinking that it might not be able to access "defaultDriverSchema" object on production but still it didn't work.

It would be really great if anyone could help

Body:
I am unable to set default object in mongoose. I have created a default object and when I am creating the new document is saves as null instead of object.

Model file code

const configSchema = new mongoose.Schema<IConfig>(
  {
    driver: {
      type: driverConfigSchema,
      default: defaultDriverSchema, // instead of this object it saves as null
    },
  },
  { timestamps: true }
);

export const defaultDriverSchema: IDriverConfig = {
  vehicle_types: [],
  service_types: [
    { service_name: SERVICE_TYPES.GROSERY, sub_services: [SUB_SERVICES.NORAML_DELIVERY] },
    { service_name: SERVICE_TYPES.FOOD, sub_services: [SUB_SERVICES.NORAML_DELIVERY] },
  ],
};

const driverConfigSchema = new mongoose.Schema<IDriverConfig>(
  {
    vehicle_types: {
      type: [String],
      required: false,
      default: [],
    },
    service_types: {
      type: [serviceTypeDriverConfigSchema],
      required: false,
      default: [],
    },
  },
  { timestamps: true, _id: false }
);

Model definition file

// create a new Interface for the driver
export interface IDriverConfig {
  vehicle_types?: string[];
  service_types?: [IServiceTypeDriverConfig] | [] | IServiceTypeDriverConfig[];
}

// create a new Interface for the driver services
export interface IServiceTypeDriverConfig {
  service_name?: SERVICE_TYPES;
  sub_services?: [SUB_SERVICES] | [];
}

// service types for driver
export enum SERVICE_TYPES {
  GROSERY = "Grosery",
  FOOD = "Food",
}

// sub services for services of driver
export enum SUB_SERVICES {
  NORAML_DELIVERY = "Normal delivery",
}

I want to set "driver" attribute as "defaultDriverSchema" default. But when I am creating a new document it saves "driver" as null. I have tried many things but still it is not working

I tried directly assigning object to default thinking that it might not be able to access "defaultDriverSchema" object on production but still it didn't work.

It would be really great if anyone could help


问:
Android moshi generic type with different types
I am using retrofit with moshi converter in my android (kotlin) app.
The api response have a general format, where I wrote a class with generic field as the following:

`

```<code>@JsonClass(generateAdapter = true)
data class ApiResponse<T>(

    @Json(name = "Status")
    val status: Boolean,

    @Json(name = "Message")
    val message: String?,

    @Json(name = "Data")
    val data: T?
)
</code>```

`

data field can be of any type. It is working fine in a normal cases. But sometimes the data field in api response comes with different types for the same api.

For example: in login api I have two cases:

Successful login:
{"Status":true, "Message":"Successful Login", "Data":{"userID":"user id", "userName":"user name"}}

Failed login:
{"Status":false, "Message":"Login Failed", "Data":false}

In first case, data is an object, while in second case data is a boolean. So my converter throws an error

I tried to write a custom adapter, to set the data field to null in case it was a boolean in the json, but I failed to handle such generic case, I had to write a custom adapter for every response type.

Is there are anyway to handle this issue without modifying the api code?
Thanks in advance.

Body:
I am using retrofit with moshi converter in my android (kotlin) app.
The api response have a general format, where I wrote a class with generic field as the following:

`

@JsonClass(generateAdapter = true)
data class ApiResponse<T>(

    @Json(name = "Status")
    val status: Boolean,

    @Json(name = "Message")
    val message: String?,

    @Json(name = "Data")
    val data: T?
)

`

data field can be of any type. It is working fine in a normal cases. But sometimes the data field in api response comes with different types for the same api.

For example: in login api I have two cases:

Successful login:
{"Status":true, "Message":"Successful Login", "Data":{"userID":"user id", "userName":"user name"}}

Failed login:
{"Status":false, "Message":"Login Failed", "Data":false}

In first case, data is an object, while in second case data is a boolean. So my converter throws an error

I tried to write a custom adapter, to set the data field to null in case it was a boolean in the json, but I failed to handle such generic case, I had to write a custom adapter for every response type.

Is there are anyway to handle this issue without modifying the api code?
Thanks in advance.


问:
JLine completer with Brigadier
I want to make a console application with jline and brigadier,
but I have problem on command completing.
I can complete the literal command but can't complete argument commands.

What I did:

private static List<Completers.TreeCompleter.Node> generateNodes(CommandNode<ConsoleSender> root) {
    List<Completers.TreeCompleter.Node> nodes = new ArrayList<>();
    for (CommandNode<ConsoleSender> commandNode : root.getChildren()) {
        List<Object> objects = new ArrayList<>();
        if (commandNode instanceof ArgumentCommandNode<?, ?>) {
            objects.add(new StringsCompleter()); // cannot complete if user input non-literal arguments
        } else {
            objects.add(commandNode.getName());
        }
        objects.addAll(generateNodes(commandNode));
        nodes.add(Completers.TreeCompleter.node(objects.toArray()));
    }
    return nodes;
}
```
```> hello literal // can complete well
> hello <name: string value> literal // "literal" cannot be completed
```
<p>What I want:</p>
```> hello literal // can complete well
> hello <name: string value> literal // "literal" can be completed well without bugs whatever the value of name argument is
```

Title: JLine completer with Brigadier

Body:
I want to make a console application with jline and brigadier,
but I have problem on command completing.
I can complete the literal command but can't complete argument commands.

What I did:

private static List<Completers.TreeCompleter.Node> generateNodes(CommandNode<ConsoleSender> root) {
    List<Completers.TreeCompleter.Node> nodes = new ArrayList<>();
    for (CommandNode<ConsoleSender> commandNode : root.getChildren()) {
        List<Object> objects = new ArrayList<>();
        if (commandNode instanceof ArgumentCommandNode<?, ?>) {
            objects.add(new StringsCompleter()); // cannot complete if user input non-literal arguments
        } else {
            objects.add(commandNode.getName());
        }
        objects.addAll(generateNodes(commandNode));
        nodes.add(Completers.TreeCompleter.node(objects.toArray()));
    }
    return nodes;
}

> hello literal // can complete well
> hello <name: string value> literal // "literal" cannot be completed

What I want:

> hello literal // can complete well
> hello <name: string value> literal // "literal" can be completed well without bugs whatever the value of name argument is


问:
AJAX call won't work on production, but works local
I've got a very strange situation.

I'm using an AJAX call to pass some parameters to my code-behind and everything works fine on local, but on my production environment I'm not being able to recover the parameter values in code-behind.

I've added here a few breakpoints just to you show where the problem is. The first one captures some parameter values just to check if they are empty/null (it's not actually part of the code) and the second will return an error if "inscricao" is null (which should not be).

When running the app in my local environment, I'm able to get the parameter values without any problems, as shown here.

But the same app, accessing the same database, with the same values will enter the second breakpoint and return a message as such, on production.

I have other AJAX post methods in the same page that work just fine, and as I said, it works fine on local. Is there any way to find out why the same code doesn't run on production? The other AJAX methods I have on the same page also work on production, this is the only exception.

I'll add the AJAX code below:

```<code>               $.ajax({
                    type: 'post',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('[name="__RequestVerificationToken"]').val());
                    },
                    url: '?handler=SolicitarSafe2Pay',
                    datatype: "application/json",
                    data: {
                        valor: valortotal,
                        IDInscricao: Number(inscricaoID),
                        HtmlResumo: resumoemail,
                        IDCupom: idUsoUnico,
                        Nome: $Nome.val(),
                        NomeSocial: $NomeSocial.val(),
                        CPF: $CPF.val(),
                        Telefone: $Telefone.val(),
                        CEP: $CEP.val(),
                        Pais: $Pais.val(),
                        Estado: $Estado.val(),
                        Cidade: $Cidade.val(),
                        Endereco: $Endereco.val(),
                        Numero: $Numero.val(),
                        Bairro: $Bairro.val(),
                        Complemento: $Complemento.val(),
                        FormaPagamento: Number($FormaPagamento.val()),
                        NomeCartao: $NomeCartao.val(),
                        NumeroCartao: $NumeroCartao.val(),
                        CVV: $CVV.val(),
                        Vencimento: $Vencimento.val(),
                        Parcelas: Number($Parcelas.val())
                    },
                    success: function (data) {
                        ...
                    },
                    error: function (xhr, status, error) {
                        console.log(xhr);  // to see the error message
                    }
                });
</code>```

I've tried adding the RequestVerificationToken as a header, directly on the data object and even decorate the page with [IgnoreAntiForgeryToken]. All these options work on my local machine, but the same error still occurs on production.

Body:
I've got a very strange situation.

I'm using an AJAX call to pass some parameters to my code-behind and everything works fine on local, but on my production environment I'm not being able to recover the parameter values in code-behind.

I've added here a few breakpoints just to you show where the problem is. The first one captures some parameter values just to check if they are empty/null (it's not actually part of the code) and the second will return an error if "inscricao" is null (which should not be).

When running the app in my local environment, I'm able to get the parameter values without any problems, as shown here.

But the same app, accessing the same database, with the same values will enter the second breakpoint and return a message as such, on production.

I have other AJAX post methods in the same page that work just fine, and as I said, it works fine on local. Is there any way to find out why the same code doesn't run on production? The other AJAX methods I have on the same page also work on production, this is the only exception.

I'll add the AJAX code below:

               $.ajax({
                    type: 'post',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('[name="__RequestVerificationToken"]').val());
                    },
                    url: '?handler=SolicitarSafe2Pay',
                    datatype: "application/json",
                    data: {
                        valor: valortotal,
                        IDInscricao: Number(inscricaoID),
                        HtmlResumo: resumoemail,
                        IDCupom: idUsoUnico,
                        Nome: $Nome.val(),
                        NomeSocial: $NomeSocial.val(),
                        CPF: $CPF.val(),
                        Telefone: $Telefone.val(),
                        CEP: $CEP.val(),
                        Pais: $Pais.val(),
                        Estado: $Estado.val(),
                        Cidade: $Cidade.val(),
                        Endereco: $Endereco.val(),
                        Numero: $Numero.val(),
                        Bairro: $Bairro.val(),
                        Complemento: $Complemento.val(),
                        FormaPagamento: Number($FormaPagamento.val()),
                        NomeCartao: $NomeCartao.val(),
                        NumeroCartao: $NumeroCartao.val(),
                        CVV: $CVV.val(),
                        Vencimento: $Vencimento.val(),
                        Parcelas: Number($Parcelas.val())
                    },
                    success: function (data) {
                        ...
                    },
                    error: function (xhr, status, error) {
                        console.log(xhr);  // to see the error message
                    }
                });

I've tried adding the RequestVerificationToken as a header, directly on the data object and even decorate the page with [IgnoreAntiForgeryToken]. All these options work on my local machine, but the same error still occurs on production.


问:
In YOLO V7, Can I combine two separate trained model (weight files) to detect different images?
Let's say, I have trained a custom model with 500 images of Apple. I have got a best.pt file which can detect apple very well. Now, I have trained another yolov7 model, with 500 images of Orange, and have got another best.pt file which can detect Orange very well. Now I want to combine that two .pt file together, so that if I provide both orange and apple image, then that combined .pt file can detect them all. Is that possible, or how can I solve this issue. Any other way, to do that instead of training a model with two types of images.

Please, experts asking for your help.

So far, I have just trained two models, but don't know how to combine and make the models as one.


问:
Replacing a static Enum with a HashMap or similar
I have a simple Enum used to map to hardcoded strings:

Think:

```<code>enum SomeThing {
   A, B, C
}
</code>```

These values are shown in a UI as RadioButtons so the user can pick one and these options are mapped to a string (the name of a file I don't control).

The way this is done at runtime time is (pseudo-code):

```<code>let xxx: HashMap::from([
    (
       SomeThing::A.to_string(),
       "value_for_a".to_string(),
    ),
    (
       SomeThing::B.to_string(),
       "value_for_b".to_string(),
   ),
   etc...
</code>```

This is done at runtime and later used to retrieve the value for the chosen option. The fact that it's an Enum has the type safety in mind. But...

I'd like to change this code to make it user-configurable, and allow the user to specify those values themselves; since it's a runtime-constructed HashMap, I could imagine a config file (of any format like YAML) having:

```<code>---
xxx:
  A: value_for_a
  B: value_for_b
  C: value_for_c
</code>```

And parsed into "the same" HashMap (without the benefits of the Enum type safety).

The questions are:

I suppose creating an Enum at runtime would not be possible right? I'd imagine the user could create a new D key/value and or remove an existing one.

What would be another way to do this instead? Keep/Use a HashMap of some sort to store the Key (A,B,C) and their values after they were parsed?
(worth mentioning: the Enum is convenient because it's used by structopt for a command line parameter via the provided arg_enum! macro, so you can specify the posible_values as &YourEnum::variants() but this is less important to keep)

Is there a "better" way to do this that you can think of?

Body:
I have a simple Enum used to map to hardcoded strings:

Think:

enum SomeThing {
   A, B, C
}

These values are shown in a UI as RadioButtons so the user can pick one and these options are mapped to a string (the name of a file I don't control).

The way this is done at runtime time is (pseudo-code):

let xxx: HashMap::from([
    (
       SomeThing::A.to_string(),
       "value_for_a".to_string(),
    ),
    (
       SomeThing::B.to_string(),
       "value_for_b".to_string(),
   ),
   etc...

This is done at runtime and later used to retrieve the value for the chosen option. The fact that it's an Enum has the type safety in mind. But...

I'd like to change this code to make it user-configurable, and allow the user to specify those values themselves; since it's a runtime-constructed HashMap, I could imagine a config file (of any format like YAML) having:

---
xxx:
  A: value_for_a
  B: value_for_b
  C: value_for_c

And parsed into "the same" HashMap (without the benefits of the Enum type safety).

The questions are:

I suppose creating an Enum at runtime would not be possible right? I'd imagine the user could create a new D key/value and or remove an existing one.

What would be another way to do this instead? Keep/Use a HashMap of some sort to store the Key (A,B,C) and their values after they were parsed?
(worth mentioning: the Enum is convenient because it's used by structopt for a command line parameter via the provided arg_enum! macro, so you can specify the posible_values as &YourEnum::variants() but this is less important to keep)

Is there a "better" way to do this that you can think of?


问:
How to resolve "cannot import name clock" error in anaconda prompt? I am on Python 3.9.12
I am trying to run the HEX game program from:
https://github.com/masouduut94/MCTS-agent-cythonized

I am getting an error: ImportError: cannot import name clock
I am assuming this is because the clock() method has been removed in Python 3.8 and I am using 3.9.12.

How can I fix this?

I tried:
"from time import clock" but it is of no use as the method has been removed.
I tried:

```<code>pip install passlib==1.7.2
</code>```

As answered in another similar query here, it did not help.

Body:
I am trying to run the HEX game program from:
https://github.com/masouduut94/MCTS-agent-cythonized

I am getting an error: ImportError: cannot import name clock
I am assuming this is because the clock() method has been removed in Python 3.8 and I am using 3.9.12.

How can I fix this?

I tried:
"from time import clock" but it is of no use as the method has been removed.
I tried:

pip install passlib==1.7.2

As answered in another similar query here, it did not help.


问:
Spring Boot: collection of owning entities ends up being null in child of @ManyToMany relationship
I have a Spring Boot application and two entities, User and Role that look like the following:

@Entity
public class User {
    // other fields
    @ManyToMany
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    @JsonDeserialize(using = RolesJsonDeserializer.class)
    @NotEmpty
    private Set<Role> roles = new HashSet<>();

    // getters and setters
 }
```
<pre class="lang-java prettyprint-override"><code>@Entity
public class Role {
    // other fields

   @ManyToMany(mappedBy = "roles")
   private List<User> users;

   @PreRemove // whenever role is removed, remove association with each user
   private void removeRolesFromUsers() {
       for (User u : users) {
           u.getRoles().remove(this);
       }
   }

    // getters and setters
 }
</code>```

And then I have a Spring JPA integration test annotated with @DataJpaTest and @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) which is tested against PostgreSQL database. I want to assert that before role is deleted, all associated users are dissociated from that role before it is removed from database.

@Test
@Transactional
public void whenRoleIsDeleted_thenItIsDeletedFromAllUsersThatHadIt() {

    clearDatabase(userRepository, roleRepository);
    populateDatabase(USERS_COUNT, null, userRepository, roleRepository); // saves a bunch of pre-defined roles first, then saves users associated with those roles
    entityManager.flush();
    Role existingRole = randomExistingRole(); // obtains role that exists
    System.out.println(existingRole.getUsers());

    Condition<RoleRepository> existingRole_ = new Condition<>(repo -> repo.findRoleByName(existingRole.getName())
                                                                          .isPresent(),     "hasExistingRole");
    assertThat(roleRepository).has(existingRole_);
    entityManager.flush();

    roleRepository.delete(existingRole);
    // then assert that no user has existingRole in its associated roles

}
```
<p>But my assertion couldn't complete as <code>NullPointException</code> is thrown when I try to remove <code>existingRole</code>.  This exception does not happen when application is used normally. It is thrown because role has no associations to any user (and is actually a null), even though I specify that it is <code>Role</code>'s <code>users</code> is <code>mappedBy = "roles"</code>. <code>User</code> on the other hand has roles in its <code>roles</code> field. If I try to set a break point before <code>roleRepository.delete()</code>, <strong>I can see that there are no changes made to the actual database</strong> until the end of test method, which I suspect is the problem. Although in logs I can see that Hibernate populates the database and creates joining table just fine.</p>
<p>I tried the following:</p>
<ol>
<li>Set <code>entityManager.setFlushMode(FlushModeType.COMMIT)</code> to force every flush to commit a transaction, that didn't work.</li>
<li>Removed <code>@Transactional</code> annotation from test method, that didn't work.</li>
<li>Tried <code>@Rollback(false)</code> annotation, that didn't work, but it confirmed that if database is populated before test method starts, then role <strong>has</strong> <code>users</code> associated with it and made me think that presence of users in actual database is important for this test to work as I expect it to.</li>
</ol>
<p>I want to understand:</p>
<ol>
<li>Why does this happen only in tests?</li>
<li>Why can't I see new users and roles in my database immediately after I commit a transaction, but only once test method finished executioe despite the absence of <code>@Transactional</code>?</li>
</ol>
<p><strong>EDIT</strong>
I solved this problem by adding logic to associate role with user manually when <code>user.setRoles()</code> is invoked. I don't know if this is right way? Why won't Hibernate do this automatically?</p>
<pre class="lang-java prettyprint-override"><code>    public void setRoles(Set<Role> roles) {
        this.roles = roles;
        roles.forEach(role -> {
            if (!role.getUsers().contains(this)) {
                role.getUsers()
                    .add(this);
            }
        });
    }
</code>```

Body:
I have a Spring Boot application and two entities, User and Role that look like the following:

@Entity
public class User {
    // other fields
    @ManyToMany
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    @JsonDeserialize(using = RolesJsonDeserializer.class)
    @NotEmpty
    private Set<Role> roles = new HashSet<>();

    // getters and setters
 }

@Entity
public class Role {
    // other fields

   @ManyToMany(mappedBy = "roles")
   private List<User> users;

   @PreRemove // whenever role is removed, remove association with each user
   private void removeRolesFromUsers() {
       for (User u : users) {
           u.getRoles().remove(this);
       }
   }

    // getters and setters
 }

And then I have a Spring JPA integration test annotated with @DataJpaTest and @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) which is tested against PostgreSQL database. I want to assert that before role is deleted, all associated users are dissociated from that role before it is removed from database.

@Test
@Transactional
public void whenRoleIsDeleted_thenItIsDeletedFromAllUsersThatHadIt() {

    clearDatabase(userRepository, roleRepository);
    populateDatabase(USERS_COUNT, null, userRepository, roleRepository); // saves a bunch of pre-defined roles first, then saves users associated with those roles
    entityManager.flush();
    Role existingRole = randomExistingRole(); // obtains role that exists
    System.out.println(existingRole.getUsers());

    Condition<RoleRepository> existingRole_ = new Condition<>(repo -> repo.findRoleByName(existingRole.getName())
                                                                          .isPresent(),     "hasExistingRole");
    assertThat(roleRepository).has(existingRole_);
    entityManager.flush();

    roleRepository.delete(existingRole);
    // then assert that no user has existingRole in its associated roles

}

But my assertion couldn't complete as NullPointException is thrown when I try to remove existingRole.  This exception does not happen when application is used normally. It is thrown because role has no associations to any user (and is actually a null), even though I specify that it is Role's users is mappedBy = "roles". User on the other hand has roles in its roles field. If I try to set a break point before roleRepository.delete(), I can see that there are no changes made to the actual database until the end of test method, which I suspect is the problem. Although in logs I can see that Hibernate populates the database and creates joining table just fine.

I tried the following:

Set entityManager.setFlushMode(FlushModeType.COMMIT) to force every flush to commit a transaction, that didn't work.

Removed @Transactional annotation from test method, that didn't work.

Tried @Rollback(false) annotation, that didn't work, but it confirmed that if database is populated before test method starts, then role has users associated with it and made me think that presence of users in actual database is important for this test to work as I expect it to.

I want to understand:

Why does this happen only in tests?

Why can't I see new users and roles in my database immediately after I commit a transaction, but only once test method finished executioe despite the absence of @Transactional?

EDIT
I solved this problem by adding logic to associate role with user manually when user.setRoles() is invoked. I don't know if this is right way? Why won't Hibernate do this automatically?

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
        roles.forEach(role -> {
            if (!role.getUsers().contains(this)) {
                role.getUsers()
                    .add(this);
            }
        });
    }


问:
Wordpress Fatal Error: Cannot access offset of type string on string in
I am trying to migrate our wordpress website and now I encounter this error:

```<code>Fatal error: Uncaught TypeError: Cannot access offset of type string on string in /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php:839 Stack trace: #0 /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php(77): SiteOrigin_Panels_Renderer->get_panels_layout_data('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00...') #1 /var/www/html/wp-content/plugins/siteorigin-panels/siteorigin-panels.php(501): SiteOrigin_Panels_Renderer->generate_css(7083) #2 /var/www/html/wp-includes/class-wp-hook.php(308): SiteOrigin_Panels->generate_post_css('') #3 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters(NULL, Array) #4 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array) #5 /var/www/html/wp-includes/script-loader.php(2180): do_action('wp_enqueue_scri...') #6 /var/www/html/wp-includes/class-wp-hook.php(308): wp_enqueue_scripts('') #7 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters(NULL, Array) #8 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array) #9 /var/www/html/wp-includes/general-template.php(3043): do_action('wp_head') #10 /var/www/html/wp-content/themes/eduma/header.php(16): wp_head() #11 /var/www/html/wp-includes/template.php(783): require_once('/var/www/html/w...') #12 /var/www/html/wp-includes/template.php(718): load_template('/var/www/html/w...', true, Array) #13 /var/www/html/wp-includes/general-template.php(48): locate_template(Array, true, true, Array) #14 /var/www/html/wp-content/themes/eduma/page-templates/homepage.php(6): get_header() #15 /var/www/html/wp-includes/template.php(783): require_once('/var/www/html/w...') #16 /var/www/html/wp-content/themes/eduma/wrapper.php(4): load_template('/var/www/html/w...') #17 /var/www/html/wp-includes/template-loader.php(106): include('/var/www/html/w...') #18 /var/www/html/wp-blog-header.php(19): require_once('/var/www/html/w...') #19 /var/www/html/index.php(17): require('/var/www/html/w...') #20 {main} thrown in /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php on line 839

</code>```

Anyone any idea how to fix this?

BR,
ElMedico

I tried changing max RAM of PHP and with different plugins as methods but nothing seems to work. Tried also doing the updates but no change so far...

Body:
I am trying to migrate our wordpress website and now I encounter this error:

Fatal error: Uncaught TypeError: Cannot access offset of type string on string in /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php:839 Stack trace: #0 /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php(77): SiteOrigin_Panels_Renderer->get_panels_layout_data('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00...') #1 /var/www/html/wp-content/plugins/siteorigin-panels/siteorigin-panels.php(501): SiteOrigin_Panels_Renderer->generate_css(7083) #2 /var/www/html/wp-includes/class-wp-hook.php(308): SiteOrigin_Panels->generate_post_css('') #3 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters(NULL, Array) #4 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array) #5 /var/www/html/wp-includes/script-loader.php(2180): do_action('wp_enqueue_scri...') #6 /var/www/html/wp-includes/class-wp-hook.php(308): wp_enqueue_scripts('') #7 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters(NULL, Array) #8 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array) #9 /var/www/html/wp-includes/general-template.php(3043): do_action('wp_head') #10 /var/www/html/wp-content/themes/eduma/header.php(16): wp_head() #11 /var/www/html/wp-includes/template.php(783): require_once('/var/www/html/w...') #12 /var/www/html/wp-includes/template.php(718): load_template('/var/www/html/w...', true, Array) #13 /var/www/html/wp-includes/general-template.php(48): locate_template(Array, true, true, Array) #14 /var/www/html/wp-content/themes/eduma/page-templates/homepage.php(6): get_header() #15 /var/www/html/wp-includes/template.php(783): require_once('/var/www/html/w...') #16 /var/www/html/wp-content/themes/eduma/wrapper.php(4): load_template('/var/www/html/w...') #17 /var/www/html/wp-includes/template-loader.php(106): include('/var/www/html/w...') #18 /var/www/html/wp-blog-header.php(19): require_once('/var/www/html/w...') #19 /var/www/html/index.php(17): require('/var/www/html/w...') #20 {main} thrown in /var/www/html/wp-content/plugins/siteorigin-panels/inc/renderer.php on line 839

Anyone any idea how to fix this?

BR,
ElMedico

I tried changing max RAM of PHP and with different plugins as methods but nothing seems to work. Tried also doing the updates but no change so far...


问:
How to address hashed remoteEntry.xxxxxx.js in routing using loadRemoteModule in module federation
I want to use hashed remoteEntry in order to overcome cached remoteEntry.js issue in micro front ends apps. currentry I have used

```<code>filename: 'remoteEntry.[hash:16].js',
</code>```

in my mfe webpack.config.js but dont know how to address it in my main app routing

```<code>const routes: Routes = [
  {
    path: '',
    component: MainRouteContainerComponent,
    children: [
      {
        path: '',
        loadChildren: () =>
          loadRemoteModule({
            remoteEntry: `${environment.Url}/remoteEntry.??????.js`,
            type: 'module',
            exposedModule: './Module',
          }).then((m) => m.RemoteEntryModule),
      },
    ],
  },
];
</code>```

I also added this

```<code>new ExternalTemplateRemotesPlugin(),
</code>```

into plugins section of mfe webpack.config.js

the way of using

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

doesnt make any sense and obviously at build, main app is still looking for remoteEntry.js file instead of remoteEntry.xxxxxx.js. where I went wrong? and maybe better and more stragitforward solutions for cache issue (except no-cache)?

Body:
I want to use hashed remoteEntry in order to overcome cached remoteEntry.js issue in micro front ends apps. currentry I have used

filename: 'remoteEntry.[hash:16].js',

in my mfe webpack.config.js but dont know how to address it in my main app routing

const routes: Routes = [
  {
    path: '',
    component: MainRouteContainerComponent,
    children: [
      {
        path: '',
        loadChildren: () =>
          loadRemoteModule({
            remoteEntry: `${environment.Url}/remoteEntry.??????.js`,
            type: 'module',
            exposedModule: './Module',
          }).then((m) => m.RemoteEntryModule),
      },
    ],
  },
];

I also added this

new ExternalTemplateRemotesPlugin(),

into plugins section of mfe webpack.config.js

the way of using

ExternalTemplateRemotesPlugin

doesnt make any sense and obviously at build, main app is still looking for remoteEntry.js file instead of remoteEntry.xxxxxx.js. where I went wrong? and maybe better and more stragitforward solutions for cache issue (except no-cache)?


问:
Validator on custom DropDown field
I have mu custom DropDown Widget.

```<code>class DropDownMenuField extends StatefulWidget {
  String title;
  final InputDecoration decoration;
  final String Function(String) validator;
  final void Function(dynamic value) onSelectionDone;
  final String initialValue;
  final Color selectedItemColor;
  final DropMenuMode menuMode;
  int selectvalueindex;
  final Function(String) onChanged;
  var model;

  DropDownMenuField(
      {Key key,
      this.title,
      this.decoration,
      this.validator,
      this.onSelectionDone,
      this.initialValue,
      this.selectedItemColor,
      this.model,
      this.menuMode,
      this.selectvalueindex,
      this.onChanged})
      : super(key: key);

  @override
  State<DropDownMenuField> createState() => _DropDownMenuFieldState();
}

class _DropDownMenuFieldState extends State<DropDownMenuField> {
  final TextEditingController _controller = TextEditingController();

  void _popUpModalBottomSheet(BuildContext context) async {
    List<String> finalDataList = [];

    List<dynamic> dataMap = await apiRegistrationDataList(widget.menuMode);
    finalDataList = parseMap(dataMap);
    final result = await showModalBottomSheet(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(9.0),
        ),
        isScrollControlled: true,
        context: context,
        builder: (context) => DialogMenu(
              title: widget.title,
              data: finalDataList,
            ));

    if (result == null) {
      widget.title = widget.title;
      _controller.text = widget.title;
    } else {
      //  widget.title = result ?? widget.title;
      //  lab
      labStyle = checkedLableStyle;
      lable = result;
      _controller.text = result;
      widget.onSelectionDone(result);
      widget.validator(result);
      setState(() {});
    }

    SetGlobalRequaerData(result, dataMap);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () => _popUpModalBottomSheet(context),
        child: TextFormField(
          controller: _controller,
          readOnly: true,
          enabled: false,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          validator: widget.validator,
          onChanged: widget.onChanged,
          style: const TextStyle(
            fontSize: 16,
            color: Color(0xFF3C3C43),
          ),
          decoration: InputDecoration(
            labelStyle: labStyle,
            hintStyle: TextStyle(
              fontFamily: 'FiraSans',
              color: GeneralStyles.greyColor,
            ),
            fillColor: Colors.white,
            filled: true,
            contentPadding: const EdgeInsets.fromLTRB(16, 0, 0, 0),
            errorStyle: const TextStyle(
                color: Colors.red,
                fontFamily: 'FiraSans',
                fontWeight: FontWeight.w400,
                fontSize: 13),
            border: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide: BorderSide(
                    color: GeneralStyles.greyColor.withOpacity(0.5),
                    width: .5)),
            enabledBorder: const OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(4)),
                borderSide: BorderSide(color: Color(0xFF707070), width: .5)),
            disabledBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide:
                    BorderSide(color: GeneralStyles.greyColor, width: .5)),
            focusedBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide:
                    BorderSide(color: GeneralStyles.blackColor, width: 1)),
            errorBorder: const OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              borderSide: BorderSide(color: Colors.red, width: .5),
            ),
            labelText: lable,
            hintText: widget.title,
            suffixIcon: Icon(
              Icons.keyboard_arrow_down,
              color: GeneralStyles.greyColor,
            ),
          ),
        ));
  }
}
</code>```

And i call it on my registration page.

```<code>DropDownMenuField(
                    title: "Anrede",
                    model: widget.model,
                    menuMode: DropMenuMode.genders,
                    selectvalueindex: 0,
                    onSelectionDone: (value){
                    print(value);
                    },
                    validator: (value){
                      if(widget.model.selectedDropMenu[0].isEmpty){
                        return 'Bitte fülle das Feld aus';
                      }
                      return null;
                    },
                  ),
</code>```

When i click button when DropDownMenuField selectedValue is empty validator is work but when i select value widget don't call validator and don't change color from red. How call validator after change value. I read that when texteditingcontroller is changed, calling validator after him. i add it but not work.

Title: Validator on custom DropDown field

Body:
I have mu custom DropDown Widget.

class DropDownMenuField extends StatefulWidget {
  String title;
  final InputDecoration decoration;
  final String Function(String) validator;
  final void Function(dynamic value) onSelectionDone;
  final String initialValue;
  final Color selectedItemColor;
  final DropMenuMode menuMode;
  int selectvalueindex;
  final Function(String) onChanged;
  var model;

  DropDownMenuField(
      {Key key,
      this.title,
      this.decoration,
      this.validator,
      this.onSelectionDone,
      this.initialValue,
      this.selectedItemColor,
      this.model,
      this.menuMode,
      this.selectvalueindex,
      this.onChanged})
      : super(key: key);

  @override
  State<DropDownMenuField> createState() => _DropDownMenuFieldState();
}

class _DropDownMenuFieldState extends State<DropDownMenuField> {
  final TextEditingController _controller = TextEditingController();

  void _popUpModalBottomSheet(BuildContext context) async {
    List<String> finalDataList = [];

    List<dynamic> dataMap = await apiRegistrationDataList(widget.menuMode);
    finalDataList = parseMap(dataMap);
    final result = await showModalBottomSheet(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(9.0),
        ),
        isScrollControlled: true,
        context: context,
        builder: (context) => DialogMenu(
              title: widget.title,
              data: finalDataList,
            ));

    if (result == null) {
      widget.title = widget.title;
      _controller.text = widget.title;
    } else {
      //  widget.title = result ?? widget.title;
      //  lab
      labStyle = checkedLableStyle;
      lable = result;
      _controller.text = result;
      widget.onSelectionDone(result);
      widget.validator(result);
      setState(() {});
    }

    SetGlobalRequaerData(result, dataMap);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () => _popUpModalBottomSheet(context),
        child: TextFormField(
          controller: _controller,
          readOnly: true,
          enabled: false,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          validator: widget.validator,
          onChanged: widget.onChanged,
          style: const TextStyle(
            fontSize: 16,
            color: Color(0xFF3C3C43),
          ),
          decoration: InputDecoration(
            labelStyle: labStyle,
            hintStyle: TextStyle(
              fontFamily: 'FiraSans',
              color: GeneralStyles.greyColor,
            ),
            fillColor: Colors.white,
            filled: true,
            contentPadding: const EdgeInsets.fromLTRB(16, 0, 0, 0),
            errorStyle: const TextStyle(
                color: Colors.red,
                fontFamily: 'FiraSans',
                fontWeight: FontWeight.w400,
                fontSize: 13),
            border: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide: BorderSide(
                    color: GeneralStyles.greyColor.withOpacity(0.5),
                    width: .5)),
            enabledBorder: const OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(4)),
                borderSide: BorderSide(color: Color(0xFF707070), width: .5)),
            disabledBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide:
                    BorderSide(color: GeneralStyles.greyColor, width: .5)),
            focusedBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(4)),
                borderSide:
                    BorderSide(color: GeneralStyles.blackColor, width: 1)),
            errorBorder: const OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              borderSide: BorderSide(color: Colors.red, width: .5),
            ),
            labelText: lable,
            hintText: widget.title,
            suffixIcon: Icon(
              Icons.keyboard_arrow_down,
              color: GeneralStyles.greyColor,
            ),
          ),
        ));
  }
}

And i call it on my registration page.

DropDownMenuField(
                    title: "Anrede",
                    model: widget.model,
                    menuMode: DropMenuMode.genders,
                    selectvalueindex: 0,
                    onSelectionDone: (value){
                    print(value);
                    },
                    validator: (value){
                      if(widget.model.selectedDropMenu[0].isEmpty){
                        return 'Bitte fülle das Feld aus';
                      }
                      return null;
                    },
                  ),

When i click button when DropDownMenuField selectedValue is empty validator is work but when i select value widget don't call validator and don't change color from red. How call validator after change value. I read that when texteditingcontroller is changed, calling validator after him. i add it but not work.


问:
How to read R dataframe as a Pandas dataframe?
I am executing the R code in python using rpy2 library where I was able to achieve a data frame that I wanted. The dataframe has column with geometry, now I am trying to read the created R dataframe as Pandas dataframe using ro.conversion.rpy2py, but when I try to do the same it is giving an empty data frame like below.

How do I convert R data frame with geometry column as an pandas data frame/ geo pandas data frame?

Code:-

from rpy2 import robjects
import rpy2.robjects as ro
robjects.r('''
  library(osrm)
  iso <- osrmIsochrone(loc = c(12.0878, 55.6419),
                       breaks = seq(from = 0, to = 60, length.out = 2), res = 50)
  print(iso)''')
```
<p>output:-</p>
```Simple feature collection with 1 feature and 3 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: 11.10805 ymin: 55.02879 xmax: 13.14378 ymax: 56.08983
Geodetic CRS:  WGS 84
  id isomin isomax                       geometry
1  1      0     60 MULTIPOLYGON (((12.54979 56...
```
<p>#converting R dataframe to python data frame</p>
<pre class="lang-py prettyprint-override"><code>r_mat = robjects.globalenv['iso']
pd_dt = ro.conversion.rpy2py(r_mat)
pd_dt
</code>```

Output:-

```<code>R/rpy2 DataFrame (1 x 4)
id  isomin  isomax  geometry
... ... ... ...
</code>```

Body:
I am executing the R code in python using rpy2 library where I was able to achieve a data frame that I wanted. The dataframe has column with geometry, now I am trying to read the created R dataframe as Pandas dataframe using ro.conversion.rpy2py, but when I try to do the same it is giving an empty data frame like below.

How do I convert R data frame with geometry column as an pandas data frame/ geo pandas data frame?

Code:-

from rpy2 import robjects
import rpy2.robjects as ro
robjects.r('''
  library(osrm)
  iso <- osrmIsochrone(loc = c(12.0878, 55.6419),
                       breaks = seq(from = 0, to = 60, length.out = 2), res = 50)
  print(iso)''')

output:-

Simple feature collection with 1 feature and 3 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: 11.10805 ymin: 55.02879 xmax: 13.14378 ymax: 56.08983
Geodetic CRS:  WGS 84
  id isomin isomax                       geometry
1  1      0     60 MULTIPOLYGON (((12.54979 56...

#converting R dataframe to python data frame

r_mat = robjects.globalenv['iso']
pd_dt = ro.conversion.rpy2py(r_mat)
pd_dt

Output:-

R/rpy2 DataFrame (1 x 4)
id  isomin  isomax  geometry
... ... ... ...