问:
Drawer animation in React Native
I am trying to make a drawer animation like the one in this image using the useDrawerProgress function but I keep on getting this error:

Here is my code:

```<code>const Drawer = createDrawerNavigator();

const DrawerScreenContainer = ({children}) => {
    const progress = useDrawerProgress();

    const scale = Animated.interpolateNode(progress, {
      inputRange: [0, 1],
      outputRange: [1, 0.8],
    });
    const borderRadius = Animated.interpolateNode(progress, {
      inputRange: [0, 1],
      outputRange: [0, 25],
    });
    return (
      <Animated.View
        style={{
          flex: 1,
          backgroundColor: COLORS.white,
          borderRadius,
          transform: [{scale}],
          overflow: 'hidden',
        }}>
        {children}
      </Animated.View>
    );
  };

</code>```

And this is the package.json

```<code>{
  "name": "eats",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-navigation/drawer": "^6.5.6",
    "@react-navigation/native": "^6.1.1",
    "expo": "~47.0.9",
    "expo-status-bar": "~1.4.2",
    "react": "18.1.0",
    "react-native": "0.70.5",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "4.4.1",
    "react-native-screens": "~3.18.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

</code>```

How do I solve this?

Many thanks...

Title: Drawer animation in React Native

Body:
I am trying to make a drawer animation like the one in this image using the useDrawerProgress function but I keep on getting this error:

Here is my code:

const Drawer = createDrawerNavigator();

const DrawerScreenContainer = ({children}) => {
    const progress = useDrawerProgress();

    const scale = Animated.interpolateNode(progress, {
      inputRange: [0, 1],
      outputRange: [1, 0.8],
    });
    const borderRadius = Animated.interpolateNode(progress, {
      inputRange: [0, 1],
      outputRange: [0, 25],
    });
    return (
      <Animated.View
        style={{
          flex: 1,
          backgroundColor: COLORS.white,
          borderRadius,
          transform: [{scale}],
          overflow: 'hidden',
        }}>
        {children}
      </Animated.View>
    );
  };

And this is the package.json

{
  "name": "eats",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-navigation/drawer": "^6.5.6",
    "@react-navigation/native": "^6.1.1",
    "expo": "~47.0.9",
    "expo-status-bar": "~1.4.2",
    "react": "18.1.0",
    "react-native": "0.70.5",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "4.4.1",
    "react-native-screens": "~3.18.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

How do I solve this?

Many thanks...


来源: stackexchange

问:
'Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' that could not be found.'
This is User class, which serves as the Entity.

```<code>package com.userproject.Entities;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "userservice")
public class User {

@Id
@Column(name="userID")
int userId;

@Column(name="username")
String username;

@Column(name="age")
int age;

public User(int userId, String username, int age) {
    super();
    this.userId = userId;
    this.username = username;
    this.age = age;
}

public User() {
    super();
    // TODO Auto-generated constructor stub
}

@Override
public String toString() {
    return "User [userId=" + userId + ", username=" + username + ", age=" + age + "]";
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}
</code>```

This is my repository interface

```<code>package com.userproject.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.userproject.Entities.User;

public interface UserRepository extends JpaRepository<User, Integer> {

public User findById(int id);

}
</code>```

This is my Service class

```<code>package com.userproject.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.userproject.Entities.User;
import com.userproject.dao.UserRepository;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public User addUser(User usr) {
    User savedUser = this.userRepository.save(usr);
    return savedUser;
}

public List<User> getAllInfo(){
    Iterable<User> allUsers = this.userRepository.findAll();
    return (List<User>)allUsers;
}

public User getUser(int usrId) {
    User usr = this.userRepository.findById(usrId);
    if (usr == null)
        throw new NullPointerException();
    return usr;
}

}
</code>```

This is my Controller

```<code>package com.userproject.Controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.userproject.Entities.User;
import com.userproject.Service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService service;

@PostMapping("/add")
public ResponseEntity<User> addUser(@RequestBody User u){
    try {
        User addUser = this.service.addUser(u);
        return ResponseEntity.ok(addUser);
    } catch(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") int userID){
    try {
        User u = this.service.getUser(userID);
        return ResponseEntity.ok(u);
    } catch(NullPointerException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

@GetMapping("/all")
public ResponseEntity<List<User>> getAllUsers(){
    try {
        return ResponseEntity.ok(this.service.getAllInfo());
    } catch(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

}
</code>```

This is my main application class

```<code>package com.userproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories("com.userproject.dao")
@SpringBootApplication(exclude =  {DataSourceAutoConfiguration.class })
public class UserProjectApplication {

public static void main(String[] args) {
 SpringApplication.run(UserProjectApplication.class, args);

}

}
</code>```

This is application.properties file

```<code>spring.jpa.database=mysql
spring.datasource.username=*****
spring.datasource.password=*****
spring.datasource.url=jdbc:mysql://*******:3306/practice
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.jooq.sql-dialect = org.hibernate.dialect.MySQL57Dialect
spring.jpa.hibernate.ddl-auto= update
</code>```

This is my project structure:
(https://i.stack.imgur.com/UR10B.png)

When I try to run the application, I keep getting the following message: `

```<code>Description:

Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
</code>```

If I remove the "exclude" parameter from @SpringBootApplication, it throws an error stating the datasource cannot be configured as the url is missing.
If I remove the @EnableJpaRepositories, it throws an error stating my userRepository field in Service class cannot be configured.

From what I understand, this whole problem arises from me trying to autowire the userRepository field (which is actually an interface) in the Service class. However, SpringBoot shall be able to do that with the help of proxy classes.

Please provide me with a solution to this.

ContentLicense: CC BY-SA 4.0

Body:
This is User class, which serves as the Entity.

package com.userproject.Entities;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "userservice")
public class User {

@Id
@Column(name="userID")
int userId;

@Column(name="username")
String username;

@Column(name="age")
int age;

public User(int userId, String username, int age) {
    super();
    this.userId = userId;
    this.username = username;
    this.age = age;
}

public User() {
    super();
    // TODO Auto-generated constructor stub
}

@Override
public String toString() {
    return "User [userId=" + userId + ", username=" + username + ", age=" + age + "]";
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}

This is my repository interface

package com.userproject.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.userproject.Entities.User;

public interface UserRepository extends JpaRepository<User, Integer> {

public User findById(int id);

}

This is my Service class

package com.userproject.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.userproject.Entities.User;
import com.userproject.dao.UserRepository;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public User addUser(User usr) {
    User savedUser = this.userRepository.save(usr);
    return savedUser;
}

public List<User> getAllInfo(){
    Iterable<User> allUsers = this.userRepository.findAll();
    return (List<User>)allUsers;
}

public User getUser(int usrId) {
    User usr = this.userRepository.findById(usrId);
    if (usr == null)
        throw new NullPointerException();
    return usr;
}

}

This is my Controller

package com.userproject.Controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.userproject.Entities.User;
import com.userproject.Service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService service;

@PostMapping("/add")
public ResponseEntity<User> addUser(@RequestBody User u){
    try {
        User addUser = this.service.addUser(u);
        return ResponseEntity.ok(addUser);
    } catch(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") int userID){
    try {
        User u = this.service.getUser(userID);
        return ResponseEntity.ok(u);
    } catch(NullPointerException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

@GetMapping("/all")
public ResponseEntity<List<User>> getAllUsers(){
    try {
        return ResponseEntity.ok(this.service.getAllInfo());
    } catch(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

}

This is my main application class

package com.userproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories("com.userproject.dao")
@SpringBootApplication(exclude =  {DataSourceAutoConfiguration.class })
public class UserProjectApplication {

public static void main(String[] args) {
 SpringApplication.run(UserProjectApplication.class, args);

}

}

This is application.properties file

spring.jpa.database=mysql
spring.datasource.username=*****
spring.datasource.password=*****
spring.datasource.url=jdbc:mysql://*******:3306/practice
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.jooq.sql-dialect = org.hibernate.dialect.MySQL57Dialect
spring.jpa.hibernate.ddl-auto= update

This is my project structure:
(https://i.stack.imgur.com/UR10B.png)

When I try to run the application, I keep getting the following message: `

Description:

Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

If I remove the "exclude" parameter from @SpringBootApplication, it throws an error stating the datasource cannot be configured as the url is missing.
If I remove the @EnableJpaRepositories, it throws an error stating my userRepository field in Service class cannot be configured.

From what I understand, this whole problem arises from me trying to autowire the userRepository field (which is actually an interface) in the Service class. However, SpringBoot shall be able to do that with the help of proxy classes.

Please provide me with a solution to this.


问:
Set Cookie value when link is clicked in Razor Pages
In a NET Core 7 using Razor Pages I have a HeaderViewComponent:

```<code>public class HeaderViewComponent : ViewComponent {

  public HeaderViewComponent() { }

  public IViewComponentResult Invoke() {
    return View();
  }

}
</code>```

Where part of the HTML is:

```<code> <ul>
   @foreach (String culture in cultures) {
     <li>
       <a href='@Url.RouteUrl(new RouteValueDictionary { { "culture", @culture } })'>@culture</a>
     </li>
   }
</ul>
</code>```

I have this View Component in all my Razor Pages.

When one of the links is clicked I want more than redirect.

I also need to set the value of a cookie named "Culture".

What would be the best way to do this?

Body:
In a NET Core 7 using Razor Pages I have a HeaderViewComponent:

public class HeaderViewComponent : ViewComponent {

  public HeaderViewComponent() { }

  public IViewComponentResult Invoke() {
    return View();
  }

}

Where part of the HTML is:

   @foreach (String culture in cultures) {

       @culture

   }

I have this View Component in all my Razor Pages.

When one of the links is clicked I want more than redirect.

I also need to set the value of a cookie named "Culture".

What would be the best way to do this?


问:
What will be the best practice to create call requests to a group of users in the most optimal order
So I have a call queue flow in our app, on incoming call the caller is put in queue based on the  verb and then I call to a group of users who needs to get this call using the Twilio REST api for creating calls.Once a user answers the call the Twiml that is returned from the url attribute on the call request returns  and he is connected to the first one in queue.

Because of the CPS limit I need to make sure the order in which I'm making the calls is optimal because the ones who I call last will have delay.The first thing I realized I can do is to just shuffle the array of the users im calling to so statistically the chance of someone who already is on a call to get the call will be lower and this will reduce the chance of the account to feel that delay.

the second thing I want to do is to give priority to the ones who are not in a call, is there a best practice of achieving this? is the Twilio task router can help me with that?

tried to read task router documentation but not sure how this can help me, felt like using it will make the implementation much more complicated.


问:
create a folder and folder inside it but getting a PermissionError: [Errno 13] Permission denied
I am trying to create a folder and a folder inside it but Permission is denied everytime not matter what mode I use (tried 0o777, 0o770 etc.). I am working inside a Docker container if that matters.

This is my code:

```<code>for tenant in get_tenants:
    os.chdir(conf_path)
    for file_fn in glob.glob("*.conf"):
        file = (file_fn.rsplit(".", 1)[0].split("-"))[0].upper()
        if file == tenant["name"]:
            with open(file_fn, 'r') as f:
                contents = f.read()
                job_name = re.search(r'Jobs = (.*)', contents).group(1)
                mkdir_with_mode(f"/var/lib/connects/state/{tenant}/{job_name}", 0o777)
</code>```

I have tried to unmask as seen in similar examples but it didn't help:

```<code>def mkdir_with_mode(directory, mode):
  if not os.path.isdir(directory):
    oldmask = os.umask(000)
    os.makedirs(directory, mode)
    os.umask(oldmask)
</code>```

Any ideas? Thank you for your help!

Body:
I am trying to create a folder and a folder inside it but Permission is denied everytime not matter what mode I use (tried 0o777, 0o770 etc.). I am working inside a Docker container if that matters.

This is my code:

for tenant in get_tenants:
    os.chdir(conf_path)
    for file_fn in glob.glob("*.conf"):
        file = (file_fn.rsplit(".", 1)[0].split("-"))[0].upper()
        if file == tenant["name"]:
            with open(file_fn, 'r') as f:
                contents = f.read()
                job_name = re.search(r'Jobs = (.*)', contents).group(1)
                mkdir_with_mode(f"/var/lib/connects/state/{tenant}/{job_name}", 0o777)

I have tried to unmask as seen in similar examples but it didn't help:

def mkdir_with_mode(directory, mode):
  if not os.path.isdir(directory):
    oldmask = os.umask(000)
    os.makedirs(directory, mode)
    os.umask(oldmask)

Any ideas? Thank you for your help!


问:
Creating a vector from input numbers in assembly at&t
Lets say I have the next numbers given as input:
1
4
3
5
10
And I want to create a vector v that contains this numbers.
I wrote the next code:

```<code>.data
    v: .space 128 # v=the space I gave for the vector
    N: .space 4 #N= the numbers from the input
    n: .space 4 #n= the number of the numbers given as input
    indexV: .space 4
    index: .space 4
    formatScanf: .asciz "%ld"
    formatPrintf: .asciz "%ld "
.text
.global main
main:

    pushl $n
    pushl $formatScanf
    call scanf
    popl %ebx
    popl %ebx

lea v, %edi
movl $0, indexV
et_vector:

        movl indexV, %ecx
        cmp %ecx, n
        je et_print

        pushl $N
        pushl $formatScanf
        call scanf
        popl %ebx
        popl %ebx

        movl $N, (%edi, %ecx, 4)
        incl indexV

    jmp et_vector

movl $0, index
et_print:
movl index, %ecx
cmp %ecx, n
je et_exit
lea v, %edi
movl (%edi, %ecx, 4), %ebx

pushl %ebx
pushl $formatPrintf
call printf
popl %ebx
popl %ebx
pushl $0
call fflush
popl %ebx
incl index
jmp et_print

et_exit:
movl $1, %eax
movl $0, %ebx
int $0x80
</code>```

It gives the next error: "Segmentation fault (core dumped)"
I am not sure how to create the vector.
Could u tell me if it's at least somewhat correct?
Or if u have a solution that works.

I tried to allocate a space for the vector in edi then insert the numbers given as input then print the vector.

Body:
Lets say I have the next numbers given as input:
1
4
3
5
10
And I want to create a vector v that contains this numbers.
I wrote the next code:

.data
    v: .space 128 # v=the space I gave for the vector
    N: .space 4 #N= the numbers from the input
    n: .space 4 #n= the number of the numbers given as input
    indexV: .space 4
    index: .space 4
    formatScanf: .asciz "%ld"
    formatPrintf: .asciz "%ld "
.text
.global main
main:

    pushl $n
    pushl $formatScanf
    call scanf
    popl %ebx
    popl %ebx

lea v, %edi
movl $0, indexV
et_vector:

        movl indexV, %ecx
        cmp %ecx, n
        je et_print

        pushl $N
        pushl $formatScanf
        call scanf
        popl %ebx
        popl %ebx

        movl $N, (%edi, %ecx, 4)
        incl indexV

    jmp et_vector

movl $0, index
et_print:
movl index, %ecx
cmp %ecx, n
je et_exit
lea v, %edi
movl (%edi, %ecx, 4), %ebx

pushl %ebx
pushl $formatPrintf
call printf
popl %ebx
popl %ebx
pushl $0
call fflush
popl %ebx
incl index
jmp et_print

et_exit:
movl $1, %eax
movl $0, %ebx
int $0x80

It gives the next error: "Segmentation fault (core dumped)"
I am not sure how to create the vector.
Could u tell me if it's at least somewhat correct?
Or if u have a solution that works.

I tried to allocate a space for the vector in edi then insert the numbers given as input then print the vector.


问:
Modularized App and Global State (Android Compose)
I am following the Now In Android sample for modularization and best practices with Jetpack Compose and I am a bit stuck with sharing a simple LocalDate state across several modules/features.

I want to be able to change a selected date in several places, and update the UI accordingly in several places (i.e. AppState, BottomSheet (BottomSheetState), Screen A (Viewmodel) / Screen B (Viewmodel), Dialog (if opened), etc.).

Now considering concepts like Ownership and Encapsulation, I am not sure which would be the preferred way to handle this. Or how I should rethink the logic.

So far I tried:

Hoisting the state in AppState and passing it onto Composables below;

Problem here was that I cannot pass the stateflow on to the VMs due to DI with hiltViewModel() and Compose Navigation. (Example of implementation:)

@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun ScreenARoute(viewModel: ScreenAViewModel = hiltViewModel()) {
ScreenA(/***/)
}
```
<pre class="lang-kt prettyprint-override"><code>@HiltViewModel
class ScreenAViewModel @Inject constructor(
    private val userPrefsRepository: UserPrefsRepository,
) : ViewModel() {
/***/
}
</code>```

Using SavedStateHolder in ViewModels, including the MainActivityViewmodel where the date should be initialized (today);

Problem here was that the state was only updated in the respective VM/SavedStateHolder and not across all places. For example I was able to update the date and state in Screen A and the UI got updated accordingly, other places/screens remained without updates though. (Example of implementation:)

@HiltViewModel
class ScreenAViewModel @Inject constructor(
    private val userPrefsRepository: UserPrefsRepository,
    val savedStateHandle: SavedStateHandle,
) : ViewModel() {
/***/

    val selectedDate: StateFlow<LocalDate> =
        savedStateHandle.getStateFlow<LocalDate>(SELECTED_DATE_SAVED_STATE_KEY, LocalDate.now())
            .stateIn(
                viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = LocalDate.now()
            )

    fun updateSelectedDate(date: LocalDate) {
        savedStateHandle[SELECTED_DATE_SAVED_STATE_KEY] = newDate
/***/
}

```

Other things I am considering:

Creating a Singleton object that holds the state, which is initialized in the MainActivityViewModel and implemented in the VMs via hilt DI.

Using Room or Preferences to save the state and share across the app per Singleton Repository and DI. But this might be overkill?

The state should survive configuration changes but can be disposed when the app gets killed. Any help will be much appreciated.

Body:
I am following the Now In Android sample for modularization and best practices with Jetpack Compose and I am a bit stuck with sharing a simple LocalDate state across several modules/features.

I want to be able to change a selected date in several places, and update the UI accordingly in several places (i.e. AppState, BottomSheet (BottomSheetState), Screen A (Viewmodel) / Screen B (Viewmodel), Dialog (if opened), etc.).

Now considering concepts like Ownership and Encapsulation, I am not sure which would be the preferred way to handle this. Or how I should rethink the logic.

So far I tried:

Hoisting the state in AppState and passing it onto Composables below;

Problem here was that I cannot pass the stateflow on to the VMs due to DI with hiltViewModel() and Compose Navigation. (Example of implementation:)

@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun ScreenARoute(viewModel: ScreenAViewModel = hiltViewModel()) {
ScreenA(/***/)
}

@HiltViewModel
class ScreenAViewModel @Inject constructor(
    private val userPrefsRepository: UserPrefsRepository,
) : ViewModel() {
/***/
}

Using SavedStateHolder in ViewModels, including the MainActivityViewmodel where the date should be initialized (today);

Problem here was that the state was only updated in the respective VM/SavedStateHolder and not across all places. For example I was able to update the date and state in Screen A and the UI got updated accordingly, other places/screens remained without updates though. (Example of implementation:)

@HiltViewModel
class ScreenAViewModel @Inject constructor(
    private val userPrefsRepository: UserPrefsRepository,
    val savedStateHandle: SavedStateHandle,
) : ViewModel() {
/***/

    val selectedDate: StateFlow<LocalDate> =
        savedStateHandle.getStateFlow<LocalDate>(SELECTED_DATE_SAVED_STATE_KEY, LocalDate.now())
            .stateIn(
                viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = LocalDate.now()
            )

    fun updateSelectedDate(date: LocalDate) {
        savedStateHandle[SELECTED_DATE_SAVED_STATE_KEY] = newDate
/***/
}

Other things I am considering:

Creating a Singleton object that holds the state, which is initialized in the MainActivityViewModel and implemented in the VMs via hilt DI.

Using Room or Preferences to save the state and share across the app per Singleton Repository and DI. But this might be overkill?

The state should survive configuration changes but can be disposed when the app gets killed. Any help will be much appreciated.


问:
Is it possible to make angular server to server requests?
I have an angular application deployed, but when it creates requests it makes all petitions from client to server api's, that is not desirable because it forces me to publish to internet the api server ports

Is it possible to make all petitions internal ?


问:
getting error: subprocess-exited-with-error when dockerizing my project for the package reportlab, but this is not added in my requirements.txt
getting the following error when dockerizing my project this is the error message

```<code>Collecting reportlab>=3.3.0
  Downloading reportlab-3.6.12.tar.gz (4.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 3.1 MB/s eta 0:00:00
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [10 lines of output]
      ##### setup-python-3.10.6-linux-x86_64: ================================================
      ##### setup-python-3.10.6-linux-x86_64: Attempting build of _rl_accel
      ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/rl_accel'
      ##### setup-python-3.10.6-linux-x86_64: ================================================
      ##### setup-python-3.10.6-linux-x86_64: ===================================================
      ##### setup-python-3.10.6-linux-x86_64: Attempting build of _renderPM
      ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/renderPM'
      ##### setup-python-3.10.6-linux-x86_64: ===================================================
      ##### setup-python-3.10.6-linux-x86_64: will use package libart 2.3.21
      !!!!! cannot find ft2build.h
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1
ERROR: Service 'demo_project' failed to build : Build failed

</code>```

this is my requirements.txt file'

```<code>celery==5.2.7
channels==3.0.4
Django==3.2.11
django-celery-beat==2.2.1
django-celery-results==2.3.1
django-environ==0.9.0
django-filter==21.1
Pillow==9.0.1
psycopg2-binary==2.9.3
pyotp==2.6.0
razorpay==1.3.0
redis==4.4.0
xhtml2pdf==0.2.5
</code>```

and this is my dockerfile

```<code>FROM python:3.10.6-alpine
ENV PYTHONUNBUFFERED 1
WORKDIR /demo_project

COPY ./requirements.txt ./requirements.txt

RUN pip install --upgrade pip wheel setuptools
RUN apk add gcc python3-dev jpeg-dev zlib-dev gpgme-dev libc-dev musl-dev g++

RUN pip install -r requirements.txt

COPY ./demo_project /demo_project
</code>```

I am new to docker please let me know whats missing or need to be changed

I tried to dockerize my project and I expected it to run correctly and get the url in the browser, but when I am running it in docker the requirements are not installing correctly.

Body:
getting the following error when dockerizing my project this is the error message

Collecting reportlab>=3.3.0
  Downloading reportlab-3.6.12.tar.gz (4.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 3.1 MB/s eta 0:00:00
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [10 lines of output]
      ##### setup-python-3.10.6-linux-x86_64: ================================================
      ##### setup-python-3.10.6-linux-x86_64: Attempting build of _rl_accel
      ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/rl_accel'
      ##### setup-python-3.10.6-linux-x86_64: ================================================
      ##### setup-python-3.10.6-linux-x86_64: ===================================================
      ##### setup-python-3.10.6-linux-x86_64: Attempting build of _renderPM
      ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/renderPM'
      ##### setup-python-3.10.6-linux-x86_64: ===================================================
      ##### setup-python-3.10.6-linux-x86_64: will use package libart 2.3.21
      !!!!! cannot find ft2build.h
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1
ERROR: Service 'demo_project' failed to build : Build failed

this is my requirements.txt file'

celery==5.2.7
channels==3.0.4
Django==3.2.11
django-celery-beat==2.2.1
django-celery-results==2.3.1
django-environ==0.9.0
django-filter==21.1
Pillow==9.0.1
psycopg2-binary==2.9.3
pyotp==2.6.0
razorpay==1.3.0
redis==4.4.0
xhtml2pdf==0.2.5

and this is my dockerfile

FROM python:3.10.6-alpine
ENV PYTHONUNBUFFERED 1
WORKDIR /demo_project

COPY ./requirements.txt ./requirements.txt

RUN pip install --upgrade pip wheel setuptools
RUN apk add gcc python3-dev jpeg-dev zlib-dev gpgme-dev libc-dev musl-dev g++

RUN pip install -r requirements.txt

COPY ./demo_project /demo_project

I am new to docker please let me know whats missing or need to be changed

I tried to dockerize my project and I expected it to run correctly and get the url in the browser, but when I am running it in docker the requirements are not installing correctly.


问:
how the use of cin.ignore and getline should be
```<code>#include <iostream>
using namespace std;

int main () {
        int pemboking, kode_lap[8], durasi[8];
        string nama[8], tanggal[8], jam[8];
        cout << "\nMasukan jumlah pembooking : ";
        cin >> pemboking;
        cout << endl;
        for (int i = 0; i < pemboking; i++) {
            cout << "Transaksi ke " << i + 1 << endl;
            cout << "Masukan Nama            : ";
            getline(cin, nama[i]);
            cout << "Masukan Kode Lapangan   : ";
            cin >> kode_lap[i];
            cout << "Masukan Tanggal Sewa    : ";
            cin >> tanggal[i];
            cout << "Masukan Jam main        : ";
            getline(cin, jam[i]);
            cout << "Masukan Durasi Jam Main : ";
            cin >> durasi[i];
            cout << endl;
            cout << endl;
        }
}
</code>```

when I use cin.ignore, the error will go directly to the input with index 1, index 0 is missed. if you don't use cin ignore it just skips the input using getline.

so how should i use the code, for a space input from the user.

although not in the same way, I hope the code meets my expectation that it can ask the user to input spaces for string type

Body:
#include <iostream>
using namespace std;

int main () {
        int pemboking, kode_lap[8], durasi[8];
        string nama[8], tanggal[8], jam[8];
        cout << "\nMasukan jumlah pembooking : ";
        cin >> pemboking;
        cout << endl;
        for (int i = 0; i < pemboking; i++) {
            cout << "Transaksi ke " << i + 1 << endl;
            cout << "Masukan Nama            : ";
            getline(cin, nama[i]);
            cout << "Masukan Kode Lapangan   : ";
            cin >> kode_lap[i];
            cout << "Masukan Tanggal Sewa    : ";
            cin >> tanggal[i];
            cout << "Masukan Jam main        : ";
            getline(cin, jam[i]);
            cout << "Masukan Durasi Jam Main : ";
            cin >> durasi[i];
            cout << endl;
            cout << endl;
        }
}

when I use cin.ignore, the error will go directly to the input with index 1, index 0 is missed. if you don't use cin ignore it just skips the input using getline.

so how should i use the code, for a space input from the user.

although not in the same way, I hope the code meets my expectation that it can ask the user to input spaces for string type


问:
Webpack Config - Include file name from which js bundle was prepared React JS?
I am using webpack and want to include the filename from which bundle was generated. I need this to investigate a specific bundle and see all scopes of minification possible in the same.

How can I achieve the same?

Currently my output folder looks like this:

```<code>output: {
        filename: 'final/[name].[contenthash].js',
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
    },
</code>```

And my bundle name looks like:
<someRandomNumber>.<someRandomHash>.js

Body:
I am using webpack and want to include the filename from which bundle was generated. I need this to investigate a specific bundle and see all scopes of minification possible in the same.

How can I achieve the same?

Currently my output folder looks like this:

output: {
        filename: 'final/[name].[contenthash].js',
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
    },

And my bundle name looks like:
<someRandomNumber>.<someRandomHash>.js


问:
python - str.cat on grouped dataframe
I am trying to bring values from rows of a data frame into a new column as a string, separated by comma.

```<code>df = pd.DataFrame({'category': [1,1,1,2,2], 'value': [1,3,4,2,3]})

   category  value
0  1         1
1  1         3
2  1         4
3  2         2
4  2         3
</code>```

and my goal would be a df as follows:

```<code>   category  agg_values
0  1         1,3,4
1  2         2,3
</code>```

I tried the following, but I get an 'AttributeError: 'SeriesGroupBy' object has no attribute 'str'' error.

```<code>df['agg_values'] = df.groupby('category').value.str.cat(sep=',')
</code>```

Do you have any idea what my mistake is here?
Thank you!

Title: python - str.cat on grouped dataframe

Body:
I am trying to bring values from rows of a data frame into a new column as a string, separated by comma.

df = pd.DataFrame({'category': [1,1,1,2,2], 'value': [1,3,4,2,3]})

   category  value
0  1         1
1  1         3
2  1         4
3  2         2
4  2         3

and my goal would be a df as follows:

   category  agg_values
0  1         1,3,4
1  2         2,3

I tried the following, but I get an 'AttributeError: 'SeriesGroupBy' object has no attribute 'str'' error.

df['agg_values'] = df.groupby('category').value.str.cat(sep=',')

Do you have any idea what my mistake is here?
Thank you!


问:
Express not sending cookies on production
I have a MERN app in the local server everything is good
But when i doployed the backend
There is no cookies sent to the browser
Why ?
Here is the code for the cookie

```<code>res.cookie("token", "some value" , {

     httpOnly: true,

     maxAge: 1000 * 60 * 60 * 24 * 20,
})

</code>```

On local server it's sends a cookie and displayed the browser dev tools and it's working fine

Body:
I have a MERN app in the local server everything is good
But when i doployed the backend
There is no cookies sent to the browser
Why ?
Here is the code for the cookie

res.cookie("token", "some value" , {

     httpOnly: true,

     maxAge: 1000 * 60 * 60 * 24 * 20,
})

On local server it's sends a cookie and displayed the browser dev tools and it's working fine


问:
How to create a new Pyspark column with a subvalue of array of udts objects?
I have a column in my pyspark dataframe that has the following structure:

```<code>keywords_embedding : [
0:
    vectorType: "dense"
    length: 100
    values: [1,2,3,4,5]
1:
   vectorType: "dense"
    length: 100
    values: [4,5,6,7,8]
.
.
.
]
</code>```

I need to create a new column that contains only the subvalue array 'values' from each position. I tried the following code:

```<code>from pyspark.sql.types import StructType, StructField, StringType, DoubleType

# Define the UDF
def extract_values(obj_array):
  return [obj.values for obj in obj_array]

# Define the return type of the UDF
extract_values_udf = F.udf(extract_values, ArrayType(ArrayType(DoubleType())))

# Extract the values from each object in the array
df_teste = df_teste.withColumn(
  'values_array',
  extract_values_udf(F.col('keywords_embedding'))
)

# View the results
df_teste.display()
</code>```

But it gives me this error:

PickleException: expected zero arguments for construction of ClassDict
(for numpy.dtype)

I didn't understand why it gives me this error. How can i achieve this result?

Body:
I have a column in my pyspark dataframe that has the following structure:

keywords_embedding : [
0:
    vectorType: "dense"
    length: 100
    values: [1,2,3,4,5]
1:
   vectorType: "dense"
    length: 100
    values: [4,5,6,7,8]
.
.
.
]

I need to create a new column that contains only the subvalue array 'values' from each position. I tried the following code:

from pyspark.sql.types import StructType, StructField, StringType, DoubleType

# Define the UDF
def extract_values(obj_array):
  return [obj.values for obj in obj_array]

# Define the return type of the UDF
extract_values_udf = F.udf(extract_values, ArrayType(ArrayType(DoubleType())))

# Extract the values from each object in the array
df_teste = df_teste.withColumn(
  'values_array',
  extract_values_udf(F.col('keywords_embedding'))
)

# View the results
df_teste.display()

But it gives me this error:

PickleException: expected zero arguments for construction of ClassDict
(for numpy.dtype)

I didn't understand why it gives me this error. How can i achieve this result?


问:
How to fit the ridge instance?
I'm getting the error (KeyError: 'target')  when I used

```<code>from sklearn.linear_model import Ridge
reg = Ridge(alpha=.1)

predictors = ["Temperature from the first internal sensor", "Outside temperature", "CPU Temperature", "Temperature from the second internal sensor", "Air Pressure", "Humidity"]

train = weather.loc[:"Thu 17 Feb 2022 08:57:02 PM"]
test = weather.loc["Thu 01 Dec 2022 10:00:02 AM":]

reg.fit(train[predictors], train["target"]) KeyError: 'target'
</code>```

I tried to use another methods to fit the model but it didn't work, I'm using Colab to execute.

Title: How to fit the ridge instance?

Body:
I'm getting the error (KeyError: 'target')  when I used

from sklearn.linear_model import Ridge
reg = Ridge(alpha=.1)

predictors = ["Temperature from the first internal sensor", "Outside temperature", "CPU Temperature", "Temperature from the second internal sensor", "Air Pressure", "Humidity"]

train = weather.loc[:"Thu 17 Feb 2022 08:57:02 PM"]
test = weather.loc["Thu 01 Dec 2022 10:00:02 AM":]

reg.fit(train[predictors], train["target"]) KeyError: 'target'

I tried to use another methods to fit the model but it didn't work, I'm using Colab to execute.


问:
Error opening stream: HTTP 404: Not Found (Kernel does not exist) - Jupyter Notebook in Pydroid 3
I have been using Pydroid 3 on my Samsung Galaxy tab S8 to learn Python programming via Jupyter Notebook. However, recently, the kernel failed to load and I am getting the error message (Error opening stream: HTTP 404: Not Found (Kernel does not exist)).

I tried unistalling and reinstalling the app and its repository plugin but the error persists. I even tried disabling all network connections and changing the browser from Samsung to Chrome but nothing works. All permissions have been granted to the app.

Here is the screenshot of the Pydroid 3 terminal.

Appreciate the help!


问:
React native locally Video file not loaded in Webview online and offline mode from local HTML file in iOS Release Build
I want to display video file in my webview form HTML. HTML is in local folder and my video file also in local folder.

My HTML located in my project as below structure
src-->html-->html-->demo.html

And my video file located at below structure
src-->html-->html-->images-->demo.mp4

in my HTML file i write code for video load as below

```<code><video id="patientvideo" width="320" height="240" controls muted>
    <source src="images/demo.mp4" type="video/mp4">
</video>
</code>```

And in my main screen in webview I am loading as below

```<code>let demoHtmlData = require('../../html/html/demo.html');

<WebView
    ref={ref => (webViewRef.current = ref)}
    source={demoHtmlData}
    styles={styles.mainContainer}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    originWhitelist={['*']}
    onMessage={m => {
      onMessage(m);
    }}
  />
</code>```

When i Run above code in debug mode it is working fine but when i make release build at that time video is not loaded and showing like as below

Any idea how can i solve this ?

Body:
I want to display video file in my webview form HTML. HTML is in local folder and my video file also in local folder.

My HTML located in my project as below structure
src-->html-->html-->demo.html

And my video file located at below structure
src-->html-->html-->images-->demo.mp4

in my HTML file i write code for video load as below

<video id="patientvideo" width="320" height="240" controls muted>
    <source src="images/demo.mp4" type="video/mp4">
</video>

And in my main screen in webview I am loading as below

let demoHtmlData = require('../../html/html/demo.html');

<WebView
    ref={ref => (webViewRef.current = ref)}
    source={demoHtmlData}
    styles={styles.mainContainer}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    originWhitelist={['*']}
    onMessage={m => {
      onMessage(m);
    }}
  />

When i Run above code in debug mode it is working fine but when i make release build at that time video is not loaded and showing like as below

Any idea how can i solve this ?


问:
Is it possible to trigger an audible alarm when certain conditions are met after the app has completely closed?
I want to receive an alarm that sounds when certain conditions are met during reception with the api even if the app is completely terminated using flutter_local_notification and workmanager in flutter .but, the trigger does not occur when the api receive is long in workmanager.</p>
```<code>void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
       while(conditions are not satisfied)
        {
        receiving api~~~~~~~
        }
        NotificationService().showNotification(some parameter);
    return Future.value(true);
  });
}
</code>```

Body:
I want to receive an alarm that sounds when certain conditions are met during reception with the api even if the app is completely terminated using flutter_local_notification and workmanager in flutter .but, the trigger does not occur when the api receive is long in workmanager.

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
       while(conditions are not satisfied)
        {
        receiving api~~~~~~~
        }
        NotificationService().showNotification(some parameter);
    return Future.value(true);
  });
}


问:
Gcp nodejs spawn pm2 enoent
In my computer
I programmed a website.
This worked well, and I can enter my website with port number 80.(http://localhost:80)
But, when I uploaded to google cloud platform, everything was all right. Npm and nodejs was successfuly downloaded, also my code from github was downloaded.
But, when I typed 'npm start',
An error occurred like this.
Error
This is log file:
Log file
I don't know what is wrong

I wanted to turn my server on in google cloud platform, bot an error was occurred.
Even if the code worked well in my computer

Title: Gcp nodejs spawn pm2 enoent


问:
Long running queries causes PG POD MASTER 0 (StatefulSet) to reach MAX CORES
I'm running My Backend on a physical machine as follows:

Backend Code in TypeScript

ORM is Sequelize

Kubernetes: K3S version v1.23.14+k3s1 (c62b03fb) go version go1.17.13

My Backend is running 2 PG PODS (Stateful Set) with the following settings:

```<code>      volume:
        size: 2500Gi
      numberOfInstances: 2
      postgresql:
        parameters:
          effective_cache_size: "105GB"
          effective_io_concurrency: "200"
          listen_addresses: '*'
          log_destination: "stderr"
          logging_collector: "false"
          log_line_prefix: '%t [%p]: [%l-1] [trx_id=%x] user=%u,db=%d'
          log_min_error_statement: "DEBUG1"
          log_error_verbosity: "verbose"
          maintenance_work_mem: "2GB"
          max_connections: "4000"
          max_wal_size: "16GB"
          min_wal_size: "4GB"
          max_worker_processes: "18"
          max_parallel_workers_per_gather: "9"
          max_parallel_workers: "18"
          max_parallel_maintenance_workers: "4"
          random_page_cost: "1.1"
          shared_bufIfers: "35GB"
          shared_preload_libraries: "pg_stat_statements"
          synchronous_commit: "false"
          syslog_facility: "LOCAL0"
          syslog_ident: "postgres"
          syslog_sequence_numbers: "true"
          syslog_split_messages: "true"
          wal_buffers: "16MB"
          work_mem: "300kB"
          checkpoint_completion_target: "0.9"
      resources:
        limits:
          cpu: 20000m
          memory: 140Gi
        requests:
          cpu: 20000m
          memory: 140Gi
</code>```

After around 2 Hours of running stress on the Backend , when I run the following PSQL Code:

```<code>SELECT
  pid,
  user,
  pg_stat_activity.query_start,
  now() - pg_stat_activity.query_start AS "QueryRunningTime",
  query,
  state,
  wait_event_type,
  wait_event
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes'
ORDER BY "QueryRunningTime" DESC;
</code>```

I get queries that take very long , such as :

```<code>pid              | 5537
user             | postgres
query_start      | 2023-01-02 13:15:45.801772+00
QueryRunningTime | 00:38:24.34075
query            | INSERT INTO "employeesDetails" ("deviceId","employeeId","depId","version","createdAt","updatedAt") VALUES (............... ,'2023-01-02 13:15:45.824 +00:00','2023-01-02 13:15:45.824 +00:00') ON CONFLICT DO NOTHING RETURNING "deviceId","employeeId","depId","version","createdAt","updatedAt";
state            | idle
wait_event_type  | Client
wait_event       | ClientRead
</code>```

This query took around 00:38:24.34075 Minutes which is a crazy amount of time.

The PG Pool for each POD is:

```<code>sequelize:
  pool:
    max: 30
    min: 10
    evict: 1000
    idle: 5000
    acquire: 10000
</code>```

Why is this happening , what makes the queries to run this long even though Sequelize uses the above params ?

It causes my PG to reach MAX Cores after around 3-6 Hours of running.

Body:
I'm running My Backend on a physical machine as follows:

Backend Code in TypeScript

ORM is Sequelize

Kubernetes: K3S version v1.23.14+k3s1 (c62b03fb) go version go1.17.13

My Backend is running 2 PG PODS (Stateful Set) with the following settings:

      volume:
        size: 2500Gi
      numberOfInstances: 2
      postgresql:
        parameters:
          effective_cache_size: "105GB"
          effective_io_concurrency: "200"
          listen_addresses: '*'
          log_destination: "stderr"
          logging_collector: "false"
          log_line_prefix: '%t [%p]: [%l-1] [trx_id=%x] user=%u,db=%d'
          log_min_error_statement: "DEBUG1"
          log_error_verbosity: "verbose"
          maintenance_work_mem: "2GB"
          max_connections: "4000"
          max_wal_size: "16GB"
          min_wal_size: "4GB"
          max_worker_processes: "18"
          max_parallel_workers_per_gather: "9"
          max_parallel_workers: "18"
          max_parallel_maintenance_workers: "4"
          random_page_cost: "1.1"
          shared_bufIfers: "35GB"
          shared_preload_libraries: "pg_stat_statements"
          synchronous_commit: "false"
          syslog_facility: "LOCAL0"
          syslog_ident: "postgres"
          syslog_sequence_numbers: "true"
          syslog_split_messages: "true"
          wal_buffers: "16MB"
          work_mem: "300kB"
          checkpoint_completion_target: "0.9"
      resources:
        limits:
          cpu: 20000m
          memory: 140Gi
        requests:
          cpu: 20000m
          memory: 140Gi

After around 2 Hours of running stress on the Backend , when I run the following PSQL Code:

SELECT
  pid,
  user,
  pg_stat_activity.query_start,
  now() - pg_stat_activity.query_start AS "QueryRunningTime",
  query,
  state,
  wait_event_type,
  wait_event
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes'
ORDER BY "QueryRunningTime" DESC;

I get queries that take very long , such as :

pid              | 5537
user             | postgres
query_start      | 2023-01-02 13:15:45.801772+00
QueryRunningTime | 00:38:24.34075
query            | INSERT INTO "employeesDetails" ("deviceId","employeeId","depId","version","createdAt","updatedAt") VALUES (............... ,'2023-01-02 13:15:45.824 +00:00','2023-01-02 13:15:45.824 +00:00') ON CONFLICT DO NOTHING RETURNING "deviceId","employeeId","depId","version","createdAt","updatedAt";
state            | idle
wait_event_type  | Client
wait_event       | ClientRead

This query took around 00:38:24.34075 Minutes which is a crazy amount of time.

The PG Pool for each POD is:

sequelize:
  pool:
    max: 30
    min: 10
    evict: 1000
    idle: 5000
    acquire: 10000

Why is this happening , what makes the queries to run this long even though Sequelize uses the above params ?

It causes my PG to reach MAX Cores after around 3-6 Hours of running.


问:
PowerShell pass a variable to background process
I can't pass $dir variable to scripts in the background "Script2" and "Script3".

What an I doing wrong?

All code is pretty simple, I'm just testing how to run background processes and get results from them.

Script1

```<code># Ask the user for the directory to check
$dir = Read-Host "Enter the directory path to check for files"

# Start the second script in the background
Start-Job -ScriptBlock { & "C:\Scripts\Script2.ps1" -dir $dir } -Arg $dir

# Start the third script in the background
Start-Job -ScriptBlock { & "C:\Scripts\Script3.ps1" -dir $dir } -Arg $dir

# Wait for the second and third scripts to complete
Wait-Job -State Completed

# Get the results of the second and third scripts
$result1 = Receive-Job -Id 1
$result2 = Receive-Job -Id 2

# Output the results
Write-Output "Script 2 completed with result: $result1"
Write-Output "Script 3 completed with result: $result2"
</code>```

Here I trying to get $dir variable from Script1

Script2

```<code>param(
   [string]$dir
)

# Check if the directory exists
if (Test-Path $dir) {
   # Get all files in the directory
   $files = Get-ChildItem $dir

   # Check if the directory is empty
   if ($files.Count -eq 0) {
      Write-Output "The directory is empty"
   } else {
      # Calculate the total size of the files in the directory
      $size = ($files | Measure-Object -Property Length -Sum).Sum
      Write-Output "The total size of the files in the directory is $size bytes"
   }
} else {
   Write-Output "The directory does not exist"
}
</code>```

Script3

```<code>param(
   [string]$dir
)

# Check if the directory exists
if (Test-Path $dir) {
   # Get all files in the directory
   $files = Get-ChildItem $dir

   # Check if the directory is empty
   if ($files.Count -eq 0) {
      Write-Output "The directory is empty"
   } else {
      Write-Output "The filenames in the directory are:"
      # List the filenames in the directory
      $files | ForEach-Object { Write-Output $_.Name }
   }
} else {
   Write-Output "The directory does not exist"
}
</code>```

I get the following error:

```<code>Cannot bind argument to parameter 'Path' because it is an empty string.
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Test
   PathCommand
    + PSComputerName        : localhost
</code>```

Body:
I can't pass $dir variable to scripts in the background "Script2" and "Script3".

What an I doing wrong?

All code is pretty simple, I'm just testing how to run background processes and get results from them.

Script1

# Ask the user for the directory to check
$dir = Read-Host "Enter the directory path to check for files"

# Start the second script in the background
Start-Job -ScriptBlock { & "C:\Scripts\Script2.ps1" -dir $dir } -Arg $dir

# Start the third script in the background
Start-Job -ScriptBlock { & "C:\Scripts\Script3.ps1" -dir $dir } -Arg $dir

# Wait for the second and third scripts to complete
Wait-Job -State Completed

# Get the results of the second and third scripts
$result1 = Receive-Job -Id 1
$result2 = Receive-Job -Id 2

# Output the results
Write-Output "Script 2 completed with result: $result1"
Write-Output "Script 3 completed with result: $result2"

Here I trying to get $dir variable from Script1

Script2

param(
   [string]$dir
)

# Check if the directory exists
if (Test-Path $dir) {
   # Get all files in the directory
   $files = Get-ChildItem $dir

   # Check if the directory is empty
   if ($files.Count -eq 0) {
      Write-Output "The directory is empty"
   } else {
      # Calculate the total size of the files in the directory
      $size = ($files | Measure-Object -Property Length -Sum).Sum
      Write-Output "The total size of the files in the directory is $size bytes"
   }
} else {
   Write-Output "The directory does not exist"
}

Script3

param(
   [string]$dir
)

# Check if the directory exists
if (Test-Path $dir) {
   # Get all files in the directory
   $files = Get-ChildItem $dir

   # Check if the directory is empty
   if ($files.Count -eq 0) {
      Write-Output "The directory is empty"
   } else {
      Write-Output "The filenames in the directory are:"
      # List the filenames in the directory
      $files | ForEach-Object { Write-Output $_.Name }
   }
} else {
   Write-Output "The directory does not exist"
}

I get the following error:

Cannot bind argument to parameter 'Path' because it is an empty string.
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Test
   PathCommand
    + PSComputerName        : localhost


问:
type Orm error findtrees Cannot read properties of undefined (reading 'joinColumns') i dont why
```<code>import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    ManyToOne,
    OneToMany,
    JoinColumn,
} from "typeorm"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @ManyToOne((type) => Category, (category) => category.children)

    parent: Category

    @OneToMany((type) => Category, (category) => category.parent)

    children: Category[]
}

   const trees = await this.dataSource.manager.getTreeRepository(Category).findTrees()

      return trees;

</code>```

[Nest] 30448  - 01/02/2023, 6:01:19 PM   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'joinColumns')
TypeError: Cannot read properties of undefined (reading 'joinColumns')
at TreeRepository.findRoots (C:\xampp\htdocs\nest\src\repository\TreeRepository.ts:42:62)
at TreeRepository.findTrees (C:\xampp\htdocs\nest\src\repository\TreeRepository.ts:26:34)
at ProfillerService.getTree (C:\xampp\htdocs\nest\src\profiller\profiller.service.ts:371:79)
at ProfillerController.getTree (C:\xampp\htdocs\nest\src\profiller\profiller.controller.ts:108:43)
at C:\xampp\htdocs\nest\node_modules@nestjs\core\router\router-execution-context.js:38:29

```<code>

i try this type of result i follow the typeorm document but error is same

</code>```

[
{
"id": 1,
"name": "a1",
"children": [
{
"id": 2,
"name": "a11",
"children": [
{
"id": 4,
"name": "a111"
},
{
"id": 5,
"name": "a112"
}
]
},
{
"id": 3,
"name": "a12"
}
]
}
]

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

Body:
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    ManyToOne,
    OneToMany,
    JoinColumn,
} from "typeorm"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @ManyToOne((type) => Category, (category) => category.children)

    parent: Category

    @OneToMany((type) => Category, (category) => category.parent)

    children: Category[]
}

   const trees = await this.dataSource.manager.getTreeRepository(Category).findTrees()

      return trees;

[Nest] 30448  - 01/02/2023, 6:01:19 PM   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'joinColumns')
TypeError: Cannot read properties of undefined (reading 'joinColumns')
at TreeRepository.findRoots (C:\xampp\htdocs\nest\src\repository\TreeRepository.ts:42:62)
at TreeRepository.findTrees (C:\xampp\htdocs\nest\src\repository\TreeRepository.ts:26:34)
at ProfillerService.getTree (C:\xampp\htdocs\nest\src\profiller\profiller.service.ts:371:79)
at ProfillerController.getTree (C:\xampp\htdocs\nest\src\profiller\profiller.controller.ts:108:43)
at C:\xampp\htdocs\nest\node_modules@nestjs\core\router\router-execution-context.js:38:29

i try this type of result i follow the typeorm document but error is same

[
{
"id": 1,
"name": "a1",
"children": [
{
"id": 2,
"name": "a11",
"children": [
{
"id": 4,
"name": "a111"
},
{
"id": 5,
"name": "a112"
}
]
},
{
"id": 3,
"name": "a12"
}
]
}
]


问:
Error: error while updating property 'startpoint' of a view managed by bvlineargradient. Null
When i change the sliders value to change the startX/startY value i get this Error: error while updating property 'startpoint' of a view managed by bvlineargradient. Null</p>
```<code>const [startX, setStartX] = useState(0);
const [startY, setStartY] = useState(0);

<LinearGradient
  start={{x: startX, y: startY}}
  end={{x: 0.5, y: 1.3}}
  locations={[0.4, 0.9]}
  colors={[colorOne, colorTwo]}
  style={{
    height: 200,
    width: '100%',
    borderRadius: 10,
}}></LinearGradient>

<Slider
  thumbTintColor="#fff"
  minimumValue={0}
  maximumValue={1}
  step={0.1}
  value={startX}
  onValueChange={val => setStartX(val)}
 />
</code>```

Body:
When i change the sliders value to change the startX/startY value i get this Error: error while updating property 'startpoint' of a view managed by bvlineargradient. Null

const [startX, setStartX] = useState(0);
const [startY, setStartY] = useState(0);

<LinearGradient
  start={{x: startX, y: startY}}
  end={{x: 0.5, y: 1.3}}
  locations={[0.4, 0.9]}
  colors={[colorOne, colorTwo]}
  style={{
    height: 200,
    width: '100%',
    borderRadius: 10,
}}></LinearGradient>

<Slider
  thumbTintColor="#fff"
  minimumValue={0}
  maximumValue={1}
  step={0.1}
  value={startX}
  onValueChange={val => setStartX(val)}
 />


问:
Net Framework WebApi Ninject Parameterless constructor error
I have a WebAPI project in .Net Framework 4.8. I want to add Ninject to this project and I am facing various issues. There are many answers on Stackoverflow but none of them could solve my error.

First of all, I installed the following packages in my API Project.

Ninject (3.3.6)

Ninject.Web.Common (3.3.2)

Ninject.Web.Common.WebHost (3.3.2)

Ninject.Web.WebApi (3.3.1)

Ninject.Web.WebApi.WebHost (3.3.1)

And after installing them, NinjectWebCommon class came under App_Start folder.

```<code>public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            RegisterServices(kernel);

            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<VersionOperations>().ToSelf();
    }
}
</code>```

After this adjustment, I made the necessary matching in the constructor of my ApiController.

```<code>public class AdminController : ApiController
{
    private readonly VersionOperations _versionOperations;

    public AdminController(
        VersionOperations versionOperations)
    {
        _versionOperations = versionOperations;
    }

    [HttpGet]
    [Route("Test")]
    public ApiResultBase Test()
    {
        return new ApiResultBase();
    }
</code>```

When I do these, I finally get the following error from Postman.

```<code>"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'AdminController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
</code>```

Here is the solution https://continuousdeveloper.com/2016/06/30/using-ninject-with-webapi-2-0/
I tried this friend's solution. But here too I get the following error while the project is standing up

Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider A cyclical dependency was detected between the constructors of two services.

Body:
I have a WebAPI project in .Net Framework 4.8. I want to add Ninject to this project and I am facing various issues. There are many answers on Stackoverflow but none of them could solve my error.

First of all, I installed the following packages in my API Project.

Ninject (3.3.6)

Ninject.Web.Common (3.3.2)

Ninject.Web.Common.WebHost (3.3.2)

Ninject.Web.WebApi (3.3.1)

Ninject.Web.WebApi.WebHost (3.3.1)

And after installing them, NinjectWebCommon class came under App_Start folder.

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            RegisterServices(kernel);

            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<VersionOperations>().ToSelf();
    }
}

After this adjustment, I made the necessary matching in the constructor of my ApiController.

public class AdminController : ApiController
{
    private readonly VersionOperations _versionOperations;

    public AdminController(
        VersionOperations versionOperations)
    {
        _versionOperations = versionOperations;
    }

    [HttpGet]
    [Route("Test")]
    public ApiResultBase Test()
    {
        return new ApiResultBase();
    }

When I do these, I finally get the following error from Postman.

"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'AdminController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",

Here is the solution https://continuousdeveloper.com/2016/06/30/using-ninject-with-webapi-2-0/
I tried this friend's solution. But here too I get the following error while the project is standing up

Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider A cyclical dependency was detected between the constructors of two services.


问:
Line width not changing with geom_pointrange
I am trying to thicken the lines of my plot with geom_pointrange.

```<code>ggplot( data, aes(x = xvar, ymin = ymin, y = yvar, ymax = ymax))+
  geom_pointrange(shape = 21, size = 1.5, fatten = 0.75,
                  position = position_dodge(width = 0.5), color = "#5a2c76")
</code>```

I've tried playing with the fatten and size variables as well as adding linewidth, width, etc. all over the code. The widths of the lines don't change.

Body:
I am trying to thicken the lines of my plot with geom_pointrange.

ggplot( data, aes(x = xvar, ymin = ymin, y = yvar, ymax = ymax))+
  geom_pointrange(shape = 21, size = 1.5, fatten = 0.75,
                  position = position_dodge(width = 0.5), color = "#5a2c76")

I've tried playing with the fatten and size variables as well as adding linewidth, width, etc. all over the code. The widths of the lines don't change.


问:
Why I can not add Gradle dependency by the Generate context menu in IntlliJ Idea IDE
Today I refer to Add a Gradle dependency section to add Gradle dependency by the Generate context menu. Unfortunately, I encounter some trouble. When I press ⌘N to open the Generate context menu in my Idea. It show like below . In the  Add a Gradle dependency tutorials, it show like below . So how can I get the windows like the Add a Gradle dependency tutorials showing.


问:
front end not able to fetch data - security access
My react frontend application is returning:
'Access to XMLHttpRequest at 'https://api-myapp.com/backoffice/forms' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource'

Therefore i installed http-proxy-middleware in my frontend app as follow:
1-create a setupProxy.js file

```<code>const { createProxyMiddleware } = require("http-proxy-middleware");

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;

module.exports = app => {

    app.use(
        createProxyMiddleware(`/backoffice/forms`,
            {
                target: API_ENDPOINT,
                changeOrigin: true,
            })
    )

}

</code>```

Edit my package.json file as follow:

```<code>{
  "name": "backoffice",
  "version": "0.1.0",
  "proxy": "https://api-myapp.com",
  etc etc
}

</code>```

CALL API

```<code>import axios from "axios";
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;

async function doGetForms() {

    const headers = {
        headers: {
            "content-type": "application/json"
        }
    };

    let response = await axios.get(API_ENDPOINT + `/backoffice/forms`, headers);
    if (response) return response.data;
}
</code>```

Unfortunately i did not manage to solve the issue. Is this something my backend developer should solve first by adding Access-Control-Allow-Origin in the resource?
I follow this tutorial (https://www.youtube.com/watch?v=4B5WgTiKIOY) and assumed it was working with all scenarios...

Body:
My react frontend application is returning:
'Access to XMLHttpRequest at 'https://api-myapp.com/backoffice/forms' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource'

Therefore i installed http-proxy-middleware in my frontend app as follow:
1-create a setupProxy.js file

const { createProxyMiddleware } = require("http-proxy-middleware");

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;

module.exports = app => {

    app.use(
        createProxyMiddleware(`/backoffice/forms`,
            {
                target: API_ENDPOINT,
                changeOrigin: true,
            })
    )

}

Edit my package.json file as follow:

{
  "name": "backoffice",
  "version": "0.1.0",
  "proxy": "https://api-myapp.com",
  etc etc
}

CALL API

import axios from "axios";
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;

async function doGetForms() {

    const headers = {
        headers: {
            "content-type": "application/json"
        }
    };

    let response = await axios.get(API_ENDPOINT + `/backoffice/forms`, headers);
    if (response) return response.data;
}

Unfortunately i did not manage to solve the issue. Is this something my backend developer should solve first by adding Access-Control-Allow-Origin in the resource?
I follow this tutorial (https://www.youtube.com/watch?v=4B5WgTiKIOY) and assumed it was working with all scenarios...


问:
Debug an AVR assembler project at source level
I want to debug a code of a plain assembler project for the ATmega2560. I want to use the Microchip debugger for that purpose. The goal is to get source level debugging with all variables and functions, breakpoints etc.

I managed to create a C "stub" file with a main() function that calls the assembler code.

```<code>extern int foo(int a);

int main(void)
{
    int a = 0;
    while (1)
    {
        a = foo(a);
    }
}
</code>```

But the assembler code also includes the interrupt vector table including the reset vector.

```<code>    .extern main

    .section .vectors
    .global RESET_
RESET_:   jmp  WARM_0

    .section code
    .global foo
 foo:
    ret

WARM_0:
    call main
    ret

    .end
</code>```

Now I want to run the code from the label RESET_. The linker has placed the code in the section  .vectors. That's okay so far, but the vector table from the GCC startup files are in that section  before the vector table in my code. The GCC startup code must be removed to get my vector to the address 0. Therefore I activate the linker option "Do not use standard start files (-nostartfiles)". That gives the desired result: The reset vector has a jump to RESET_.

But this has the important side effect, that the debugger is not able to debug at source code level anymore. The C file with the main() function is still linked. But the source level debug support is lost.

How can I debug a plan assembler project with Microchip debugger/simulator for AVR8?

Remark: The code in the assembler file is not sufficient for a valid program. It's reduced to get a minimal example that should work in the Microchip environment.

Body:
I want to debug a code of a plain assembler project for the ATmega2560. I want to use the Microchip debugger for that purpose. The goal is to get source level debugging with all variables and functions, breakpoints etc.

I managed to create a C "stub" file with a main() function that calls the assembler code.

extern int foo(int a);

int main(void)
{
    int a = 0;
    while (1)
    {
        a = foo(a);
    }
}

But the assembler code also includes the interrupt vector table including the reset vector.

    .extern main

    .section .vectors
    .global RESET_
RESET_:   jmp  WARM_0

    .section code
    .global foo
 foo:
    ret

WARM_0:
    call main
    ret

    .end

Now I want to run the code from the label RESET_. The linker has placed the code in the section  .vectors. That's okay so far, but the vector table from the GCC startup files are in that section  before the vector table in my code. The GCC startup code must be removed to get my vector to the address 0. Therefore I activate the linker option "Do not use standard start files (-nostartfiles)". That gives the desired result: The reset vector has a jump to RESET_.

But this has the important side effect, that the debugger is not able to debug at source code level anymore. The C file with the main() function is still linked. But the source level debug support is lost.

How can I debug a plan assembler project with Microchip debugger/simulator for AVR8?

Remark: The code in the assembler file is not sufficient for a valid program. It's reduced to get a minimal example that should work in the Microchip environment.


问:
pyqt5 opening third new window from second window
firstly i have created a object form MainWindow than i am trying to make another object with same
how i should close Third window

```<code>
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(548, 479)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(14)
.         ...
    def users_window(self):
        self.window = QtWidgets.QMainWindow()
        ui = Ui_SecondWindow()
        ui.setupUi(self.window )
        self.window.show()
        MainWindow.hide()

     def admin_window(self):
        self.window1 = QtWidgets.QMainWindow()
        ui1 = Ui_ThirdWindow()
        ui1.setupUi(self.window1)
        self.window1.show()
        MainWindow.hide()

class Ui_SecondWindow(object):
    def setupUi(self, SecondWindow ):
        SecondWindow.setObjectName("SecondWindow")
        SecondWindow.resize(588, 437)
        SecondWindow.setStyleSheet("background-color:#c5d5cb;")
        self.centralwidget = QtWidgets.QWidget(SecondWindow)
        ...
class Ui_ThirdWindow(object):
    def setupUi(self, ThirdWindow):
        ThirdWindow.setObjectName("ThirdWindow")
        ThirdWindow.resize(588, 437)
        ThirdWindow.setStyleSheet("background-color:#c5d5cb;")
        ...

     def validating_admin(self):
        AdminID = self.AdminID.text()
        print(AdminID)
        Admin_password = self.Admin_password.text()
        print(type(Admin_password))
        validation = f"""
        select password from admin where adminID = {AdminID};"""
        result = database1.execute_query(None , validation)
        if (result == Admin_password) :
            print("Correct password")
            self.window2 = QtWidgets.QMainWindow()
            ui2 = Ui_Admin_main_page()
            ui2.setupUi(self.window2)
            self.window2.show()
            print(result)
            ThirdWindow.hide()   #here if ThirdWindow is not Hiding
        else :
            print("Wrong Password")
            QMessageBox.about( "Alert", "Wrong password or userID !!)

</code>```

above here is my problem solve it

```<code>
class Ui_Admin_main_page(object):
    def setupUi(self, Admin_main_page):
        Admin_main_page.setObjectName("Admin_main_page")
        Admin_main_page.resize(588, 437)

</code>```

how i should hide ThirdWindow with running window2 at same time
ThirdWindow is not Hiding

Body:
firstly i have created a object form MainWindow than i am trying to make another object with same
how i should close Third window

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(548, 479)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(14)
.         ...
    def users_window(self):
        self.window = QtWidgets.QMainWindow()
        ui = Ui_SecondWindow()
        ui.setupUi(self.window )
        self.window.show()
        MainWindow.hide()

     def admin_window(self):
        self.window1 = QtWidgets.QMainWindow()
        ui1 = Ui_ThirdWindow()
        ui1.setupUi(self.window1)
        self.window1.show()
        MainWindow.hide()

class Ui_SecondWindow(object):
    def setupUi(self, SecondWindow ):
        SecondWindow.setObjectName("SecondWindow")
        SecondWindow.resize(588, 437)
        SecondWindow.setStyleSheet("background-color:#c5d5cb;")
        self.centralwidget = QtWidgets.QWidget(SecondWindow)
        ...
class Ui_ThirdWindow(object):
    def setupUi(self, ThirdWindow):
        ThirdWindow.setObjectName("ThirdWindow")
        ThirdWindow.resize(588, 437)
        ThirdWindow.setStyleSheet("background-color:#c5d5cb;")
        ...

     def validating_admin(self):
        AdminID = self.AdminID.text()
        print(AdminID)
        Admin_password = self.Admin_password.text()
        print(type(Admin_password))
        validation = f"""
        select password from admin where adminID = {AdminID};"""
        result = database1.execute_query(None , validation)
        if (result == Admin_password) :
            print("Correct password")
            self.window2 = QtWidgets.QMainWindow()
            ui2 = Ui_Admin_main_page()
            ui2.setupUi(self.window2)
            self.window2.show()
            print(result)
            ThirdWindow.hide()   #here if ThirdWindow is not Hiding
        else :
            print("Wrong Password")
            QMessageBox.about( "Alert", "Wrong password or userID !!)

above here is my problem solve it

class Ui_Admin_main_page(object):
    def setupUi(self, Admin_main_page):
        Admin_main_page.setObjectName("Admin_main_page")
        Admin_main_page.resize(588, 437)

how i should hide ThirdWindow with running window2 at same time
ThirdWindow is not Hiding


问:
Getting org.glassfish.hk2.extension.ServiceLocatorGenerator: Provider org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl not a subtype
Getting below error

```<code>Caused by: java.lang.IllegalStateException: No generator was provided and there is no default generator registered
</code>```

When I dig deep into the issue on debug mode, I realized that actual error is below one.

```<code>Getting org.glassfish.hk2.extension.ServiceLocatorGenerator: Provider org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl not a subtype
</code>```

It was failing when invoking providers.next() in hk2-api lib

```<code>final ClassLoader classLoader = ServiceLocatorFactoryImpl.class.getClassLoader();
      Iterator<ServiceLocatorGenerator> providers = java.util.ServiceLoader.load(ServiceLocatorGenerator.class,
              classLoader).iterator();
      while (providers.hasNext()) {
          try {
              return providers.next();
          } catch (ServiceConfigurationError sce) {
              // This can happen. See the exception javadoc for more details.
              Logger.getLogger().debug("ServiceLocatorFactoryImpl", "getGenerator", sce);
                  // We will try the next one
          }
      }
</code>```

There is a interface ServiceLocatorGenerator present in kh2-api lib (org.glassfish.hk2:hk2-api:2.6.1). Error says that implementation ServiceLocatorGeneratorImpl present in hk2-locater lib (org.glassfish.hk2:hk2-locator:2.6.1) is not subtype even though it is a subtype.

Understood that an implementation class (concrete class) cannot be a subtype of interface if they are not loader by same class loader. Assuming this was the one causing the issue.

Can someone help how to fix this issue in gralde? My env is not OSGi based.

Body:
Getting below error

Caused by: java.lang.IllegalStateException: No generator was provided and there is no default generator registered

When I dig deep into the issue on debug mode, I realized that actual error is below one.

Getting org.glassfish.hk2.extension.ServiceLocatorGenerator: Provider org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl not a subtype

It was failing when invoking providers.next() in hk2-api lib

final ClassLoader classLoader = ServiceLocatorFactoryImpl.class.getClassLoader();
      Iterator<ServiceLocatorGenerator> providers = java.util.ServiceLoader.load(ServiceLocatorGenerator.class,
              classLoader).iterator();
      while (providers.hasNext()) {
          try {
              return providers.next();
          } catch (ServiceConfigurationError sce) {
              // This can happen. See the exception javadoc for more details.
              Logger.getLogger().debug("ServiceLocatorFactoryImpl", "getGenerator", sce);
                  // We will try the next one
          }
      }

There is a interface ServiceLocatorGenerator present in kh2-api lib (org.glassfish.hk2:hk2-api:2.6.1). Error says that implementation ServiceLocatorGeneratorImpl present in hk2-locater lib (org.glassfish.hk2:hk2-locator:2.6.1) is not subtype even though it is a subtype.

Understood that an implementation class (concrete class) cannot be a subtype of interface if they are not loader by same class loader. Assuming this was the one causing the issue.

Can someone help how to fix this issue in gralde? My env is not OSGi based.


问:
Wpf - Create a Style in a resource dictionary that sets properties of children of a grid
I have the following grid, with some resource styles that apply to its children, a standard WPF styling:

```<code><Grid>

    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10 10 0 0"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="Margin" Value="0 10 10 0"/>
        </Style>
    </Grid.Resources>

    <!-- Result: all TextBlock and TextBox elements will have a style applied to them -->
    <!-- Add grid children here -->
</Grid>
</code>```

Now, I want to move this particular style to a resource dictionary, so I can apply this to many other grids (important: not necessarily all grids).

I want to have something like <Grid Style="{StaticResource MyStyle}"> that will set properties of all the contained TextBox and TextBlock elements.

Note that: I don't want to have to make <TextBox Style=.../><TextBox Style=.../> for the huge number of boxes contained in that grid.

How an I achieve that?

Currently I have something that applies to the grid in a resource dictionary

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyNamespace">

    <!-- This is the style that will be used in the grid/panel -->
    <Style x:Key="Overlay" TargetType="Panel">

        <!-- These are properties of the grid/panel itself, all good -->
        <Setter Property="Visibility" Value="Collapsed"/>
        <Setter Property="Panel.ZIndex" Value="1000"/>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="Black" Opacity=".7"/>
            </Setter.Value>
        </Setter>

        <!-- here!! what do I put here to affect contained TextBox and TextBlock elements?? -->

        <!-- triggers for the grid/panel, all good -->
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsBusy}" Value="true">
                <Setter Property="Visibility" Value="Visible"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</code>```

Body:
I have the following grid, with some resource styles that apply to its children, a standard WPF styling:

<Grid>

    <Grid.Resources>

    </Grid.Resources>

</Grid>

Now, I want to move this particular style to a resource dictionary, so I can apply this to many other grids (important: not necessarily all grids).

I want to have something like <Grid Style="{StaticResource MyStyle}"> that will set properties of all the contained TextBox and TextBlock elements.

Note that: I don't want to have to make <TextBox Style=.../><TextBox Style=.../> for the huge number of boxes contained in that grid.

How an I achieve that?

Currently I have something that applies to the grid in a resource dictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyNamespace">

    </Style>


问:
DayNight cannot be applied for BottomDialogSheet
I came across this post but it didn't really heplp:
How to set DayNight theme for BottomSheetDialog

Whenever I set the theme to Theme.MaterialComponents.DayNight.BottomSheetDialog like this:

```<code> <style name="CustomBottomSheetDialog" parent="@style/Theme.MaterialComponents.DayNight.BottomSheetDialog">
        <item name="shapeAppearanceOverlay">@style/CustomShapeAppearanceBottomSheetDialog</item>
    </style>
    <style name="CustomShapeAppearanceBottomSheetDialog" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSizeTopRight">16dp</item>
        <item name="cornerSizeTopLeft">16dp</item>
        <item name="cornerSizeBottomRight">0dp</item>
        <item name="cornerSizeBottomLeft">0dp</item>
    </style>
</code>```

I get a grayish background for some reason:

Also, the textColor for both textViews inside the CardViews are set to colorOnSecondary (white) but as you can see, it's returning black.

The UI was originally a fragment, then I changed it to BottomSheetDialogFragment() so I know the UI were just fine before that change. Do I need to override something that's forcing the BottomSheetDialog to become grey?

Body:
I came across this post but it didn't really heplp:
How to set DayNight theme for BottomSheetDialog

Whenever I set the theme to Theme.MaterialComponents.DayNight.BottomSheetDialog like this:

I get a grayish background for some reason:

Also, the textColor for both textViews inside the CardViews are set to colorOnSecondary (white) but as you can see, it's returning black.

The UI was originally a fragment, then I changed it to BottomSheetDialogFragment() so I know the UI were just fine before that change. Do I need to override something that's forcing the BottomSheetDialog to become grey?


问:
Python Setuptools: Is it possible to add preinstall code which creates dynamic file?
I have the following structure of packages:

repo
|__pckg1
    |__settings.txt
    |__create_new_file.py
    |__setup.py
    |__requirements1.txt
|__pckg2
    |__requirements2.txt
```

Requirements2.txt has: file:../pckg1

create_new_file.py creates new file based on settings.txt
It should run before setup.py so the newly created file will be part of the installation.
Is it possible to achieve this?

I tried all the options from here but nothing worked

Body:
I have the following structure of packages:

repo
|__pckg1
    |__settings.txt
    |__create_new_file.py
    |__setup.py
    |__requirements1.txt
|__pckg2
    |__requirements2.txt

Requirements2.txt has: file:../pckg1

create_new_file.py creates new file based on settings.txt
It should run before setup.py so the newly created file will be part of the installation.
Is it possible to achieve this?

I tried all the options from here but nothing worked


问:
how can linked between component in to the card
I want to link the card button with another component that I already have, but I don't know how to do it, could you help me?

Here I show you the card component, where in the Card.Footer label I want to put the link to the roles component

```<code>import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import { useEffect, useState } from "react";
import axios from 'axios';
import AllRoles from './Roles';
import Card from 'react-bootstrap/Card';

const baseURL = "../cartas.json";

const Cards = () => {
    const [carta, setCarta] = useState([])

    //FORMA CON AXIOS
    useEffect(() => {
        axios
            .get(`${baseURL}`)
            .then((response) => {
                setCarta(response.data.cita);
            })
            .catch(err => { console.log(err.message) });
    }, []);
    console.log(carta);

    const renderCard = (card, index) => {
        if (carta.length) {
            return (
                // <Routes>
                <Card className=" col-1 col-md-3 w-15 mx-auto" key={index} >
                    <Card.Img src={card.imagen}
                        alt={card.nombre}
                        className="py-3 px-3 mx-auto"
                        style={{ width: "12rem" }}>
                    </Card.Img>
                    <Card.Body>
                        <p className="card-title">{card.descripcion}</p>
                    </Card.Body>
                    <Card.Footer className=" fs-3 py-3 px-3">
                        {/* <Link to="roles">Roles</Link> */}
                        {/* <NavLink to={card.link}>Roles</NavLink> */}
                        {/* <Routes>
                            <Route path={card.link}>
                                <Roles/>
                            </Route>

                            </Routes> */}
                        {/* <BrowserRouter>

                        </BrowserRouter> */}
                    </Card.Footer>

                    {/* <Route exact path="/roles" component={AllRoles}></Route> */}
                </Card>
                // </Routes>

            )
        }
        //     )
        // }
    }
    return (
            <div className='app row row-cols-12 gap-5 justify-content-md-center'>
                {carta.map(renderCard)}
            </div>
    )
}
export default Cards;
</code>```

As you can see I have tried with the routes but without success, I have commented it because when I put it everything disappears

```<code>import React from 'react';
import { useEffect, useState } from "react";
import axios from 'axios';

const baseURL = "https://pokeapi.co/api/v2/pokemon/ditto";

const AllRoles = () => {
    const [roles, setRol] = useState([]);

    ///FORMA CON FETCH
    useEffect(() => {
        fetch(`${baseURL}`)
            .then(response => {
                console.log(response);
                return response.json();
            })

            .then(data => {
                console.log(data)
                // setCarta(data.cita);
            })
            .catch((err) => {
                console.log(err.message)
            });
    }, []);
console.log("hola");

}

export default AllRoles;
</code>```

Then here I have the roles component, which I want that when clicking on the card, the information will appear on the console for now

Body:
I want to link the card button with another component that I already have, but I don't know how to do it, could you help me?

Here I show you the card component, where in the Card.Footer label I want to put the link to the roles component

import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import { useEffect, useState } from "react";
import axios from 'axios';
import AllRoles from './Roles';
import Card from 'react-bootstrap/Card';

const baseURL = "../cartas.json";

const Cards = () => {
    const [carta, setCarta] = useState([])

    //FORMA CON AXIOS
    useEffect(() => {
        axios
            .get(`${baseURL}`)
            .then((response) => {
                setCarta(response.data.cita);
            })
            .catch(err => { console.log(err.message) });
    }, []);
    console.log(carta);

    const renderCard = (card, index) => {
        if (carta.length) {
            return (
                // <Routes>
                <Card className=" col-1 col-md-3 w-15 mx-auto" key={index} >
                    <Card.Img src={card.imagen}
                        alt={card.nombre}
                        className="py-3 px-3 mx-auto"
                        style={{ width: "12rem" }}>
                    </Card.Img>
                    <Card.Body>

{card.descripcion}

                    </Card.Body>
                    <Card.Footer className=" fs-3 py-3 px-3">
                        {/* <Link to="roles">Roles</Link> */}
                        {/* <NavLink to={card.link}>Roles</NavLink> */}
                        {/* <Routes>
                            <Route path={card.link}>
                                <Roles/>
                            </Route>

                            </Routes> */}
                        {/* <BrowserRouter>

                        </BrowserRouter> */}
                    </Card.Footer>

                    {/* <Route exact path="/roles" component={AllRoles}></Route> */}
                </Card>
                // </Routes>

            )
        }
        //     )
        // }
    }
    return (

                {carta.map(renderCard)}

    )
}
export default Cards;

As you can see I have tried with the routes but without success, I have commented it because when I put it everything disappears

import React from 'react';
import { useEffect, useState } from "react";
import axios from 'axios';

const baseURL = "https://pokeapi.co/api/v2/pokemon/ditto";

const AllRoles = () => {
    const [roles, setRol] = useState([]);

    ///FORMA CON FETCH
    useEffect(() => {
        fetch(`${baseURL}`)
            .then(response => {
                console.log(response);
                return response.json();
            })

            .then(data => {
                console.log(data)
                // setCarta(data.cita);
            })
            .catch((err) => {
                console.log(err.message)
            });
    }, []);
console.log("hola");

}

export default AllRoles;

Then here I have the roles component, which I want that when clicking on the card, the information will appear on the console for now


问:
Google data studio control default selection dynamic
I am new to Google Data Studio. I have a control drop-down element of release number and I want it to show by default the last release number that we working on (it is also the Max number in the list).

I see the "default selection" but I don't want to insert a static number because the release number list is dynamically changing.

Is there a way to specify to show the max number by default?