问:
Set-Cookie in header and also in response cookies under dev tools, but Application > Cookies is empty and has no cookie?
I'm trying to set a cookie for my Vue app using express and axios.

Here is my request using axios:

```<code>axios.post('http://127.0.0.1:8000/auth/login/', loginDetails, {
        withCredentials: true,
        credentials: 'include'
    })
    .then(function (response) {
        console.log('login response: ', response);
    })
    .catch(error => {
        console.error(error.message)
        console.error(error.response.status)
    });
</code>```

It is handled by express where I use res.cookie() like so:

```<code>// Set Status
res.status(200)

// Set User Cookie
res.cookie("token", token, { httpOnly: true, sameSite: 'none', secure: true, maxAge: 86400 })

// Send the JWT to the client
res.send({
    data: user,
    token: token,
    message: "Logged in successfully!"
})
</code>```

After sending the request, I can see the cookie in the response cookies dev tools:

I also see Set-Cookie in the response headers:

However, when I check my Application > Storage > Cookies in dev tools it is empty

I've tried setting withCredentials = true on both my client side request and server side response but it doesn't seem to work.

I also played around with my cors setting based on other similar questions but to no avail.

I've also read here:
set-cookie is set in response header but it is not showing in Application->Cookies
that I need to use a subdomain to set the cookie but I do not quite understand the solution or how to implement it

Body:
I'm trying to set a cookie for my Vue app using express and axios.

Here is my request using axios:

axios.post('http://127.0.0.1:8000/auth/login/', loginDetails, {
        withCredentials: true,
        credentials: 'include'
    })
    .then(function (response) {
        console.log('login response: ', response);
    })
    .catch(error => {
        console.error(error.message)
        console.error(error.response.status)
    });

It is handled by express where I use res.cookie() like so:

// Set Status
res.status(200)

// Set User Cookie
res.cookie("token", token, { httpOnly: true, sameSite: 'none', secure: true, maxAge: 86400 })

// Send the JWT to the client
res.send({
    data: user,
    token: token,
    message: "Logged in successfully!"
})

After sending the request, I can see the cookie in the response cookies dev tools:

I also see Set-Cookie in the response headers:

However, when I check my Application > Storage > Cookies in dev tools it is empty

I've tried setting withCredentials = true on both my client side request and server side response but it doesn't seem to work.

I also played around with my cors setting based on other similar questions but to no avail.

I've also read here:
set-cookie is set in response header but it is not showing in Application->Cookies
that I need to use a subdomain to set the cookie but I do not quite understand the solution or how to implement it


来源: stackexchange

问:
How to remove the date part and still keep the data type as datetime64[ns]
Can someone please guide how can I remove the date using pandas and keep the datatype as datetime64[ns]:

```<code>0    2023-01-02 11:00:00
1    2023-01-02 16:00:00
2    2023-01-02 14:00:00
5                    NaT
6    2023-01-02 12:00:00
7                    NaT
8                    NaT
9    2023-01-02 13:30:00
10                   NaT
18   2023-01-02 09:00:00

TIME OBSERVED        datetime64[ns]
</code>```

I tried to find something on Youtube but havent found anything very specific.

ContentLicense: CC BY-SA 4.0

Body:
Can someone please guide how can I remove the date using pandas and keep the datatype as datetime64[ns]:

0    2023-01-02 11:00:00
1    2023-01-02 16:00:00
2    2023-01-02 14:00:00
5                    NaT
6    2023-01-02 12:00:00
7                    NaT
8                    NaT
9    2023-01-02 13:30:00
10                   NaT
18   2023-01-02 09:00:00

TIME OBSERVED        datetime64[ns]

I tried to find something on Youtube but havent found anything very specific.


问:
Multi column joins and Federated Tables
I am having a problem with getting information from two tables in our databases.

Table A is a federated table from our accounts server which works perfectly well if queried on its own.  It has no unique ID field, but Job and Code fields are unique

Table B is an analogue to Table A on our Production server and has Job and Code fields that should match those in the Accounts server.

I would like to create a query that gives me all the Codes in table A that do no exist in table B for a given Job.

When I try and perform any query that links Table A and Table B directly I get Connection Errors - is this something that is outside the scope of Federated Tables?

ContentLicense: CC BY-SA 3.0

Title: Multi column joins and Federated Tables


问:
Hadoop 3.3.0 on WSL 2 - Failed to start name node, but data node works fine
I'm running Hadoop 3.3.0 on WSL 2 in Windows 11, I followed this guide to setup my configuration: Install Hadoop 3.3.0 on WSL 2

When I start namenode and datanode with:

```<code>start-dfs.sh
</code>```

It shows no error, but in jps the namenode is not running:

```<code>8805 DataNode
9034 Seconday Namenode
9212 Jps
</code>```

Looking in the namenode log file, it shows failed to start namenode:

```<code>    2023-01-02 20:50:51,714 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Stopping NameNode metrics system...
2023-01-02 20:50:51,715 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system stopped.
2023-01-02 20:50:51,715 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system shutdown complete.
2023-01-02 20:50:51,719 ERROR org.apache.hadoop.hdfs.server.namenode.NameNode: Failed to start namenode.
java.io.IOException: Could not parse line: Filesystem     1024-blocks      Used Available Capacity Mounted on
        at org.apache.hadoop.fs.DF.parseOutput(DF.java:195)
        at org.apache.hadoop.fs.DF.getFilesystem(DF.java:76)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker$CheckedVolume.<init>(NameNodeResourceChecker.java:70)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker.addDirToCheck(NameNodeResourceChecker.java:166)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker.<init>(NameNodeResourceChecker.java:135)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startCommonServices(FSNamesystem.java:1266)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.startCommonServices(NameNode.java:862)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:783)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:1014)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:987)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1756)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1821)
2023-01-02 20:50:51,722 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 1: java.io.IOException: Could not parse line: Filesystem     1024-blocks      Used Available Capacity Mounted on
2023-01-02 20:50:51,725 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: SHUTDOWN_MSG:
</code>```

Here is my configuration file core-site.xml:

```<code><configuration>
  <property>
     <name>fs.defaultFS</name>
     <value>hdfs://localhost:9000</value>
  </property>

</configuration>
</code>```

And for hdfs-site.xml:

```<code><configuration>
 <property>
   <name>dfs.replication</name>
   <value>1</value>
 </property>

</configuration>
</code>```

I've been stuck with this problem for several days, thank you for all the help!

Body:
I'm running Hadoop 3.3.0 on WSL 2 in Windows 11, I followed this guide to setup my configuration: Install Hadoop 3.3.0 on WSL 2

When I start namenode and datanode with:

start-dfs.sh

It shows no error, but in jps the namenode is not running:

8805 DataNode
9034 Seconday Namenode
9212 Jps

Looking in the namenode log file, it shows failed to start namenode:

    2023-01-02 20:50:51,714 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Stopping NameNode metrics system...
2023-01-02 20:50:51,715 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system stopped.
2023-01-02 20:50:51,715 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system shutdown complete.
2023-01-02 20:50:51,719 ERROR org.apache.hadoop.hdfs.server.namenode.NameNode: Failed to start namenode.
java.io.IOException: Could not parse line: Filesystem     1024-blocks      Used Available Capacity Mounted on
        at org.apache.hadoop.fs.DF.parseOutput(DF.java:195)
        at org.apache.hadoop.fs.DF.getFilesystem(DF.java:76)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker$CheckedVolume.<init>(NameNodeResourceChecker.java:70)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker.addDirToCheck(NameNodeResourceChecker.java:166)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeResourceChecker.<init>(NameNodeResourceChecker.java:135)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startCommonServices(FSNamesystem.java:1266)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.startCommonServices(NameNode.java:862)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:783)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:1014)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:987)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1756)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1821)
2023-01-02 20:50:51,722 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 1: java.io.IOException: Could not parse line: Filesystem     1024-blocks      Used Available Capacity Mounted on
2023-01-02 20:50:51,725 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: SHUTDOWN_MSG:

Here is my configuration file core-site.xml:

<configuration>
  <property>
     <name>fs.defaultFS</name>
     <value>hdfs://localhost:9000</value>
  </property>

</configuration>

And for hdfs-site.xml:

<configuration>
 <property>
   <name>dfs.replication</name>
   <value>1</value>
 </property>

</configuration>

I've been stuck with this problem for several days, thank you for all the help!


问:
Mongoose parser error while connecting with mongoDB atlas
while trying to connect with my mongoDB atlas using mongoose connect method in node js I'm getting below mentioned parser error, I've checked my DB credentials and there are no special characters (:, /, ?, #, [], @) present in it.

Error:

```<code>MongoParseError: URI malformed, cannot be parsed
</code>```

Code:

```<code>const mongoose = require('mongoose');
const DB = process.env.DB.replace('<password>', process.env.DB_PASSWORD);
mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log(con.connections);
    console.log('DB connection successful!');
  });
</code>```

Body:
while trying to connect with my mongoDB atlas using mongoose connect method in node js I'm getting below mentioned parser error, I've checked my DB credentials and there are no special characters (:, /, ?, #, [], @) present in it.

Error:

MongoParseError: URI malformed, cannot be parsed

Code:

const mongoose = require('mongoose');
const DB = process.env.DB.replace('<password>', process.env.DB_PASSWORD);
mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log(con.connections);
    console.log('DB connection successful!');
  });


问:
How to inner join 3 tables in SQL with different path
I want to do an inner join adding the database table SPF but different paths and table CSF, also different paths. For the RSG table using the path of the string connection.

Please recommend.

Table CSF

Path : C:\STACK\ADMIN

NMA
RFN

TATI
B.01.01.001.033

Table SPF

Path: C:\STACK\ADMIN

NMA
RFN

TATI
B.01.01.001.033

Thanks

```<code>SELECT s.NMA
FROM CSF AS s
INNER JOIN RSG AS c ON c.SAC = s.RFN
WHERE PNM = @PNM
</code>```

Body:
I want to do an inner join adding the database table SPF but different paths and table CSF, also different paths. For the RSG table using the path of the string connection.

Please recommend.

Table CSF

Path : C:\STACK\ADMIN

NMA
RFN

TATI
B.01.01.001.033

Table SPF

Path: C:\STACK\ADMIN

NMA
RFN

TATI
B.01.01.001.033

Thanks

SELECT s.NMA
FROM CSF AS s
INNER JOIN RSG AS c ON c.SAC = s.RFN
WHERE PNM = @PNM


问:
java.lang.IllegalStateException: Failed to load ApplicationContext error while running maven install
Below is my DTO class:

```<code>@Entity
@Data
@Table(name = "carservice")
public class CarService {

//  public static void main(String[] args) {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        long serviceCode;

        @Column(name = "service")
        private String service;

        @Column(name = "hatchback")
        private String hatchback;

        @Column(name = "sedan")
        private String sedan;

        @Column(name = "suv")
        private String suv;

        public CarService(long serviceCode, String service, String hatchback, String sedan, String suv) {
            super();
            this.serviceCode = serviceCode;
            this.service = service;
            this.hatchback = hatchback;
            this.sedan = sedan;
            this.suv = suv;
        }

        public long getServiceCode() {
            return serviceCode;
        }

        public void setServiceCode(long serviceCode) {
            this.serviceCode = serviceCode;
        }

        public String getService() {
            return service;
        }

        public void setService(String service) {
            this.service = service;
        }

        public String getHatchback() {
            return hatchback;
        }

        public void setHatchback(String hatchback) {
            this.hatchback = hatchback;
        }

        public String getSedan() {
            return sedan;
        }

        public void setSedan(String sedan) {
            this.sedan = sedan;
        }
.....
</code>```

My controller is as follows:

```<code>@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class CarServiceController {

    @Autowired
    CarServiceRepository CarServiceRepository;

    @GetMapping("/CarServices/{id}")
    public ResponseEntity<CarService> getCarServiceById(@PathVariable("id") long id) {
        List<CarService> CarServiceData = CarServiceRepository.findByServiceCode(id);

        if (CarServiceData!=null) {
            return new ResponseEntity<>(CarServiceData.get(0), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

}
</code>```

And the repository class is as follows:

```<code>@Repository
public interface CarServiceRepository extends JpaRepository<CarService, Long> {

    @Query(value = "SELECT * FROM CARSERVICE", nativeQuery = true)
    List<CarService> findByServiceCode(Long id);

//  List<CarService> findByTitleContaining(Long id);

    }
</code>```

When I am running the maven install command , the tests are failing and the error in surefire-reports are as follows:

-------------------------------------------------------------------------------
Test set: com.example.demo.CarServiceApplicationTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.445 s <<< FAILURE! - in com.example.demo.CarServiceApplicationTests
contextLoads  Time elapsed: 0.036 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@7a78d380 testClass = com.example.demo.CarServiceApplicationTests, locations = [], classes = [com.example.demo.CarServiceApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5082d622, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4278284b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@44c73c26, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1ab06251, org.springframework.boot.test.context.SpringBootTestAnnotation@8dc993d1], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carServiceController': Unsatisfied dependency expressed through field 'CarServiceRepository': Error creating bean with name 'carServiceRepository' defined in com.example.demo.repository.CarServiceRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.CarService
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carServiceRepository' defined in com.example.demo.repository.CarServiceRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.CarService
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.model.CarService
```

I've tried many solutions found on the net regarding similar issues but didn't solve my issue. Please help. Thanks in advance!

Body:
Below is my DTO class:

@Entity
@Data
@Table(name = "carservice")
public class CarService {

//  public static void main(String[] args) {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        long serviceCode;

        @Column(name = "service")
        private String service;

        @Column(name = "hatchback")
        private String hatchback;

        @Column(name = "sedan")
        private String sedan;

        @Column(name = "suv")
        private String suv;

        public CarService(long serviceCode, String service, String hatchback, String sedan, String suv) {
            super();
            this.serviceCode = serviceCode;
            this.service = service;
            this.hatchback = hatchback;
            this.sedan = sedan;
            this.suv = suv;
        }

        public long getServiceCode() {
            return serviceCode;
        }

        public void setServiceCode(long serviceCode) {
            this.serviceCode = serviceCode;
        }

        public String getService() {
            return service;
        }

        public void setService(String service) {
            this.service = service;
        }

        public String getHatchback() {
            return hatchback;
        }

        public void setHatchback(String hatchback) {
            this.hatchback = hatchback;
        }

        public String getSedan() {
            return sedan;
        }

        public void setSedan(String sedan) {
            this.sedan = sedan;
        }
.....

My controller is as follows:

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class CarServiceController {

    @Autowired
    CarServiceRepository CarServiceRepository;

    @GetMapping("/CarServices/{id}")
    public ResponseEntity<CarService> getCarServiceById(@PathVariable("id") long id) {
        List<CarService> CarServiceData = CarServiceRepository.findByServiceCode(id);

        if (CarServiceData!=null) {
            return new ResponseEntity<>(CarServiceData.get(0), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

}

And the repository class is as follows:

@Repository
public interface CarServiceRepository extends JpaRepository<CarService, Long> {

    @Query(value = "SELECT * FROM CARSERVICE", nativeQuery = true)
    List<CarService> findByServiceCode(Long id);

//  List<CarService> findByTitleContaining(Long id);

    }

When I am running the maven install command , the tests are failing and the error in surefire-reports are as follows:

-------------------------------------------------------------------------------
Test set: com.example.demo.CarServiceApplicationTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.445 s <<< FAILURE! - in com.example.demo.CarServiceApplicationTests
contextLoads  Time elapsed: 0.036 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@7a78d380 testClass = com.example.demo.CarServiceApplicationTests, locations = [], classes = [com.example.demo.CarServiceApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5082d622, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4278284b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@44c73c26, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1ab06251, org.springframework.boot.test.context.SpringBootTestAnnotation@8dc993d1], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carServiceController': Unsatisfied dependency expressed through field 'CarServiceRepository': Error creating bean with name 'carServiceRepository' defined in com.example.demo.repository.CarServiceRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.CarService
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carServiceRepository' defined in com.example.demo.repository.CarServiceRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.CarService
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.model.CarService

I've tried many solutions found on the net regarding similar issues but didn't solve my issue. Please help. Thanks in advance!


问:
sbt publish generates html instead of class
I have a scala library that i'm packaging with sbt, in my local bash, i can publish it succesfully to nexus, but when i use gitlab ci/cd with same command (sbt publish) the generated jar contains only html files:
here's my build.sbt:

```<code>organization := "com.example"
name := "liblib"
version := "1.0"

publishTo := Some("nexus" at "nexus/repo")

credentials += Credentials(Path.userHome / ".sbt" / ".credentials")
</code>```

and my gitlab.ci

```<code>package:
  stage: build
  image: scala-sbt:8u312_1.5.5_2.12.15
  script:
    # Build
    - sbt clean test:compile
    # Test
    - sbt coverage test
    - sbt coverageReport
    - mv target target-for-sonar
    # Package
    - sbt clean compile package
  artifacts:
    name: "$CI_JOB_NAME artifacts from $CI_PROJECT_NAME on $CI_COMMIT_REF_SLUG"
    paths:
      - target
      - target-for-sonar
    expire_in: 1 week

publish:
  stage: publish
  image: scala-sbt:8u312_1.5.5_2.12.15
  script:
    - sbt publish
  rules:
    - when: manual
</code>```

Body:
I have a scala library that i'm packaging with sbt, in my local bash, i can publish it succesfully to nexus, but when i use gitlab ci/cd with same command (sbt publish) the generated jar contains only html files:
here's my build.sbt:

organization := "com.example"
name := "liblib"
version := "1.0"

publishTo := Some("nexus" at "nexus/repo")

credentials += Credentials(Path.userHome / ".sbt" / ".credentials")

and my gitlab.ci

package:
  stage: build
  image: scala-sbt:8u312_1.5.5_2.12.15
  script:
    # Build
    - sbt clean test:compile
    # Test
    - sbt coverage test
    - sbt coverageReport
    - mv target target-for-sonar
    # Package
    - sbt clean compile package
  artifacts:
    name: "$CI_JOB_NAME artifacts from $CI_PROJECT_NAME on $CI_COMMIT_REF_SLUG"
    paths:
      - target
      - target-for-sonar
    expire_in: 1 week

publish:
  stage: publish
  image: scala-sbt:8u312_1.5.5_2.12.15
  script:
    - sbt publish
  rules:
    - when: manual


问:
itemSelectionChanged not firing a signal
I've created this whole thing with ChatGPT so I don't have much knowledge on how each individual part works but essentially whenever I click on a "tag" in the list widget, I want it to add/remove that "tag" to from a "global array" which I believe is called "self.tags".

```<code>import sys
import sqlite3

from PyQt5.QtWidgets import QAbstractItemView
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QTextStream, QFile, QIODevice
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QPushButton,
                             QVBoxLayout, QHBoxLayout, QFileDialog, QListWidget, QLineEdit, QSplitter)

class ImageTagger(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.tags = []
        # Create a label to display the image
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)

        # Create a list widget to display the tags
        self.tag_list = QListWidget()
        self.tag_list.setSelectionMode(QListWidget.MultiSelection)
        self.tag_list.itemClicked.connect(self.updateSelectedTags)

        # Create a line edit for the search bar
        self.search_bar = QLineEdit()
        self.search_bar.textChanged.connect(self.searchTags)

        # Create a button to select the folder
        self.select_folder_button = QPushButton("Select Folder")
        self.select_folder_button.clicked.connect(self.selectFolder)

        # Create a button to save the tags
        self.save_tags_button = QPushButton("Save Tags")
        self.save_tags_button.clicked.connect(self.saveTags)

        # Create a button to go to the next image
        self.next_button = QPushButton("Next")
        self.next_button.clicked.connect(self.nextImage)

        # Create a button to go to the previous image
        self.prev_button = QPushButton("Prev")
        self.prev_button.clicked.connect(self.prevImage)

        # Create a vertical layout to hold the search bar and tag list
        vbox = QVBoxLayout()
        vbox.addWidget(self.search_bar)
        vbox.addWidget(self.tag_list)

        # Create a horizontal layout to hold the buttons
        hbox = QHBoxLayout()
        hbox.addWidget(self.select_folder_button)
        hbox.addWidget(self.save_tags_button)
        hbox.addWidget(self.prev_button)
        hbox.addWidget(self.next_button)

        # Add the layouts to a widget
        widget = QWidget()
        widget.setLayout(vbox)

        # Create a splitter to split the main layout into two parts
        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.image_label)
        splitter.addWidget(widget)

        # Set the sizes of the widgets in the splitter
        splitter.setSizes([600, 200])

        # Add the splitter and the hbox layout to the main layout
        main_layout = QVBoxLayout()
        main_layout.addWidget(splitter)
        main_layout.addLayout(hbox)

        # Create a central widget and set its layout
        central_widget = QWidget()
        central_widget.setLayout(main_layout)

        # Set the central widget as the central widget of the main window
        self.setCentralWidget(central_widget)

        # Load the tags from the database
        self.loadTags()

        # Set the main window properties
        self.setGeometry(300, 300, 800, 600)
        self.setWindowTitle("Image Tagger")

    def selectFolder(self):
        # Show the "Select Folder" dialog and get the selected folder
        folder = QFileDialog.getExistingDirectory(self, "Select Folder")
        if folder:
            # Set the current folder
            self.current_folder = folder
            # Get the list of images in the folder
            self.image_list = [f for f in os.listdir(self.current_folder) if f.endswith(".jpg") or f.endswith(".png")]
            # Set the current image index to the first image
            self.current_image_index = 0
            # Display the first image
            self.displayImage()
        # Clear the list of tags
        self.tag_list.clear()

        # Load the tags from the database
        self.loadTags()

    def displayImage(self):
        try:
            # Load the image file
            image_file_path = os.path.join(self.current_folder, self.image_list[self.current_image_index])
            image = QPixmap(image_file_path)
            # Display the image
            max_size = self.image_label.maximumSize()
            scaled_image = image.scaled(max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.image_label.setPixmap(QPixmap(image))
        except Exception as e:
            print(f"Error loading image: {e}")
            self.image_label.setText("Error loading image")

    def saveTags(self):
        # Get the list of selected tags
        selected_tags = [self.tag_list.item(i).text() for i in range(self.tag_list.count()) if
                         self.tag_list.item(i).isSelected()]
        # Join the tags into a single string
        tags_string = ", ".join(selected_tags)
        # Get the name of the current image file
        image_file_name = self.image_list[self.current_image_index]
        # Create the name of the text file
        text_file_name = os.path.splitext(image_file_name)[0] + ".txt"
        # Open the text file for writing
        with open(os.path.join(self.current_folder, text_file_name), "w") as f:
            # Write the tags to the text file
            f.write(tags_string)

    def nextImage(self):
        # Increment the current image index
        self.current_image_index += 1
        # If the index is out of range, wrap around to the first image
        if self.current_image_index >= len(self.image_list):
            self.current_image_index = 0
        # Display the image
        self.displayImage()

    def prevImage(self):
        # Decrement the current image index
        self.current_image_index -= 1
        # If the index is out of range, wrap around to the last image
        if self.current_image_index < 0:
            self.current_image_index = len(self.image_list) - 1
        # Display the image
        self.displayImage()

    def loadTags(self):
        # Check if the current folder is set
        if not hasattr(self, 'current_folder'):
            return

        # Connect to the database
        conn = sqlite3.connect(os.path.join(self.current_folder, "tags.db"))
        c = conn.cursor()

        # Load the tags from the database
        c.execute("SELECT tag FROM tags")
        tags = c.fetchall()

        # Add the tags to the list widget
        self.tag_list.clear()
        for tag in tags:
            self.tag_list.addItem(tag[0])

        # Sort the tags alphabetically
        self.tags = sorted(tags)

        # Close the connection to the database
        conn.close()

    def searchTags(self):
        # Get the search string
        search_text = self.search_bar.text()

        # Clear the list widget
        self.tag_list.clear()
        try:
            # Iterate through the tags and add the ones that contain the search string
            for tag in self.tags:
                if search_text.lower() in tag[0].lower():
                    self.tag_list.addItem(tag[0])
        except Exception as e:
            # Print the error message
            print(e)

    def updateSelectedTags(self):
        # Get the list of selected items in the list widget
        selected_items = self.tag_list.selectedItems()

        # Clear the list of selected tags
        self.tags.clear()

        # Add the text of each selected item to the list of selected tags
        for item in selected_items:
            self.tags.append(item.text())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ImageTagger()
    ex.show()
    sys.exit(app.exec_())

</code>```

The reason why I am doing this is because when the .db file is loaded and stored into a tag_list array and when I click on a tag in the list widget then type any character in the search bar it forgets/replaces the tags that I previously clicked. I have NO CLUE why the self.tag_list.itemClicked.connect(self.updateSelectedTags) signal isn't firing (or at least the debug isn't catching it)

I'm done ripping me hair out over this. I would appreciate any help or a better method of doing this. ChatGPT can only help so much.

Body:
I've created this whole thing with ChatGPT so I don't have much knowledge on how each individual part works but essentially whenever I click on a "tag" in the list widget, I want it to add/remove that "tag" to from a "global array" which I believe is called "self.tags".

import sys
import sqlite3

from PyQt5.QtWidgets import QAbstractItemView
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QTextStream, QFile, QIODevice
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QPushButton,
                             QVBoxLayout, QHBoxLayout, QFileDialog, QListWidget, QLineEdit, QSplitter)

class ImageTagger(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.tags = []
        # Create a label to display the image
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)

        # Create a list widget to display the tags
        self.tag_list = QListWidget()
        self.tag_list.setSelectionMode(QListWidget.MultiSelection)
        self.tag_list.itemClicked.connect(self.updateSelectedTags)

        # Create a line edit for the search bar
        self.search_bar = QLineEdit()
        self.search_bar.textChanged.connect(self.searchTags)

        # Create a button to select the folder
        self.select_folder_button = QPushButton("Select Folder")
        self.select_folder_button.clicked.connect(self.selectFolder)

        # Create a button to save the tags
        self.save_tags_button = QPushButton("Save Tags")
        self.save_tags_button.clicked.connect(self.saveTags)

        # Create a button to go to the next image
        self.next_button = QPushButton("Next")
        self.next_button.clicked.connect(self.nextImage)

        # Create a button to go to the previous image
        self.prev_button = QPushButton("Prev")
        self.prev_button.clicked.connect(self.prevImage)

        # Create a vertical layout to hold the search bar and tag list
        vbox = QVBoxLayout()
        vbox.addWidget(self.search_bar)
        vbox.addWidget(self.tag_list)

        # Create a horizontal layout to hold the buttons
        hbox = QHBoxLayout()
        hbox.addWidget(self.select_folder_button)
        hbox.addWidget(self.save_tags_button)
        hbox.addWidget(self.prev_button)
        hbox.addWidget(self.next_button)

        # Add the layouts to a widget
        widget = QWidget()
        widget.setLayout(vbox)

        # Create a splitter to split the main layout into two parts
        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.image_label)
        splitter.addWidget(widget)

        # Set the sizes of the widgets in the splitter
        splitter.setSizes([600, 200])

        # Add the splitter and the hbox layout to the main layout
        main_layout = QVBoxLayout()
        main_layout.addWidget(splitter)
        main_layout.addLayout(hbox)

        # Create a central widget and set its layout
        central_widget = QWidget()
        central_widget.setLayout(main_layout)

        # Set the central widget as the central widget of the main window
        self.setCentralWidget(central_widget)

        # Load the tags from the database
        self.loadTags()

        # Set the main window properties
        self.setGeometry(300, 300, 800, 600)
        self.setWindowTitle("Image Tagger")

    def selectFolder(self):
        # Show the "Select Folder" dialog and get the selected folder
        folder = QFileDialog.getExistingDirectory(self, "Select Folder")
        if folder:
            # Set the current folder
            self.current_folder = folder
            # Get the list of images in the folder
            self.image_list = [f for f in os.listdir(self.current_folder) if f.endswith(".jpg") or f.endswith(".png")]
            # Set the current image index to the first image
            self.current_image_index = 0
            # Display the first image
            self.displayImage()
        # Clear the list of tags
        self.tag_list.clear()

        # Load the tags from the database
        self.loadTags()

    def displayImage(self):
        try:
            # Load the image file
            image_file_path = os.path.join(self.current_folder, self.image_list[self.current_image_index])
            image = QPixmap(image_file_path)
            # Display the image
            max_size = self.image_label.maximumSize()
            scaled_image = image.scaled(max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.image_label.setPixmap(QPixmap(image))
        except Exception as e:
            print(f"Error loading image: {e}")
            self.image_label.setText("Error loading image")

    def saveTags(self):
        # Get the list of selected tags
        selected_tags = [self.tag_list.item(i).text() for i in range(self.tag_list.count()) if
                         self.tag_list.item(i).isSelected()]
        # Join the tags into a single string
        tags_string = ", ".join(selected_tags)
        # Get the name of the current image file
        image_file_name = self.image_list[self.current_image_index]
        # Create the name of the text file
        text_file_name = os.path.splitext(image_file_name)[0] + ".txt"
        # Open the text file for writing
        with open(os.path.join(self.current_folder, text_file_name), "w") as f:
            # Write the tags to the text file
            f.write(tags_string)

    def nextImage(self):
        # Increment the current image index
        self.current_image_index += 1
        # If the index is out of range, wrap around to the first image
        if self.current_image_index >= len(self.image_list):
            self.current_image_index = 0
        # Display the image
        self.displayImage()

    def prevImage(self):
        # Decrement the current image index
        self.current_image_index -= 1
        # If the index is out of range, wrap around to the last image
        if self.current_image_index < 0:
            self.current_image_index = len(self.image_list) - 1
        # Display the image
        self.displayImage()

    def loadTags(self):
        # Check if the current folder is set
        if not hasattr(self, 'current_folder'):
            return

        # Connect to the database
        conn = sqlite3.connect(os.path.join(self.current_folder, "tags.db"))
        c = conn.cursor()

        # Load the tags from the database
        c.execute("SELECT tag FROM tags")
        tags = c.fetchall()

        # Add the tags to the list widget
        self.tag_list.clear()
        for tag in tags:
            self.tag_list.addItem(tag[0])

        # Sort the tags alphabetically
        self.tags = sorted(tags)

        # Close the connection to the database
        conn.close()

    def searchTags(self):
        # Get the search string
        search_text = self.search_bar.text()

        # Clear the list widget
        self.tag_list.clear()
        try:
            # Iterate through the tags and add the ones that contain the search string
            for tag in self.tags:
                if search_text.lower() in tag[0].lower():
                    self.tag_list.addItem(tag[0])
        except Exception as e:
            # Print the error message
            print(e)

    def updateSelectedTags(self):
        # Get the list of selected items in the list widget
        selected_items = self.tag_list.selectedItems()

        # Clear the list of selected tags
        self.tags.clear()

        # Add the text of each selected item to the list of selected tags
        for item in selected_items:
            self.tags.append(item.text())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ImageTagger()
    ex.show()
    sys.exit(app.exec_())

The reason why I am doing this is because when the .db file is loaded and stored into a tag_list array and when I click on a tag in the list widget then type any character in the search bar it forgets/replaces the tags that I previously clicked. I have NO CLUE why the self.tag_list.itemClicked.connect(self.updateSelectedTags) signal isn't firing (or at least the debug isn't catching it)

I'm done ripping me hair out over this. I would appreciate any help or a better method of doing this. ChatGPT can only help so much.


问:
How to convert grayscale photo pixel values from 10bit to 8bit in Python?
I have a binary file with pixels whose grayscale depth is 10 bits. How can I make an image out of such pixels?

```<code>from bitstring import ConstBitStream
import bitstring, time, sys
start_time = time.time()
b = ConstBitStream(filename=str(sys.argv[1]))
while True:
    try:
        output = b.read(10)
    except bitstring.ReadError:
        print("--- %s seconds ---" % (time.time() - start_time))
        sys.exit()
    with open(str(sys.argv[2]), 'ab') as file:
        file.write((int(output.uint/4)).to_bytes(1, byteorder='big', signed=False))
</code>```

I tried this code to convert 10bit pixels to 8bit to save it as an 8bit grayscale image, but converting such a file from 10bit to 8bit takes a very long time. How can I make it faster?

UPDATE

I decided to redo this script. I decided to convert the file to a bit stream and then divide it into values of 10 bits -> deleting the last 2 bits and writing to the file. It works very fast!

```<code>Total chunks: 104751130
Input file weight: 130938912
Output file weight: 104751130
Total time: 58.524515867233276
</code>```

And new code:

```<code>import bitstring, time, os
start_time = time.time()
file = open('file.bin', 'rb').read() # Read input file
b = bitstring.BitStream(file).bin # Make bitstream
chunks = [b[i:i+10] for i in range(0, len(b), 10)] # Make list with bin data and with len = 10 bit
chunks = [str[:-2] for str in chunks] # cut 2 bit from end (10->8 bit)
with open('outdata.new', 'wb') as file:
    bitstring.BitArray(bin=''.join(chunks)).tofile(file) # Convert List to Str and write bits to file
print('Total chunks: '+str(len(chunks)))
print('Input file weight: '+str(os.path.getsize("file.bin")))
print('Output file weight: '+str(os.path.getsize("outdata.new")))
print('Total time: '+str(time.time()-start_time))
</code>```

I hope this can also help someone!

Body:
I have a binary file with pixels whose grayscale depth is 10 bits. How can I make an image out of such pixels?

from bitstring import ConstBitStream
import bitstring, time, sys
start_time = time.time()
b = ConstBitStream(filename=str(sys.argv[1]))
while True:
    try:
        output = b.read(10)
    except bitstring.ReadError:
        print("--- %s seconds ---" % (time.time() - start_time))
        sys.exit()
    with open(str(sys.argv[2]), 'ab') as file:
        file.write((int(output.uint/4)).to_bytes(1, byteorder='big', signed=False))

I tried this code to convert 10bit pixels to 8bit to save it as an 8bit grayscale image, but converting such a file from 10bit to 8bit takes a very long time. How can I make it faster?

UPDATE

I decided to redo this script. I decided to convert the file to a bit stream and then divide it into values of 10 bits -> deleting the last 2 bits and writing to the file. It works very fast!

Total chunks: 104751130
Input file weight: 130938912
Output file weight: 104751130
Total time: 58.524515867233276

And new code:

import bitstring, time, os
start_time = time.time()
file = open('file.bin', 'rb').read() # Read input file
b = bitstring.BitStream(file).bin # Make bitstream
chunks = [b[i:i+10] for i in range(0, len(b), 10)] # Make list with bin data and with len = 10 bit
chunks = [str[:-2] for str in chunks] # cut 2 bit from end (10->8 bit)
with open('outdata.new', 'wb') as file:
    bitstring.BitArray(bin=''.join(chunks)).tofile(file) # Convert List to Str and write bits to file
print('Total chunks: '+str(len(chunks)))
print('Input file weight: '+str(os.path.getsize("file.bin")))
print('Output file weight: '+str(os.path.getsize("outdata.new")))
print('Total time: '+str(time.time()-start_time))

I hope this can also help someone!


问:
How can I fix the Cors Enable issue in an API I created in WSO2 Integration Studio?
When I call an API that I created in Integration Studio from within a localhost application, I get a CORS error. How can I fix this.?

Although cors enabled  in deployment.toml file.

```<code>[synapse_properties]
'synapse.rest.CORSConfig.enabled' = "true"
'synapse.rest.CORSConfig.Access-Control-Allow-Origin' = "*"
'synapse.rest.CORSConfig.Access-Control-Allow-Headers' = "content-type"
</code>```

Body:
When I call an API that I created in Integration Studio from within a localhost application, I get a CORS error. How can I fix this.?

Although cors enabled  in deployment.toml file.

[synapse_properties]
'synapse.rest.CORSConfig.enabled' = "true"
'synapse.rest.CORSConfig.Access-Control-Allow-Origin' = "*"
'synapse.rest.CORSConfig.Access-Control-Allow-Headers' = "content-type"


问:
*solved* Nginx Rewrite : Regex failed, i need some advice
I tried many versions but my regex doesn't work.

url tested : https://mywebsite.com/mypage.html#page123

All of this fail

```<code>rewrite ^/\#(.*)$ /myscript.php?mode=multi&blob=$1 break
rewrite ^/\#(page)[0-9]$ /myscript.php?mode=multi&blob=$1 break
rewrite ^/[[:graph:]](page)[0-9]$ /myscript.php?mode=multi&blob=$1 break
</code>```

nginx reboot fail because {1,3} part

```<code>rewrite ^/\#(page)[0-9]{1,3}*$ /myscript.php?mode=multi&blob=$1 break
</code>```

OK, this works fine but missing information about page

```<code>rewrite ^/([a-z0-9\-]+).html$ /myscript.php?mode=default&id=$1 break;
</code>```

myscript.php has only one line :

```<code>print_r($\_REQUEST);
exit();
</code>```

Each time, my script only print : Array ( [mode] => default [id] => mypage )

(sorry, bad english sometime)

All of this works fine too on https://regex101.com/

Body:
I tried many versions but my regex doesn't work.

url tested : https://mywebsite.com/mypage.html#page123

All of this fail

rewrite ^/\#(.*)$ /myscript.php?mode=multi&blob=$1 break
rewrite ^/\#(page)[0-9]$ /myscript.php?mode=multi&blob=$1 break
rewrite ^/[[:graph:]](page)[0-9]$ /myscript.php?mode=multi&blob=$1 break

nginx reboot fail because {1,3} part

rewrite ^/\#(page)[0-9]{1,3}*$ /myscript.php?mode=multi&blob=$1 break

OK, this works fine but missing information about page

rewrite ^/([a-z0-9\-]+).html$ /myscript.php?mode=default&id=$1 break;

myscript.php has only one line :

print_r($\_REQUEST);
exit();

Each time, my script only print : Array ( [mode] => default [id] => mypage )

(sorry, bad english sometime)

All of this works fine too on https://regex101.com/


问:
Swagger generates a correct scheme for derived objects but does not serialize them correct
I am trying to generate an API that responses with an Object that have an array property of a Base class.

In the Setup I have tried both UseAllOfForInheritance and UseOneOfForPolymorphism options with specifying corresponded settings like SelectSubTypesUsing, SelectDiscriminatorNameUsing and SelectDiscriminatorValueUsing.

As the result I see in Swagger UI the corect scheme and in the generated code the Base Object with correct genereated fromJS() method. The derived objects are also correct generated and have proper implementation their toJSON(data?: any) method.

The problem is that I cannot see the correct serialized derived objects in the Swagger UI and direct in the response. The indicators of the problem are:

the "discriminator" property is not serialized

the own public properties of the derived classes are not serialized.

What I am still missing?

As a workaround I could solve my issue this way:

```<code>services.AddControllers().AddNewtonsoftJson(j =>
            {
                var converterBuilder = JsonSubtypesConverterBuilder.Of(typeof(MyBaseDto), discriminator);
                var baseType = typeof(MyBaseDto);

                foreach (var subtype in baseType.Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType)))
                {
                    converterBuilder.RegisterSubtype(subtype, subtype.Name);
                }

                j.SerializerSettings.Converters.Add(converterBuilder.SerializeDiscriminatorProperty().Build());
            });
</code>```

but I am not sure if I gave up a little bit early, and replaced initial swagger idea by a hack.

version info: <PackageReference Include="NSwag.MSBuild" Version="13.15.10">

Body:
I am trying to generate an API that responses with an Object that have an array property of a Base class.

In the Setup I have tried both UseAllOfForInheritance and UseOneOfForPolymorphism options with specifying corresponded settings like SelectSubTypesUsing, SelectDiscriminatorNameUsing and SelectDiscriminatorValueUsing.

As the result I see in Swagger UI the corect scheme and in the generated code the Base Object with correct genereated fromJS() method. The derived objects are also correct generated and have proper implementation their toJSON(data?: any) method.

The problem is that I cannot see the correct serialized derived objects in the Swagger UI and direct in the response. The indicators of the problem are:

the "discriminator" property is not serialized

the own public properties of the derived classes are not serialized.

What I am still missing?

As a workaround I could solve my issue this way:

services.AddControllers().AddNewtonsoftJson(j =>
            {
                var converterBuilder = JsonSubtypesConverterBuilder.Of(typeof(MyBaseDto), discriminator);
                var baseType = typeof(MyBaseDto);

                foreach (var subtype in baseType.Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType)))
                {
                    converterBuilder.RegisterSubtype(subtype, subtype.Name);
                }

                j.SerializerSettings.Converters.Add(converterBuilder.SerializeDiscriminatorProperty().Build());
            });

but I am not sure if I gave up a little bit early, and replaced initial swagger idea by a hack.

version info: <PackageReference Include="NSwag.MSBuild" Version="13.15.10">


问:
Removing data from seurat object
I have single cell sequencing data stored in a seurat object. I tried different clustering resolutions on it using:

```<code>sunion <- ScaleData(sunion, verbose = FALSE)
sunion <- RunPCA(sunion, npcs = 50, verbose = FALSE)
sunion <- RunUMAP(sunion, reduction = "pca", dims = 1:50)
sunion <- FindNeighbors(sunion, reduction = "pca", dims = 1:50)
sunion <- FindClusters(sunion, resolution = 0.5)
</code>```

Just now I noticed that I have total of 9 different resolutions of clusterings saved in the seurat object and that has inflated the file size. I tried to remove unnecessary resolutions like this

```<code>data<-sunion@meta.data[,c(1:26,29,30,31,34,35,41)]
sunion<-data
</code>```

but this only saved the meta.data from seurat object and the object turned into a dataframe. How do I remove the unnecessary data from my object?

Edit: Additional info: The data is stored in sunion@meta.data$integrated_snn_res.XXX

Title: Removing data from seurat object

Body:
I have single cell sequencing data stored in a seurat object. I tried different clustering resolutions on it using:

sunion <- ScaleData(sunion, verbose = FALSE)
sunion <- RunPCA(sunion, npcs = 50, verbose = FALSE)
sunion <- RunUMAP(sunion, reduction = "pca", dims = 1:50)
sunion <- FindNeighbors(sunion, reduction = "pca", dims = 1:50)
sunion <- FindClusters(sunion, resolution = 0.5)

Just now I noticed that I have total of 9 different resolutions of clusterings saved in the seurat object and that has inflated the file size. I tried to remove unnecessary resolutions like this

data<-sunion@meta.data[,c(1:26,29,30,31,34,35,41)]
sunion<-data

but this only saved the meta.data from seurat object and the object turned into a dataframe. How do I remove the unnecessary data from my object?

Edit: Additional info: The data is stored in sunion@meta.data$integrated_snn_res.XXX


问:
How to remove boxes around symbols in ggplot2 legend
Similar to the recent post (see: How to remove boxes around ggplot2 legend labels), I am not able to get rid of the boxes around the symbols of in the legend. Here the code and below some of the data and the plot:

```<code>theme_opts_V5 <- list(theme(
  panel.grid.minor.x = element_line(color = "transparent"),
  panel.grid.major.x = element_line(color = "transparent"),
  panel.grid.minor = element_line(color = "grey"),
  panel.grid.major = element_line(color = "grey"),
  panel.background = element_blank(),
  plot.background = element_rect(),
  panel.border = element_blank(),
  axis.line = element_line(colour = "black")
))

ggplot(data, aes(x = value, y = old_value, fill = category, color = category)) +
  geom_hline(
    yintercept = 0, linetype = "solid",
    color = "#898800", size = 1
  ) +
  geom_vline(
    xintercept = 57, linetype = "solid",
    color = "#898800", size = 1
  ) +
  geom_text(aes(x = 61, label = "Mean", y = 15), colour = "#898800", angle = 0, size = 3.4) +
  geom_point(size = 3, shape = 23) +
  labs(
    title = "Title",
    subtitle = "Subtitle",
    caption = "Source"
  ) +
  xlab("new, in %") +
  ylab("change to old") +
  scale_color_manual(values = c("#440154", "#3b528b")) +
  scale_fill_manual(values = c("#440154", "#3b528b")) +
  theme(
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.key = element_rect(fill = NA)
  ) +
  theme(legend.background = element_blank()) +
  theme_opts_V5 +
  scale_x_continuous(limits = c(30, 80), breaks = seq(30, 80, by = 10), expand = c(0, 0)) +
  scale_y_continuous(limits = c(-30, 20), breaks = seq(-30, 20, by = 10), expand = c(0, 0))
</code>```

Here you find a snippet of my data:

```<code>structure(list(city = c("Aadorf", "Affeltrangen", "Altnau", "Amlikon-Bissegg",
"Amriswil", "Arbon", "Basadingen-Schlattingen", "Berg", "Berlingen",
"Bettwiesen", "Bichelsee-Balterswil", "Birwinken", "Bischofszell",
"Bottighofen", "Braunau", "Bürglen", "Bussnang", "Diessenhofen",
"Dozwil", "Egnach"), value = c(55L, 48L, 60L, 70L, 63L, 76L,
52L, 42L, 53L, 49L, 49L, 57L, 70L, 36L, 49L, 69L, 47L, 47L, 44L,
57L), old_value = c(4L, 2L, -1L, 0L, 0L, 0L, 3L, -3L, -2L, 6L,
5L, -11L, -2L, -3L, -3L, 6L, -3L, 0L, -8L, -3L), category = c("low",
"low", "low", "low", "high", "high", "low", "low", "low", "low",
"low", "low", "low", "low", "low", "low", "low", "low", "low",
"low")), row.names = c(NA, 20L), class = "data.frame")

</code>```

And the plot:

Thanks for any help!

Sorry for the incompleteness of the post. Here is the code for theme_opts_V5 that only defines background and grid lines of the plot: `

```<code>theme_opts_V5 <- list(theme(panel.grid.minor.x = element_line(color = "transparent"),
                            panel.grid.major.x = element_line(color = "transparent"),
                            panel.grid.minor = element_line(color = "grey"),
                            panel.grid.major = element_line(color = "grey"),
                            panel.background = element_blank(),
                            plot.background = element_rect(),
                            panel.border = element_blank(),
                            axis.line = element_line(colour = "black")))

```

Thank you in advance!
```

Body:
Similar to the recent post (see: How to remove boxes around ggplot2 legend labels), I am not able to get rid of the boxes around the symbols of in the legend. Here the code and below some of the data and the plot:

theme_opts_V5 <- list(theme(
  panel.grid.minor.x = element_line(color = "transparent"),
  panel.grid.major.x = element_line(color = "transparent"),
  panel.grid.minor = element_line(color = "grey"),
  panel.grid.major = element_line(color = "grey"),
  panel.background = element_blank(),
  plot.background = element_rect(),
  panel.border = element_blank(),
  axis.line = element_line(colour = "black")
))

ggplot(data, aes(x = value, y = old_value, fill = category, color = category)) +
  geom_hline(
    yintercept = 0, linetype = "solid",
    color = "#898800", size = 1
  ) +
  geom_vline(
    xintercept = 57, linetype = "solid",
    color = "#898800", size = 1
  ) +
  geom_text(aes(x = 61, label = "Mean", y = 15), colour = "#898800", angle = 0, size = 3.4) +
  geom_point(size = 3, shape = 23) +
  labs(
    title = "Title",
    subtitle = "Subtitle",
    caption = "Source"
  ) +
  xlab("new, in %") +
  ylab("change to old") +
  scale_color_manual(values = c("#440154", "#3b528b")) +
  scale_fill_manual(values = c("#440154", "#3b528b")) +
  theme(
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.key = element_rect(fill = NA)
  ) +
  theme(legend.background = element_blank()) +
  theme_opts_V5 +
  scale_x_continuous(limits = c(30, 80), breaks = seq(30, 80, by = 10), expand = c(0, 0)) +
  scale_y_continuous(limits = c(-30, 20), breaks = seq(-30, 20, by = 10), expand = c(0, 0))

Here you find a snippet of my data:

structure(list(city = c("Aadorf", "Affeltrangen", "Altnau", "Amlikon-Bissegg",
"Amriswil", "Arbon", "Basadingen-Schlattingen", "Berg", "Berlingen",
"Bettwiesen", "Bichelsee-Balterswil", "Birwinken", "Bischofszell",
"Bottighofen", "Braunau", "Bürglen", "Bussnang", "Diessenhofen",
"Dozwil", "Egnach"), value = c(55L, 48L, 60L, 70L, 63L, 76L,
52L, 42L, 53L, 49L, 49L, 57L, 70L, 36L, 49L, 69L, 47L, 47L, 44L,
57L), old_value = c(4L, 2L, -1L, 0L, 0L, 0L, 3L, -3L, -2L, 6L,
5L, -11L, -2L, -3L, -3L, 6L, -3L, 0L, -8L, -3L), category = c("low",
"low", "low", "low", "high", "high", "low", "low", "low", "low",
"low", "low", "low", "low", "low", "low", "low", "low", "low",
"low")), row.names = c(NA, 20L), class = "data.frame")

And the plot:

Thanks for any help!

Sorry for the incompleteness of the post. Here is the code for theme_opts_V5 that only defines background and grid lines of the plot: `

theme_opts_V5 <- list(theme(panel.grid.minor.x = element_line(color = "transparent"),
                            panel.grid.major.x = element_line(color = "transparent"),
                            panel.grid.minor = element_line(color = "grey"),
                            panel.grid.major = element_line(color = "grey"),
                            panel.background = element_blank(),
                            plot.background = element_rect(),
                            panel.border = element_blank(),
                            axis.line = element_line(colour = "black")))

```

Thank you in advance!


问:
Leaflet draw does not show the area of the Polygon
I've seen that in some examples using leaflet draw, after drawing the third point, a popup shows the area of the drawn item on the map. I'm unable to replicate this function even setting the

```<code>polygon: {
          showArea: true,
        },
</code>```

Here's my code (angular 13)

```<code>    var drawnItems = new L.FeatureGroup();
    this.map.addLayer(drawnItems);

    var drawControl = new L.Control.Draw({
      draw: {
        polygon: {
          showArea: true,
        },
        marker: false
    },
    edit: {
        featureGroup: drawnItems,
    }
});

  this.map.addControl(drawControl);
  this.map.on('draw:created', function (e) {
    const type = (e as L.DrawEvents.Created).layerType,
    layer = (e as L.DrawEvents.Created).layer;

    drawnItems.addLayer(layer);

});
</code>```

Could you suggest how to do it?

Body:
I've seen that in some examples using leaflet draw, after drawing the third point, a popup shows the area of the drawn item on the map. I'm unable to replicate this function even setting the

polygon: {
          showArea: true,
        },

Here's my code (angular 13)

    var drawnItems = new L.FeatureGroup();
    this.map.addLayer(drawnItems);

    var drawControl = new L.Control.Draw({
      draw: {
        polygon: {
          showArea: true,
        },
        marker: false
    },
    edit: {
        featureGroup: drawnItems,
    }
});

  this.map.addControl(drawControl);
  this.map.on('draw:created', function (e) {
    const type = (e as L.DrawEvents.Created).layerType,
    layer = (e as L.DrawEvents.Created).layer;

    drawnItems.addLayer(layer);

});

Could you suggest how to do it?


问:
Can an end point is connected to more than one router in a NoC topology in gem5 garnet3.0?
I am running gem5 version 22.0.0.2. I operate Garnet in a standalone manner in conjunction with the Garnet Synthetic Traffic injector. I want to emulate a routerless NoC so I guess I need to connect an end point (e.g, Cores, Caches, Directories) to more than one "local" router. I just use a python configuration to configure the topology. But when I do this, there is a runtime error:

```<code>build/NULL/mem/ruby/network/garnet/GarnetNetwork.cc:125: info: Garnet version 3.0
build/NULL/base/stats/group.cc:121: panic: panic condition statGroups.find(name) != statGroups.end() occurred: Stats of the same group share the same name `power_state`.
Memory Usage: 692360 KBytes
Program aborted at tick 0
</code>```

Here is a description from the gem5 documentation: "Each network interface is connected to one or more “local” routers which is could be connected through an “External” link." Here is the link:https://www.gem5.org/documentation/general_docs/ruby/heterogarnet/

Here is the constructor of Stats::Group

```<code>Group(Group *parent, const char *name = nullptr)
</code>```

Here is a description from the gem5 documentation: "there are special cases where the parent group may be null. One such special case is SimObjects where the Python code performs late binding of the group parent."
Here is the link:https://www.gem5.org/documentation/general_docs/statistics/api.
I guess the error may be related to this, but I don't know the exact reason.

Any help would be appreciated.

Thank you.

Body:
I am running gem5 version 22.0.0.2. I operate Garnet in a standalone manner in conjunction with the Garnet Synthetic Traffic injector. I want to emulate a routerless NoC so I guess I need to connect an end point (e.g, Cores, Caches, Directories) to more than one "local" router. I just use a python configuration to configure the topology. But when I do this, there is a runtime error:

build/NULL/mem/ruby/network/garnet/GarnetNetwork.cc:125: info: Garnet version 3.0
build/NULL/base/stats/group.cc:121: panic: panic condition statGroups.find(name) != statGroups.end() occurred: Stats of the same group share the same name `power_state`.
Memory Usage: 692360 KBytes
Program aborted at tick 0

Here is a description from the gem5 documentation: "Each network interface is connected to one or more “local” routers which is could be connected through an “External” link." Here is the link:https://www.gem5.org/documentation/general_docs/ruby/heterogarnet/

Here is the constructor of Stats::Group

Group(Group *parent, const char *name = nullptr)

Here is a description from the gem5 documentation: "there are special cases where the parent group may be null. One such special case is SimObjects where the Python code performs late binding of the group parent."
Here is the link:https://www.gem5.org/documentation/general_docs/statistics/api.
I guess the error may be related to this, but I don't know the exact reason.

Any help would be appreciated.

Thank you.


问:
Generated classes using jaxws-maven-plugin ignores the elements default values
I use the jaxws-maven-plugin to generate Java classes from a wsdl file during the maven build. The pom structure is as below:

```<code>            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.6</version>

                <configuration>
                    <wsdlDirectory>${basedir}/services</wsdlDirectory>
                    <verbose>true</verbose>
                    <keep>true</keep>
                    <xadditionalHeaders>true</xadditionalHeaders>
                    <extension>true</extension>
                </configuration>
                <executions>
                    <execution>
                        <id>wsimport</id>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <phase>generate-sources</phase>
                        <configuration>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

The generated files (example below) do not have the typical getter, like JAXB generated classes, for the xml elements which have default values. When calling the service, the SOAP message does not have the values which were not explicitly set.

```<code>public class Example {

    @XmlElement(name = "Example_tag", required = true, defaultValue = "0")
    protected BigInteger exampleTag;

    /**
     *
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getExampleTag() {
        return exampleTag;
    }
</code>```

I searched a few hours and I found a other plugins (cxf-codegen-plugin or axis2-wsdl2code-maven-plugin) which would work, but are not available for me in our closed nexus system.
Any ideas how to generate the classes with jaxws-maven-plugin and use the elements default values?

I would expect a generated getter as below:

```<code>    public BigInteger getExampleTag() {
    if (exampleTag == null) {
        return BigInteger.ZERO;
    } else {
        return exampleTag;
    }
</code>```

Body:
I use the jaxws-maven-plugin to generate Java classes from a wsdl file during the maven build. The pom structure is as below:

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.6</version>

                <configuration>
                    <wsdlDirectory>${basedir}/services</wsdlDirectory>
                    <verbose>true</verbose>
                    <keep>true</keep>
                    <xadditionalHeaders>true</xadditionalHeaders>
                    <extension>true</extension>
                </configuration>
                <executions>
                    <execution>
                        <id>wsimport</id>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <phase>generate-sources</phase>
                        <configuration>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

The generated files (example below) do not have the typical getter, like JAXB generated classes, for the xml elements which have default values. When calling the service, the SOAP message does not have the values which were not explicitly set.

public class Example {

    @XmlElement(name = "Example_tag", required = true, defaultValue = "0")
    protected BigInteger exampleTag;

    /**
     *
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getExampleTag() {
        return exampleTag;
    }

I searched a few hours and I found a other plugins (cxf-codegen-plugin or axis2-wsdl2code-maven-plugin) which would work, but are not available for me in our closed nexus system.
Any ideas how to generate the classes with jaxws-maven-plugin and use the elements default values?

I would expect a generated getter as below:

    public BigInteger getExampleTag() {
    if (exampleTag == null) {
        return BigInteger.ZERO;
    } else {
        return exampleTag;
    }


问:
NextJS CredentialsProvider only returns { email }
this is my first post here on stackoverflow! I'm a beginner in web development.

I'm creating a web application with the NextJS framework.

And I am using NextAuth to authenticate users with data on my database.
But when I return my fetched user from the database with authorize function, this is what I get.
returned object when user logged in

```<code>import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { compare } from 'bcryptjs'

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export const authOptions = {
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        CredentialsProvider({
            type: 'credentials',
            async authorize(credentials, req) {
                const dbUser = await prisma.users.findUnique({
                    where: {
                        email: credentials.email,
                    },
                })
                if (!dbUser) return null
                if (dbUser) {
                    console.log('user found : ', dbUser)
                    const checkPassword = await compare(credentials.password, dbUser.password)
                    console.log(' — checkPassword : ' + checkPassword)
                    if (checkPassword && dbUser) {
                        console.log('credentials OK, user logged in')
                        console.log('lastDbUser', dbUser)
                        return dbUser
                    }
                } else {
                    throw new Error('Invalid credentials')
                }
            },
        }),
    ],
    pages: {
        signIn: '/connexion',
    },
}

export default NextAuth(authOptions)
</code>```

here is my user fetched from the database in dbUser
and i'd like to get this in the session.user

thanks !

I tried the session strategy 'jwt' in options, but no success.

I also saw the callbacks options but in didn't really understand it, if someone can explain it ?

Body:
this is my first post here on stackoverflow! I'm a beginner in web development.

I'm creating a web application with the NextJS framework.

And I am using NextAuth to authenticate users with data on my database.
But when I return my fetched user from the database with authorize function, this is what I get.
returned object when user logged in

import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { compare } from 'bcryptjs'

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export const authOptions = {
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        CredentialsProvider({
            type: 'credentials',
            async authorize(credentials, req) {
                const dbUser = await prisma.users.findUnique({
                    where: {
                        email: credentials.email,
                    },
                })
                if (!dbUser) return null
                if (dbUser) {
                    console.log('user found : ', dbUser)
                    const checkPassword = await compare(credentials.password, dbUser.password)
                    console.log(' — checkPassword : ' + checkPassword)
                    if (checkPassword && dbUser) {
                        console.log('credentials OK, user logged in')
                        console.log('lastDbUser', dbUser)
                        return dbUser
                    }
                } else {
                    throw new Error('Invalid credentials')
                }
            },
        }),
    ],
    pages: {
        signIn: '/connexion',
    },
}

export default NextAuth(authOptions)

here is my user fetched from the database in dbUser
and i'd like to get this in the session.user

thanks !

I tried the session strategy 'jwt' in options, but no success.

I also saw the callbacks options but in didn't really understand it, if someone can explain it ?


问:
How to view photos selected by PhotoPicker(android 13) in phone's gallery
Android 13(sdk 33) has introduced a new PhotoPicker that provides a better way to let the user pick photos in apps but it has some limits.

Now it's possible to get the uri when you select a photo(or photos) but when I want to re-open that uri with Intent.ACTION_VIEW it doesn't work and only opens the google photos app and I have not been able to find a solution for this. The only thing that I found was this link that explains that PhotoPicker URIs are different from other ones and there's a limited set of things that you can do with them. Also here's what google document says if it add any more context:

Specifically, picker URIs can only be opened for read and queried for
columns in PickerMediaColumns

So I need to know if there's a way to open a photo in photo gallery useing PhotoPicker uri or if it's entirely impossible. I'll be glad if you share your thoughts.


问:
Sort elements HTML with javascript [without framework]
I can't find a clear solution to sort elements displayed on screen.

I'm expecting that after clicking button NAME, elements displayed on the screen will be sorted alphabetically. I'm beginner in programming so I don't know how to ask question in google to find solution how to do it.

I found something like sort function but it doesn't work. It works when I displayed list in console log but on page nothing happening.

let closebtns = document.querySelectorAll("span");
//add animal button form
const addMovieModal = document.getElementById('add-modal');
const startAddMovieButton = document.querySelector('section button');
const backdrop = document.getElementById('backdrop');
const cancelAdd = addMovieModal.querySelector('.btn--passive');
const addButton = addMovieModal.querySelector('#btn--success');
const userInput = addMovieModal.querySelectorAll('input');

const clearInputs = () => {
  for (const usrInput of userInput) {
    usrInput.value = "";
  }
}

let listOfAnimals = [{
    name: "Meowsalot",
    age: 10,
    type: "cat",
    favFoods: ["tuna", "catnip", "celery"]
  },

  {
    name: "Barksalot",
    age: 7,
    type: "cat",
    favFoods: []
  },
  {
    name: "Barksalot",
    age: 10,
    type: "dog",
    favFoods: ["tuna", "catnip", "celery"]
  }
];
const name = "NAME: ";
const age = "AGE: ";
const typ = "TYPE: ";
const favFood = "FOOD: "
document.getElementById('li').innerHTML = name + listOfAnimals[0].name + "
" + age + listOfAnimals[0].age + "
" +
  typ + listOfAnimals[0].type + "
" + favFood + listOfAnimals[0].favFoods + "
";
document.getElementById('li1').innerHTML = name + listOfAnimals[1].name + "
" + age + listOfAnimals[1].age + "
" +
  typ + listOfAnimals[1].type + "
" + favFood + listOfAnimals[1].favFoods + "
"
document.getElementById('li2').innerHTML = name + listOfAnimals[2].name + "
" + age + listOfAnimals[2].age + "
" +
  typ + listOfAnimals[2].type + "
" + favFood + listOfAnimals[2].favFoods + "
"

const addNewAnimal = () => {
  const nameAnimal = userInput[0].value;
  const type = userInput[2].value;
  const ageAnimal = userInput[3].value;
  const image = userInput[1].value;
  if (nameAnimal.trim() === "" ||
    type.trim() === "" ||
    image.trim() === "" ||
    ageAnimal.trim() === ""
  ) {
    alert("Please enter a valid value ");
    return;
  }
  const newAnimal = {
    name: nameAnimal,
    url: image,
    type: type,
    age: ageAnimal,
  };
  listOfAnimals.push(newAnimal);
  console.log(newAnimal);
  toggleMovieModal();
  renderLiElement(newAnimal.name, newAnimal.type, newAnimal.age, newAnimal.url);
  clearInputs();
};
addButton.addEventListener('click', addNewAnimal);
const renderLiElement = (type, name, age, imageURL) => {
  const newLiElement = document.createElement('li');
  newLiElement.innerHTML = `

            ×

Name : ${name}

Age :  ${age}

Type : ${type}

Food

`;
  newLiElement.querySelector('.close').addEventListener('click', closeFunction);
  const listRoot = document.getElementById('ulList');
  listRoot.append(newLiElement);
  newLiElement.style.border = 'none';
}

const toggleBackdrop = () => {
  backdrop.classList.toggle('visible');
};

const toggleMovieModal = () => {
  addMovieModal.classList.toggle('visible');
  toggleBackdrop();
};

const cancel = () => {
  toggleMovieModal();
  clearInputs();
};

startAddMovieButton.addEventListener('click', toggleMovieModal);
backdrop.addEventListener('click', toggleMovieModal);
cancelAdd.addEventListener('click', cancel);

//close li element
const closeFunction = function() {
  this.parentElement.style.display = 'none';
};
for (i = 0; i < closebtns.length; i++) {
  closebtns[i].addEventListener("click", closeFunction);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link href="Zadanie1.css" rel="stylesheet" type="text/css">
  <script src="Zadanie1.js" defer></script>
</head>

<body>
  <div class="body">
    <div class="titles">
      <h4>Sort</h4>
      <h4>Filter</h4>
    </div>
    <div class="controlPanel" id="controlPanel">
      <button id="sort-age">AGE</button>
      <button class="sort-name" id="sort-name">NAME</button>
      <input type="number" placeholder="Types" id="input-number" />
      <label for="input-number"></label>
    </div>
    <ul class="UL" id="ulList">
      <li class="animalElement">
        <img alt="cat-2" src="dog-1.jpg">
        <span class="close">×</span>
        <ul class="ulOfLi" id="li2">
        </ul>
      </li>
      <li class="animalElement">
        <img alt="cat-1" src="cat-2.jpg">
        <span class="close">×</span>
        <ul class="ulOfLi" id="li1">
        </ul>
      </li>
      <li class="animalElement">
        <img alt="dog-1" src="cat-1.jpg">
        <span class="close">×</span>
        <p class="ulOfLi" id="li">
        </p>
      </li>
    </ul>
    <div id="backdrop"></div>
    <div class="modal card" id="add-modal">
      <div class="modal__content">
        <label for="name"></label>
        <input type="text" name='name' id="name" placeholder="NAME" />
        <label for="imageURL"></label>
        <input type="text" name="imageURL" id="imageURL" placeholder="url" />
        <label for="type"></label>
        <input type="text" name="type" id="type" placeholder="TYPE" />
        <label for="age"></label>
        <input placeholder="AGE" type="number" step="1" max="20" min="1" name="age" id="age" />
      </div>
      <div class="modal__actions">
        <button class="btn btn--passive">Cancel</button>
        <button class="btn btn--success" id="btn--success">Add</button>
      </div>
    </div>
    <section>
      <button class="add">×</button>
    </section>
  </div>
</body>

</html></code>```

Body:
I can't find a clear solution to sort elements displayed on screen.

I'm expecting that after clicking button NAME, elements displayed on the screen will be sorted alphabetically. I'm beginner in programming so I don't know how to ask question in google to find solution how to do it.

I found something like sort function but it doesn't work. It works when I displayed list in console log but on page nothing happening.

let closebtns = document.querySelectorAll("span");
//add animal button form
const addMovieModal = document.getElementById('add-modal');
const startAddMovieButton = document.querySelector('section button');
const backdrop = document.getElementById('backdrop');
const cancelAdd = addMovieModal.querySelector('.btn--passive');
const addButton = addMovieModal.querySelector('#btn--success');
const userInput = addMovieModal.querySelectorAll('input');

const clearInputs = () => {
  for (const usrInput of userInput) {
    usrInput.value = "";
  }
}

let listOfAnimals = [{
    name: "Meowsalot",
    age: 10,
    type: "cat",
    favFoods: ["tuna", "catnip", "celery"]
  },

  {
    name: "Barksalot",
    age: 7,
    type: "cat",
    favFoods: []
  },
  {
    name: "Barksalot",
    age: 10,
    type: "dog",
    favFoods: ["tuna", "catnip", "celery"]
  }
];
const name = "NAME: ";
const age = "AGE: ";
const typ = "TYPE: ";
const favFood = "FOOD: "
document.getElementById('li').innerHTML = name + listOfAnimals[0].name + "
" + age + listOfAnimals[0].age + "
" +
  typ + listOfAnimals[0].type + "
" + favFood + listOfAnimals[0].favFoods + "
";
document.getElementById('li1').innerHTML = name + listOfAnimals[1].name + "
" + age + listOfAnimals[1].age + "
" +
  typ + listOfAnimals[1].type + "
" + favFood + listOfAnimals[1].favFoods + "
"
document.getElementById('li2').innerHTML = name + listOfAnimals[2].name + "
" + age + listOfAnimals[2].age + "
" +
  typ + listOfAnimals[2].type + "
" + favFood + listOfAnimals[2].favFoods + "
"

const addNewAnimal = () => {
  const nameAnimal = userInput[0].value;
  const type = userInput[2].value;
  const ageAnimal = userInput[3].value;
  const image = userInput[1].value;
  if (nameAnimal.trim() === "" ||
    type.trim() === "" ||
    image.trim() === "" ||
    ageAnimal.trim() === ""
  ) {
    alert("Please enter a valid value ");
    return;
  }
  const newAnimal = {
    name: nameAnimal,
    url: image,
    type: type,
    age: ageAnimal,
  };
  listOfAnimals.push(newAnimal);
  console.log(newAnimal);
  toggleMovieModal();
  renderLiElement(newAnimal.name, newAnimal.type, newAnimal.age, newAnimal.url);
  clearInputs();
};
addButton.addEventListener('click', addNewAnimal);
const renderLiElement = (type, name, age, imageURL) => {
  const newLiElement = document.createElement('li');
  newLiElement.innerHTML = `

            ×

Name : ${name}

Age :  ${age}

Type : ${type}

Food

`;
  newLiElement.querySelector('.close').addEventListener('click', closeFunction);
  const listRoot = document.getElementById('ulList');
  listRoot.append(newLiElement);
  newLiElement.style.border = 'none';
}

const toggleBackdrop = () => {
  backdrop.classList.toggle('visible');
};

const toggleMovieModal = () => {
  addMovieModal.classList.toggle('visible');
  toggleBackdrop();
};

const cancel = () => {
  toggleMovieModal();
  clearInputs();
};

startAddMovieButton.addEventListener('click', toggleMovieModal);
backdrop.addEventListener('click', toggleMovieModal);
cancelAdd.addEventListener('click', cancel);

//close li element
const closeFunction = function() {
  this.parentElement.style.display = 'none';
};
for (i = 0; i < closebtns.length; i++) {
  closebtns[i].addEventListener("click", closeFunction);
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Title</title>
  <link href="Zadanie1.css" rel="stylesheet" type="text/css">

Sort

Filter

      <button id="sort-age">AGE</button>
      <button class="sort-name" id="sort-name">NAME</button>
      <input type="number" placeholder="Types" id="input-number" />

        ×

        ×

        ×

        <input type="text" name='name' id="name" placeholder="NAME" />

        <input type="text" name="imageURL" id="imageURL" placeholder="url" />

        <input type="text" name="type" id="type" placeholder="TYPE" />

        <input placeholder="AGE" type="number" step="1" max="20" min="1" name="age" id="age" />

        <button class="btn btn--passive">Cancel</button>
        <button class="btn btn--success" id="btn--success">Add</button>

      <button class="add">×</button>


问:
Flutter launchUrl - network security config settings not applied
My network_security_config:

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>
</code>```

And it's set to in android manifest:

```<code><application
        android:label="my app"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:allowBackup="false"

       android:networkSecurityConfig="@xml/network_security_config"
</code>```

CA has been installed as user certificate and it's confirmed working - Chrome is able to open url without ssl errors. But I'm not able to open page in my app, with launchUrl:

```<code>await launchUrlString(url, mode:  LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableJavaScript: true));
</code>```

It throws exception:

unable to get local issuer certificate

Any ideas why CA from user store is not applied?

Body:
My network_security_config:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

And it's set to in android manifest:

<application
        android:label="my app"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:allowBackup="false"

       android:networkSecurityConfig="@xml/network_security_config"

CA has been installed as user certificate and it's confirmed working - Chrome is able to open url without ssl errors. But I'm not able to open page in my app, with launchUrl:

await launchUrlString(url, mode:  LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableJavaScript: true));

It throws exception:

unable to get local issuer certificate

Any ideas why CA from user store is not applied?


问:
How to use react-pdf annotation?
I am loading pdf by react-pdf. I have two buttons Title and Author. When the user clicks on the title button, the background of the title will change, then click on the author, and it will change all author's name background colors of the pdf document.
How can I achieve this feature using react-pdf or any other react library for pdf? I have not found proper documentation on this topic - annotation based on user events.
Screenshot: https://paste.pics/2c8a9c449e86375c69624f62edad733c</p>

Title: How to use react-pdf annotation?


问:
pandas - Overwrite existing file using df.to_parquet(output_folder, engine='pyarrow')
I use pandas to write my output as parquet to an existing folder, I don't pass any file names so it generates the output file in the given path with a random id. I didn't use the file name because I have to partition the file based on a few columns before writing the output.

I am trying it this way.

df.to_parquet(output_folder, engine='pyarrow')

But it does not overwrite the existing file when I run the script again next time. What is the kwargs for overwriting the existing output file,