问:
Low pass filter with gaussian weighting in Python
I am trying to apply a low pass filter to a signal in the frequency domain, with gaussian weighting/roll off curve.
I got the first version of the for loop from my collegues and I admit that I do not understand it. Why is the sigma definition the way it is with the logarythm? I would just put it the Gauss function as I read it in wikipedia (second version).

Why is the resulting filter characteristic a little offset (by approx. 0.2?) for both versions and why is the result 0 for the second?

the code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.fftpack import ifft

data = np.loadtxt("profil.txt")
t = data[:,0]
x = data[:,1]

amplitudes = fft(x)
c = np.abs(amplitudes)
c_norm = 2 * c/len(t)
c[0] /= 2
c_half = c[0:len(amplitudes)//2]
f = np.fft.fftfreq(len(t), d = t[len(t)-1]/(len(t)-1))

p_t = np.zeros(len(amplitudes))
sigma = np.sqrt(np.log(0.5)/(-2.))/np.pi/10      #FIRST VERSION
s = 0.7                                           #SECOND VERSION
for i in range(len(c)):
    e = np.exp(-2*np.pi**2*sigma**2*f[i]**2)    #FIRST VERSION
    #e = np.e**(-f[i]**2/2/s**2)/s/np.sqrt(2*np.pi)    #SECOND VERSION
    if e > 0.1:
        #FIRST VERSION
        p_t[i] = np.exp(-2*np.pi**2*sigma**2*f[i]**2)
        p_t[-i] = np.exp(-2 * np.pi ** 2 * sigma ** 2 * f[i] ** 2)
        #SECOND VERSION:
        #p_t[i] = np.e**(-f[i]**2/2/s**2)/s/np.sqrt(2*np.pi)
        #p_t[-i] = np.e ** (-f[i] ** 2 / 2 / s ** 2)/s/np.sqrt(2*np.pi)
    else:
        pass

x_filtered = ifft(amplitudes * p_t)

fig = plt.figure(constrained_layout = True)
gs = fig.add_gridspec(2, 1)
a00 = fig.add_subplot(gs[0, 0])
a00.plot(t, x,color='blue', label="original")
a00.plot(t,x_filtered, color='red', label="filtered")
a00.legend(bbox_to_anchor=(0,1,1,0), loc="lower left", ncol = 1)
a01 = fig.add_subplot(gs[1, 0])
a01.plot(f,c, label="amplitudes")
a01.set_ylim([0,1000])
a01.legend()
a03 = a01.twinx()
a03.plot(f, p_t, color='red', label='filter characteristic')
plt.show()

</code>```

thanks in advance for any idea or explanation. The resulting plot (first version):

second version:

Body:
I am trying to apply a low pass filter to a signal in the frequency domain, with gaussian weighting/roll off curve.
I got the first version of the for loop from my collegues and I admit that I do not understand it. Why is the sigma definition the way it is with the logarythm? I would just put it the Gauss function as I read it in wikipedia (second version).

Why is the resulting filter characteristic a little offset (by approx. 0.2?) for both versions and why is the result 0 for the second?

the code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.fftpack import ifft

data = np.loadtxt("profil.txt")
t = data[:,0]
x = data[:,1]

amplitudes = fft(x)
c = np.abs(amplitudes)
c_norm = 2 * c/len(t)
c[0] /= 2
c_half = c[0:len(amplitudes)//2]
f = np.fft.fftfreq(len(t), d = t[len(t)-1]/(len(t)-1))

p_t = np.zeros(len(amplitudes))
sigma = np.sqrt(np.log(0.5)/(-2.))/np.pi/10      #FIRST VERSION
s = 0.7                                           #SECOND VERSION
for i in range(len(c)):
    e = np.exp(-2*np.pi**2*sigma**2*f[i]**2)    #FIRST VERSION
    #e = np.e**(-f[i]**2/2/s**2)/s/np.sqrt(2*np.pi)    #SECOND VERSION
    if e > 0.1:
        #FIRST VERSION
        p_t[i] = np.exp(-2*np.pi**2*sigma**2*f[i]**2)
        p_t[-i] = np.exp(-2 * np.pi ** 2 * sigma ** 2 * f[i] ** 2)
        #SECOND VERSION:
        #p_t[i] = np.e**(-f[i]**2/2/s**2)/s/np.sqrt(2*np.pi)
        #p_t[-i] = np.e ** (-f[i] ** 2 / 2 / s ** 2)/s/np.sqrt(2*np.pi)
    else:
        pass

x_filtered = ifft(amplitudes * p_t)

fig = plt.figure(constrained_layout = True)
gs = fig.add_gridspec(2, 1)
a00 = fig.add_subplot(gs[0, 0])
a00.plot(t, x,color='blue', label="original")
a00.plot(t,x_filtered, color='red', label="filtered")
a00.legend(bbox_to_anchor=(0,1,1,0), loc="lower left", ncol = 1)
a01 = fig.add_subplot(gs[1, 0])
a01.plot(f,c, label="amplitudes")
a01.set_ylim([0,1000])
a01.legend()
a03 = a01.twinx()
a03.plot(f, p_t, color='red', label='filter characteristic')
plt.show()

thanks in advance for any idea or explanation. The resulting plot (first version):

second version:


来源: stackexchange

问:
Cortex-M remote target with LLDB script
I'm currently able to connect, load and debugg a Nucleo-G0B1 board with LLDB and pyOCD (also with OpenOCD) using the following sequence of commands:

```<code>$ lldb Build/temp.elf
(lldb) gdb-remote 127.0.0.1:3333
(lldb) target modules load --load .text 0x08000000
(lldb) process plugin packet monitor reset halt
</code>```

But i'm not able to do the same thing with the LLDB python interface, currently

I'm trying to use the following mehods, prints for testing purposes

import lldb

debugger = lldb.SBDebugger.Create()

print(debugger.GetInstanceName())
error = lldb.SBError()
target = debugger.CreateTarget('Build/temp.elf', 'armv6m-*-none-eabi', 'remote-gdb-server', False, error)

print(error.GetCString())
print(target)
```
<p>But so far no target is created. if I change the platform parameter to 'host' the target is created but I'm looking  for a remote target not local</p>
<p>script output for remote-gdb-server</p>
```$ python lldbinit.py
debugger_1
platform 'remote-gdb-server' doesn't support 'armv6m-*-none-eabi'
No value
```
<p>script output for host</p>
```$ python lldbinit.py
debugger_1
None
temp.elf
```

ContentLicense: CC BY-SA 4.0

Title: Cortex-M remote target with LLDB script

Body:
I'm currently able to connect, load and debugg a Nucleo-G0B1 board with LLDB and pyOCD (also with OpenOCD) using the following sequence of commands:

$ lldb Build/temp.elf
(lldb) gdb-remote 127.0.0.1:3333
(lldb) target modules load --load .text 0x08000000
(lldb) process plugin packet monitor reset halt

But i'm not able to do the same thing with the LLDB python interface, currently

I'm trying to use the following mehods, prints for testing purposes

import lldb

debugger = lldb.SBDebugger.Create()

print(debugger.GetInstanceName())
error = lldb.SBError()
target = debugger.CreateTarget('Build/temp.elf', 'armv6m-*-none-eabi', 'remote-gdb-server', False, error)

print(error.GetCString())
print(target)

But so far no target is created. if I change the platform parameter to 'host' the target is created but I'm looking  for a remote target not local

script output for remote-gdb-server

$ python lldbinit.py
debugger_1
platform 'remote-gdb-server' doesn't support 'armv6m-*-none-eabi'
No value

script output for host

$ python lldbinit.py
debugger_1
None
temp.elf


问:
Using keycloak public client token to communicate with confidential client
I have a quarkus backend app with a react frontend. I want to add a security layer where a user has to login in order to be able to access the UI, and any API calls made from the UI to the backend requires a token with the user is authenticated. Keycloak is the best and simplest(ish) solution for this.

I found this tutorial and it's exactly what I need but doesn't work :(

My keycloak setup is a client for the frontend and backend.

Frontend Setup

The frontend client is a public access type

I then defined a few different JS files to setup the connection to keycloak and the header token...

UserService.ts

```<code>import Keycloak, {KeycloakInstance} from 'keycloak-js'

const keycloak: KeycloakInstance = Keycloak('/keycloak.json');

/**
 * Initializes Keycloak instance and calls the provided callback function if successfully authenticated.
 *
 * @param onAuthenticatedCallback
 */
const initKeycloak = (onAuthenticatedCallback) => {
    keycloak.init({
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri: window.location.origin + /silent-check-sso.html,
        checkLoginIframe: false,
    })
    .then((authenticated) => {
        if (authenticated) {
            onAuthenticatedCallback();
        } else {
            doLogin();
        }
    })
};

const doLogin = keycloak.login;

const doLogout = keycloak.logout;

const getToken = () => keycloak.token;

const getKeycloakId = () => keycloak.subject; // subject is the keycloak id

const isLoggedIn = () => !!keycloak.token;

const updateToken = (successCallback) =>
        keycloak.updateToken(5)
                .then(successCallback)
                .catch(doLogin);

const getUserInfo = async () => await keycloak.loadUserInfo();

const getUsername = () => keycloak.tokenParsed?.sub;

const hasRole = (roles) => roles.some((role) => keycloak.hasResourceRole(role, 'frontend'));

export const UserService = {
    initKeycloak,
    doLogin,
    doLogout,
    isLoggedIn,
    getToken,
    getKeycloakId,
    updateToken,
    getUsername,
    hasRole,
};
</code>```

keycloak.json

```<code>{
  "realm": "buddydata",
  "auth-server-url": "http://127.0.0.1:8180/auth/",
  "ssl-required": "external",
  "resource": "app",
  "public-client": true,
  "verify-token-audience": true,
  "use-resource-role-mappings": true,
  "confidential-port": 0
}
</code>```

HttpService.ts

```<code>import axios from "axios";
import {UserService} from "@/services/UserService";

const HttpMethods = {
  GET: 'GET',
  POST: 'POST',
  DELETE: 'DELETE',
  PUT: 'PUT',
};

const baseURL = 'http://localhost:9000/api/v1';

const _axios = axios.create({baseURL: baseURL});

const configure = () => {
  _axios.interceptors.request.use((config) => {
    if (UserService.isLoggedIn()) {
      const cb = () => {
        config.headers.Authorization = `Bearer ${UserService.getToken()}`;
        return Promise.resolve(config);
      };
      return UserService.updateToken(cb);
    }
  });
};

const getAxiosClient = () => _axios;

export const HttpService = {
  HttpMethods,
  configure,
  getAxiosClient
};

</code>```

Backend Setup

There is no need to define any code updates, just config updates for quarkus...

application.properties

```<code>quarkus.resteasy-reactive.path=/api/v1
quarkus.http.port=9000
quarkus.http.cors=true

quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/buddydata
quarkus.oidc.client-id=api
quarkus.oidc.credentials.secret=ff5b3f63-446f-4ca4-8623-1475cb59a343
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
</code>```

That is the keycloak config setup along with quarkus and react setup too. I have included all the information to show it all matches up. When the user logs in on the frontend a call is made to the backend to get the initial state, pre oidc setup, this worked but now it doesn't.

Root.tsx

```<code>const store = StoreService.setup();

export const Root = (): JSX.Element => {
    StoreService.getInitialData(store)
        .then(_ => console.log("Initial state loaded"));

    return (
        <RenderOnAuthenticated>
            <h1>Hello {UserService.getUsername()}</h1>
        </RenderOnAuthenticated>
    )
};
</code>```

StoreService.ts

```<code>const setup = () => {
  const enhancers = [];
  const middleware = [
    thunk,
    axiosMiddleware(HttpService.getAxiosClient())
  ];

  if (process.env.NODE_ENV === 'development') {
    enhancers.push(applyMiddleware(logger));
  }

  // const composedEnhancers = compose(applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), ...enhancers);
  const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers);

  return createStore(rootReducer, composedEnhancers);
};

const getInitialData = async store => {
  // Get the logged in user first
  await store.dispatch(getLoggedInUser());
  const user = selectCurrentUser(store.getState());
}

const StoreService = {
  setup,
  getInitialData
};

export default StoreService;
</code>```

currentUser.ts

```<code>const axios = HttpService.getAxiosClient();

// User state interface
export interface UserState {
    id: number
    keycloakId: string,
    address?: {},
    title?: string,
    firstName?: string,
    lastName?: string,
    jobTitle?: string,
    dateOfBirth?: string,
    mobile?: string,
    email: string,
    isAdmin?: boolean,
    creationDate?: Date,
    updatedDate?: Date
}

// Action Types
const GET_USER_SUCCESS = 'currentUser/GET_USER_SUCCESS';

// Reducer
const initialUser: UserState = {id: -1, keycloakId: "-1", email: "no@email"}
export const currentUserReducer = (currentUserState = initialUser, action) => {
    switch (action.type) {
        case GET_USER_SUCCESS:
            return {...currentUserState, ...action.payload.user};
        default:
            return currentUserState;
    }
};

// Synchronous action creator
export const getLoggedInUserSuccess = userResponse => ({
    type: GET_USER_SUCCESS,
    payload: { user: userResponse.data }
})

// Asynchronous thunk action creator
// calls api, then dispatches the synchronous action creator
export const getLoggedInUser = (keycloakId = UserService.getKeycloakId()) => {
    return async getLoggedInUser => {
        try {
            let axiosResponse = await axios.get(`/initial/users/${keycloakId}`)
            getLoggedInUser(getLoggedInUserSuccess(axiosResponse))
        } catch(e) {
            console.log(e);
        }
    }
}

// Selectors
export const selectCurrentUser = state => state.currentUser;
</code>```

InitialDataController.java

```<code>@Path("/initial")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class InitialDataController {

    @Inject
    UserService userService;

    @GET
    @Path("/users/{keycloakId}")
    public Response getUserByKeycloakId(@PathParam("keycloakId") String keycloakId) {
        UserEntity user = userService.getUserWithKeycloakId(keycloakId);
        return Response
                .ok(user)
                .build();
    }
}
</code>```

UserService.java

```<code>@ApplicationScoped
public class UserService {

    @Inject
    UserRepository repository;

    public UserEntity getUserWithKeycloakId(@NotNull String keycloakId) {
        return repository.findUserWithKeycloakId(keycloakId);
    }
}
</code>```

UserRepository.java

```<code>@ApplicationScoped
public class UserRepository implements PanacheRepositoryBase<UserEntity, Long> {

    public UserEntity findUserWithKeycloakId(String keycloakId) {
        return find("#User.getUserByKeycloakId", keycloakId).firstResult();
    }
}
</code>```

The named query is SELECT u FROM User u WHERE u.keycloakId = ?1

I have provided my config setup for keycloak, react and quarkus and a step through the code on how calls are made to the backend from the UI.
How can I secure the backend client on keycloak and have the frontend public, and then be able to make secure requests from the frontend to the backend. At the moment any requests made is giving a 401 Unauthorized response. I don't know how to get around this and I feel it's a keycloak config issue but not sure which option to change/update specifically. Any new knowledge/information on how to get over this would be great.

Body:
I have a quarkus backend app with a react frontend. I want to add a security layer where a user has to login in order to be able to access the UI, and any API calls made from the UI to the backend requires a token with the user is authenticated. Keycloak is the best and simplest(ish) solution for this.

I found this tutorial and it's exactly what I need but doesn't work :(

My keycloak setup is a client for the frontend and backend.

Frontend Setup

The frontend client is a public access type

I then defined a few different JS files to setup the connection to keycloak and the header token...

UserService.ts

import Keycloak, {KeycloakInstance} from 'keycloak-js'

const keycloak: KeycloakInstance = Keycloak('/keycloak.json');

/**
 * Initializes Keycloak instance and calls the provided callback function if successfully authenticated.
 *
 * @param onAuthenticatedCallback
 */
const initKeycloak = (onAuthenticatedCallback) => {
    keycloak.init({
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri: window.location.origin + /silent-check-sso.html,
        checkLoginIframe: false,
    })
    .then((authenticated) => {
        if (authenticated) {
            onAuthenticatedCallback();
        } else {
            doLogin();
        }
    })
};

const doLogin = keycloak.login;

const doLogout = keycloak.logout;

const getToken = () => keycloak.token;

const getKeycloakId = () => keycloak.subject; // subject is the keycloak id

const isLoggedIn = () => !!keycloak.token;

const updateToken = (successCallback) =>
        keycloak.updateToken(5)
                .then(successCallback)
                .catch(doLogin);

const getUserInfo = async () => await keycloak.loadUserInfo();

const getUsername = () => keycloak.tokenParsed?.sub;

const hasRole = (roles) => roles.some((role) => keycloak.hasResourceRole(role, 'frontend'));

export const UserService = {
    initKeycloak,
    doLogin,
    doLogout,
    isLoggedIn,
    getToken,
    getKeycloakId,
    updateToken,
    getUsername,
    hasRole,
};

keycloak.json

{
  "realm": "buddydata",
  "auth-server-url": "http://127.0.0.1:8180/auth/",
  "ssl-required": "external",
  "resource": "app",
  "public-client": true,
  "verify-token-audience": true,
  "use-resource-role-mappings": true,
  "confidential-port": 0
}

HttpService.ts

import axios from "axios";
import {UserService} from "@/services/UserService";

const HttpMethods = {
  GET: 'GET',
  POST: 'POST',
  DELETE: 'DELETE',
  PUT: 'PUT',
};

const baseURL = 'http://localhost:9000/api/v1';

const _axios = axios.create({baseURL: baseURL});

const configure = () => {
  _axios.interceptors.request.use((config) => {
    if (UserService.isLoggedIn()) {
      const cb = () => {
        config.headers.Authorization = `Bearer ${UserService.getToken()}`;
        return Promise.resolve(config);
      };
      return UserService.updateToken(cb);
    }
  });
};

const getAxiosClient = () => _axios;

export const HttpService = {
  HttpMethods,
  configure,
  getAxiosClient
};

Backend Setup

There is no need to define any code updates, just config updates for quarkus...

application.properties

quarkus.resteasy-reactive.path=/api/v1
quarkus.http.port=9000
quarkus.http.cors=true

quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/buddydata
quarkus.oidc.client-id=api
quarkus.oidc.credentials.secret=ff5b3f63-446f-4ca4-8623-1475cb59a343
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated

That is the keycloak config setup along with quarkus and react setup too. I have included all the information to show it all matches up. When the user logs in on the frontend a call is made to the backend to get the initial state, pre oidc setup, this worked but now it doesn't.

Root.tsx

const store = StoreService.setup();

export const Root = (): JSX.Element => {
    StoreService.getInitialData(store)
        .then(_ => console.log("Initial state loaded"));

    return (
        <RenderOnAuthenticated>

Hello {UserService.getUsername()}

        </RenderOnAuthenticated>
    )
};

StoreService.ts

const setup = () => {
  const enhancers = [];
  const middleware = [
    thunk,
    axiosMiddleware(HttpService.getAxiosClient())
  ];

  if (process.env.NODE_ENV === 'development') {
    enhancers.push(applyMiddleware(logger));
  }

  // const composedEnhancers = compose(applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), ...enhancers);
  const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers);

  return createStore(rootReducer, composedEnhancers);
};

const getInitialData = async store => {
  // Get the logged in user first
  await store.dispatch(getLoggedInUser());
  const user = selectCurrentUser(store.getState());
}

const StoreService = {
  setup,
  getInitialData
};

export default StoreService;

currentUser.ts

const axios = HttpService.getAxiosClient();

// User state interface
export interface UserState {
    id: number
    keycloakId: string,
    address?: {},
    title?: string,
    firstName?: string,
    lastName?: string,
    jobTitle?: string,
    dateOfBirth?: string,
    mobile?: string,
    email: string,
    isAdmin?: boolean,
    creationDate?: Date,
    updatedDate?: Date
}

// Action Types
const GET_USER_SUCCESS = 'currentUser/GET_USER_SUCCESS';

// Reducer
const initialUser: UserState = {id: -1, keycloakId: "-1", email: "no@email"}
export const currentUserReducer = (currentUserState = initialUser, action) => {
    switch (action.type) {
        case GET_USER_SUCCESS:
            return {...currentUserState, ...action.payload.user};
        default:
            return currentUserState;
    }
};

// Synchronous action creator
export const getLoggedInUserSuccess = userResponse => ({
    type: GET_USER_SUCCESS,
    payload: { user: userResponse.data }
})

// Asynchronous thunk action creator
// calls api, then dispatches the synchronous action creator
export const getLoggedInUser = (keycloakId = UserService.getKeycloakId()) => {
    return async getLoggedInUser => {
        try {
            let axiosResponse = await axios.get(`/initial/users/${keycloakId}`)
            getLoggedInUser(getLoggedInUserSuccess(axiosResponse))
        } catch(e) {
            console.log(e);
        }
    }
}

// Selectors
export const selectCurrentUser = state => state.currentUser;

InitialDataController.java

@Path("/initial")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class InitialDataController {

    @Inject
    UserService userService;

    @GET
    @Path("/users/{keycloakId}")
    public Response getUserByKeycloakId(@PathParam("keycloakId") String keycloakId) {
        UserEntity user = userService.getUserWithKeycloakId(keycloakId);
        return Response
                .ok(user)
                .build();
    }
}

UserService.java

@ApplicationScoped
public class UserService {

    @Inject
    UserRepository repository;

    public UserEntity getUserWithKeycloakId(@NotNull String keycloakId) {
        return repository.findUserWithKeycloakId(keycloakId);
    }
}

UserRepository.java

@ApplicationScoped
public class UserRepository implements PanacheRepositoryBase<UserEntity, Long> {

    public UserEntity findUserWithKeycloakId(String keycloakId) {
        return find("#User.getUserByKeycloakId", keycloakId).firstResult();
    }
}

The named query is SELECT u FROM User u WHERE u.keycloakId = ?1

I have provided my config setup for keycloak, react and quarkus and a step through the code on how calls are made to the backend from the UI.
How can I secure the backend client on keycloak and have the frontend public, and then be able to make secure requests from the frontend to the backend. At the moment any requests made is giving a 401 Unauthorized response. I don't know how to get around this and I feel it's a keycloak config issue but not sure which option to change/update specifically. Any new knowledge/information on how to get over this would be great.


问:
clustering days from csv data in python
I have CSV data that is already in a datetime format. I need to analyze the data by comparing days and finding the most similar ones. The data is organized in 10minute intervalls which means 144 rows per day need to be clustered into one day. It would be ideal if every day would be copied into an array and could be accessed by saying e.g. print(array_26.08.2022).
[CSV Screenshot]
(https://i.stack.imgur.com/bZEAR.png)

i searched online but couldnt find a solution

Title: clustering days from csv data in python


问:
libusb_blk_transfer works but libusb_fill_bulk_transfer/libusb_submit_transfer does not
I want to setup an asynchronous bulk transfer to a callback routine but I never enter the callback routine. I changed the code to a synchronous transfer and it works. Please help me understand what I'm doing wrong with the asynchronous transfer. Below is the synchronous transfer

```<code>#include <stdio.h>
#include <libusb.h>

#define LB04_VID 4302
#define LB04_PID 60307

unsigned char in_buf[32];

void hexdump(unsigned char* data, int len)
{
    int i;

    for (i = 0; i < len; i++) printf("%02X ", data[i]);
    puts("\n");
}

int main(int argc, char* argv[])
{
    libusb_device** devs;
    libusb_device_handle* dev_handle;
    libusb_context* context = NULL;

    size_t list;
    int ret;
    int iLen;

    ret = libusb_init(&context);

    if (ret < 0) {
        perror("libusb_init");
        return 1;
    }

    libusb_set_option(context, LIBUSB_OPTION_MAX);
    list = libusb_get_device_list(context, &devs);
    if (list < 0) {
        perror("libusb_get_device_list");
        return 1;
    }

    dev_handle = libusb_open_device_with_vid_pid(context, LB04_VID, LB04_PID);
    libusb_free_device_list(devs, 1);

    printf("found XHC-HB04 device\n");

    if (dev_handle) {
        if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
            libusb_detach_kernel_driver(dev_handle, 0);
        }

        ret = libusb_claim_interface(dev_handle, 0);
        if (ret < 0) {
            perror("libusb_claim_interface");
            return 1;
        }

        ret = libusb_set_configuration(dev_handle, 1);

        while (1) {
            ret = libusb_bulk_transfer(dev_handle, (0x01 | LIBUSB_ENDPOINT_IN), in_buf, sizeof(in_buf), &iLen, 0);

            hexdump((unsigned char*)&in_buf, iLen);
        }
        libusb_release_interface(dev_handle, 0);
        libusb_close(dev_handle);
    }

    libusb_exit(context);
}

</code>```

This loops forever like I want. However, when I try to use asynchronous transfer like the below, my callback never gets called. Please help as I'm stuck with what to try next.

```<code>#include <stdio.h>
#include <libusb.h>

#define LB04_VID 4302
#define LB04_PID 60307

unsigned char in_buf[32];
libusb_device** devs;
libusb_device_handle* dev_handle;
libusb_context* context = NULL;
struct libusb_transfer* transfer_in = NULL;

int setup_asynch_transfer(libusb_device_handle* dev_handle);

void hexdump(unsigned char* data, int len)
{
    int i;

    for (i = 0; i < len; i++)
        printf("%02X ", data[i]);

    puts("\n");
}
void cb_response_in(struct libusb_transfer* transfer)
{
    printf("cb_response_in\n");
    if (transfer->actual_length > 0)
        hexdump((unsigned char*)&in_buf, transfer->actual_length);

    setup_asynch_transfer(transfer->dev_handle);
}

int setup_asynch_transfer(libusb_device_handle* dev_handle)
{
    int ret;

    printf("setup_asynch_transfer\n");

    transfer_in = libusb_alloc_transfer(0);
    libusb_fill_bulk_transfer(transfer_in, dev_handle, (0x01 | LIBUSB_ENDPOINT_IN),
        in_buf, sizeof(in_buf),
        cb_response_in, NULL, 500); // no user data

    return (ret = libusb_submit_transfer(transfer_in));
}

int main(int argc, char* argv[])
{
    size_t list;
    int ret;

    ret = libusb_init(&context);

    if (ret < 0) {
        perror("libusb_init");
        return 1;
    }

    libusb_set_option(context, LIBUSB_OPTION_MAX);
    list = libusb_get_device_list(context, &devs);
    if (list < 0) {
        perror("libusb_get_device_list");
        return 1;
    }

    dev_handle = libusb_open_device_with_vid_pid(context, LB04_VID, LB04_PID);
    libusb_free_device_list(devs, 1);

    printf("found XHC-HB04 device\n");

    if (dev_handle) {
        if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
            libusb_detach_kernel_driver(dev_handle, 0);
        }

        ret = libusb_claim_interface(dev_handle, 0);
        if (ret < 0) {
            perror("libusb_claim_interface");
            return 1;
        }

        ret = libusb_set_configuration(dev_handle, 1);

        ret = setup_asynch_transfer(dev_handle);

            // Loop forever
            while (1);

        libusb_release_interface(dev_handle, 0);
        libusb_close(dev_handle);
    }

    libusb_exit(context);
}

</code>```

I made sure I could execute a bulk synchronous transfer and then converted the code to execute asynchronous transfer. I expected the callback routine to print the data and schedule another asynchronous routine while the main routine waited in a while loop forever.

I'm using libusb-1.0 and Microsoft Visual Studio Community 2022 on Windows 10.

Body:
I want to setup an asynchronous bulk transfer to a callback routine but I never enter the callback routine. I changed the code to a synchronous transfer and it works. Please help me understand what I'm doing wrong with the asynchronous transfer. Below is the synchronous transfer

#include <stdio.h>
#include <libusb.h>

#define LB04_VID 4302
#define LB04_PID 60307

unsigned char in_buf[32];

void hexdump(unsigned char* data, int len)
{
    int i;

    for (i = 0; i < len; i++) printf("%02X ", data[i]);
    puts("\n");
}

int main(int argc, char* argv[])
{
    libusb_device** devs;
    libusb_device_handle* dev_handle;
    libusb_context* context = NULL;

    size_t list;
    int ret;
    int iLen;

    ret = libusb_init(&context);

    if (ret < 0) {
        perror("libusb_init");
        return 1;
    }

    libusb_set_option(context, LIBUSB_OPTION_MAX);
    list = libusb_get_device_list(context, &devs);
    if (list < 0) {
        perror("libusb_get_device_list");
        return 1;
    }

    dev_handle = libusb_open_device_with_vid_pid(context, LB04_VID, LB04_PID);
    libusb_free_device_list(devs, 1);

    printf("found XHC-HB04 device\n");

    if (dev_handle) {
        if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
            libusb_detach_kernel_driver(dev_handle, 0);
        }

        ret = libusb_claim_interface(dev_handle, 0);
        if (ret < 0) {
            perror("libusb_claim_interface");
            return 1;
        }

        ret = libusb_set_configuration(dev_handle, 1);

        while (1) {
            ret = libusb_bulk_transfer(dev_handle, (0x01 | LIBUSB_ENDPOINT_IN), in_buf, sizeof(in_buf), &iLen, 0);

            hexdump((unsigned char*)&in_buf, iLen);
        }
        libusb_release_interface(dev_handle, 0);
        libusb_close(dev_handle);
    }

    libusb_exit(context);
}

This loops forever like I want. However, when I try to use asynchronous transfer like the below, my callback never gets called. Please help as I'm stuck with what to try next.

#include <stdio.h>
#include <libusb.h>

#define LB04_VID 4302
#define LB04_PID 60307

unsigned char in_buf[32];
libusb_device** devs;
libusb_device_handle* dev_handle;
libusb_context* context = NULL;
struct libusb_transfer* transfer_in = NULL;

int setup_asynch_transfer(libusb_device_handle* dev_handle);

void hexdump(unsigned char* data, int len)
{
    int i;

    for (i = 0; i < len; i++)
        printf("%02X ", data[i]);

    puts("\n");
}
void cb_response_in(struct libusb_transfer* transfer)
{
    printf("cb_response_in\n");
    if (transfer->actual_length > 0)
        hexdump((unsigned char*)&in_buf, transfer->actual_length);

    setup_asynch_transfer(transfer->dev_handle);
}

int setup_asynch_transfer(libusb_device_handle* dev_handle)
{
    int ret;

    printf("setup_asynch_transfer\n");

    transfer_in = libusb_alloc_transfer(0);
    libusb_fill_bulk_transfer(transfer_in, dev_handle, (0x01 | LIBUSB_ENDPOINT_IN),
        in_buf, sizeof(in_buf),
        cb_response_in, NULL, 500); // no user data

    return (ret = libusb_submit_transfer(transfer_in));
}

int main(int argc, char* argv[])
{
    size_t list;
    int ret;

    ret = libusb_init(&context);

    if (ret < 0) {
        perror("libusb_init");
        return 1;
    }

    libusb_set_option(context, LIBUSB_OPTION_MAX);
    list = libusb_get_device_list(context, &devs);
    if (list < 0) {
        perror("libusb_get_device_list");
        return 1;
    }

    dev_handle = libusb_open_device_with_vid_pid(context, LB04_VID, LB04_PID);
    libusb_free_device_list(devs, 1);

    printf("found XHC-HB04 device\n");

    if (dev_handle) {
        if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
            libusb_detach_kernel_driver(dev_handle, 0);
        }

        ret = libusb_claim_interface(dev_handle, 0);
        if (ret < 0) {
            perror("libusb_claim_interface");
            return 1;
        }

        ret = libusb_set_configuration(dev_handle, 1);

        ret = setup_asynch_transfer(dev_handle);

            // Loop forever
            while (1);

        libusb_release_interface(dev_handle, 0);
        libusb_close(dev_handle);
    }

    libusb_exit(context);
}

I made sure I could execute a bulk synchronous transfer and then converted the code to execute asynchronous transfer. I expected the callback routine to print the data and schedule another asynchronous routine while the main routine waited in a while loop forever.

I'm using libusb-1.0 and Microsoft Visual Studio Community 2022 on Windows 10.


问:
Lights pass through the objects in unity
I'm having a trouble, I'm trying to create a dark scene for my project, but, when I add lights, the lights pass through the objects, it has no sense, becouse it pass through the walls.

Light beside of an object

Light passing through the object

I tried setting my objects to static, but it is not working.

Also I tried setting Bias in my Universal Render Pipeline settings to 0, but, the same.


问:
Can we use websockets protocal in the Google Cloud run? (Not the current socket.io)
Currently, GCloud run support socket.io for bi-directional comunication. But I am looking for websockets protocal. How can we use websockets communication in the GCloud run?

I did deploy my backend app (node.js) in the Gcloud run and found that it support only socket.io, not websockets implementation.


问:
VBA Select Range Color Scale Formatting Per Row
I'm trying to make a code that will format each row individually using the first option in the color scale formatting on the selected cells. it seems to recognize the change in the cells and is pointing to the right ones as far as I can tell but it will only format the first row of the selection. does anybody know why this is happening? I'm not familiar with VBA formatting. Any help would be greatly appreciated!!</p>
```<code>Sub ColorScaleFormatPerRow()
    Dim a As Range, b As Range, i As Integer

    Set a = Selection
'    Range(a.Cells(1, 1), a.Cells(1, a.Columns.Count)).Select
    For i = 1 To a.Rows.Count
        Range(a.Cells(i, 1), a.Cells(i, a.Columns.Count)).Select
        Range("AA2").Activate
        Selection.FormatConditions.AddColorScale ColorScaleType:=3
        Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
            xlConditionValueLowestValue
        With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
            .Color = 7039480
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
            xlConditionValuePercentile
        Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
        With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
            .Color = 8711167
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
            xlConditionValueHighestValue
        With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
            .Color = 8109667
            .TintAndShade = 0
        End With
    Next i

End Sub
</code>```

Body:
I'm trying to make a code that will format each row individually using the first option in the color scale formatting on the selected cells. it seems to recognize the change in the cells and is pointing to the right ones as far as I can tell but it will only format the first row of the selection. does anybody know why this is happening? I'm not familiar with VBA formatting. Any help would be greatly appreciated!!

Sub ColorScaleFormatPerRow()
    Dim a As Range, b As Range, i As Integer

    Set a = Selection
'    Range(a.Cells(1, 1), a.Cells(1, a.Columns.Count)).Select
    For i = 1 To a.Rows.Count
        Range(a.Cells(i, 1), a.Cells(i, a.Columns.Count)).Select
        Range("AA2").Activate
        Selection.FormatConditions.AddColorScale ColorScaleType:=3
        Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
            xlConditionValueLowestValue
        With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
            .Color = 7039480
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
            xlConditionValuePercentile
        Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
        With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
            .Color = 8711167
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
            xlConditionValueHighestValue
        With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
            .Color = 8109667
            .TintAndShade = 0
        End With
    Next i

End Sub


问:
Screenshot of a Flutter WebView using JavaScript
I am trying to take a screenshot of a WebView widget, which does not support normal screenshots due to it using the PlatformView widget. It does however support using a javascript channel. I am using this JavaScript code, to take a screenshot of the document body using html2canvas.

```<code>function injectScript(uri) {
    const document = window.document;
    const script = document.createElement("script");
    script.setAttribute("src", uri);
    document.body.appendChild(script);
}

function sendScreenshot(canvas) {
  Toaster.postMessage(canvas);
}

injectScript("//html2canvas.hertzen.com/dist/html2canvas.js");

html2canvas(document.body, {
    allowTaint: true,
    useCORS: true
}).then(sendScreenshot);
</code>```

I get this error when it runs:
Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)

My javascript channel on the WebView widget looks like this:

```<code>JavascriptChannel(
                  name: "Toaster",
                  onMessageReceived: (msg) async { ... }
</code>```

Body:
I am trying to take a screenshot of a WebView widget, which does not support normal screenshots due to it using the PlatformView widget. It does however support using a javascript channel. I am using this JavaScript code, to take a screenshot of the document body using html2canvas.

function injectScript(uri) {
    const document = window.document;
    const script = document.createElement("script");
    script.setAttribute("src", uri);
    document.body.appendChild(script);
}

function sendScreenshot(canvas) {
  Toaster.postMessage(canvas);
}

injectScript("//html2canvas.hertzen.com/dist/html2canvas.js");

html2canvas(document.body, {
    allowTaint: true,
    useCORS: true
}).then(sendScreenshot);

I get this error when it runs:
Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)

My javascript channel on the WebView widget looks like this:

JavascriptChannel(
                  name: "Toaster",
                  onMessageReceived: (msg) async { ... }


问:
How do I create a pie chart in pdf with springboot?
I want to create a report that downloads pdf when clicked from the frontend and has a pie chart in this pdf. I will pull the information in the report from a different method. I need to do it with rest api. There were html and ajax codes in the examples I found, but this is too old so I'm looking for an up-to-date example. How can I do that?enter image description here</p>


问:
Determination of the main colors of the image by percentage
I have identified 8 colors: 3 from the RGB model, 4 from the CMYK model (cyan, pink, yellow and black) and white.
From the image, I need to determine what percentage of each color is contained in the image

```<code>const colors = [
     {r: 255, g: 0, b: 0, name: 'red'},
     {r: 0, g: 255, b: 0, name: 'green'},
     {r: 0, g: 0, b: 255, name: 'blue'},
     {r: 0, g: 255, b: 255, name: 'cyan'},
     {r: 255, g: 0, b: 255, name: 'pink'},
     {r: 255, g: 255, b: 0, name: 'yellow'},
     {r: 0, g: 0, b: 0, name: 'black'},
     {r: 255, g: 255, b: 255, name: 'white'}
]
</code>```

The number of colors is determined by finding the minimum discrepancy between the color of a pixel in the picture and one of the above colors:

```<code>const colorNumber = (color, pixel_rgba) => {
    const number = Math.abs(color.r - pixel_rgba.r) + Math.abs(color.g - pixel_rgba.g) + Math.abs(color.b - pixel_rgba.b)
    return number
}
</code>```

The program works fine with simple images (documents or clearly distinguishable colors), but detects too much black and white on "complex" images

Example

I understand why this is happening, but I would like to avoid it and make the definition of primary colors more "human"

Please advise the algorithm for determining the nearest color, which allows you to get rid of excess white and black

Editted:
I tried artificially increasing the color difference if it is white or black, but it seems to me that this method cannot be called good:

```<code>const colorNumber = (color, pixel_rgba) => {
    const number = Math.abs(color.r - pixel_rgba.r) + Math.abs(color.g - pixel_rgba.g) + Math.abs(color.b - pixel_rgba.b)
    return color.name === "black" || color.name === "white" ? number * 2 : number
}
</code>```

Body:
I have identified 8 colors: 3 from the RGB model, 4 from the CMYK model (cyan, pink, yellow and black) and white.
From the image, I need to determine what percentage of each color is contained in the image

const colors = [
     {r: 255, g: 0, b: 0, name: 'red'},
     {r: 0, g: 255, b: 0, name: 'green'},
     {r: 0, g: 0, b: 255, name: 'blue'},
     {r: 0, g: 255, b: 255, name: 'cyan'},
     {r: 255, g: 0, b: 255, name: 'pink'},
     {r: 255, g: 255, b: 0, name: 'yellow'},
     {r: 0, g: 0, b: 0, name: 'black'},
     {r: 255, g: 255, b: 255, name: 'white'}
]

The number of colors is determined by finding the minimum discrepancy between the color of a pixel in the picture and one of the above colors:

const colorNumber = (color, pixel_rgba) => {
    const number = Math.abs(color.r - pixel_rgba.r) + Math.abs(color.g - pixel_rgba.g) + Math.abs(color.b - pixel_rgba.b)
    return number
}

The program works fine with simple images (documents or clearly distinguishable colors), but detects too much black and white on "complex" images

Example

I understand why this is happening, but I would like to avoid it and make the definition of primary colors more "human"

Please advise the algorithm for determining the nearest color, which allows you to get rid of excess white and black

Editted:
I tried artificially increasing the color difference if it is white or black, but it seems to me that this method cannot be called good:

const colorNumber = (color, pixel_rgba) => {
    const number = Math.abs(color.r - pixel_rgba.r) + Math.abs(color.g - pixel_rgba.g) + Math.abs(color.b - pixel_rgba.b)
    return color.name === "black" || color.name === "white" ? number * 2 : number
}


问:
How can I add external python modules in runtime?
I am trying to load a torch model, in order to do this, the model .pt needs two modules.

In my code I have the following structure:

```<code>src
  __init__.py
   ....
</code>```

I am trying to add that two modules to src in runtime with sys.path.insert(0, path) but doesn't work, it only works if I copy the modules at the same level that src like

```<code>module_a
src
</code>```

the problem is that I don't want to set this code in the code base of that application I only want to load it from an external folder.

Is this possible?

Thanks

Body:
I am trying to load a torch model, in order to do this, the model .pt needs two modules.

In my code I have the following structure:

src
  __init__.py
   ....

I am trying to add that two modules to src in runtime with sys.path.insert(0, path) but doesn't work, it only works if I copy the modules at the same level that src like

module_a
src

the problem is that I don't want to set this code in the code base of that application I only want to load it from an external folder.

Is this possible?

Thanks


问:
Create WordPress post from self-hosted Gitlab Markdown page
We have a self-hosted, private Gitlab server where we are hosting some documentation in the form of markdown pages. This documentation is supposed to go on our website's (a WordPress server hosted on WP Engine) knowledge base.

I am trying to figure out if I can push the content from the markdown pages on Gitlab to our website in the form of a post. Trying to keep the documentation in sync between the two as developers and others within the organization will be updating the documentation in Gitlab and I would like it to sync back to WordPress.

I foresee a couple of potential issues:

The Gitlab server being self-hosted and private means that I can't just used a WordPress plugin to retrieve the information from the Gitlab server.

The WordPress server being hosted on WP Engine restricts what I can install on the web server's backend.

I have tried installing WP-CLI on a server where I have my local version of my Gitlab documentation repository, but I am unable to install git on the WordPress web server to establish a connection there to be able to push after pulling from Gitlab server.


问:
Is there a way to force Doxygen to show only cyclic header dependencies?
I'm using the Doxygen GUI frontend app on Windows, and for the Diagrams topic, I choose the 2 "Include dependency graphs" and "Included by dependency graphs" options under the "Use dot tool from the GraphViz package" option. However, I don't need to see everything; I'm only interested in the circular header dependencies. Is there a way to tell Doxygen to show only the dependency cycles?


问:
Where exactly in ExecutionContext closure function keeps data (variables) from external scope?
I read a lot about LexicalEnvironment, but haven't found how closure is implemented at this level.

Closure function keeps its LexicalEnvironment despite that ExecutionContext of outer function is deleted. Could you help me find out where this data is stored after outer function is executed and its context is deleted?

Any idea regarding FunctionObject, keeping several LexicalEnvironments simultaneously?
Is it possible to illustrate closure like this:

```<code>GlobalExectionContext = {
  ThisBinding: <Global Object>,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Object",
      a: < uninitialized >,
      b: < uninitialized >,
      multiply: < func >
    }
    outer: <null>
  },
  VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Object",
      c: undefined,
    }
    outer: <null>
  }
}
FunctionExectionContext = {

  ThisBinding: <Global Object>,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative",
      Arguments: {0: 20, 1: 30, length: 2},
    },
    outer: <GlobalLexicalEnvironment>
  },
VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative",
      g: undefined
    },
    outer: <GlobalLexicalEnvironment>
  }
}
</code>```

Thanks!

I read attentively ECMA Specification, watched youtube :) but the best what I found looked like this:
"When outer function is executed its context will be deleted. At the same time its LexicalEnvironment is kept as inner (closure) function has access to its variables".
or
"Even though an execution context is deleted from the stack once it has run all the codes inside, a reference to the function is alive when the original function returns a new function that uses a variable out of its scope. Then, the link to the outer function won’t be deleted until its codes are executed and completely removed from the stack. This is called Closure. Closure is a function that allows you to access the parent’s function scope, even though its execution phase is finished."
In Chrome I see Closure scope appearing during Debug.

Body:
I read a lot about LexicalEnvironment, but haven't found how closure is implemented at this level.

Closure function keeps its LexicalEnvironment despite that ExecutionContext of outer function is deleted. Could you help me find out where this data is stored after outer function is executed and its context is deleted?

Any idea regarding FunctionObject, keeping several LexicalEnvironments simultaneously?
Is it possible to illustrate closure like this:

GlobalExectionContext = {
  ThisBinding: <Global Object>,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Object",
      a: < uninitialized >,
      b: < uninitialized >,
      multiply: < func >
    }
    outer: <null>
  },
  VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Object",
      c: undefined,
    }
    outer: <null>
  }
}
FunctionExectionContext = {

  ThisBinding: <Global Object>,
  LexicalEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative",
      Arguments: {0: 20, 1: 30, length: 2},
    },
    outer: <GlobalLexicalEnvironment>
  },
VariableEnvironment: {
    EnvironmentRecord: {
      Type: "Declarative",
      g: undefined
    },
    outer: <GlobalLexicalEnvironment>
  }
}

Thanks!

I read attentively ECMA Specification, watched youtube :) but the best what I found looked like this:
"When outer function is executed its context will be deleted. At the same time its LexicalEnvironment is kept as inner (closure) function has access to its variables".
or
"Even though an execution context is deleted from the stack once it has run all the codes inside, a reference to the function is alive when the original function returns a new function that uses a variable out of its scope. Then, the link to the outer function won’t be deleted until its codes are executed and completely removed from the stack. This is called Closure. Closure is a function that allows you to access the parent’s function scope, even though its execution phase is finished."
In Chrome I see Closure scope appearing during Debug.


问:
Anyway to launch an existing installed 3rd party app on boot in an Android Emulator?
Using the stock android emulator I want to launch a 3rd party app on boot, is there anyway to do this?

Note: I dont want to use a third party app to handle this launching either.


问:
Fetching data from useeffect
After I added some logic to the server side, I don't get the result on the client side. I tested my server with postman and I'm getting the response via postman, but not with my react app, so I think it's a client side issue, and I don't know what I'm missing.

```<code>    const getData= async () => {
        const { history } = props;
        const response = await fetch('member/data');
        if (response.status === 401) {
            history.push('/unauthorized');
            setUser({ ...user, loggedIn: false })
        } else {
            const data = JSON.parse(await response.text());
            console.log(data)// prints nothing to cosole
            setLoading(false);
            setData(data.allUsers);
        }
    }

    useEffect( () => {
        getData().catch(console.error);
    }, []);
</code>```

I don't see any errors in the console, and nothing is printed to it

Server side before change:

```<code>public IActionResult Get()
{
  return Ok(new {_usersRepository.GetAll().ToList()});
}
</code>```

Server side after change:

```<code>public async Task<IActionResult> Get()
{
//getting user id from token...
   return Ok(new {await context.Users.Include(x => x.Enrolled).SingleOrDefaultAsync(x => x.Id==id)});
}
</code>```

Title: Fetching data from useeffect

Body:
After I added some logic to the server side, I don't get the result on the client side. I tested my server with postman and I'm getting the response via postman, but not with my react app, so I think it's a client side issue, and I don't know what I'm missing.

    const getData= async () => {
        const { history } = props;
        const response = await fetch('member/data');
        if (response.status === 401) {
            history.push('/unauthorized');
            setUser({ ...user, loggedIn: false })
        } else {
            const data = JSON.parse(await response.text());
            console.log(data)// prints nothing to cosole
            setLoading(false);
            setData(data.allUsers);
        }
    }

    useEffect( () => {
        getData().catch(console.error);
    }, []);

I don't see any errors in the console, and nothing is printed to it

Server side before change:

public IActionResult Get()
{
  return Ok(new {_usersRepository.GetAll().ToList()});
}

Server side after change:

public async Task<IActionResult> Get()
{
//getting user id from token...
   return Ok(new {await context.Users.Include(x => x.Enrolled).SingleOrDefaultAsync(x => x.Id==id)});
}


问:
Is there a hook that allows us to store variable thats dependent on which page is the user in
Currently I'm trying to find a way to store value (given that value is a shared variable) depending which page the user is in right now. For example
User is in page A , Value is 1
User is in page B , Value is 2</p>


问:
Pandas issue SettingWithCopyWarning
I am trying to do some simple replacements and I keep getting the dreaded copy warning.

```<code>bvr_filtered = bvr.loc[~ bvr['LOCATION'].str.endswith('NEW')]
# set LOC_TYPE to 1100 if null
bvr_filtered.loc[bvr_filtered['LOC_TYPE'].isna(), 'LOC_TYPE'] = 1100
# fix errors in OWNED_BY
owned_by = bvr_filtered.loc[:, 'OWNED_BY']
owned_by.loc[owned_by.isna()] = 'N/A'
</code>```

The line: 'owned_by.loc[owned_by.isna()] = "N/A"' is throwing the warning.
What am I doing wrong?

I looked at the Pandas documentation and tried the .loc, but it seems I am not understanding the issue.

Title: Pandas issue SettingWithCopyWarning

Body:
I am trying to do some simple replacements and I keep getting the dreaded copy warning.

bvr_filtered = bvr.loc[~ bvr['LOCATION'].str.endswith('NEW')]
# set LOC_TYPE to 1100 if null
bvr_filtered.loc[bvr_filtered['LOC_TYPE'].isna(), 'LOC_TYPE'] = 1100
# fix errors in OWNED_BY
owned_by = bvr_filtered.loc[:, 'OWNED_BY']
owned_by.loc[owned_by.isna()] = 'N/A'

The line: 'owned_by.loc[owned_by.isna()] = "N/A"' is throwing the warning.
What am I doing wrong?

I looked at the Pandas documentation and tried the .loc, but it seems I am not understanding the issue.


问:
can we get unique data from Redis to multiple instances of apps to all the apps with Python
I am trying to get data from Redis to 8 instances of the app, but the data is duplicated in each instances, I needed unique data in all the instances, Is it possible?

I am expecting unique data from the Redis to all the instances of the app.


问:
Is it possible to merge two OUs with a simple if/else to one OU?
Hello i need a advise / idea how i can solve the following problem:

I have two OUs, a primary and secondary OU, the primary OU would be filled up by a synchronisation process and in the secondary OU are entrys stored from user input via a website for temporary overwrites with a valid through timestamp.
In the client software its not possible to implement filter rules, so this must be implemented in openldap, that a search for a DN only give one result, when there is a entry in the secondary OU and the actually date is lower as the stored timestamp respond with the values from that entry. When there is no entry with that DN in the secondary OU but in the primary OU then respond the values from that entry.

Client Request for DN=ID1234
Check if DN=ID1234 in OU=secondary exists and validate current date with the validThrough Timestamp
If yes, response the values from DN=ID1234,OU=secondary
If not, check if DN=ID1234,OU=primary exists
If yes, response with this values
If not, response with nothing found

Here is a example:

```<code>DN=ID1234,OU=primary,dc=example,dc=local
> attributeX = "Blue"
DN=ID1234,OU=secondary,dc=example,dc=local
> attributeX = "Red"
> validThrough = 05.01.2023 (Human readable)
</code>```

So a response before the 05.01.23 delivers "Red" and after that date i get "Blue"

My idea was something like a third merged OU where is every time the actuall entry.

I probed to achive that with the merge backend but actually i am stuck regarding i had no idea to get a current timestamp like NOW() in sql to create a filter like that

(&(dn=<DN>)(|(!(validThroughTimestamp<=<current timestamp>))(!(validThroughTimestamp=*))))

Did anyone can advise me how to solve that, is there any overlay or has a complete other idea to reach that?

Body:
Hello i need a advise / idea how i can solve the following problem:

I have two OUs, a primary and secondary OU, the primary OU would be filled up by a synchronisation process and in the secondary OU are entrys stored from user input via a website for temporary overwrites with a valid through timestamp.
In the client software its not possible to implement filter rules, so this must be implemented in openldap, that a search for a DN only give one result, when there is a entry in the secondary OU and the actually date is lower as the stored timestamp respond with the values from that entry. When there is no entry with that DN in the secondary OU but in the primary OU then respond the values from that entry.

Client Request for DN=ID1234
Check if DN=ID1234 in OU=secondary exists and validate current date with the validThrough Timestamp
If yes, response the values from DN=ID1234,OU=secondary
If not, check if DN=ID1234,OU=primary exists
If yes, response with this values
If not, response with nothing found

Here is a example:

DN=ID1234,OU=primary,dc=example,dc=local
> attributeX = "Blue"
DN=ID1234,OU=secondary,dc=example,dc=local
> attributeX = "Red"
> validThrough = 05.01.2023 (Human readable)

So a response before the 05.01.23 delivers "Red" and after that date i get "Blue"

My idea was something like a third merged OU where is every time the actuall entry.

I probed to achive that with the merge backend but actually i am stuck regarding i had no idea to get a current timestamp like NOW() in sql to create a filter like that

(&(dn=<DN>)(|(!(validThroughTimestamp<=<current timestamp>))(!(validThroughTimestamp=*))))

Did anyone can advise me how to solve that, is there any overlay or has a complete other idea to reach that?


问:
react express auto populate a select tag using hooks
I am using React to abstract and make a custom looking and reusable  tag. I have an express call that returns a state variable. I am trying to set the state variable to the select tag as the populated value but it isn't working.

my select component...

```<code>const InputSelect = ({
  children,
  defaultVal,
  title,
  changeVal,
  name,
  isWide = false,
}) => {
  // if (defaultVal == null) {
  //   return <h1>Error: A default value is needed</h1>;
  // }
  if (title == null) {
    return <h1>Error: A title is needed</h1>;
  }
  if (changeVal == null) {
    return <h1>Error: A call back is needed</h1>;
  }
  if (children == null) {
    return <h1>Error: most have a populated list</h1>;
  }
  if (name == null) {
    return <h1>Error: most have a name</h1>;
  }
  return (
    <div className="py-4">
      <div className={`relative ${isWide ? "xl-width" : "w-60"}`}>
        <select
          defaultValue={"DEFAULT"}
          htmlFor="selector"
          name={name}
          onChange={changeVal}
          className="w-full p-2.5 border-2 border-gray-500 rounded-md outline-none text-black cursor-pointer appearance-none bg-white"
        >
          {/* //leave as the default text// */}
          <option disabled value="DEFAULT">
            {defaultVal}
          </option>
          {/* //map// */}
          {children}
          {/* //map end// */}
        </select>
        <span className="absolute bottom-9 left-2 px-1 border-l-2 border-r-2 border-white bg-white text-gray-500">
          {title}
        </span>
        {/* //down arrow// */}
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="1.5"
          stroke="currentColor"
          className="w-5 h-5 absolute right-2 top-3.5 text-gray-500 pointer-events-none"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3"
          />
        </svg>
        {/* //spacer// */}
        <div className="w-1 h-8  absolute right-7 top-2 border-l-2 border-r-6 border-l-gray-500 border-r-transparent opacity-25 pointer-events-none"></div>
      </div>
    </div>
  );
};

</code>```

created in main using

```<code>  // Cycle Type
  const [SampleData, setSampleData] = useState([
    { id: 1, value: "1", word: "Type 1" },
    { id: 2, value: "2", word: "Type 2" },
    { id: 3, value: "3", word: "Type 3" },
    { id: 4, value: "4", word: "Type 4" },
  ]);

const initValues = {
  cycleType: "",
};

  const handleChange = async (e) => {
    const { name, value } = e.target;
    setState({
      ...state,
      [name]: value,
    });
  };

 <InputSelect
              title={"Cycle type"}
              //defaultVal={"--Select a cycle type--"}
              name="cycleType"
              changeVal={handleChange}
              //value={3}
            >
              {SampleData.map((SampleData) => {
                const list = (
                  <option key={SampleData.id} value={SampleData.value}>
                    {SampleData.word}
                  </option>
                );
                return list;
              })}
            </InputSelect>
</code>```

and trying to populate it using an express call

```<code>setState({cycleType:data[0].type})
</code>```

cycleType will be set to any number 1-4. I'd like it to take that number then auto fill the field with 'type:1', 'type2'... based on the number cycleType is.

Currently cycleType works and will return 1-4, however I can't get the select field to auto populate.

Body:
I am using React to abstract and make a custom looking and reusable  tag. I have an express call that returns a state variable. I am trying to set the state variable to the select tag as the populated value but it isn't working.

my select component...

const InputSelect = ({
  children,
  defaultVal,
  title,
  changeVal,
  name,
  isWide = false,
}) => {
  // if (defaultVal == null) {
  //   return
Error: A default value is needed
;
  // }
  if (title == null) {
    return
Error: A title is needed
;
  }
  if (changeVal == null) {
    return
Error: A call back is needed
;
  }
  if (children == null) {
    return
Error: most have a populated list
;
  }
  if (name == null) {
    return
Error: most have a name
;
  }
  return (

      <div className={`relative ${isWide ? "xl-width" : "w-60"}`}>
        <select
          defaultValue={"DEFAULT"}
          htmlFor="selector"
          name={name}
          onChange={changeVal}
          className="w-full p-2.5 border-2 border-gray-500 rounded-md outline-none text-black cursor-pointer appearance-none bg-white"
        >
          {/* //leave as the default text// */}
          <option disabled value="DEFAULT">
            {defaultVal}
          </option>
          {/* //map// */}
          {children}
          {/* //map end// */}
        </select>

          {title}

        {/* //down arrow// */}
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="1.5"
          stroke="currentColor"
          className="w-5 h-5 absolute right-2 top-3.5 text-gray-500 pointer-events-none"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3"
          />
        </svg>
        {/* //spacer// */}

  );
};

created in main using

  // Cycle Type
  const [SampleData, setSampleData] = useState([
    { id: 1, value: "1", word: "Type 1" },
    { id: 2, value: "2", word: "Type 2" },
    { id: 3, value: "3", word: "Type 3" },
    { id: 4, value: "4", word: "Type 4" },
  ]);

const initValues = {
  cycleType: "",
};

  const handleChange = async (e) => {
    const { name, value } = e.target;
    setState({
      ...state,
      [name]: value,
    });
  };

 <InputSelect
              title={"Cycle type"}
              //defaultVal={"--Select a cycle type--"}
              name="cycleType"
              changeVal={handleChange}
              //value={3}
            >
              {SampleData.map((SampleData) => {
                const list = (
                  <option key={SampleData.id} value={SampleData.value}>
                    {SampleData.word}
                  </option>
                );
                return list;
              })}
            </InputSelect>

and trying to populate it using an express call

setState({cycleType:data[0].type})

cycleType will be set to any number 1-4. I'd like it to take that number then auto fill the field with 'type:1', 'type2'... based on the number cycleType is.

Currently cycleType works and will return 1-4, however I can't get the select field to auto populate.


问:
Gradle error: java.lang.ExceptionInInitializerError (no error message)
I have Gradle 3.51 installed and JDK180_351. When i run the command Gradle -v i got the error message of the title. I already double check the PATH, JAVA_HOME. I also try using the option on inteli-j "invalidate cache and restart" and rebuild my project. And the problem persists, i can't download the dependencies and Gradle are becoming a truly nightmare for me.</p>


问:
filtering rows of a data frame based on whether or not a column's content is in a list
I want to filter a data frame based on whether they are in a list or not:

```<code>my_list = [1, 2, 3]
df[df['class'] in my_list]

lib\site-packages\pandas\core\generic.py:1527, in NDFrame.__nonzero__(self)
   1525 @final
   1526 def __nonzero__(self):
-> 1527     raise ValueError(
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

</code>```

I was expecting a data frame which only has classes of my_list

Body:
I want to filter a data frame based on whether they are in a list or not:

my_list = [1, 2, 3]
df[df['class'] in my_list]

lib\site-packages\pandas\core\generic.py:1527, in NDFrame.__nonzero__(self)
   1525 @final
   1526 def __nonzero__(self):
-> 1527     raise ValueError(
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I was expecting a data frame which only has classes of my_list


问:
Why isn't this protecting the whole Excel file with a password?
I want this to save with a password that protects the whole file from being opened, but it just doesn't. I don't want to protect the structure of the sheets, I don't want to protect each sheet, I just want the file to not even open to be viewable if you don't have the password.</p>
```<code>Sub FY23_PWProtectCompFile()

Dim i As Integer
Dim chapterComp As Workbook
Dim emailList As Worksheet
Dim rng As Range
Dim pw As String
Dim chapter As String
Dim rows As Integer
Dim subj As String
Dim attachment As String
Dim chapterFile As Workbook

Set outlookapp = CreateObject("Outlook.Application")
    Set outlookmailitem = outlookapp.createitem(0)
    Set myAttachments = outlookmailitem.Attachments

Set chapterComp = Workbooks.Open("I:\Calendar 2023\2023 Budget\2023 Misc. Budget Info\blahblah.xlsm")
Set emailList = chapterComp.Sheets("EmailList")
Set rng = emailList.Range("B1:Z1000")

Workbooks.Open ("I:\Calendar 2023\2023 Budget\2023 Misc. Budget Info\blahblah.xlsm")
emailList.Activate

rows = Range("B2").End(xlDown).Row

For i = 2 To rows
    chapter = Range("B" & i).Value
    email = Range("H" & i).Value
    pw = Range("I" & i).Value

    Set chapterFile = Workbooks.Open("C:\Users\blah\Documents\Chapters\" & chapter & ".xlsx")
    Workbooks.Open ("C:\Users\blah\Documents\Chapters\" & chapter & ".xlsx")

    ActiveWorkbook.SaveAs Password:=pw

        outlookmailitem.To = email
        outlookmailitem.cc = ""
        outlookmailitem.bcc = ""
        outlookmailitem.Subject = chapter & " Compensation"
        outlookmailitem.body = "A copy of your compensation budget is attached!"

        attachment = chapterFile.Name

        myAttachments.Add (attachment)
        outlookmailitem.display
        'outlookmailitem.send

Next i

End Sub
</code>```

Body:
I want this to save with a password that protects the whole file from being opened, but it just doesn't. I don't want to protect the structure of the sheets, I don't want to protect each sheet, I just want the file to not even open to be viewable if you don't have the password.

Sub FY23_PWProtectCompFile()

Dim i As Integer
Dim chapterComp As Workbook
Dim emailList As Worksheet
Dim rng As Range
Dim pw As String
Dim chapter As String
Dim rows As Integer
Dim subj As String
Dim attachment As String
Dim chapterFile As Workbook

Set outlookapp = CreateObject("Outlook.Application")
    Set outlookmailitem = outlookapp.createitem(0)
    Set myAttachments = outlookmailitem.Attachments

Set chapterComp = Workbooks.Open("I:\Calendar 2023\2023 Budget\2023 Misc. Budget Info\blahblah.xlsm")
Set emailList = chapterComp.Sheets("EmailList")
Set rng = emailList.Range("B1:Z1000")

Workbooks.Open ("I:\Calendar 2023\2023 Budget\2023 Misc. Budget Info\blahblah.xlsm")
emailList.Activate

rows = Range("B2").End(xlDown).Row

For i = 2 To rows
    chapter = Range("B" & i).Value
    email = Range("H" & i).Value
    pw = Range("I" & i).Value

    Set chapterFile = Workbooks.Open("C:\Users\blah\Documents\Chapters\" & chapter & ".xlsx")
    Workbooks.Open ("C:\Users\blah\Documents\Chapters\" & chapter & ".xlsx")

    ActiveWorkbook.SaveAs Password:=pw

        outlookmailitem.To = email
        outlookmailitem.cc = ""
        outlookmailitem.bcc = ""
        outlookmailitem.Subject = chapter & " Compensation"
        outlookmailitem.body = "A copy of your compensation budget is attached!"

        attachment = chapterFile.Name

        myAttachments.Add (attachment)
        outlookmailitem.display
        'outlookmailitem.send

Next i

End Sub


问:
How do i get my spyder to stop giving me an error and open
Spyder will not launch no matter what i try. This is what comes upenter image description here

I have uninstalled and reinstalled spyder and anaconda multiple times but it has not helped. I have also tried upgrading and downgrading spyder. I have tried lots of solutions found on the internet as well\I did it!


问:
How to make AWS S3 replication faster
I want to back up my S3 storage to Glacier, and I set up some replication rules on the bucket. But after I check the metrics, the processing speed is 6000 objects per day which is super slow. I have 200k objects in my bucket, it may takes a month to complete replication. Is there any way can make replication faster?</p>

Title: How to make AWS S3 replication faster


问:
Unable to log into expo on Android Emulator
I've tried logging into expo on two Android emulators on my computer, but I get a mangled screen instead.  One emulator is a Pixel 6 Pro, the other is a Pixel 3a.  In both emulators everything looks normal until I click on the login button.  Here's a screenshot of the login page:

Here's a screenshot of what it looks like after I click on the login page:

I'm running

Edition Windows 11 Pro
Version 22H2
Installed on    10/5/2022
OS build    22621.963
Experience  Windows Feature Experience Pack 1000.22638.1000.0

The Expo client 2.26.6 and Node Version v18.12.1.


问:
Rabbitmq consumer not consuming messages
I have 120 kubernetes pods that connects to the same rabbitmq queue and consume messages (same python code in all).
the consumers pods triggers up when there are messages in the queue.

I have thousands of messages in the queue, but not all consumers get messages.
If I restart the pod, sometimes it starts to consume messages and sometimes it's not.

on the rabbitmq management, I see 120 active consumers with status = up. everything looks ok. but not all consumers actually work.

what can be the problem? or how can I check further?


问:
Why is self.whitecheckbox.stateChanged not working?
I am coding a simple chatbot with GUI in python (the GUI is made with pyqt5 and qt designer) and I am currently working on the settings menu. When I change the background from white to black in the settings menu and click the save button, it does not change to black. I am very frustrated with this and would greatly appreciate if anyone would care to help.

Here is my code:

```<code>import time
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtGui import QColor
import requests
from random import randint as r
from datetime import datetime

class MyGUI(QMainWindow):

    def __init__(self):
        global black
        global white
        global stngs
        stngs = 0
        super(MyGUI, self).__init__()
        uic.loadUi("ChatbotUI.ui", self)
        self.show()

        self.pushButton.clicked.connect(self.pressenter)
        self.actionClose.triggered.connect(exit)
        self.actionSettings1.triggered.connect(self.gotosettings)

    def gotosettings(self):
        global stngs
        stngs = 1
        self.close()

        try:
            black
        except Exception:
            white = 1
            black = 0

        if black == 1:
            self.setStyleSheet("background-color: black;")
            self.pushButton.setStyleSheet("background-color : white;")
            self.lineEdit.setStyleSheet("color: white;")
            self.menubar.setStyleSheet("color: white;")
            self.textBrowser.setTextColor(QColor(255, 255, 255))
        elif white == 1:
            self.setStyleSheet("background-color: white;")
            self.pushButton.setStyleSheet("background-color : white;")
            self.lineEdit.setStyleSheet("color: black;")
            self.menubar.setStyleSheet("color: black;")
            self.textBrowser.setTextColor(QColor(0, 0, 0))

    def pressenter(self):
        userinput = self.lineEdit.text()
        response = self.get_response(userinput)
        self.textBrowser.setText(response)

    def get_response(self, userinput):
        global ait_ball_ans
        ait_ball_ans = [
            "Yes",
            "No",
            "Question unclear, ask later",
            "Maybe",
            "Obviously not",
            "Of course"
        ]

        #getting ip adress of user
        def get_ip():
            response = requests.get('https://api64.ipify.org?format=json').json()
            return response["ip"]

        #getting location info of user
        ip_address = get_ip()
        response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()

        #weather api key and location info
        api_key = '14aaded169c4d6e2a5a2547d126b3f70'
        city = response.get("city") + ", " + response.get("country_code")
        qsi = userinput
        qs = qsi.lower().split()
        length = len(qs)

        if "what" in qs and ("name" in qs or "name?" in qs) and ("your" in qs or "ur" in qs) and (length == 3 or length == 4):
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif ("chatbot" in qs or "chatbot?" in qs) and ("you" in qs and "are" in qs):
            print("Yes, my name is chatbot, a language model trained by Zayan Arshad.")
            text = "Yes, my name is chatbot, a language model trained by Zayan Arshad."
        elif "is" in qs and length == 4 and "chatbot" not in qs and "name" in qs:
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif "should" and "you" and "what" and "call" in qs:
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif ("hello" in qs or "hi" in qs) or ("good" and "evening") in qs or ("good" and "morning") in qs or ("good" and "afternoon") in qs:
            print("Hello! Is there any way I can help you?")
            text = "Hello! Is there any way I can help you?"
        elif ("weather" in qs or "weather?" in qs) and ("what" in qs or "pls" in qs or "tell" in qs or "what's" in qs or "whats" in qs):
            url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
            response = requests.get(url)
            data = response.json()
            conditions = data['weather'][0]['main']
            temperature = data['main']['temp']
            temperature_celsius = temperature - 273.15
            print("The weather condition is " + conditions + " and the temprature is " + str(temperature_celsius) + " in celcius.")
            text = "The weather condition is " + conditions + " and the temprature is " + str(temperature_celsius) + " in celcius."
        elif ("time" in qs or "time?" in qs) and ("what" in qs or "pls" in qs or "tell" in qs or "what's" in qs or "whats" in qs):
            print("The time is " + str(datetime.now().time()))
            text = "The time is " + str(datetime.now().time())
        elif ("give" in qs or "tell" in qs) and ("joke" in qs or "joke!" in qs):
            response = requests.get("https://sv443.net/jokeapi/v2/joke/Any")
            data = response.json()
            if 'setup' in data:
                setup = data['setup']
                delivery = data['delivery']
                print(setup + "\n" + delivery)
                text = setup + "\n" + delivery
            else:
                joke = data['joke']
                print(joke)
        elif ("give" in qs or "tell" in qs) and "fact" in qs:
            response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en")
            data = response.json()
            fact = data['text']
            print("Your random fact is:\n" + fact)
            text = "Your random fact is:\n" + fact
        elif ("8" in qs or "eight" in qs) and ("ball" in qs or "ball," in qs):
            ans_num = r(1, 5)
            ans = ait_ball_ans[ans_num]
            print(ans)
            text = ans
        else:
            print("I'm sorry, but I am not advanced enough to answer your question or statement, a child has made me and my creator is a beginner to python and he has somehow made me. Feel free to ask me anything else or tell me something.")
            text = "I'm sorry, but I am not advanced enough to answer your question or statement, a child has made me and my creator is a beginner to python and he has somehow made me. Feel free to ask me anything else or tell me something."
        return text

class settings(QWidget):
    global stngs
    def __init__(self):
        super(settings, self).__init__()
        uic.loadUi("SettingsUI.ui", self)
        self.show()
        self.whitecheckbox.stateChanged.connect(self.check)
        self.blackcheckbox.stateChanged.connect(self.check)
        self.pushButton_2.clicked.connect(self.gotomain)

    def gotomain(self):
        global stngs
        global mn
        stngs = 0
        mn = 1
        self.close()

    def check(self):
        if self.whitecheckbox.isChecked():
            self.white

        if self.blackcheckbox.isChecked():
            self.black

    def black(self):
        global black
        global white
        black = 1
        white = 0
        self.whitecheckbox.setChecked(False)

    def white(self):
        global white
        global black
        white = 1
        black = 0
        self.blackcheckbox.setChecked(False)

def main():
    app = QApplication([])
    window = MyGUI()
    app.exec_()

    if stngs == 1:
        settingsfunc()

def settingsfunc():
    time.sleep(1)
    app = QApplication([])
    settingswindow = settings()
    app.exec_()

    if mn == 1:
        main()

if __name__ == '__main__':
    main()

</code>```

I think the reason why this is occurring is because of the code not detecting the state of the checkboxes for the background colour changing options (there is a checkbox for black and one for white) but I do not know why. Please help.

Thanks.

Body:
I am coding a simple chatbot with GUI in python (the GUI is made with pyqt5 and qt designer) and I am currently working on the settings menu. When I change the background from white to black in the settings menu and click the save button, it does not change to black. I am very frustrated with this and would greatly appreciate if anyone would care to help.

Here is my code:

import time
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtGui import QColor
import requests
from random import randint as r
from datetime import datetime

class MyGUI(QMainWindow):

    def __init__(self):
        global black
        global white
        global stngs
        stngs = 0
        super(MyGUI, self).__init__()
        uic.loadUi("ChatbotUI.ui", self)
        self.show()

        self.pushButton.clicked.connect(self.pressenter)
        self.actionClose.triggered.connect(exit)
        self.actionSettings1.triggered.connect(self.gotosettings)

    def gotosettings(self):
        global stngs
        stngs = 1
        self.close()

        try:
            black
        except Exception:
            white = 1
            black = 0

        if black == 1:
            self.setStyleSheet("background-color: black;")
            self.pushButton.setStyleSheet("background-color : white;")
            self.lineEdit.setStyleSheet("color: white;")
            self.menubar.setStyleSheet("color: white;")
            self.textBrowser.setTextColor(QColor(255, 255, 255))
        elif white == 1:
            self.setStyleSheet("background-color: white;")
            self.pushButton.setStyleSheet("background-color : white;")
            self.lineEdit.setStyleSheet("color: black;")
            self.menubar.setStyleSheet("color: black;")
            self.textBrowser.setTextColor(QColor(0, 0, 0))

    def pressenter(self):
        userinput = self.lineEdit.text()
        response = self.get_response(userinput)
        self.textBrowser.setText(response)

    def get_response(self, userinput):
        global ait_ball_ans
        ait_ball_ans = [
            "Yes",
            "No",
            "Question unclear, ask later",
            "Maybe",
            "Obviously not",
            "Of course"
        ]

        #getting ip adress of user
        def get_ip():
            response = requests.get('https://api64.ipify.org?format=json').json()
            return response["ip"]

        #getting location info of user
        ip_address = get_ip()
        response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()

        #weather api key and location info
        api_key = '14aaded169c4d6e2a5a2547d126b3f70'
        city = response.get("city") + ", " + response.get("country_code")
        qsi = userinput
        qs = qsi.lower().split()
        length = len(qs)

        if "what" in qs and ("name" in qs or "name?" in qs) and ("your" in qs or "ur" in qs) and (length == 3 or length == 4):
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif ("chatbot" in qs or "chatbot?" in qs) and ("you" in qs and "are" in qs):
            print("Yes, my name is chatbot, a language model trained by Zayan Arshad.")
            text = "Yes, my name is chatbot, a language model trained by Zayan Arshad."
        elif "is" in qs and length == 4 and "chatbot" not in qs and "name" in qs:
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif "should" and "you" and "what" and "call" in qs:
            print("My name is chatbot, and I am a language model trained by Zayan Arshad.")
            text = "My name is chatbot, and I am a language model trained by Zayan Arshad."
        elif ("hello" in qs or "hi" in qs) or ("good" and "evening") in qs or ("good" and "morning") in qs or ("good" and "afternoon") in qs:
            print("Hello! Is there any way I can help you?")
            text = "Hello! Is there any way I can help you?"
        elif ("weather" in qs or "weather?" in qs) and ("what" in qs or "pls" in qs or "tell" in qs or "what's" in qs or "whats" in qs):
            url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
            response = requests.get(url)
            data = response.json()
            conditions = data['weather'][0]['main']
            temperature = data['main']['temp']
            temperature_celsius = temperature - 273.15
            print("The weather condition is " + conditions + " and the temprature is " + str(temperature_celsius) + " in celcius.")
            text = "The weather condition is " + conditions + " and the temprature is " + str(temperature_celsius) + " in celcius."
        elif ("time" in qs or "time?" in qs) and ("what" in qs or "pls" in qs or "tell" in qs or "what's" in qs or "whats" in qs):
            print("The time is " + str(datetime.now().time()))
            text = "The time is " + str(datetime.now().time())
        elif ("give" in qs or "tell" in qs) and ("joke" in qs or "joke!" in qs):
            response = requests.get("https://sv443.net/jokeapi/v2/joke/Any")
            data = response.json()
            if 'setup' in data:
                setup = data['setup']
                delivery = data['delivery']
                print(setup + "\n" + delivery)
                text = setup + "\n" + delivery
            else:
                joke = data['joke']
                print(joke)
        elif ("give" in qs or "tell" in qs) and "fact" in qs:
            response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en")
            data = response.json()
            fact = data['text']
            print("Your random fact is:\n" + fact)
            text = "Your random fact is:\n" + fact
        elif ("8" in qs or "eight" in qs) and ("ball" in qs or "ball," in qs):
            ans_num = r(1, 5)
            ans = ait_ball_ans[ans_num]
            print(ans)
            text = ans
        else:
            print("I'm sorry, but I am not advanced enough to answer your question or statement, a child has made me and my creator is a beginner to python and he has somehow made me. Feel free to ask me anything else or tell me something.")
            text = "I'm sorry, but I am not advanced enough to answer your question or statement, a child has made me and my creator is a beginner to python and he has somehow made me. Feel free to ask me anything else or tell me something."
        return text

class settings(QWidget):
    global stngs
    def __init__(self):
        super(settings, self).__init__()
        uic.loadUi("SettingsUI.ui", self)
        self.show()
        self.whitecheckbox.stateChanged.connect(self.check)
        self.blackcheckbox.stateChanged.connect(self.check)
        self.pushButton_2.clicked.connect(self.gotomain)

    def gotomain(self):
        global stngs
        global mn
        stngs = 0
        mn = 1
        self.close()

    def check(self):
        if self.whitecheckbox.isChecked():
            self.white

        if self.blackcheckbox.isChecked():
            self.black

    def black(self):
        global black
        global white
        black = 1
        white = 0
        self.whitecheckbox.setChecked(False)

    def white(self):
        global white
        global black
        white = 1
        black = 0
        self.blackcheckbox.setChecked(False)

def main():
    app = QApplication([])
    window = MyGUI()
    app.exec_()

    if stngs == 1:
        settingsfunc()

def settingsfunc():
    time.sleep(1)
    app = QApplication([])
    settingswindow = settings()
    app.exec_()

    if mn == 1:
        main()

if __name__ == '__main__':
    main()

I think the reason why this is occurring is because of the code not detecting the state of the checkboxes for the background colour changing options (there is a checkbox for black and one for white) but I do not know why. Please help.

Thanks.


问:
How to access webhook event data in Terraform aws_codepipeline configuration?
I have a Terraform configuration that creates a github_repository_webhook and an aws_codepipeline_webhook, and sets up an aws_codepipeline with a source stage that retrieves code from a GitHub repository. The github_repository_webhook is configured to trigger a push event, and the aws_codepipeline_webhook filters for JSON path $.ref with a match of refs/heads/(.*).

I want to capture the branch name from the webhook event and use it in the aws_codepipeline configuration for the Branch field in the source stage action. However, I am not sure how to access the webhook event data to retrieve the branch name.

Is there a way to access the webhook event data and use it to set the Branch field in the aws_codepipeline configuration?

Code sample below:

```<code>resource "github_repository_webhook" "source_webhook" {
  repository = var.source_repo

  configuration {
    url          = aws_codepipeline_webhook.codepipeline_source_webhook.url
    content_type = "json"
    insecure_ssl = false
    secret       = var.webhook_secret
  }

  events = ["push"]
}

resource "aws_codepipeline_webhook" "codepipeline_source_webhook" {
  name            = "my-project-webhook"
  authentication  = "GITHUB_HMAC"
  target_pipeline = aws_codepipeline.codepipeline.name
  target_action   = "Source"

  authentication_configuration {
    secret_token = var.webhook_secret
  }

  filter {
    json_path    = "$.ref"
    match_equals = "refs/heads/(.*)"
  }
}

resource "aws_codepipeline" "codepipeline" {
  name     = "my-project-pipeline"
  role_arn = aws_iam_role.codepipeline_role.arn

  artifact_store {
    location = aws_s3_bucket.my-project_codepipeline_bucket.bucket
    type     = "S3"
  }

  stage {
    name = "my-project-pipeline-source"

    action {
      name             = "Source"
      category         = "Source"
      owner            = "ThirdParty"
      provider         = "GitHub"
      version          = "1"
      run_order        = 1
      output_artifacts = ["source_output"]

      configuration = {
        Repo       = var.source_repo
        Branch     = var.source_branch
        OAuthToken = var.source_token
        Owner      = var.source_owner
      }
    }
  }

  stage {
    name = "my-project-pipeline-test"

    action {
      name             = "Test"
      category         = "Test"
      owner            = "AWS"
      provider         = "CodeBuild"
      version          = "1"
      input_artifacts  = ["source_output"]
      output_artifacts = ["test_output"]

      configuration = {
        ProjectName = "my-project-tests"
      }
    }
  }
}
</code>```

Body:
I have a Terraform configuration that creates a github_repository_webhook and an aws_codepipeline_webhook, and sets up an aws_codepipeline with a source stage that retrieves code from a GitHub repository. The github_repository_webhook is configured to trigger a push event, and the aws_codepipeline_webhook filters for JSON path $.ref with a match of refs/heads/(.*).

I want to capture the branch name from the webhook event and use it in the aws_codepipeline configuration for the Branch field in the source stage action. However, I am not sure how to access the webhook event data to retrieve the branch name.

Is there a way to access the webhook event data and use it to set the Branch field in the aws_codepipeline configuration?

Code sample below:

resource "github_repository_webhook" "source_webhook" {
  repository = var.source_repo

  configuration {
    url          = aws_codepipeline_webhook.codepipeline_source_webhook.url
    content_type = "json"
    insecure_ssl = false
    secret       = var.webhook_secret
  }

  events = ["push"]
}

resource "aws_codepipeline_webhook" "codepipeline_source_webhook" {
  name            = "my-project-webhook"
  authentication  = "GITHUB_HMAC"
  target_pipeline = aws_codepipeline.codepipeline.name
  target_action   = "Source"

  authentication_configuration {
    secret_token = var.webhook_secret
  }

  filter {
    json_path    = "$.ref"
    match_equals = "refs/heads/(.*)"
  }
}

resource "aws_codepipeline" "codepipeline" {
  name     = "my-project-pipeline"
  role_arn = aws_iam_role.codepipeline_role.arn

  artifact_store {
    location = aws_s3_bucket.my-project_codepipeline_bucket.bucket
    type     = "S3"
  }

  stage {
    name = "my-project-pipeline-source"

    action {
      name             = "Source"
      category         = "Source"
      owner            = "ThirdParty"
      provider         = "GitHub"
      version          = "1"
      run_order        = 1
      output_artifacts = ["source_output"]

      configuration = {
        Repo       = var.source_repo
        Branch     = var.source_branch
        OAuthToken = var.source_token
        Owner      = var.source_owner
      }
    }
  }

  stage {
    name = "my-project-pipeline-test"

    action {
      name             = "Test"
      category         = "Test"
      owner            = "AWS"
      provider         = "CodeBuild"
      version          = "1"
      input_artifacts  = ["source_output"]
      output_artifacts = ["test_output"]

      configuration = {
        ProjectName = "my-project-tests"
      }
    }
  }
}


问:
Cannot use unisharp/laravel-filemanager's latest version v2.5.1 as it requires ext-exif * which is missing from your platform
this is my first time using unisharp, i don't know how to upgrade it also i can't seems to find lfm config, i found some solution in the internet which is change it from ^1.8 to the latest version which is did also it says that i should check in my LFM config file and set 'use_package_routes' => true, but i don't know where it is and i have my exif extension enabled in my php.ini too.

here is my composer.json

`

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/tinker": "^2.7",
        "laravel/ui": "^4.1",
        "unisharp/laravel-filemanager": "^1.8"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

</code>```

`

Body:
this is my first time using unisharp, i don't know how to upgrade it also i can't seems to find lfm config, i found some solution in the internet which is change it from ^1.8 to the latest version which is did also it says that i should check in my LFM config file and set 'use_package_routes' => true, but i don't know where it is and i have my exif extension enabled in my php.ini too.

here is my composer.json

`

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/tinker": "^2.7",
        "laravel/ui": "^4.1",
        "unisharp/laravel-filemanager": "^1.8"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

`