问:
Error locating resource with require() in react app
I am practicing my recently acquired react knowledge by making this online store, with react, redux and react-router.
My products are stored inside an object of my redux's store, each product has a img property which stores the path of the image resource, but when I try to print the list of products I get:

cannot find module 'mypath'

But the strange thing is, when I print that path on the console is fine, I don't see any problem with the path itself

Here is my code, I want to print the images of the products, if a delete the img tag at Productos.js the titles show with no problem

app.js

```<code>import './App.css';
import Navbar from './Navbar/Navbar';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { Productos } from './Productos/Productos';

function App() {
  return (
    <div className="App">
      <Router>
        <header>
          <div className='banner'>
            <h1>FerreTienda</h1>
            <Navbar />
          </div>
        </header>
        <Route>
          <Productos />
        </Route>
      </Router>
    </div>
  );
}
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import productSlice from './Productos/ProductosSlice';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';

const store = configureStore({
  reducer : {
    productos : productSlice
  }
})

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

ProductosSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";

const path = '../resources';
const initialState = [
    {
        id: 0,
        titulo: 'Taladro total de media',
        descripcion: 'Taladro de media para labores hogareñas, la caja viene sin accesorios y las brocas deben comprarse a parte',
        precio : 90,
        cantidad: 5,
        img: `${path}/taladro-total.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 1,
        titulo: 'Juego de llaves',
        descripcion: 'Juego de llaves para tuerca con rache copas y saca bujías, ideal para quienes tienen una moto',
        precio: 54,
        cantidad: 3,
        img: `${path}/juego-llaves.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 2,
        titulo: 'Llave de tubo',
        descripcion: 'Llave de tubo larga, ideal para trabajos de plomería marca Stanley',
        precio: 16,
        cantidad: 1,
        img: `${path}/llave-tubo`,
        categoria: 'herramientas'
    },
    {
        id: 3,
        titulo: 'Paca de cemento',
        descripcion: 'Paca de cemento gris Portland tipo I de 42,5Kg original',
        precio: 7,
        cantidad: 15,
        img: `${path}/paga-cemento.jpg`,
        categoria: 'materiales'
    },
    {
        id: 4,
        titulo: 'Caladora',
        descripcion: 'Caladora de 570W marca total con accesorios',
        precio: 23,
        cantidad: 1,
        img: `${path}/caladora-total.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 5,
        titulo: 'Teipe',
        descripcion: 'Teipe marca cobra color negro original',
        precio: 3,
        cantidad: 35,
        img: `${path}/teipe-cobra.jpg`,
        categoria: 'materiales'
    },
    {
        id: 6,
        titulo: 'Guadaña',
        descripcion: 'Guadaña de 2,9CV a gasolina, motor dos tiempos viene con 1lt de aceite',
        precio: 45,
        cantidad: 1,
        img: `${path}/guadana.jpg`,
        categoria: 'jardin'
    },
    {
        id: 7,
        titulo: 'Machete',
        descripcion: 'Machete para jardín marca Epa de acero inoxidable',
        precio: 13,
        cantidad: 3,
        img: `${path}/machete.jpg`,
        categoria: 'jardin'
    },
    {
        id: 8,
        titulo: 'Cortadora de grama',
        descripcion: 'Máquina cortadora de grama 170cc marca Powersmart a gasolina, motod 4 tiempos',
        precio: 560,
        cantidad: 2,
        img: `${path}/maquina-cortadora.jpg`,
        categoria: 'jardin'
    },
    {
        id: 9,
        titulo: 'Bolsa de arena',
        descripcion: 'Bolsa de arena lavada, mezclilla de 15kg',
        precio: 2,
        img: `${path}/bolsa-arena.jpg`,
        categoria: 'materiales'
    }

];

const productSlice = createSlice({
    name: 'productos',
    initialState: initialState,
    reducers: {
        showAll: (state, action) => {
            return state;
        }
    }
})

export const {showAll} = productSlice.actions;
export default productSlice.reducer;
</code>```

Productos.js

```<code>import { useSelector } from "react-redux"

export function Productos(props){
    const productos = useSelector(state => state.productos);
    let body = productos.map((item, index) => {
        return (<div key={index}>
            <h3>{item.titulo}</h3>
            <img src={require(item.img)} />
        </div>);
    })
    return (
        <div>
            {body}
        </div>
    )
}
</code>```

Body:
I am practicing my recently acquired react knowledge by making this online store, with react, redux and react-router.
My products are stored inside an object of my redux's store, each product has a img property which stores the path of the image resource, but when I try to print the list of products I get:

cannot find module 'mypath'

But the strange thing is, when I print that path on the console is fine, I don't see any problem with the path itself

Here is my code, I want to print the images of the products, if a delete the img tag at Productos.js the titles show with no problem

app.js

import './App.css';
import Navbar from './Navbar/Navbar';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { Productos } from './Productos/Productos';

function App() {
  return (

      <Router>

FerreTienda

            <Navbar />

        <Route>
          <Productos />
        </Route>
      </Router>

  );
}

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import productSlice from './Productos/ProductosSlice';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';

const store = configureStore({
  reducer : {
    productos : productSlice
  }
})

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

ProductosSlice.js

import { createSlice } from "@reduxjs/toolkit";

const path = '../resources';
const initialState = [
    {
        id: 0,
        titulo: 'Taladro total de media',
        descripcion: 'Taladro de media para labores hogareñas, la caja viene sin accesorios y las brocas deben comprarse a parte',
        precio : 90,
        cantidad: 5,
        img: `${path}/taladro-total.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 1,
        titulo: 'Juego de llaves',
        descripcion: 'Juego de llaves para tuerca con rache copas y saca bujías, ideal para quienes tienen una moto',
        precio: 54,
        cantidad: 3,
        img: `${path}/juego-llaves.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 2,
        titulo: 'Llave de tubo',
        descripcion: 'Llave de tubo larga, ideal para trabajos de plomería marca Stanley',
        precio: 16,
        cantidad: 1,
        img: `${path}/llave-tubo`,
        categoria: 'herramientas'
    },
    {
        id: 3,
        titulo: 'Paca de cemento',
        descripcion: 'Paca de cemento gris Portland tipo I de 42,5Kg original',
        precio: 7,
        cantidad: 15,
        img: `${path}/paga-cemento.jpg`,
        categoria: 'materiales'
    },
    {
        id: 4,
        titulo: 'Caladora',
        descripcion: 'Caladora de 570W marca total con accesorios',
        precio: 23,
        cantidad: 1,
        img: `${path}/caladora-total.jpg`,
        categoria: 'herramientas'
    },
    {
        id: 5,
        titulo: 'Teipe',
        descripcion: 'Teipe marca cobra color negro original',
        precio: 3,
        cantidad: 35,
        img: `${path}/teipe-cobra.jpg`,
        categoria: 'materiales'
    },
    {
        id: 6,
        titulo: 'Guadaña',
        descripcion: 'Guadaña de 2,9CV a gasolina, motor dos tiempos viene con 1lt de aceite',
        precio: 45,
        cantidad: 1,
        img: `${path}/guadana.jpg`,
        categoria: 'jardin'
    },
    {
        id: 7,
        titulo: 'Machete',
        descripcion: 'Machete para jardín marca Epa de acero inoxidable',
        precio: 13,
        cantidad: 3,
        img: `${path}/machete.jpg`,
        categoria: 'jardin'
    },
    {
        id: 8,
        titulo: 'Cortadora de grama',
        descripcion: 'Máquina cortadora de grama 170cc marca Powersmart a gasolina, motod 4 tiempos',
        precio: 560,
        cantidad: 2,
        img: `${path}/maquina-cortadora.jpg`,
        categoria: 'jardin'
    },
    {
        id: 9,
        titulo: 'Bolsa de arena',
        descripcion: 'Bolsa de arena lavada, mezclilla de 15kg',
        precio: 2,
        img: `${path}/bolsa-arena.jpg`,
        categoria: 'materiales'
    }

];

const productSlice = createSlice({
    name: 'productos',
    initialState: initialState,
    reducers: {
        showAll: (state, action) => {
            return state;
        }
    }
})

export const {showAll} = productSlice.actions;
export default productSlice.reducer;

Productos.js

import { useSelector } from "react-redux"

export function Productos(props){
    const productos = useSelector(state => state.productos);
    let body = productos.map((item, index) => {
        return (

{item.titulo}

);
    })
    return (

            {body}

    )
}


来源: stackexchange

问:
Two related sequences
I want to find the values of this two sequences but I still not able to do that:

here is the code of my attempt:

```<code>from math import sqrt,pi
def a(n,b):
    if n==1:

        return 30
    else:
        return a(n-1)*1.1+(sqrt(2)/(1+pi))*b(n-1)

def  b(n):
    if n == 1:

        return 10
    else:

      return b(n - 1) * 1.1 - (sqrt(2) / (1 + pi)) * a(n - 1)

print(a(2,b))
</code>```

Programming this two sequences in python

ContentLicense: CC BY-SA 4.0

Title: Two related sequences

Body:
I want to find the values of this two sequences but I still not able to do that:

here is the code of my attempt:

from math import sqrt,pi
def a(n,b):
    if n==1:

        return 30
    else:
        return a(n-1)*1.1+(sqrt(2)/(1+pi))*b(n-1)

def  b(n):
    if n == 1:

        return 10
    else:

      return b(n - 1) * 1.1 - (sqrt(2) / (1 + pi)) * a(n - 1)

print(a(2,b))

Programming this two sequences in python


问:
Python3 pyotp timed generated codes not matching/the same on Aegis or Google Authenticator
The problems I'm having is the timed codes that pyotp generated are not the same. The following code is what I'm doing.

key = "ThiskeyDoesNotChange"

totp = pyotp.TOTP(key)

uri = pyotp.totp.TOTP(key).provisioning_uri(name="therealOri", issuer_name="Genter")
#otpauth://totp/Genter:therealOri?secret=ThiskeyDoesNotChange&issuer=Genter
qrcode.make(uri).save('totp.png')
```
<p>I will then scan the generated QRcode with my authenticator and it... at first glance looks like it'd work but when I try to verify the code it returns False.</p>
<pre class="lang-py prettyprint-override"><code>while True:
        print(totp.verify(input("Enter Code: ")))
</code>```

The codes generated by totp.now() do not match what is shown in my authenticator.

I tried to look through stack for similar questions and found a couple. One with an answer and one without. I tried out the answer for this question, however I use Manjaro/Arch instead of ubuntu and I do have ntp but whenever I try to reload the service, "unit ntp.service isn't found". So that doesn't seem to help me. The other questions I found aren't helpful either and didn't work. I'm also doing this in python3 and not in c# or java, etc.

I am expecting the pyotp codes in my authenticator to be the same as the ones generated by totp.now(). I've tried using different libraries and the same thing keeps happening. I'm not entirely sure how to fix this issue or what the actual issue is. I can only assume some sort of timing is off? Idk.

Any help is very much appreciated and yes I know there are a few of the same questions that have been asked but they DO NOT help or work for me.

PS. I'd add more tags but I can't make new ones yet.

Body:
The problems I'm having is the timed codes that pyotp generated are not the same. The following code is what I'm doing.

key = "ThiskeyDoesNotChange"

totp = pyotp.TOTP(key)

uri = pyotp.totp.TOTP(key).provisioning_uri(name="therealOri", issuer_name="Genter")
#otpauth://totp/Genter:therealOri?secret=ThiskeyDoesNotChange&issuer=Genter
qrcode.make(uri).save('totp.png')

I will then scan the generated QRcode with my authenticator and it... at first glance looks like it'd work but when I try to verify the code it returns False.

while True:
        print(totp.verify(input("Enter Code: ")))

The codes generated by totp.now() do not match what is shown in my authenticator.

I tried to look through stack for similar questions and found a couple. One with an answer and one without. I tried out the answer for this question, however I use Manjaro/Arch instead of ubuntu and I do have ntp but whenever I try to reload the service, "unit ntp.service isn't found". So that doesn't seem to help me. The other questions I found aren't helpful either and didn't work. I'm also doing this in python3 and not in c# or java, etc.

I am expecting the pyotp codes in my authenticator to be the same as the ones generated by totp.now(). I've tried using different libraries and the same thing keeps happening. I'm not entirely sure how to fix this issue or what the actual issue is. I can only assume some sort of timing is off? Idk.

Any help is very much appreciated and yes I know there are a few of the same questions that have been asked but they DO NOT help or work for me.

PS. I'd add more tags but I can't make new ones yet.


问:
What is the proper way of importing SVG image as a React component?
I have the following code. Importing an SVG image as a component. A webpack loader allows me to import SVGs.

```<code>var MouseHighlight = (props: Properties) => {
  return (
    <ReactShadowRoot>
      <Box className="quizmeai-body">
        <Box ... >
          <Button ... >
            <Logo
              style={{
                height: "20px",
                width: "20px",
                left: "-21px",
                display: "block",
                position: "absolute",
                top: "-1px",
                boxShadow: "0px 8px 15px rgb(0 0 0 / 40%)",
                transition: "all 0.3s ease 0s",
                zIndex: "5",
              }}
            />
            <Box>
              ...
            </Box>
          </Button>
        </Box>
      </Box>
    </ReactShadowRoot>
  );
};

</code>```

When run npm run build, the compiler complains with the following.

```<code>ERROR in /Users/murat/Desktop/quizme/extension/src/contentScripts/example.tsx
./src/contentScripts/example.tsx 162:14-19
[tsl] ERROR in /Users/murat/Desktop/quizme/extension/src/contentScripts/example.tsx(162,15)
      TS2322: Type '{ style: { height: string; width: string; left: string; display: string; position: string; top: string; boxShadow: string; transition: string; zIndex: string; }; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'style' does not exist on type 'IntrinsicAttributes'.
</code>```

How can I import import the SVG image properly? Thanks.

I couldn't really try anything. I just started working on this code and I'm a little lost.

Body:
I have the following code. Importing an SVG image as a component. A webpack loader allows me to import SVGs.

var MouseHighlight = (props: Properties) => {
  return (
    <ReactShadowRoot>
      <Box className="quizmeai-body">
        <Box ... >
          <Button ... >
            <Logo
              style={{
                height: "20px",
                width: "20px",
                left: "-21px",
                display: "block",
                position: "absolute",
                top: "-1px",
                boxShadow: "0px 8px 15px rgb(0 0 0 / 40%)",
                transition: "all 0.3s ease 0s",
                zIndex: "5",
              }}
            />
            <Box>
              ...
            </Box>
          </Button>
        </Box>
      </Box>
    </ReactShadowRoot>
  );
};

When run npm run build, the compiler complains with the following.

ERROR in /Users/murat/Desktop/quizme/extension/src/contentScripts/example.tsx
./src/contentScripts/example.tsx 162:14-19
[tsl] ERROR in /Users/murat/Desktop/quizme/extension/src/contentScripts/example.tsx(162,15)
      TS2322: Type '{ style: { height: string; width: string; left: string; display: string; position: string; top: string; boxShadow: string; transition: string; zIndex: string; }; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'style' does not exist on type 'IntrinsicAttributes'.

How can I import import the SVG image properly? Thanks.

I couldn't really try anything. I just started working on this code and I'm a little lost.


问:
How to tell Terraform to start a destroy and re-create action if some arguments of a configuration in tf file has been changed?
From terraform documentation below, destroy-and-recreate resource is one of the four resource behavior but it seems that update in-place is the default behavior if any of the arguments in a configuration file ( tf ) has been changed such as

https://developer.hashicorp.com/terraform/language/resources/behavior

webvm_order.order1 will be updated in-place

~ resource "webvm_order" "order1" { id                = "123" ~ web_vm_group    = "group1" -> "group2"
Plan: 0 to add, 1 to change, 0 to destroy

If my case cannot support in-place update and a new resource has to be created. How can my custom Terraform provider tell Terraform cli to invoke my delete resource function, followed by create resource function such that the Plan: line will become

Plan: 1 to add, 0 to change, 1 to destroy    ?

I observe that some AWS resources can achieve that. Does anyone know how to implement that ?

I tried the following code snipplet but terraform still thinks that an in-place update is needed.

func resouceOrderUpdate(ctx context.Context, d *schemea.ResourceData, m interface{}) diag.Diagnostics { resourceOrderDelete(ctx, d, m) resourceOrderCreate(ctx, d, m) }

My expected result should be

Plan: 1 to add, 0 to change, 1 to destroy


问:
Should /token endpoint in an IDP be protected with API gateway
This is a design question

We have keycloak as Idp and Mule as API gateway, both on-premise DC.

As per design all traffic to DC will go through WAF

All external calls to our apis(microservies), will follow this path ExternalSystem-> WAF -> ApiGateway -> Microservices.

Ideally, should the issue access-token endpoint should follow

4.1 ExternalSystem -> WAF-> http://keycloakxx:/auth/token

or should it be behind api gateway like

4.2 ExternalSystem  -> WAF -> API gateway -> http://keycloakxx:/auth/token

Since WAF can already take care of security measures like DDos, what are the advantages/disadvantages of going with option 4.2


问:
Clustering using Quicksom package
I am trying to cluster similar data points using quicksom package which is GPU based SOM using Pytorch. All the functions are running smoothly except when I am using som.predict() function that calculates quantization errors and topographic errors. But the function stops in the middle and throws the following errors:

When I am using batch size =25
'IndexError: too many indices for tensor of dimension 1'

And when I am using default batch size = 100

'ValueError: too many values to unpack (expected 2)'

IndexError: too many indices for tensor of dimension 1

ValueError: too many values to unpack (expected 2)

Dataset, Id- is unique column.

Title: Clustering using Quicksom package


问:
Office Word add-in – Msal using login redirect not working on Mac (Safari webkit 1.0)
We’re using Azure B2C to authenticate the users in the Word add-in. The library in Angular (14.1.2) that we use is MSAL which works as expected on Windows.

However, when using it on Mac, the redirect inside the add-in dialog gets stuck and doesn’t go to the Azure B2C page. It writes the cookies and local storage, but never redirects.

angular 14.1.2
azure/msal-angular 2.5.1

azure/msal-browser 2.32.1

Call
this.msalService.loginRedirect().subscribe();

Msal Configuration

```<code>`export function msalInstanceFactory(appConfigService: AppConfigService): IPublicClientApplication {
  const appConfig = appConfigService.config;
  return new PublicClientApplication({
    auth: {
      clientId: appConfig.aadB2CClientId,
      authority: 'https://${appConfig.aadB2CDomain}/${appConfig.aadB2CTenant}/${appConfig.aadB2CSIPolicy}',
      redirectUri: appConfig.aadB2CRedirectUri,
      postLogoutRedirectUri: getLocationOriginWithPath('logout'),
      knownAuthorities: [appConfig.aadB2CDomain],
      navigateToLoginRequestUrl: false,
    },
    cache: {
      cacheLocation: BrowserCacheLocation.LocalStorage,
      storeAuthStateInCookie: isIE,
    },
    system: {
      loggerOptions: {
        loggerCallback: msalLoggerCallback,
        logLevel: LogLevel.Verbose,
        piiLoggingEnabled: true,
      },
    },
  });
}

export function msalGuardConfigFactory(appConfigService: AppConfigService): MsalGuardConfiguration {
  return {
    interactionType: InteractionType.Redirect,
    authRequest: {
      scopes: appConfigService.config.aadB2CConsentScopes,
      loginHint: getLoginHint(),
    },
  };
}`
</code>```

The funny fact is that if I set a break point just before the execution of the loginRedirect and then press continue it works. So, I tried to set a timeout before that to see if it works but it doesn't.

Also tried to disable ITP security in Safari, but didn't take any effect.

Body:
We’re using Azure B2C to authenticate the users in the Word add-in. The library in Angular (14.1.2) that we use is MSAL which works as expected on Windows.

However, when using it on Mac, the redirect inside the add-in dialog gets stuck and doesn’t go to the Azure B2C page. It writes the cookies and local storage, but never redirects.

angular 14.1.2
azure/msal-angular 2.5.1

azure/msal-browser 2.32.1

Call
this.msalService.loginRedirect().subscribe();

Msal Configuration

`export function msalInstanceFactory(appConfigService: AppConfigService): IPublicClientApplication {
  const appConfig = appConfigService.config;
  return new PublicClientApplication({
    auth: {
      clientId: appConfig.aadB2CClientId,
      authority: 'https://${appConfig.aadB2CDomain}/${appConfig.aadB2CTenant}/${appConfig.aadB2CSIPolicy}',
      redirectUri: appConfig.aadB2CRedirectUri,
      postLogoutRedirectUri: getLocationOriginWithPath('logout'),
      knownAuthorities: [appConfig.aadB2CDomain],
      navigateToLoginRequestUrl: false,
    },
    cache: {
      cacheLocation: BrowserCacheLocation.LocalStorage,
      storeAuthStateInCookie: isIE,
    },
    system: {
      loggerOptions: {
        loggerCallback: msalLoggerCallback,
        logLevel: LogLevel.Verbose,
        piiLoggingEnabled: true,
      },
    },
  });
}

export function msalGuardConfigFactory(appConfigService: AppConfigService): MsalGuardConfiguration {
  return {
    interactionType: InteractionType.Redirect,
    authRequest: {
      scopes: appConfigService.config.aadB2CConsentScopes,
      loginHint: getLoginHint(),
    },
  };
}`

The funny fact is that if I set a break point just before the execution of the loginRedirect and then press continue it works. So, I tried to set a timeout before that to see if it works but it doesn't.

Also tried to disable ITP security in Safari, but didn't take any effect.


问:
jpql join without relationship cannot map to column
I am suing left join to join table that has no relationship

```<code>SELECT a, u.fullname FROM admin a
LEFT JOIN useru ON a.username = u.username
</code>```

and return it as an  List<Admin>

Admin class:

```<code>public class Admin {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String email;
    private Integer status;
    @Transient
    private String fullname;
}
</code>```

but fullname is null

Body:
I am suing left join to join table that has no relationship

SELECT a, u.fullname FROM admin a
LEFT JOIN useru ON a.username = u.username

and return it as an  List<Admin>

Admin class:

public class Admin {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String email;
    private Integer status;
    @Transient
    private String fullname;
}

but fullname is null


问:
Laravel 9 Sanctum (with cookies) error 401 after successful login SPA React
I am building the authentication of a SPA in React with Laravel 9 Sanctum. I have my SPA at https://agefa.devetapia.cl and the server at https://backend.devetapia.cl. I am authenticating using cookies (not token) and everything is fine until login. After the successful login I try to make a request and it gives me a 401 error that I am not authenticated. I have read a lot of documentation and I think that I have the error in the domains and subdomains. I have tried many different ways. All the tutorials and videos are with localhost with ports, but it is not my case.

My domains are https.

My cors.php file:

```<code>    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,
</code>```

My config/sanctum.php:

```<code>    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort()
    ))),
</code>```

My .env

```<code>SESSION_DRIVER=cookie
SESSION_DOMAIN=.devetapia.cl
SANCTUM_STATEFUL_DOMAINS=devetapia.cl
</code>```

My config/session.php

```<code>'domain' => env('SESSION_DOMAIN'),
</code>```

My routes/api.php:

```<code>use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\LoginController;

Route::post('login', [LoginController::class, 'login']);

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
        return response()->json(['status' => true, 'user' => auth()->user()]);
});
</code>```

my axios setup in react:

```<code>import axios from 'axios';

const apiClient = axios.create({
    baseURL: 'https://backend.devetapia.cl',
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
    },
});

export default apiClient;
</code>```

and the call from React:

```<code>   async function getUser()  {

        const csrf = await apiClient.get('/sanctum/csrf-cookie');

        const login = await apiClient.post('/api/login', {
            email: 'correo@gmail.com',
            password: 'clavesecreta',
        }).then(response => {
                if(response.data.user) {
                    console.log('login=', response.data.user.name);
                }
            }).catch(error => {
                console.log(error.response.data.message);
            });

        const user = await apiClient.get('/api/user');

        console.log('user= ', user);
    }
</code>```

The 401 error gives me when I do:

```<code>const user = await apiClient.get('/api/user');
</code>```

even though the login was successful.

It seems to me that the problem is the definition in the .env of SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS but I have not been able to find the correct configuration.

Body:
I am building the authentication of a SPA in React with Laravel 9 Sanctum. I have my SPA at https://agefa.devetapia.cl and the server at https://backend.devetapia.cl. I am authenticating using cookies (not token) and everything is fine until login. After the successful login I try to make a request and it gives me a 401 error that I am not authenticated. I have read a lot of documentation and I think that I have the error in the domains and subdomains. I have tried many different ways. All the tutorials and videos are with localhost with ports, but it is not my case.

My domains are https.

My cors.php file:

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

My config/sanctum.php:

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort()
    ))),

My .env

SESSION_DRIVER=cookie
SESSION_DOMAIN=.devetapia.cl
SANCTUM_STATEFUL_DOMAINS=devetapia.cl

My config/session.php

'domain' => env('SESSION_DOMAIN'),

My routes/api.php:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\LoginController;

Route::post('login', [LoginController::class, 'login']);

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
        return response()->json(['status' => true, 'user' => auth()->user()]);
});

my axios setup in react:

import axios from 'axios';

const apiClient = axios.create({
    baseURL: 'https://backend.devetapia.cl',
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
    },
});

export default apiClient;

and the call from React:

   async function getUser()  {

        const csrf = await apiClient.get('/sanctum/csrf-cookie');

        const login = await apiClient.post('/api/login', {
            email: 'correo@gmail.com',
            password: 'clavesecreta',
        }).then(response => {
                if(response.data.user) {
                    console.log('login=', response.data.user.name);
                }
            }).catch(error => {
                console.log(error.response.data.message);
            });

        const user = await apiClient.get('/api/user');

        console.log('user= ', user);
    }

The 401 error gives me when I do:

const user = await apiClient.get('/api/user');

even though the login was successful.

It seems to me that the problem is the definition in the .env of SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS but I have not been able to find the correct configuration.


问:
Strapi config:dump Error loading the local configurationDump command
Strapi version:  3.0.0-beta.19.4

database: mongodb 4.2.6 (using from docker container)

Running strapi project at local with mongodb & mongodb is running inside docker container.All is working fine as expected I can access and create new collections & components from strapi CMS.

Strapi has own ways for deployment, So for UAT deployment I need dump.json file
I tried creating dump.json file with

```<code>strapi configuration:dump -f dump.json
</code>```

got error:

```<code>Error loading the local configurationDump command. Strapi might not be installed in your "node_modules". You may need to run "npm install"
</code>```

Note: Strapi is installed can see under node_modules folder as well. package.json file is also updated under scripts with following cmds

```<code>    "strapi:dump": "strapi configuration:dump -f dump.json",
    "strapi:restore": "strapi configuration:restore -f dump.json"
</code>```

Body:
Strapi version:  3.0.0-beta.19.4

database: mongodb 4.2.6 (using from docker container)

Running strapi project at local with mongodb & mongodb is running inside docker container.All is working fine as expected I can access and create new collections & components from strapi CMS.

Strapi has own ways for deployment, So for UAT deployment I need dump.json file
I tried creating dump.json file with

strapi configuration:dump -f dump.json

got error:

Error loading the local configurationDump command. Strapi might not be installed in your "node_modules". You may need to run "npm install"

Note: Strapi is installed can see under node_modules folder as well. package.json file is also updated under scripts with following cmds

    "strapi:dump": "strapi configuration:dump -f dump.json",
    "strapi:restore": "strapi configuration:restore -f dump.json"


问:
How to apply WithTriviaFrom recursively for an IfStatement?
As you can see, only the if statement gets the leading trivia and not the rest of it:

Input:

```<code>            __Internal.DestroyContext(__arg0);
</code>```

Current result:

```<code>            if (IntPtr.Size == 4)
{
    __Internal32.DestroyContext(__arg0);
}
else
{
    __Internal64.DestroyContext(__arg0);
}
</code>```

Expected:

```<code>            if (IntPtr.Size == 4)
            {
                __Internal32.DestroyContext(__arg0);
            }
            else
            {
                __Internal64.DestroyContext(__arg0);
            }
</code>```

Code used:

```<code>var statement =
    IfStatement(GetImportCondition(),
            Block(ExpressionStatement(GetImportIdentifier32(invocation, name2))))
        .WithElse(ElseClause(
            Block(ExpressionStatement(GetImportIdentifier64(invocation, name2)))))
        .NormalizeWhitespace()
        .WithTriviaFrom(exp);

node = node.ReplaceNode(exp, statement);
</code>```

If I remove NormalizeWhitespace, it works obviously but it isn't formatted anymore:

```<code>        if(IntPtr.Size==4){__Internal32.DestroyContext(__arg0);}else{__Internal64.DestroyContext(__arg0);}
</code>```

Question:

How can one apply WithTriviaFrom recursively when used for an IfStatement?

Please don't suggest to normalize whitespace at root as this formats the whole document.

Body:
As you can see, only the if statement gets the leading trivia and not the rest of it:

Input:

            __Internal.DestroyContext(__arg0);

Current result:

            if (IntPtr.Size == 4)
{
    __Internal32.DestroyContext(__arg0);
}
else
{
    __Internal64.DestroyContext(__arg0);
}

Expected:

            if (IntPtr.Size == 4)
            {
                __Internal32.DestroyContext(__arg0);
            }
            else
            {
                __Internal64.DestroyContext(__arg0);
            }

Code used:

var statement =
    IfStatement(GetImportCondition(),
            Block(ExpressionStatement(GetImportIdentifier32(invocation, name2))))
        .WithElse(ElseClause(
            Block(ExpressionStatement(GetImportIdentifier64(invocation, name2)))))
        .NormalizeWhitespace()
        .WithTriviaFrom(exp);

node = node.ReplaceNode(exp, statement);

If I remove NormalizeWhitespace, it works obviously but it isn't formatted anymore:

        if(IntPtr.Size==4){__Internal32.DestroyContext(__arg0);}else{__Internal64.DestroyContext(__arg0);}

Question:

How can one apply WithTriviaFrom recursively when used for an IfStatement?

Please don't suggest to normalize whitespace at root as this formats the whole document.


问:
Dimensions lost in list to array conversion seemingly only when using line.split()
I am reading in files with two loops iterating through the names (my code after the MWE below) and using line.split(). In my code this produces a list which give the correct value (number of columns) when I check the length, but when I convert it to an array it becomes 1D with a shape (1245,) where the first value is the correct number of rows but the second dimension is now missing.

When I created a minimal working example it ran just fine, maintaining the dimensions, so I must be doing something silly with the read in. In the conversion it does show it's converting it to an array of lists which I can't find a solution to when searching, and oddly doesn't come up in the MWE.

(I believe this is my first post on here so please excuse any bad form).

MWE (which oddly works fine):

```<code>import numpy as np

entry_list = [['12','34','56'],['78','910','1112']]

print(len(entry_list[0]))
print(entry_list)
print(type(entry_list))

entry_array = np.array(entry_list)
print(type(entry_array))
print ('size: ',entry_array.shape)
print ('first row:  ',entry_array[0])
print ('one in one down: ',entry_array[1,1])
</code>```

My code (does not work fine) which is looping through file names and using split before the part that mimics the above.  Note that I checked that the output of the split is exactly the syntax of the list used in the MWE.

```<code>
prefix1 = "/Some/Path/prefix_"

#for each file in prefix1 set
for wl in range(300,700,100):
    for pa in range(0,185,5):
        pa = format(pa,'03')
        afile = str(prefix1) + str(wl) + str(pa) + "_suffix.dat"
        print (afile)
        with open(afile) as Frank1:
                f1_list = [line.split() for line in Frank1]
                print(len(f1_list[0])) #shows correct length of row (#columns)
                print(f1_list) #shows whole giant data set
                f1_array = np.array(f1_list)
                print (f1_array) # will show an array of list** like: [list(['0.1','0.2','0.3', 0.4', '0.5'])...list(['0.6', '0.7', '0.8', '0.9', '0.0'])]
                print ('size: ',f1_array.shape) # now (1256,) or something
                print ('first row:  ',f1_array[0]) # shows first item correctly like ['0.1', '0.2', '0.3', '0.4', '0.5']
                print ('one in one down: ',f1_array[3,3]) #can't, of course
</code>```

** I have tried searching for a solution to this as a hint but haven't come across this exact problem as far as I can tell

Most pertinent output from the above print statements print(f1_array) and print('size: ',f1_array.shape) if that's any help:

[list(['0.300000', '33333.332031', '-22', '-4', '0.428851E+03', '0.236303E+02', '0.351592E+02', '0.276694E+01', '-0.104056E+01', '-0.000000E+00', '-22.14159', '22.14159', '180.00000-180.00000', '83.62063', '83.62063'])
list(['0.300000', '33333.332031', '-22', '-3', '0.428851E+03', '0.236303E+02', '0.378484E+02', '0.361102E+01', '-0.100348E+01', '-0.000000E+00', '-22.29910', '22.29910', '180.00000', '0.00000', '80.68976', '80.68976'])
list(['0.300000', '33333.332031', '-22', '-2', '0.428851E+03', '0.236303E+02', '0.390155E+02', '0.403966E+01', '-0.740604E+00', '-0.000000E+00', '-22.41093', '22.41093', '180.00000', '0.00000', '79.05499', '79.05499'])
...
list(['0.300000', '33333.332031', '22', '2', '0.428851E+03', '0.403838E+02', '0.390155E+02', '0.403966E+01', '-0.740604E+00', '0.000000E+00', '-22.41093', '22.41093', '180.00000', '0.00000', '79.05499', '79.05499'])
list(['0.300000', '33333.332031', '22', '3', '0.428851E+03', '0.403838E+02', '0.378484E+02', '0.361102E+01', '-0.100348E+01', '0.000000E+00', '-22.29910', '22.29910', '180.00000', '0.00000', '80.68976', '80.68976'])
list(['0.300000', '33333.332031', '22', '4', '0.428851E+03', '0.403838E+02', '0.351592E+02', '0.276694E+01', '-0.104056E+01', '0.000000E+00', '-22.14159', '22.14159', '180.00000', '0.00000', '83.62063', '83.62063'])]
size:  (1597,)

Body:
I am reading in files with two loops iterating through the names (my code after the MWE below) and using line.split(). In my code this produces a list which give the correct value (number of columns) when I check the length, but when I convert it to an array it becomes 1D with a shape (1245,) where the first value is the correct number of rows but the second dimension is now missing.

When I created a minimal working example it ran just fine, maintaining the dimensions, so I must be doing something silly with the read in. In the conversion it does show it's converting it to an array of lists which I can't find a solution to when searching, and oddly doesn't come up in the MWE.

(I believe this is my first post on here so please excuse any bad form).

MWE (which oddly works fine):

import numpy as np

entry_list = [['12','34','56'],['78','910','1112']]

print(len(entry_list[0]))
print(entry_list)
print(type(entry_list))

entry_array = np.array(entry_list)
print(type(entry_array))
print ('size: ',entry_array.shape)
print ('first row:  ',entry_array[0])
print ('one in one down: ',entry_array[1,1])

My code (does not work fine) which is looping through file names and using split before the part that mimics the above.  Note that I checked that the output of the split is exactly the syntax of the list used in the MWE.

prefix1 = "/Some/Path/prefix_"

#for each file in prefix1 set
for wl in range(300,700,100):
    for pa in range(0,185,5):
        pa = format(pa,'03')
        afile = str(prefix1) + str(wl) + str(pa) + "_suffix.dat"
        print (afile)
        with open(afile) as Frank1:
                f1_list = [line.split() for line in Frank1]
                print(len(f1_list[0])) #shows correct length of row (#columns)
                print(f1_list) #shows whole giant data set
                f1_array = np.array(f1_list)
                print (f1_array) # will show an array of list** like: [list(['0.1','0.2','0.3', 0.4', '0.5'])...list(['0.6', '0.7', '0.8', '0.9', '0.0'])]
                print ('size: ',f1_array.shape) # now (1256,) or something
                print ('first row:  ',f1_array[0]) # shows first item correctly like ['0.1', '0.2', '0.3', '0.4', '0.5']
                print ('one in one down: ',f1_array[3,3]) #can't, of course

** I have tried searching for a solution to this as a hint but haven't come across this exact problem as far as I can tell

Most pertinent output from the above print statements print(f1_array) and print('size: ',f1_array.shape) if that's any help:

[list(['0.300000', '33333.332031', '-22', '-4', '0.428851E+03', '0.236303E+02', '0.351592E+02', '0.276694E+01', '-0.104056E+01', '-0.000000E+00', '-22.14159', '22.14159', '180.00000-180.00000', '83.62063', '83.62063'])
list(['0.300000', '33333.332031', '-22', '-3', '0.428851E+03', '0.236303E+02', '0.378484E+02', '0.361102E+01', '-0.100348E+01', '-0.000000E+00', '-22.29910', '22.29910', '180.00000', '0.00000', '80.68976', '80.68976'])
list(['0.300000', '33333.332031', '-22', '-2', '0.428851E+03', '0.236303E+02', '0.390155E+02', '0.403966E+01', '-0.740604E+00', '-0.000000E+00', '-22.41093', '22.41093', '180.00000', '0.00000', '79.05499', '79.05499'])
...
list(['0.300000', '33333.332031', '22', '2', '0.428851E+03', '0.403838E+02', '0.390155E+02', '0.403966E+01', '-0.740604E+00', '0.000000E+00', '-22.41093', '22.41093', '180.00000', '0.00000', '79.05499', '79.05499'])
list(['0.300000', '33333.332031', '22', '3', '0.428851E+03', '0.403838E+02', '0.378484E+02', '0.361102E+01', '-0.100348E+01', '0.000000E+00', '-22.29910', '22.29910', '180.00000', '0.00000', '80.68976', '80.68976'])
list(['0.300000', '33333.332031', '22', '4', '0.428851E+03', '0.403838E+02', '0.351592E+02', '0.276694E+01', '-0.104056E+01', '0.000000E+00', '-22.14159', '22.14159', '180.00000', '0.00000', '83.62063', '83.62063'])]
size:  (1597,)


问:
tbl_regression (gtsummary) warning
Trying to understand how to fix this new warning that I get when I knit a .qmd file, running the same tbl_regression command that I have done previously without issue.

```<code>lm(y ~ x, data = dat) |>
  tbl_regression(intercept = T) |>
  add_glance_source_note() |>
  as_flex_table() |>
  flextable::font(fontname = "Consolas", part = "all")

Usage of empty symbol '' with footnote should not happen, use `add_footer_lines()` instead, it does not require any symbol. This usage will be forbidden in the next release. Please, wait for 10 seconds!
</code>```

How do I keep the glance source note without the warning showing?

Title: tbl_regression (gtsummary) warning

Body:
Trying to understand how to fix this new warning that I get when I knit a .qmd file, running the same tbl_regression command that I have done previously without issue.

lm(y ~ x, data = dat) |>
  tbl_regression(intercept = T) |>
  add_glance_source_note() |>
  as_flex_table() |>
  flextable::font(fontname = "Consolas", part = "all")

Usage of empty symbol '' with footnote should not happen, use `add_footer_lines()` instead, it does not require any symbol. This usage will be forbidden in the next release. Please, wait for 10 seconds!

How do I keep the glance source note without the warning showing?


问:
FFmpeg Batch extracting frames from multiple videos on Windows
I want to extract frames/images per video that will import from a directory and then save those frames into a new folder and the folder name as import video filename.

I tried the below code on Linux and it works perfectly but i can't convert the code to Windows

```<code>for i in *.mp4; do mkdir -p "${i%.*}" && ffmpeg -i "$i" -vf fps=1/1 "${i%.*}/%d.jpg"; done
</code>```

I tried the Linux bash shell on windows and it's worked.

Does have any other options/formats to properly write or convert the code for Windows OS?

Body:
I want to extract frames/images per video that will import from a directory and then save those frames into a new folder and the folder name as import video filename.

I tried the below code on Linux and it works perfectly but i can't convert the code to Windows

for i in *.mp4; do mkdir -p "${i%.*}" && ffmpeg -i "$i" -vf fps=1/1 "${i%.*}/%d.jpg"; done

I tried the Linux bash shell on windows and it's worked.

Does have any other options/formats to properly write or convert the code for Windows OS?


问:
Nginx returning 301 when mod_zip tried
I would like to download my folders as a zip from /opt directory. I have the Nginx as a webserver. I found out that mod_zip can handle such a task. I installed and configured it as stated in GitHub.
From my understanding, I created this Nginx.conf:

```<code>uwsgi_intercept_errors on;

upstream geoserver_proxy {
  server 10.0.14.84:8080;
}

upstream ziplist {
        server 10.0.14.84:5555;

}

# Expires map
map $sent_http_content_type $expires {
  default                    off;
  text/html                  epoch;
  text/css                   max;
  application/javascript     max;
  ~image/                    max;
}

server {
    listen 5555;

    location /reports/ {
        alias /opt/geonode/;
        add_header X-Archive-Files 'zip';

        # this line sets the name of the zip that the user gets
        add_header Content-Disposition 'attachment; filename=example.zip';

    }
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/html;
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  charset utf-8;

  etag on;
  expires $expires;
  proxy_read_timeout 600s;
  # set client body size to 2M #
  client_max_body_size 50000M;

  location / {
    etag off;
    uwsgi_pass 127.0.0.1:8000;
    uwsgi_read_timeout 600s;
    include uwsgi_params;
  }

  location /static/ {
    alias /opt/geonode/geonode/static_root/;
  }

  location /uploaded/ {
    alias /opt/geonode/geonode/uploaded/;
  }

  location /reports/ {
    alias /opt/geonode/;
    # hides the header to the user
    proxy_hide_header X-Archive-Files;

        # I don't remember if this is needed
    proxy_set_header Accept-Encoding "";

        # I don't know what this means
    proxy_pass_request_headers off;

        # pass the request to server B
    proxy_pass http://ziplist;
  }

  location /geoserver {
    proxy_pass http://geoserver_proxy;
    include proxy_params;
  }
}
</code>```

Unfortunately, when I try localhost/reports/folder I am getting 301 301 Moved Permanently error.
What is wrong with my config?

Title: Nginx returning 301 when mod_zip tried

Body:
I would like to download my folders as a zip from /opt directory. I have the Nginx as a webserver. I found out that mod_zip can handle such a task. I installed and configured it as stated in GitHub.
From my understanding, I created this Nginx.conf:

uwsgi_intercept_errors on;

upstream geoserver_proxy {
  server 10.0.14.84:8080;
}

upstream ziplist {
        server 10.0.14.84:5555;

}

# Expires map
map $sent_http_content_type $expires {
  default                    off;
  text/html                  epoch;
  text/css                   max;
  application/javascript     max;
  ~image/                    max;
}

server {
    listen 5555;

    location /reports/ {
        alias /opt/geonode/;
        add_header X-Archive-Files 'zip';

        # this line sets the name of the zip that the user gets
        add_header Content-Disposition 'attachment; filename=example.zip';

    }
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/html;
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  charset utf-8;

  etag on;
  expires $expires;
  proxy_read_timeout 600s;
  # set client body size to 2M #
  client_max_body_size 50000M;

  location / {
    etag off;
    uwsgi_pass 127.0.0.1:8000;
    uwsgi_read_timeout 600s;
    include uwsgi_params;
  }

  location /static/ {
    alias /opt/geonode/geonode/static_root/;
  }

  location /uploaded/ {
    alias /opt/geonode/geonode/uploaded/;
  }

  location /reports/ {
    alias /opt/geonode/;
    # hides the header to the user
    proxy_hide_header X-Archive-Files;

        # I don't remember if this is needed
    proxy_set_header Accept-Encoding "";

        # I don't know what this means
    proxy_pass_request_headers off;

        # pass the request to server B
    proxy_pass http://ziplist;
  }

  location /geoserver {
    proxy_pass http://geoserver_proxy;
    include proxy_params;
  }
}

Unfortunately, when I try localhost/reports/folder I am getting 301 301 Moved Permanently error.
What is wrong with my config?


问:
SSRS Report CreateCatalogItem using pySSRS
Currently, I am migrating a Powershell script that deploys the SSRS report dll to the SSRS server. I am unable to the step where it creates the Catalog Item.

Powershell:

```<code>$r = $ra.CreateCatalogItem(
     "typeReport",
     $Name,
     $Path,
     $true,
     $filebytes,
     $warnings
)
</code>```

pySSRS:

```<code>rs.ServiceClient.service.CreateCatalogItem("typeReport", name, file_path, file_bytes)
</code>```

Looks like the library doesn't have the CreateCatalogItem method in it. I can't find any other way to create it.

Body:
Currently, I am migrating a Powershell script that deploys the SSRS report dll to the SSRS server. I am unable to the step where it creates the Catalog Item.

Powershell:

$r = $ra.CreateCatalogItem(
     "typeReport",
     $Name,
     $Path,
     $true,
     $filebytes,
     $warnings
)

pySSRS:

rs.ServiceClient.service.CreateCatalogItem("typeReport", name, file_path, file_bytes)

Looks like the library doesn't have the CreateCatalogItem method in it. I can't find any other way to create it.


问:
Access variable which is declared inside function, without calling functiom ,function inside class

I wanted to access a variable that is declared inside a function which is defined inside the class without calling the function in python

```<code>class take:

    def loop(self):
        global query
        print("funcction is running")
        query = "variable is decleared"

obj = take()

def exe():
    ans=obj.loop()
    print (query)

exe()
</code>```

I wanted to access the variable which is declared inside the function, which is defined inside the class, without calling the function in python (i don't want the function to be called)(instead, I just want to access the variable which is inside it.

Body:
I wanted to access a variable that is declared inside a function which is defined inside the class without calling the function in python

class take:

    def loop(self):
        global query
        print("funcction is running")
        query = "variable is decleared"

obj = take()

def exe():
    ans=obj.loop()
    print (query)

exe()

I wanted to access the variable which is declared inside the function, which is defined inside the class, without calling the function in python (i don't want the function to be called)(instead, I just want to access the variable which is inside it.


问:
SVD on huge dataset with dask and xarray
I use xarray and dask to open multiple netcdf4 files that all together are around 200Gb via

```<code>import xarray as xr

ds = xr.open_mfdataset('/path/files*.nc', parallel=True)
</code>```

The dimensions of this dataset "ds" are (longitude, latitude, height, time).
The files are automatically concatenated along time, which is okay.
Now I would like to apply the "svd_compressed" function from the dask library.
I would like to reshape the longitude, latitude, and height dimension into one dimension, such that I have a 2-d matrix on which I can apply the svd.

I tried using the

```<code>dask.array.reshape
</code>```

function, but I get "'Dataset' object has no attribute 'shape'".

I can convert the xarray dataset to an array and use stack, which makes it 2-d, but If I then use

```<code>Dataset.to_dask_dataframe
</code>```

to convert my xarray to a dask dataframe, my memory runs out.

Somebody has an Idea how I can tackle this problem?
Should I chunk my data differently for the "to_dask_dataframe" function?
Or can I use somehow the "dask svd_compressed" function on the loaded netcdf4 dataset without a reshape?

Thanks for the help.

Edit:

Here a code example that is not working. I have donwloaded Data from the ERA5 (https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-pressure-levels?tab=overview), which I load from disk.
After that I take the temperature data and stack the longitude, latitude, and level values in one dimension to have a time-space 2d-array.
Then I would like to apply an SVD on the data.

```<code>from dask.distributed import Client, progress
import xarray as xr
import dask
import dask.array as da

client = Client(processes=False, threads_per_worker=4,
                n_workers=1, memory_limit='9GB')

ds = xr.open_mfdataset('/home/user/Arbeit/ERA5/Data/era_5_m*.nc', parallel=True)
ds = ds['t']
ds = ds.stack(z=("longitude", "latitude", "level"))

u, s, v = da.linalg.svd_compressed(ds, k=5, compute=True)
</code>```

I get an error "dot only operates on DataArrays."
I assume its because I need to convert it to a dask array, so I do.

```<code>da = ds.to_dask_dataframe()
</code>```

which gives me "DataArray' object has no attribute 'to_dask_dataframe".
So I try

```<code>ds = ds.to_dataset(name="temperature")
da = ds.to_dask_dataframe()
</code>```

which results in "Unable to allocate 89.4 GiB for an array with shape".
I guess I need to rechunk it?

Body:
I use xarray and dask to open multiple netcdf4 files that all together are around 200Gb via

import xarray as xr

ds = xr.open_mfdataset('/path/files*.nc', parallel=True)

The dimensions of this dataset "ds" are (longitude, latitude, height, time).
The files are automatically concatenated along time, which is okay.
Now I would like to apply the "svd_compressed" function from the dask library.
I would like to reshape the longitude, latitude, and height dimension into one dimension, such that I have a 2-d matrix on which I can apply the svd.

I tried using the

dask.array.reshape

function, but I get "'Dataset' object has no attribute 'shape'".

I can convert the xarray dataset to an array and use stack, which makes it 2-d, but If I then use

Dataset.to_dask_dataframe

to convert my xarray to a dask dataframe, my memory runs out.

Somebody has an Idea how I can tackle this problem?
Should I chunk my data differently for the "to_dask_dataframe" function?
Or can I use somehow the "dask svd_compressed" function on the loaded netcdf4 dataset without a reshape?

Thanks for the help.

Edit:

Here a code example that is not working. I have donwloaded Data from the ERA5 (https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-pressure-levels?tab=overview), which I load from disk.
After that I take the temperature data and stack the longitude, latitude, and level values in one dimension to have a time-space 2d-array.
Then I would like to apply an SVD on the data.

from dask.distributed import Client, progress
import xarray as xr
import dask
import dask.array as da

client = Client(processes=False, threads_per_worker=4,
                n_workers=1, memory_limit='9GB')

ds = xr.open_mfdataset('/home/user/Arbeit/ERA5/Data/era_5_m*.nc', parallel=True)
ds = ds['t']
ds = ds.stack(z=("longitude", "latitude", "level"))

u, s, v = da.linalg.svd_compressed(ds, k=5, compute=True)

I get an error "dot only operates on DataArrays."
I assume its because I need to convert it to a dask array, so I do.

da = ds.to_dask_dataframe()

which gives me "DataArray' object has no attribute 'to_dask_dataframe".
So I try

ds = ds.to_dataset(name="temperature")
da = ds.to_dask_dataframe()

which results in "Unable to allocate 89.4 GiB for an array with shape".
I guess I need to rechunk it?


问:
How can i get a helpful error from a failed websocket connection?
Tried to setup a simple and very basic php websocket chat. Got it working on my computer, then uploaded the files to a server, but it doesn't work there.

I saw the example on a website (https://phppot.com/php/simple-php-chat-using-websocket/)
got it working on my computer, this is the chathandler class:

```<code>
<?php
class ChatHandler {
    function send($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

    function seal($socketData) {
        $b1 = 0x80 | (0x1 & 0x0f);
        $length = strlen($socketData);

        if($length <= 125)
            $header = pack('CC', $b1, $length);
        elseif($length > 125 && $length < 65536)
            $header = pack('CCn', $b1, 126, $length);
        elseif($length >= 65536)
            $header = pack('CCNN', $b1, 127, $length);
        return $header.$socketData;
    }

    function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
        $headers = array();
        $lines = preg_split("/\r\n/", $received_header);
        foreach($lines as $line)
        {
            $line = chop($line);
            if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
            {
                $headers[$matches[1]] = $matches[2];
            }
        }

        $secKey = $headers['Sec-WebSocket-Key'];
        $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host_name\r\n" .
        "WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
        socket_write($client_socket_resource,$buffer,strlen($buffer));
    }

    function newConnectionACK($client_ip_address) {
        $message = $client_ip_address;
        $messageArray = array('message'=>$message,'message_type'=>'login');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function connectionDisconnectACK($client_ip_address) {
        $message = $client_ip_address;
        $messageArray = array('message'=>$message,'message_type'=>'logoff');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function createChatBoxMessage($chat_user,$chat_box_message) {
        $message = $chat_box_message;
        $messageArray = array('message'=>$message,'message_type'=>'mensaje','user'=>$chat_user);
        $chatMessage = $this->seal(json_encode($messageArray));
        return $chatMessage;
    }
}
?>

</code>```

this is the php-socket.php file:

```<code>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
define('HOST_NAME',"localhost");
define('PORT',"8090");
$null = NULL;

require_once("class.chathandler.php");
$chatHandler = new ChatHandler();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);

$clientSocketArray = array($socketResource);
while (true) {
    $newSocketArray = $clientSocketArray;
    socket_select($newSocketArray, $null, $null, 0, 10);

    if (in_array($socketResource, $newSocketArray)) {
        $newSocket = socket_accept($socketResource);
        $clientSocketArray[] = $newSocket;

        $header = socket_read($newSocket, 1024);
        $chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);

        socket_getpeername($newSocket, $client_ip_address);
        $connectionACK = $chatHandler->newConnectionACK($client_ip_address);

        $chatHandler->send($connectionACK);

        $newSocketIndex = array_search($socketResource, $newSocketArray);
        unset($newSocketArray[$newSocketIndex]);
    }

    foreach ($newSocketArray as $newSocketArrayResource) {
        while(socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1){
            $socketMessage = $chatHandler->unseal($socketData);
            $messageObj = json_decode($socketMessage);

            $chat_box_message = $chatHandler->createChatBoxMessage($messageObj->user, $messageObj->message);
            $chatHandler->send($chat_box_message);
            break 2;
        }

        $socketData = @socket_read($newSocketArrayResource, 1024, PHP_NORMAL_READ);
        if ($socketData === false) {
            socket_getpeername($newSocketArrayResource, $client_ip_address);
            $connectionACK = $chatHandler->connectionDisconnectACK($client_ip_address);
            $chatHandler->send($connectionACK);
            $newSocketIndex = array_search($newSocketArrayResource, $clientSocketArray);
            unset($clientSocketArray[$newSocketIndex]);
        }
    }
}
socket_close($socketResource);
?>

</code>```

And finally, this is the file used from the browser:

```<code>
<html>
<head>
    <style>
    body{width:600px;font-family:calibri;}
    .error {color:#FF0000;}
    .chat-connection-ack{color: #26af26;}
    .chat-message {border-bottom-left-radius: 4px;border-bottom-right-radius: 4px;
    }
    #btnSend {background: #26af26;border: #26af26 1px solid;    border-radius: 4px;color: #FFF;display: block;margin: 15px 0px;padding: 10px 50px;cursor: pointer;
    }
    #chat-box {background: #fff8f8;border: 1px solid #ffdddd;border-radius: 4px;border-bottom-left-radius:0px;border-bottom-right-radius: 0px;min-height: 300px;padding: 10px;overflow: auto;
    }
    .chat-box-html{color: #09F;margin: 10px 0px;font-size:0.8em;}
    .chat-box-message{color: #09F;padding: 5px 10px; background-color: #fff;border: 1px solid #ffdddd;border-radius:4px;display:inline-block;}
    .chat-input{border: 1px solid #ffdddd;border-top: 0px;width: 100%;box-sizing: border-box;padding: 10px 8px;color: #191919;
    }
    </style>
    <script>
    function showMessage(messageHTML) {
        document.getElementById('chat-box').innerHTML += messageHTML;
        // console.log(messageHTML);
    }

    document.addEventListener("DOMContentLoaded", function(event) {
        var websocket = new WebSocket("ws://my-server-url:8090");
        // var websocket = new WebSocket("ws://localhost:8090");
        websocket.onopen = function(event) {
            showMessage("<div class='chat-connection-ack'>Connection is established!</div>");
        }
        websocket.onmessage = function(event) {
            var Data = JSON.parse(event.data);
            showMessage("<div class='"+Data.message_type+"'>"+Data.message+"</div>");
            document.getElementById('chat-message').value = '';
        };

        websocket.onerror = function(event){
            showMessage("<div class='error'>Problem due to some Errora</div>"+event);
            console.log(event);
        };
        websocket.onclose = function(event){
            showMessage("<div class='chat-connection-ack'>Connection Closed</div>"+event.data);
        };
        const fChat = document.getElementById('btnSend');

        fChat.onclick = function() {
            event.preventDefault();
            // document.getElementById('chat-user').setAttribute("type","hidden");
            // let user = document.getElementById('chat-user').value;
            let user = "Biro";
            let message = document.getElementById('chat-message').value;

            var messageJSON = {
                user: user,
                message: message
            };
            websocket.send(JSON.stringify(messageJSON));
        };
    });

    </script>
    </head>
    <body>
        <form name="frmChat" id="frmChat" onsubmit="return false;">
            <div id="chat-box"></div>
            <!-- <input type="text" name="chat-user" id="chat-user" placeholder="Name" class="chat-input" required /> -->
            <input type="text" name="chat-message" id="chat-message" placeholder="Message"  class="chat-input chat-message" required />
            <button id="btnSend" name="send-chat-message" >Send</button>
        </form>
</body>
</html>

</code>```

When used in my computer, it connects succesfully. when called from the server, firefox says

```<code>Firefox can’t establish a connection to the server at ws://my-server-url:8090/
</code>```

thanks in advance, it's my first question here, so please let me know if there's something i can improve in it.

Body:
Tried to setup a simple and very basic php websocket chat. Got it working on my computer, then uploaded the files to a server, but it doesn't work there.

I saw the example on a website (https://phppot.com/php/simple-php-chat-using-websocket/)
got it working on my computer, this is the chathandler class:

<?php
class ChatHandler {
    function send($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

    function seal($socketData) {
        $b1 = 0x80 | (0x1 & 0x0f);
        $length = strlen($socketData);

        if($length <= 125)
            $header = pack('CC', $b1, $length);
        elseif($length > 125 && $length < 65536)
            $header = pack('CCn', $b1, 126, $length);
        elseif($length >= 65536)
            $header = pack('CCNN', $b1, 127, $length);
        return $header.$socketData;
    }

    function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
        $headers = array();
        $lines = preg_split("/\r\n/", $received_header);
        foreach($lines as $line)
        {
            $line = chop($line);
            if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
            {
                $headers[$matches[1]] = $matches[2];
            }
        }

        $secKey = $headers['Sec-WebSocket-Key'];
        $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host_name\r\n" .
        "WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
        socket_write($client_socket_resource,$buffer,strlen($buffer));
    }

    function newConnectionACK($client_ip_address) {
        $message = $client_ip_address;
        $messageArray = array('message'=>$message,'message_type'=>'login');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function connectionDisconnectACK($client_ip_address) {
        $message = $client_ip_address;
        $messageArray = array('message'=>$message,'message_type'=>'logoff');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function createChatBoxMessage($chat_user,$chat_box_message) {
        $message = $chat_box_message;
        $messageArray = array('message'=>$message,'message_type'=>'mensaje','user'=>$chat_user);
        $chatMessage = $this->seal(json_encode($messageArray));
        return $chatMessage;
    }
}
?>

this is the php-socket.php file:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
define('HOST_NAME',"localhost");
define('PORT',"8090");
$null = NULL;

require_once("class.chathandler.php");
$chatHandler = new ChatHandler();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);

$clientSocketArray = array($socketResource);
while (true) {
    $newSocketArray = $clientSocketArray;
    socket_select($newSocketArray, $null, $null, 0, 10);

    if (in_array($socketResource, $newSocketArray)) {
        $newSocket = socket_accept($socketResource);
        $clientSocketArray[] = $newSocket;

        $header = socket_read($newSocket, 1024);
        $chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);

        socket_getpeername($newSocket, $client_ip_address);
        $connectionACK = $chatHandler->newConnectionACK($client_ip_address);

        $chatHandler->send($connectionACK);

        $newSocketIndex = array_search($socketResource, $newSocketArray);
        unset($newSocketArray[$newSocketIndex]);
    }

    foreach ($newSocketArray as $newSocketArrayResource) {
        while(socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1){
            $socketMessage = $chatHandler->unseal($socketData);
            $messageObj = json_decode($socketMessage);

            $chat_box_message = $chatHandler->createChatBoxMessage($messageObj->user, $messageObj->message);
            $chatHandler->send($chat_box_message);
            break 2;
        }

        $socketData = @socket_read($newSocketArrayResource, 1024, PHP_NORMAL_READ);
        if ($socketData === false) {
            socket_getpeername($newSocketArrayResource, $client_ip_address);
            $connectionACK = $chatHandler->connectionDisconnectACK($client_ip_address);
            $chatHandler->send($connectionACK);
            $newSocketIndex = array_search($newSocketArrayResource, $clientSocketArray);
            unset($clientSocketArray[$newSocketIndex]);
        }
    }
}
socket_close($socketResource);
?>

And finally, this is the file used from the browser:

        <form name="frmChat" id="frmChat" onsubmit="return false;">

            <input type="text" name="chat-message" id="chat-message" placeholder="Message"  class="chat-input chat-message" required />
            <button id="btnSend" name="send-chat-message" >Send</button>
        </form>

When used in my computer, it connects succesfully. when called from the server, firefox says

Firefox can’t establish a connection to the server at ws://my-server-url:8090/

thanks in advance, it's my first question here, so please let me know if there's something i can improve in it.


问:
replace the existing three fonts with the other three
I'd like to replace the existing three fonts(Waterfall, Codystar, Cormorant)  with the other three. Customers have already selected and used the font, and I want to replace each font without breaking. Which part should I modify?
Is it okay to replace the fonts written in the image below with other fonts in order?

replacing the existing three fonts with the other three


问:
error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::future<_Result>' (or there is no acceptable conversion)
I am getting there is no acceptable conversion error because it seems the return value of Submit is not what I expect.

Here's a simple reproduceable

```<code>template<typename Task>
std::future<typename std::invoke_result<Task()>::type> Submit(Task task)
{

    std::future<typename std::invoke_result<Task()>::type> result;
    return result;

}
struct Mystruct
{
    std::vector<std::future<int>> Futures;
    int MyFunc(int i) { return i; };
    void Run() {
        for (int i = 0; i < 2; ++i)

        { // i tried bind and lambda
            Futures[i] = Submit(std::bind(&Mystruct::MyFunc, this, i));
            Futures[i] = Submit([this, i]() {return this->MyFunc(i); });
        }
    }

};
</code>```

Shouldn't std::invoke_result<Task()>::type be an int?? because MyFunc returns an int, I expect std::future<typename std::invoke_result<Task()>::type>  to be converted to std::future<int>, so can someone explain what's going on!!

Body:
I am getting there is no acceptable conversion error because it seems the return value of Submit is not what I expect.

Here's a simple reproduceable

template<typename Task>
std::future<typename std::invoke_result<Task()>::type> Submit(Task task)
{

    std::future<typename std::invoke_result<Task()>::type> result;
    return result;

}
struct Mystruct
{
    std::vector<std::future<int>> Futures;
    int MyFunc(int i) { return i; };
    void Run() {
        for (int i = 0; i < 2; ++i)

        { // i tried bind and lambda
            Futures[i] = Submit(std::bind(&Mystruct::MyFunc, this, i));
            Futures[i] = Submit([this, i]() {return this->MyFunc(i); });
        }
    }

};

Shouldn't std::invoke_result<Task()>::type be an int?? because MyFunc returns an int, I expect std::future<typename std::invoke_result<Task()>::type>  to be converted to std::future<int>, so can someone explain what's going on!!


问:
how I can login with facebook or something else, after that i integrate with google account to get the service of google

Because when integrate with google account the auth user set into google account but i wan't the information of authentication i have made before

hope everyone to give me solution


问:
speech synthesis in javascript not filling voices
i have a select drop down box with the ID of "set"

here is the javascript for filling the box

```<code>   var voiceSelect = document.getElementById("set");

    var voices = window.speechSynthesis.getVoices();
    for (var i = 0; i < voices.length; i++) {
      var option = document.createElement('option');
      option.value = voices[i].name;
      option.innerHTML = voices[i].name;
      voiceSelect.appendChild(option);
    }`
</code>```

 what happens when i look at the get voices
i tried getting the voices and this is what happened

Body:
i have a select drop down box with the ID of "set"

here is the javascript for filling the box

   var voiceSelect = document.getElementById("set");

    var voices = window.speechSynthesis.getVoices();
    for (var i = 0; i < voices.length; i++) {
      var option = document.createElement('option');
      option.value = voices[i].name;
      option.innerHTML = voices[i].name;
      voiceSelect.appendChild(option);
    }`

 what happens when i look at the get voices
i tried getting the voices and this is what happened


问:
hide the section if the umbraco content is empty
I have created a description section for a website, and the description content is added through the Umbraco CMS. So now what i want is hide the description column if the Umbraco CMS content for this description section is empty or no content.</p>
```<code><CustomListVue
      class="mt-8"
      v-if="pageData.items"
      v-show="showDetails"
      :startCollapse="true"
      :collapsable="true"
      :data="{
        title: 'Description',
      }"
    >
      <ul class="desc-box">
        <li
          v-for="(i, index) in pageData.items.filter((x) => x.content)"
          :key="'item_' + index"
          class="desc"
          v-html="i.content"
        ></li>
      </ul>
</CustomListVue>

data() {
    return {
      showTnc: false,
    };
},
computed: {

},

</code>```

Body:
I have created a description section for a website, and the description content is added through the Umbraco CMS. So now what i want is hide the description column if the Umbraco CMS content for this description section is empty or no content.

<CustomListVue
      class="mt-8"
      v-if="pageData.items"
      v-show="showDetails"
      :startCollapse="true"
      :collapsable="true"
      :data="{
        title: 'Description',
      }"
    >

 x.content)"
          :key="'item_' + index"
          class="desc"
          v-html="i.content"
        >

</CustomListVue>

data() {
    return {
      showTnc: false,
    };
},
computed: {

},


问:
Route to an empty page does not work in a React app
I want to establish a standalone route to a login page apart from the routes that render the content of a page with a header and footer. For now the login page is supposed to close the current window as it is expected to be opened in a popup.

For that I have a following structure for my React app:

App.js

<Router>
  <Route path="/login" element={<Login />} />

  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/page1" element={<Page1 />} />
  </Routes>

</Router>
```
<p>Login.js</p>
<pre class="lang-javascript prettyprint-override"><code>import React, { useEffect } from "react";

function Login() {
  useEffect(() => {
    return () => {
      window.close();
    };
  }, []);

  return <h1>This window should be closed</h1>;
}

export default Login;
</code>```

While if I skip the <Route path="/login" element={<Login />} /> clause, the app works fine doing what is expected. But, for some reason, if I add the top level <Route path="/login" element={<Login />} />, it makes my app blank altogether, routes '/' and '/page1' stop working giving a blank page and <Login /> is not rendered.

Placing the <Route path="/login" element={<Login />} /> into the <Routes></Routes> does not help - it renders the header and the footer for '/login', which is not what I want. Also I tried using <Route path="/login" render={() => <Login />} />, it also does not work behaving the same way as with the element prop.

How can I make my app render a standalone route?

Body:
I want to establish a standalone route to a login page apart from the routes that render the content of a page with a header and footer. For now the login page is supposed to close the current window as it is expected to be opened in a popup.

For that I have a following structure for my React app:

App.js

<Router>
  <Route path="/login" element={<Login />} />

  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/page1" element={<Page1 />} />
  </Routes>

</Router>

Login.js

import React, { useEffect } from "react";

function Login() {
  useEffect(() => {
    return () => {
      window.close();
    };
  }, []);

  return
This window should be closed
;
}

export default Login;

While if I skip the <Route path="/login" element={<Login />} /> clause, the app works fine doing what is expected. But, for some reason, if I add the top level <Route path="/login" element={<Login />} />, it makes my app blank altogether, routes '/' and '/page1' stop working giving a blank page and <Login /> is not rendered.

Placing the <Route path="/login" element={<Login />} /> into the <Routes></Routes> does not help - it renders the header and the footer for '/login', which is not what I want. Also I tried using <Route path="/login" render={() => <Login />} />, it also does not work behaving the same way as with the element prop.

How can I make my app render a standalone route?


问:
How to move center line in gridhelper?
I use GridHelper to draw grid on picture. Now, i want to move center line(blue line) down y-axis 20 units, and to the left along the x-axis 20 units. After that, i want assign two characters x, y, number on center line
Can you help me.

Title: How to move center line in gridhelper?


问:
What is the best way to access an integer value from multiple threads?
I'm confused about how to choose the most effective way to synchronize multi threads.
Supposed we have an integer value i to synchronize.

1-Write/1-Read : just simply ignore it or add volatile before i?

1-Write/N-Read : just simply ignore it or add volatile before i?

N-Write/1-Read : Interlocked is the best way.

N-Write/1-Read : Interlocked is the best way.

Should i use volatile, Interlocked or lock?


问:
`nlp.add_pipe` now takes the string name of the registered component factory, not a callable component
With Spacy version 3.0 facing problem in adding pipeline, Below is my code which I am using, also I have attached screenshot for error

```<code>nlp = spacy.blank('en')

def train_model(train_data):
    # Remove all pipelines and add NER pipeline from the model

    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)

    #Add labels in the NLP pipeline
    for _, annotation in train_data:
        for ent in annotation.get('entities'):
            ner.add_label(ent[2])

    #Remove other pipelines if they are there
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    print(other_pipes)

    with nlp.disable_pipes(*other_pipes):  # only train NER
        optimizer = nlp.begin_training()
        for itn in range(10): # train for 10 iterations
            print("Starting iteration " + str(itn))
            random.shuffle(train_data)
            losses = {}
            index = 0
            for text, annotations in train_data:
                try:
                    nlp.update(
                        [text],  # batch of texts
                        [annotations],  # batch of annotations
                        drop=0.2,  # dropout - make it harder to memorise data
                        sgd=optimizer,  # callable to update weights
                        losses=losses)
                except Exception as e:
                    pass

            print(losses)
</code>```

Body:
With Spacy version 3.0 facing problem in adding pipeline, Below is my code which I am using, also I have attached screenshot for error

nlp = spacy.blank('en')

def train_model(train_data):
    # Remove all pipelines and add NER pipeline from the model

    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)

    #Add labels in the NLP pipeline
    for _, annotation in train_data:
        for ent in annotation.get('entities'):
            ner.add_label(ent[2])

    #Remove other pipelines if they are there
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    print(other_pipes)

    with nlp.disable_pipes(*other_pipes):  # only train NER
        optimizer = nlp.begin_training()
        for itn in range(10): # train for 10 iterations
            print("Starting iteration " + str(itn))
            random.shuffle(train_data)
            losses = {}
            index = 0
            for text, annotations in train_data:
                try:
                    nlp.update(
                        [text],  # batch of texts
                        [annotations],  # batch of annotations
                        drop=0.2,  # dropout - make it harder to memorise data
                        sgd=optimizer,  # callable to update weights
                        losses=losses)
                except Exception as e:
                    pass

            print(losses)


问:
WSL Distros not visible to VSCode or IntelliJ IDEs
For a few weeks now I have had this very strange issue and have been unable to resolve it:

I usually code on WSL2, and it used to work fine on this machine and user. But now, whenever I try to open the Remote Explorer in Visual Studio Code or try to open a "New Project from Existing Files" in an IntelliJ IDE, no WSL Distros show up.

They are still there - wsl -l -v lists them and I can open them in the terminal. Everything inside of them works (aside from opening VSCode).

In Windows Explorer, their filesystems do show up. But in Visual Studio Code the list of Distros is empty and I get an error message stating "Cannot read properties of undefined (reading 'name')" when I open the Remote Explorer. In IntelliJ IDEs, only my local drives appear where there used to be additional entries for WSL.

When I navigate to a directory in WSL in the terminal and then execute code ., it opens a VSCode window, but then I get the notification "No WSL distros found".

Interestingly, previously opened projects in IntelliJ IDEs can still be opened (but I am getting Line-Ending issues).

I have tried reinstalling the WSL extension in VSCode, restarting the LXSSManager-Service, doing a network reset with netsh winsock reset, netsh int ip reset, ipconfig /release, ipconfig /renew, ipconfig /flushdns - and I have tried reinstalling VSCode entirely... to no avail. I have also looked at the registry entries for the WSL Distros under Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Lxss\, and they look fine to me.

I have also uninstalled my non-primary distros and reinstalled them - same issue across all installed distros, old or freshly installed.

I am sadly unable to specify how to reproduce the issue as everything used to work in this setup and nothing was deliberately changed.

My Windows version is Windows 11 Version 22H2 (OS Build 22621.963).


问:
Angular saves the first route and reuses
I have two pages: login and account.
There are two scenarios:

first route is /login

first route is /account

First route is when, for example, I open chrome and type localhost:8100/login /login would be the first route.

First scenario, when first route is /login:

user is currently at /login;

user loggs in to account1 and now user is at /account;

/account shows account1 data;

user loggs out and goes back to /login;

user loggs in to account2 goes to /account;

/account show account2 data as it should.

Second scenario, when first route is /account:

user is currently at /account and is logged in to account1;

user loggs out and goes to /login;

user loggs in to account2 and goes back to /account;

/account shows account1 data instead of account2 and the ngOnInit was not called.

I'm guessing, the problem is when the first route is /account it is saved, and reused by Angular.

I have implemented a custom route reuse strategy, it works perfectly. I set /account route to not be reused by the strategy. And it is not, it is not saved in storedRoutes, variable where saved routes are. But it is reused anyway. Same thing with /login route: when /login route is the first route it is saved, not by my custom RRS, and angular reuses it.

this is the custom route reuse strategy:

```<code>class CustomRouteReuseStrategy implements RouteReuseStrategy {

    /**
     * Object which will store RouteStorageObjects indexed by keys
     * The keys will all be a path (as in route.routeConfig.path)
     * This allows us to see if we've got a route stored for the requested path
     */
    storedRoutes: { [key: string]: RouteStorageObject } = {};

    /**
     * Decides when the route should be stored
     * If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
     * _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
     * An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
     * @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
     * @returns boolean indicating that we want to (true) or do not want to (false) store that route
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        const detach: boolean = route.data.routeReuse === true;

        return detach;
    }

    /**
     * Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
     * @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
     * @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
     */
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        const storedRoute: RouteStorageObject = {
            snapshot: route,
            handle: handle
        };

        // routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
        this.storedRoutes[route.routeConfig.path] = storedRoute;
    }

    /**
    * Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
    * @param route The route the user requested
    * @returns boolean indicating whether or not to render the stored route
    */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {

        // this will be true if the route has been stored before
        const canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];

        // this decides whether the route already stored should be rendered in place of the requested route, and is the return value
        // at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
        // so, if the route.params and route.queryParams also match, then we should reuse the component
        if (canAttach) {
            const willAttach: boolean = true;

            const paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
            const queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);

            return paramsMatch && queryParamsMatch;
        } else {
            return false;
        }
    }

    /**
    * Finds the locally stored instance of the requested route, if it exists, and returns it
    * @param route New route the user has requested
    * @returns DetachedRouteHandle object which can be used to render the component
    */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

        // return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
        if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;

        /** returns handle when the route.routeConfig.path is already stored */
        return this.storedRoutes[route.routeConfig.path].handle;
    }

    /**
    * Determines whether or not the current route should be reused
    * @param future The route the user is going to, as triggered by the router
    * @param curr The route the user is currently on
    * @returns boolean basically indicating true if the user intends to leave the current route
    */
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}
</code>```

Body:
I have two pages: login and account.
There are two scenarios:

first route is /login

first route is /account

First route is when, for example, I open chrome and type localhost:8100/login /login would be the first route.

First scenario, when first route is /login:

user is currently at /login;

user loggs in to account1 and now user is at /account;

/account shows account1 data;

user loggs out and goes back to /login;

user loggs in to account2 goes to /account;

/account show account2 data as it should.

Second scenario, when first route is /account:

user is currently at /account and is logged in to account1;

user loggs out and goes to /login;

user loggs in to account2 and goes back to /account;

/account shows account1 data instead of account2 and the ngOnInit was not called.

I'm guessing, the problem is when the first route is /account it is saved, and reused by Angular.

I have implemented a custom route reuse strategy, it works perfectly. I set /account route to not be reused by the strategy. And it is not, it is not saved in storedRoutes, variable where saved routes are. But it is reused anyway. Same thing with /login route: when /login route is the first route it is saved, not by my custom RRS, and angular reuses it.

this is the custom route reuse strategy:

class CustomRouteReuseStrategy implements RouteReuseStrategy {

    /**
     * Object which will store RouteStorageObjects indexed by keys
     * The keys will all be a path (as in route.routeConfig.path)
     * This allows us to see if we've got a route stored for the requested path
     */
    storedRoutes: { [key: string]: RouteStorageObject } = {};

    /**
     * Decides when the route should be stored
     * If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
     * _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
     * An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
     * @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
     * @returns boolean indicating that we want to (true) or do not want to (false) store that route
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        const detach: boolean = route.data.routeReuse === true;

        return detach;
    }

    /**
     * Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
     * @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
     * @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
     */
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        const storedRoute: RouteStorageObject = {
            snapshot: route,
            handle: handle
        };

        // routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
        this.storedRoutes[route.routeConfig.path] = storedRoute;
    }

    /**
    * Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
    * @param route The route the user requested
    * @returns boolean indicating whether or not to render the stored route
    */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {

        // this will be true if the route has been stored before
        const canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];

        // this decides whether the route already stored should be rendered in place of the requested route, and is the return value
        // at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
        // so, if the route.params and route.queryParams also match, then we should reuse the component
        if (canAttach) {
            const willAttach: boolean = true;

            const paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
            const queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);

            return paramsMatch && queryParamsMatch;
        } else {
            return false;
        }
    }

    /**
    * Finds the locally stored instance of the requested route, if it exists, and returns it
    * @param route New route the user has requested
    * @returns DetachedRouteHandle object which can be used to render the component
    */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

        // return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
        if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;

        /** returns handle when the route.routeConfig.path is already stored */
        return this.storedRoutes[route.routeConfig.path].handle;
    }

    /**
    * Determines whether or not the current route should be reused
    * @param future The route the user is going to, as triggered by the router
    * @param curr The route the user is currently on
    * @returns boolean basically indicating true if the user intends to leave the current route
    */
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}


问:
How does a read-eval-print-loop (REPL) Works? How is the state of previous commands stored? does it recompile and runs again each time?

How is this achieved?
does it store in a file like test.py which has

```<code># test.py
def foo():
    print('foo was called')

foo()
</code>```

and runs $ python test.py

I am asking about the internal workings of the repl.

how is the state of previous commands stored?

Body:
How is this achieved?
does it store in a file like test.py which has

# test.py
def foo():
    print('foo was called')

foo()

and runs $ python test.py

I am asking about the internal workings of the repl.

how is the state of previous commands stored?