问:
How to make SpringDoc/Swagger detect beanMethod from abstract superclass
I am having issues with Spring-doc / Swagger while using Spring Boot WebFlux with the functional approach (RouterFunction and Handler).

pom.xml:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webflux-core</artifactId>
    <version>1.6.4</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webflux-ui</artifactId>
    <version>1.6.4</version>
</dependency>
```
<p><strong>End points in router config:</strong></p>
<pre class="lang-java prettyprint-override"><code>@Bean
@ParticipantDoc
public RouterFunction<ServerResponse> participantRoutes() {
  return RouterFunctions
    .route(GET("/participants/{publicId}"), participantHandler::byPublicId)
    .andRoute(POST("/participants"), participantHandler::create)
    .andRoute(PUT("/participants"), participantHandler::update)
    .andRoute(DELETE("/participants/{publicId}"), participantHandler::delete);
}
</code>```

Sample open api doc annotation for single operation (@ParticipantDoc):

@RouterOperation(
    path = "/participants/{publicId}",
    produces = { MediaType.APPLICATION_JSON_VALUE },
    method = RequestMethod.GET,
    operation = @Operation(
        tags = "Participant",
        operationId = "getParticipantByPublicId",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "Successful operation",
                content = @Content(
                    schema = @Schema(implementation = ParticipantModel.class))),
            @ApiResponse(responseCode = "404", description = "Participant not found")
        },
        parameters = { @Parameter(in = ParameterIn.PATH, name = "publicId") })),
```
<p><strong>The superclass with the base methods:</strong></p>
<pre class="lang-java prettyprint-override"><code>@RequiredArgsConstructor
public abstract class AbstractHandler<E extends BaseEntity, ID extends Serializable, M extends BaseModel, S extends AbstractService<E, ID, M>> {

    private static final String idTemplate = "publicId";

    private final S service;
    private final M model;

    public Mono<ServerResponse> byPublicId(ServerRequest req) {
        var id = req.pathVariable(idTemplate);

        return ServerResponse.ok().body(service.findOne(id),
            model.getClass())
            .onErrorResume(e -> {
                return Mono.error(e);
            });
    }

    // other methods
}
</code>```

ParticipantHandler which extends the AbstractHandler:

@Component
public class ParticipantHandler extends AbstractHandler<Participant, Long, ParticipantModel, ParticipantService> {

    public ParticipantHandler(ParticipantService service) {
        super(service, new ParticipantModel());
    }
}
```

Before using this approach, each method was coded inside the ParticipantHandler class (No inheritance) and I was able to test the end points using Swagger-UI by defining beanClass and beanMethod parameters.

When these parameters are set while on the new implementaion, no end points are displayed on the Swagger-UI page. On the otherhand if I ignore these two parameters, the testing functionality on Swagger-UI doesn't work.

I would like to know if there is a solutution for this.

Body:
I am having issues with Spring-doc / Swagger while using Spring Boot WebFlux with the functional approach (RouterFunction and Handler).

pom.xml:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webflux-core</artifactId>
    <version>1.6.4</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webflux-ui</artifactId>
    <version>1.6.4</version>
</dependency>

End points in router config:

@Bean
@ParticipantDoc
public RouterFunction<ServerResponse> participantRoutes() {
  return RouterFunctions
    .route(GET("/participants/{publicId}"), participantHandler::byPublicId)
    .andRoute(POST("/participants"), participantHandler::create)
    .andRoute(PUT("/participants"), participantHandler::update)
    .andRoute(DELETE("/participants/{publicId}"), participantHandler::delete);
}

Sample open api doc annotation for single operation (@ParticipantDoc):

@RouterOperation(
    path = "/participants/{publicId}",
    produces = { MediaType.APPLICATION_JSON_VALUE },
    method = RequestMethod.GET,
    operation = @Operation(
        tags = "Participant",
        operationId = "getParticipantByPublicId",
        responses = {
            @ApiResponse(
                responseCode = "200",
                description = "Successful operation",
                content = @Content(
                    schema = @Schema(implementation = ParticipantModel.class))),
            @ApiResponse(responseCode = "404", description = "Participant not found")
        },
        parameters = { @Parameter(in = ParameterIn.PATH, name = "publicId") })),

The superclass with the base methods:

@RequiredArgsConstructor
public abstract class AbstractHandler<E extends BaseEntity, ID extends Serializable, M extends BaseModel, S extends AbstractService<E, ID, M>> {

    private static final String idTemplate = "publicId";

    private final S service;
    private final M model;

    public Mono<ServerResponse> byPublicId(ServerRequest req) {
        var id = req.pathVariable(idTemplate);

        return ServerResponse.ok().body(service.findOne(id),
            model.getClass())
            .onErrorResume(e -> {
                return Mono.error(e);
            });
    }

    // other methods
}

ParticipantHandler which extends the AbstractHandler:

@Component
public class ParticipantHandler extends AbstractHandler<Participant, Long, ParticipantModel, ParticipantService> {

    public ParticipantHandler(ParticipantService service) {
        super(service, new ParticipantModel());
    }
}

Before using this approach, each method was coded inside the ParticipantHandler class (No inheritance) and I was able to test the end points using Swagger-UI by defining beanClass and beanMethod parameters.

When these parameters are set while on the new implementaion, no end points are displayed on the Swagger-UI page. On the otherhand if I ignore these two parameters, the testing functionality on Swagger-UI doesn't work.

I would like to know if there is a solutution for this.


来源: stackexchange

问:
How to add MKMapCamera and read current value?
I have a map with marks. When you press it, it centers. But when I rotate the map and click on the marker, it returns to its original value. I don't want the map to come back and the degrees stay the same.

I think that this can be solved through the camera, but I do not know how to do it.

I don't want the rotation to happen and the marker to just be centered. And rotation, if necessary, you can click on the compass in the upper right corner.

My code:

```<code>import SwiftUI
import MapKit

struct MapScreenView: View {

    @StateObject private var vm = LocationsViewModel()
    @State private var camera = MKMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698), fromDistance: 7500, pitch: 0, heading: 0)

    var body: some View {

        ZStack {
            VStack {
                HStack {
                    ButtonFilterView()
                    Spacer()
                }
                Spacer()
            }.zIndex(1)
            Map(coordinateRegion:
                    $vm.mapRegion, annotationItems: vm.locations) {
                location in
                MapAnnotation(coordinate: location.coordinate) {
                    LocationMapAnnotationView()
                        .scaleEffect(vm.mapLocation == location ? 1.1 : 0.7)
                        .offset(y: vm.mapLocation == location ? -11.5 : 0)
                        .animation(.easeInOut, value: vm.mapLocation == location)
                        .onTapGesture {
                            vm.showTappedLocation(location: location)
                        }
                }
            }

                    .onAppear {
                        MKMapView.appearance().isZoomEnabled = false
                        MKMapView.appearance().preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .realistic)
                        MKMapView.appearance().pointOfInterestFilter = .some(MKPointOfInterestFilter.excludingAll)
                        MKMapView.appearance().isRotateEnabled = true
                        MKMapView.appearance().isPitchEnabled = true
                        MKMapView.appearance().isScrollEnabled = false
                    }
                    .edgesIgnoringSafeArea(.all)
        }
    }
}

struct MapScreenView_Previews: PreviewProvider {
    static var previews: some View {
        MapScreenView()
    }
}

</code>```
```<code>import Foundation
import MapKit
import SwiftUI

class LocationsViewModel: ObservableObject {

    @Published var locations: [Location] = LocationDataService.locations

    @Published var mapLocation: Location {
        didSet {
            updateMapRegion(location: mapLocation)
        }
    }

    @Published var mapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698),
                                                  span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
    @Published var mapSpan = MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04)

    init() {
        self.mapLocation = Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698))
        updateMapRegion(location: Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698)))
    }

    private func updateMapRegion(location: Location) {
        withAnimation(.easeInOut) {
            mapRegion.center = location.coordinate
        }
    }

    func showTappedLocation(location: Location) {
            mapLocation = location
    }
}
</code>```

I think that this can be solved through the camera, but I do not know how to do it.

ContentLicense: CC BY-SA 4.0

Body:
I have a map with marks. When you press it, it centers. But when I rotate the map and click on the marker, it returns to its original value. I don't want the map to come back and the degrees stay the same.

I think that this can be solved through the camera, but I do not know how to do it.

I don't want the rotation to happen and the marker to just be centered. And rotation, if necessary, you can click on the compass in the upper right corner.

My code:

import SwiftUI
import MapKit

struct MapScreenView: View {

    @StateObject private var vm = LocationsViewModel()
    @State private var camera = MKMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698), fromDistance: 7500, pitch: 0, heading: 0)

    var body: some View {

        ZStack {
            VStack {
                HStack {
                    ButtonFilterView()
                    Spacer()
                }
                Spacer()
            }.zIndex(1)
            Map(coordinateRegion:
                    $vm.mapRegion, annotationItems: vm.locations) {
                location in
                MapAnnotation(coordinate: location.coordinate) {
                    LocationMapAnnotationView()
                        .scaleEffect(vm.mapLocation == location ? 1.1 : 0.7)
                        .offset(y: vm.mapLocation == location ? -11.5 : 0)
                        .animation(.easeInOut, value: vm.mapLocation == location)
                        .onTapGesture {
                            vm.showTappedLocation(location: location)
                        }
                }
            }

                    .onAppear {
                        MKMapView.appearance().isZoomEnabled = false
                        MKMapView.appearance().preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .realistic)
                        MKMapView.appearance().pointOfInterestFilter = .some(MKPointOfInterestFilter.excludingAll)
                        MKMapView.appearance().isRotateEnabled = true
                        MKMapView.appearance().isPitchEnabled = true
                        MKMapView.appearance().isScrollEnabled = false
                    }
                    .edgesIgnoringSafeArea(.all)
        }
    }
}

struct MapScreenView_Previews: PreviewProvider {
    static var previews: some View {
        MapScreenView()
    }
}

import Foundation
import MapKit
import SwiftUI

class LocationsViewModel: ObservableObject {

    @Published var locations: [Location] = LocationDataService.locations

    @Published var mapLocation: Location {
        didSet {
            updateMapRegion(location: mapLocation)
        }
    }

    @Published var mapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698),
                                                  span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
    @Published var mapSpan = MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04)

    init() {
        self.mapLocation = Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698))
        updateMapRegion(location: Location(name: "", coordinate: CLLocationCoordinate2D(latitude: 55.755864, longitude: 37.617698)))
    }

    private func updateMapRegion(location: Location) {
        withAnimation(.easeInOut) {
            mapRegion.center = location.coordinate
        }
    }

    func showTappedLocation(location: Location) {
            mapLocation = location
    }
}

I think that this can be solved through the camera, but I do not know how to do it.


问:
Nginx: How to run my flask application after setting up Nginx and gunicorn?
How to run my flask application after setting Nginx and gunicorn.

Earlier I used python run.py (http://127.0.0.1:5000/users)

I've tried to run using http://<ip_address>/

Configurations

gunicorn- my-server.service

```<code>[Unit]
Description=Flask Web Application Server using Gunicorn
After=network.target

[Service]
User=naveen.p@ah.zymrinc.com
Group=www-data
WorkingDirectory=/home/naveen/Documents/GitHub/flask-demo
Environment="PATH=/home/naveen/Documents/GitHub/flask-demo/myenv/bin"
ExecStart=/home/naveen/Documents/GitHub/flask-demo/myenv/bin/gunicorn --workers 3 --bind unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock run:app
Restart=always

[Install]
WantedBy=multi-user.target

</code>```

sites-available/my-server

```<code>
server {
    listen 80;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock;
    }
}

</code>```

nginx.conf

```<code>user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
</code>```

These are my configurations now I want to what to type in postman or web browser to access my API's.

As of now I'm getting "404 Not Found
nginx/1.22.1"

Body:
How to run my flask application after setting Nginx and gunicorn.

Earlier I used python run.py (http://127.0.0.1:5000/users)

I've tried to run using http://<ip_address>/

Configurations

gunicorn- my-server.service

[Unit]
Description=Flask Web Application Server using Gunicorn
After=network.target

[Service]
User=naveen.p@ah.zymrinc.com
Group=www-data
WorkingDirectory=/home/naveen/Documents/GitHub/flask-demo
Environment="PATH=/home/naveen/Documents/GitHub/flask-demo/myenv/bin"
ExecStart=/home/naveen/Documents/GitHub/flask-demo/myenv/bin/gunicorn --workers 3 --bind unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock run:app
Restart=always

[Install]
WantedBy=multi-user.target

sites-available/my-server

server {
    listen 80;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock;
    }
}

nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

These are my configurations now I want to what to type in postman or web browser to access my API's.

As of now I'm getting "404 Not Found
nginx/1.22.1"


问:
Pyqtgraph plot symbols do not scale correctly after zooming with mouse wheel
I monitor folders with a watchdog for new files. If a certain csv file is placed in the folder, it should be read out and the punte should be added to the plot. The plot is displayed as a line with symbols. This works fine so far.
However, when I start zooming in or out of the plot, the symbols do not scale with the line (see screenshot).
What could be the reason for this?
When exporting the plot window, the data points are displayed correctly again on the png image.

PNG Export
Screenshot

Here is a minimal example:

```<code>from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget,QGridLayout
from PyQt5.QtCore import Qt
from sys import argv
import pandas as pd
from pyqtgraph import PlotWidget
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from os import makedirs
from os.path import abspath,dirname,split,join, splitext
from errno import EEXIST
import csv
from random import randint
from time import sleep
from shutil import rmtree
import numpy as np
import pyqtgraph as pg

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(1134, 842)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.graphicsView = PlotWidget(self.centralwidget)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)
        self.widget = QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.gridLayout.addWidget(self.widget, 0, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

class MainWindowPlot(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindowPlot, self).__init__(parent)
        self.setupUi(self)

        path = abspath(dirname(__file__))

        # clear folders if exists
        for i in range(0,4):
            folder_path = join(path, str(i))
            try:
                rmtree(folder_path)
            except OSError as e:
                print(e)
            else:
                print("The directory is deleted successfully")

        list_folder_paths = self.create_folders(path)
        self.start_watchdog(list_folder_paths)
        sleep(2)
        list_csv_file_paths = []
        for i in range(0,len(list_folder_paths)):
            csv_file_path = self.create_csv(i, list_folder_paths[i])
            list_csv_file_paths.append(csv_file_path)
            sleep(2)

    def create_folders(self, path):
        list_folder_paths = []
        for i in range(0,4):
            folder_path = join(path, str(i))
            list_folder_paths.append(folder_path)
            self.create_folder(folder_path)
        return list_folder_paths

    def create_folder(self, path):
        try:
            makedirs(path)
        except OSError as e:
            if e.errno == EEXIST:
                pass

    def start_watchdog(self, list_folder_paths):
        patterns = ["*"]
        ignore_patterns = None
        ignore_directories = False
        case_sensitive = True
        self.my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
        self.my_event_handler.on_created = self.on_created
        go_recursively = False
        my_observer = Observer()
        for folder_path in list_folder_paths:
            my_observer.schedule(self.my_event_handler, folder_path, recursive = go_recursively)
        my_observer.start()

    def on_created(self, event):
        path = event.src_path
        #folder = split(split(path)[0])[1]
        ending = splitext(path)[1]
        file_name = split(splitext(path)[0])[1]
        if ending == '.csv':
            #print('Neue CSV im Ordner '+str(folder))
            if file_name == 'Test':
                #print('Torque CSV im Ordner '+str(folder))
                self.get_data(path)

    def create_csv(self, i, path):
        file_path = join(path, 'Test.csv')
        fieldnames = ['x', 'y']
        with open(file_path, 'w', encoding='UTF8', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(fieldnames)
            writer.writerow([i,randint(0,5)])
        return file_path

    def read_csv(self, path):
        csv = pd.read_csv(path)
        list_header = list(csv.columns)
        mat_csv_data = csv.to_numpy()
        return list_header, mat_csv_data

    def get_data(self, path):
        index = int(split(split(splitext(path)[0])[0])[1])
        list_header, mat_csv_data = self.read_csv(path)
        x = mat_csv_data[0,0]
        y = mat_csv_data[0,1]
        if index == 0:
            self.mat_data = np.array([[x, y]])
        else:
            self.mat_data = np.append(self.mat_data, [[x, y]],axis = 0)
        self.plot_data()

    def plot_data(self):
        self.graphicsView.clear()
        pen = pg.mkPen(color=(255, 0, 0), width=2, style=Qt.SolidLine)
        self.plot = self.graphicsView.plot(self.mat_data,pen=pen, symbol='o', symbolSize=15)

if __name__ == "__main__":
    app = QApplication(argv)
    gui = MainWindowPlot()
    gui.show()
    app.exec_()
</code>```

If I do not update the plot cyclically and add point by point to the matrix, but plot all data points at once, I do not get this behavior.
However, I have not yet been able to figure out what the problem is.

Body:
I monitor folders with a watchdog for new files. If a certain csv file is placed in the folder, it should be read out and the punte should be added to the plot. The plot is displayed as a line with symbols. This works fine so far.
However, when I start zooming in or out of the plot, the symbols do not scale with the line (see screenshot).
What could be the reason for this?
When exporting the plot window, the data points are displayed correctly again on the png image.

PNG Export
Screenshot

Here is a minimal example:

from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget,QGridLayout
from PyQt5.QtCore import Qt
from sys import argv
import pandas as pd
from pyqtgraph import PlotWidget
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from os import makedirs
from os.path import abspath,dirname,split,join, splitext
from errno import EEXIST
import csv
from random import randint
from time import sleep
from shutil import rmtree
import numpy as np
import pyqtgraph as pg

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(1134, 842)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.graphicsView = PlotWidget(self.centralwidget)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)
        self.widget = QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.gridLayout.addWidget(self.widget, 0, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

class MainWindowPlot(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindowPlot, self).__init__(parent)
        self.setupUi(self)

        path = abspath(dirname(__file__))

        # clear folders if exists
        for i in range(0,4):
            folder_path = join(path, str(i))
            try:
                rmtree(folder_path)
            except OSError as e:
                print(e)
            else:
                print("The directory is deleted successfully")

        list_folder_paths = self.create_folders(path)
        self.start_watchdog(list_folder_paths)
        sleep(2)
        list_csv_file_paths = []
        for i in range(0,len(list_folder_paths)):
            csv_file_path = self.create_csv(i, list_folder_paths[i])
            list_csv_file_paths.append(csv_file_path)
            sleep(2)

    def create_folders(self, path):
        list_folder_paths = []
        for i in range(0,4):
            folder_path = join(path, str(i))
            list_folder_paths.append(folder_path)
            self.create_folder(folder_path)
        return list_folder_paths

    def create_folder(self, path):
        try:
            makedirs(path)
        except OSError as e:
            if e.errno == EEXIST:
                pass

    def start_watchdog(self, list_folder_paths):
        patterns = ["*"]
        ignore_patterns = None
        ignore_directories = False
        case_sensitive = True
        self.my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
        self.my_event_handler.on_created = self.on_created
        go_recursively = False
        my_observer = Observer()
        for folder_path in list_folder_paths:
            my_observer.schedule(self.my_event_handler, folder_path, recursive = go_recursively)
        my_observer.start()

    def on_created(self, event):
        path = event.src_path
        #folder = split(split(path)[0])[1]
        ending = splitext(path)[1]
        file_name = split(splitext(path)[0])[1]
        if ending == '.csv':
            #print('Neue CSV im Ordner '+str(folder))
            if file_name == 'Test':
                #print('Torque CSV im Ordner '+str(folder))
                self.get_data(path)

    def create_csv(self, i, path):
        file_path = join(path, 'Test.csv')
        fieldnames = ['x', 'y']
        with open(file_path, 'w', encoding='UTF8', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(fieldnames)
            writer.writerow([i,randint(0,5)])
        return file_path

    def read_csv(self, path):
        csv = pd.read_csv(path)
        list_header = list(csv.columns)
        mat_csv_data = csv.to_numpy()
        return list_header, mat_csv_data

    def get_data(self, path):
        index = int(split(split(splitext(path)[0])[0])[1])
        list_header, mat_csv_data = self.read_csv(path)
        x = mat_csv_data[0,0]
        y = mat_csv_data[0,1]
        if index == 0:
            self.mat_data = np.array([[x, y]])
        else:
            self.mat_data = np.append(self.mat_data, [[x, y]],axis = 0)
        self.plot_data()

    def plot_data(self):
        self.graphicsView.clear()
        pen = pg.mkPen(color=(255, 0, 0), width=2, style=Qt.SolidLine)
        self.plot = self.graphicsView.plot(self.mat_data,pen=pen, symbol='o', symbolSize=15)

if __name__ == "__main__":
    app = QApplication(argv)
    gui = MainWindowPlot()
    gui.show()
    app.exec_()

If I do not update the plot cyclically and add point by point to the matrix, but plot all data points at once, I do not get this behavior.
However, I have not yet been able to figure out what the problem is.


问:
How to use System.Text.Json 7 in a in-process Azure function?
I've a nuget reference to System.Text.Json 7.0.1 in a in-process Azure function, targeting

.NET 6  When starting the function locally I got a runtime error,

Could not load file or assembly 'System.Text.Json, Version=7.0.0.0,
Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51

What is the problem? Is it due to the fact that the function is running in-process?


问:
debug.log file is not created, what is the alternative?
/etc/httpd/vhost.d/domainname

```<code><VirtualHost *:443>
  ServerName domain_name.com
  ServerAlias www.domain_name.com

  DirectoryIndex index.php index.html
  DocumentRoot /data/www/domain_name

  ErrorLog /var/log/httpd/domain_name-error.log
  CustomLog /var/log/httpd/domain_name-access.log combined

  Protocols h2 http/1.1

  RedirectMatch 404 /\\.(svn|git|gitignore|hg|bzr|cvs)(/|$)

  <Directory /data/www/domain_name>
    AllowOverride All
    Options All -Indexes
    Require all granted
  </Directory>
</VirtualHost>
</code>```

wp-config.php

```<code>define( 'WP_DEBUG', true );
define('WP_DEBUG_LOG', true);
define( 'WP_DEBUG_DISPLAY', false );
</code>```

I am a server admin, my developers wants debug.log to be created in wp-content which seems to be blocked by hosting provider.

but the file /var/log/httpd/domain_name-error.log seems to be logging fine, is this file same as debug.log or are they log different errors?

if they are different, is there any alternative, i can create debug.log for this wordpress site?

I have also tried with .htaccess file

```<code>php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log
</code>```

which  is also throwing 500 internal server error, seems that

Body:
/etc/httpd/vhost.d/domainname

<VirtualHost *:443>
  ServerName domain_name.com
  ServerAlias www.domain_name.com

  DirectoryIndex index.php index.html
  DocumentRoot /data/www/domain_name

  ErrorLog /var/log/httpd/domain_name-error.log
  CustomLog /var/log/httpd/domain_name-access.log combined

  Protocols h2 http/1.1

  RedirectMatch 404 /\\.(svn|git|gitignore|hg|bzr|cvs)(/|$)

  <Directory /data/www/domain_name>
    AllowOverride All
    Options All -Indexes
    Require all granted
  </Directory>
</VirtualHost>

wp-config.php

define( 'WP_DEBUG', true );
define('WP_DEBUG_LOG', true);
define( 'WP_DEBUG_DISPLAY', false );

I am a server admin, my developers wants debug.log to be created in wp-content which seems to be blocked by hosting provider.

but the file /var/log/httpd/domain_name-error.log seems to be logging fine, is this file same as debug.log or are they log different errors?

if they are different, is there any alternative, i can create debug.log for this wordpress site?

I have also tried with .htaccess file

php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

which  is also throwing 500 internal server error, seems that


问:
Algorithm for solving sparse linear system in C++
I need to solve the heat equation for 2D object using C++. I've found many sources explaining the mathematics behind it. I am using the Crank-Nicholson scheme, but given that I need a 1001 x 1001 discretization, the resulting linear system is huge and memory would blow in case of a "traditional" implementation.

Therefore, I am recurring to methods for solving sparse linear systems. I have been looking online and cannot find any source explaining an algorithm to solve this sparse system efficiently. I've found several packages that do solve it (like csparse, eigen, SciPy under-the-hood implementation), but found no theoretical explanation to really code it myself. For the moment I am trying to do "reverse engineering" on the source code of SuperLU.

What I am looking for is an algorithm that you may know to solve sparse linear systems.

Thanks in advance


问:
error during helmfile.yaml.part.0 parsing :
I am running my pipeline in gitlab .. and this pipeline pull a helmfile from a github repo.. and  when i am trying to deploy this error appears when start to put parsing because my values file like that
kubeContext: cech027
this is the helmfile
`

```<code># Make sure we have the ENV variable set: {{ requiredEnv "ENV" }}

environments:
  default:
    values:
      - environments/defaults.yaml.gotmpl
      - versions.yaml
      - {{ env "ENVCONFIG" |default ".." }}/config/defaults.yaml.gotmpl
      - {{ env "ENVCONFIG" |default ".." }}/config/{{ requiredEnv "ENV" }}/values.yaml.gotmpl
      - systemVersion: {{ (exec "./utils/git-version.sh" (list "")) }}
      - kubeVersion: {{ (exec "./utils/kube-version.sh" (list .Values.kubeContext)) }}
    secrets:
      - {{ env "ENVCONFIG" |default ".." }}/config/secrets.yaml
      - {{ env "ENVCONFIG" |default ".." }}/config/{{ requiredEnv "ENV" }}/secrets.yaml

  local:
    values:
      - environments/defaults.yaml.gotmpl
      - versions.yaml
      - environments/local/values.yaml.gotmpl
      - environments/local/secrets.yaml
      {{- if eq (exec "./utils/fileexists.sh" (list "overrides.yaml.gotmpl")) "true"}}
      - overrides.yaml.gotmpl
      {{- end }}
      {{- if eq (exec "./utils/fileexists.sh" (list "overrides.yaml")) "true"}}
      - overrides.yaml
      {{- end }}
      - systemVersion: {{ (exec "./utils/git-version.sh" (list "dev")) }}
      - kubeVersion: {{ (exec "./utils/kube-version.sh" (list .Values.kubeContext)) }}

---

repositories:
{{- if .Values.helm }}
- name: softsense
  url: {{ .Values.helm.url }}
  username: {{ .Values.helm.username }}
  password: {{ .Values.helm.password }}
{{- if .Values.allowSnapshots }}
- name: softsense-dev
  url: {{ .Values.helm.devURL }}
  username: {{ .Values.helm.username }}
  password: {{ .Values.helm.password }}
{{- end }}
{{- end }}

helmDefaults:
  cleanupOnFail: true
  verify: false # does not work with charts in directories
  wait: true
  timeout: 900
  recreatePods: false # recreatePods is not supported in helm3
  force: false
  kubeContext: {{ .Values.kubeContext }} # force usage of a specific kube-context
  createNamespace: false
</code>```

`
but i have this error since a week ( and we did not do any changes) ..
the gitlab uses a runner to run this pipeline..

this is the error : rror during helmfile.yaml.part.0 parsing: template: stringTemplate:11:69: executing "stringTemplate" at <.Values.kubeContext>: map has no entry for key "kubeContext"

and when i run from my local machine it deployed successfully

Body:
I am running my pipeline in gitlab .. and this pipeline pull a helmfile from a github repo.. and  when i am trying to deploy this error appears when start to put parsing because my values file like that
kubeContext: cech027
this is the helmfile
`

# Make sure we have the ENV variable set: {{ requiredEnv "ENV" }}

environments:
  default:
    values:
      - environments/defaults.yaml.gotmpl
      - versions.yaml
      - {{ env "ENVCONFIG" |default ".." }}/config/defaults.yaml.gotmpl
      - {{ env "ENVCONFIG" |default ".." }}/config/{{ requiredEnv "ENV" }}/values.yaml.gotmpl
      - systemVersion: {{ (exec "./utils/git-version.sh" (list "")) }}
      - kubeVersion: {{ (exec "./utils/kube-version.sh" (list .Values.kubeContext)) }}
    secrets:
      - {{ env "ENVCONFIG" |default ".." }}/config/secrets.yaml
      - {{ env "ENVCONFIG" |default ".." }}/config/{{ requiredEnv "ENV" }}/secrets.yaml

  local:
    values:
      - environments/defaults.yaml.gotmpl
      - versions.yaml
      - environments/local/values.yaml.gotmpl
      - environments/local/secrets.yaml
      {{- if eq (exec "./utils/fileexists.sh" (list "overrides.yaml.gotmpl")) "true"}}
      - overrides.yaml.gotmpl
      {{- end }}
      {{- if eq (exec "./utils/fileexists.sh" (list "overrides.yaml")) "true"}}
      - overrides.yaml
      {{- end }}
      - systemVersion: {{ (exec "./utils/git-version.sh" (list "dev")) }}
      - kubeVersion: {{ (exec "./utils/kube-version.sh" (list .Values.kubeContext)) }}

---

repositories:
{{- if .Values.helm }}
- name: softsense
  url: {{ .Values.helm.url }}
  username: {{ .Values.helm.username }}
  password: {{ .Values.helm.password }}
{{- if .Values.allowSnapshots }}
- name: softsense-dev
  url: {{ .Values.helm.devURL }}
  username: {{ .Values.helm.username }}
  password: {{ .Values.helm.password }}
{{- end }}
{{- end }}

helmDefaults:
  cleanupOnFail: true
  verify: false # does not work with charts in directories
  wait: true
  timeout: 900
  recreatePods: false # recreatePods is not supported in helm3
  force: false
  kubeContext: {{ .Values.kubeContext }} # force usage of a specific kube-context
  createNamespace: false

`
but i have this error since a week ( and we did not do any changes) ..
the gitlab uses a runner to run this pipeline..

this is the error : rror during helmfile.yaml.part.0 parsing: template: stringTemplate:11:69: executing "stringTemplate" at <.Values.kubeContext>: map has no entry for key "kubeContext"

and when i run from my local machine it deployed successfully


问:
Field is null after contstructor - spring
```<code>@RestController
@RequestMapping("/v1/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        System.err.println(userService);
        this.userService = userService;
        System.err.println(this.userService);
    }

    @PostMapping("/login")
    private ResponseEntity<ServiceResponse<UserResp>> login(@RequestBody UserReq userReq) {
        System.err.println(userService);
        return ResponseEntity.ok(userService.login(userReq));
    }
</code>```

userService is null inside the method, but it is setting inside the constructor

Cannot invoke "mscore.service.UserService.login(mscore.model.req.UserReq)" because "this.userService" is null

Body:
@RestController
@RequestMapping("/v1/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        System.err.println(userService);
        this.userService = userService;
        System.err.println(this.userService);
    }

    @PostMapping("/login")
    private ResponseEntity<ServiceResponse<UserResp>> login(@RequestBody UserReq userReq) {
        System.err.println(userService);
        return ResponseEntity.ok(userService.login(userReq));
    }

userService is null inside the method, but it is setting inside the constructor

Cannot invoke "mscore.service.UserService.login(mscore.model.req.UserReq)" because "this.userService" is null


问:
Convert base class to derived class when returning object
I have classes and functions which I don't want to change, but I want to expose them to Python with some additional functionalities (Dunder Methods etc.). So what I have is derived class like follows:

C++

```<code>#include "boost/python.hpp"

namespace py = boost::python;

class MyClass {};

class PyClass : public MyClass {};

void func_a(MyClass param) {}
MyClass func_b() { return MyClass(); }

BOOST_PYTHON_MODULE(example_module)
{
    py::def("func_a", &func_a);
    py::def("func_b", &func_b);

    py::class_<MyClass>("MyClass");
    py::class_<PyClass, py::bases<MyClass>>("PyClass");
}
</code>```

So for func_a to work, I declared MyClass as base of PyClass and it works fine. Problems start when I want to call func_b as it returns to Python object of type MyClass. Is there any way of specifically declaring how does return value should be converted?

I've tried creating to_python_converter:

```<code>#include "boost/python.hpp"

namespace py = boost::python;

class MyClass {};

class PyClass : public MyClass
{
public:
    PyClass() {};
    PyClass(const MyClass& ref) : MyClass(ref) {};
};

void func_a(MyClass param) {}
MyClass func_b() { return MyClass(); }

class BaseToDerived
{
public:
    static PyObject* convert(MyClass const& obj)
    {
        PyClass* n_obj = new PyClass(obj);
        return py::incref(py::object(n_obj).ptr());;

    }
};

BOOST_PYTHON_MODULE(example_module)
{
    py::def("func_a", &func_a);
    py::def("func_b", &func_b);

    py::class_<MyClass>("MyClass");
    py::class_<PyClass, py::bases<MyClass>>("PyClass");

    py::to_python_converter<MyClass, BaseToDerived>();
}
</code>```

but it ends up crashing with Microsoft Visual C++ Runtime Library Assertion failed

Body:
I have classes and functions which I don't want to change, but I want to expose them to Python with some additional functionalities (Dunder Methods etc.). So what I have is derived class like follows:

C++

#include "boost/python.hpp"

namespace py = boost::python;

class MyClass {};

class PyClass : public MyClass {};

void func_a(MyClass param) {}
MyClass func_b() { return MyClass(); }

BOOST_PYTHON_MODULE(example_module)
{
    py::def("func_a", &func_a);
    py::def("func_b", &func_b);

    py::class_<MyClass>("MyClass");
    py::class_<PyClass, py::bases<MyClass>>("PyClass");
}

So for func_a to work, I declared MyClass as base of PyClass and it works fine. Problems start when I want to call func_b as it returns to Python object of type MyClass. Is there any way of specifically declaring how does return value should be converted?

I've tried creating to_python_converter:

#include "boost/python.hpp"

namespace py = boost::python;

class MyClass {};

class PyClass : public MyClass
{
public:
    PyClass() {};
    PyClass(const MyClass& ref) : MyClass(ref) {};
};

void func_a(MyClass param) {}
MyClass func_b() { return MyClass(); }

class BaseToDerived
{
public:
    static PyObject* convert(MyClass const& obj)
    {
        PyClass* n_obj = new PyClass(obj);
        return py::incref(py::object(n_obj).ptr());;

    }
};

BOOST_PYTHON_MODULE(example_module)
{
    py::def("func_a", &func_a);
    py::def("func_b", &func_b);

    py::class_<MyClass>("MyClass");
    py::class_<PyClass, py::bases<MyClass>>("PyClass");

    py::to_python_converter<MyClass, BaseToDerived>();
}

but it ends up crashing with Microsoft Visual C++ Runtime Library Assertion failed


问:
Odd Keycloak behavior when using proxy
I'm trying to request Keycloak container from another container within the same network using PHP curl with proxy. The Keycloak's service name is keycloak and its exposed port is 8080.

Here is my code:

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:10210/realms/test/.well-known/openid-configuration");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "keycloak:8080");

$response = curl_exec($ch);

curl_close($ch);
</code>```

When I execute this code I receive this error message:

```<code>{"error":"RESTEASY003210: Could not find resource for full path: http://localhost:10210http://localhost:10210/realms/test/.well-known/openid-configuration"}
</code>```

It looks like it duplicates the hostname when I use proxy option and I have no idea why it happens.

Title: Odd Keycloak behavior when using proxy

Body:
I'm trying to request Keycloak container from another container within the same network using PHP curl with proxy. The Keycloak's service name is keycloak and its exposed port is 8080.

Here is my code:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:10210/realms/test/.well-known/openid-configuration");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "keycloak:8080");

$response = curl_exec($ch);

curl_close($ch);

When I execute this code I receive this error message:

{"error":"RESTEASY003210: Could not find resource for full path: http://localhost:10210http://localhost:10210/realms/test/.well-known/openid-configuration"}

It looks like it duplicates the hostname when I use proxy option and I have no idea why it happens.


问:
React Native Flatlist
I want to use async function inside render function of Flatlist so i can use await insode for translation_function which convert my text into different language text.

```<code>    <FlatList
                            data={category}
                            horizontal={true}
                            showsHorizontalScrollIndicator={false}
                            renderItem={async ({ item }) => {
                                return (
                                    <>
                                        <JobBox source={item.cat_img} name={await Trasnlate_dummy(item.cat_name) + ' (' + item.openings + ')'} marginHorizontal={10} onPress={() => {
                                            action.tags(item.cat_name)
                                            setItem("cat_id", JSON.stringify(item.catid))
                                            setItem("cat_name", JSON.stringify(item.cat_name))
                                            navigation.navigate('jobopening')
                                        }} />

                                    </>
                                )
                            }}
                        />
  const Trasnlate_dummy = async (text) => {
    let a = await translatation_api(text).then(async (res) => {
        // console.log(res.data.translations[0].translatedText);
        return await res.data.translatations
    }).catch((err) => {
        console.warn(err);
    })
    return await a
}
</code>```

When i use async function inside renderitem it gives me error like :
Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X, _1}). If you meant to render a collection of children, use an array instead.

Title: React Native Flatlist

Body:
I want to use async function inside render function of Flatlist so i can use await insode for translation_function which convert my text into different language text.

    <FlatList
                            data={category}
                            horizontal={true}
                            showsHorizontalScrollIndicator={false}
                            renderItem={async ({ item }) => {
                                return (
                                    <>
                                        <JobBox source={item.cat_img} name={await Trasnlate_dummy(item.cat_name) + ' (' + item.openings + ')'} marginHorizontal={10} onPress={() => {
                                            action.tags(item.cat_name)
                                            setItem("cat_id", JSON.stringify(item.catid))
                                            setItem("cat_name", JSON.stringify(item.cat_name))
                                            navigation.navigate('jobopening')
                                        }} />

                                    </>
                                )
                            }}
                        />
  const Trasnlate_dummy = async (text) => {
    let a = await translatation_api(text).then(async (res) => {
        // console.log(res.data.translations[0].translatedText);
        return await res.data.translatations
    }).catch((err) => {
        console.warn(err);
    })
    return await a
}

When i use async function inside renderitem it gives me error like :
Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X, _1}). If you meant to render a collection of children, use an array instead.


问:
How to find out that the user's login time has expired in sharepoint with pnp js?
I know when error 403 in a request that's mean user does not have access.
But if the login time expires , again request give error 403.

can you help me?

I looked in other sites but I did not find the answer.


问:
How to deal with Xamarin.Essentials which Android 13 seems to have broken?
I want to send users who press a button in my Uno Platform (Xamarin) Android mobile app to a pre-populated email with the body and subject passed as a parameter, so as to automate the process of sending a report.

The app uses the MVVM pattern, the button in the View is bound to a command in the ViewModel which puts together some strings and tries to send them along with the user to their email app of choice. Nothing overtly complex.

Since Android 13 the following piece of code causes the app to consistently crash (which it didn't do earlier)

```<code>var message = new Xamarin.Essentials.EmailMessage
{
    Subject = Report.SUBJECT,
    Body = Report.DATA
    To = new List<string> { Report.RECIPIENT }, // "example@example.com"
};
await Xamarin.Essentials.Email.ComposeAsync(message);
</code>```

Stack trace yields the following

```<code>ApplicationActivity+<>c__DisplayClass29_0.<SetContentView>b__0 (System.Object s, Android.Views.View+ViewAttachedToWindowEventArgs e)
System.NullReferenceException: Object reference not set to an instance of an object
</code>```

which is weird. The message is not null (seen in the debugger). Also, despite the app crashing, the message itself is correctly generated in the chosen email app (if I navigate there manually after my app crashed, that is)

Minimum Android version for the app is Android 9 (API level 28), target is 11 (API 30).
The newest .NET Core SDK is 6.0.101, and .NET Core Runtime is 6.0.1, as seen in the SDK manager.
I'm working in Visual Studio 2019 for Mac community edition version 8.10.22 (build 11)

How do I deal with this?

What I tried so far:

Replacing ComposeAsync with Launcher.OpenAsync results in the same failure.

```<code>var uri = $"mailto:{Report.RECIPIENT}?subject={Report.SUBJECT}&body={Report.DATA}";
await Xamarin.Essentials.Launcher.OpenAsync(uri);
</code>```

In fact, even just going to some example website turns out to crash in the same way

```<code>var uri = "https://example.com";
await Xamarin.Essentials.Launcher.OpenAsync(uri);
</code>```

Wrapping the whole method (regardless of launcher or email) in a try-catch statement fails to catch anything and app crashes nonetheless

```<code>private async void SendReport()
{
    try
    {
        // Do the thing
    }
    catch (Exception ex)
    {
        // Some exception occurred
    }
}
</code>```

Elsewhere in the app, using a hyperlink button in the View (instead of a ViewModel method) surprisingly does work normally

```<code><HyperlinkButton
    NavigateUri="mailto:example@example.com">
    <TextBlock Text="Contact via e-mail"/>
</HyperlinkButton>
</code>```

which suggests that it is Xamarin.Essentials that isn't working for me, not just emails in Android.

I would much prefer solving the issue in the SendReport method in the ViewModel instead of resorting to that one weird trick that programmers hate (of switching to a hyperlink button in UI) to make it work.

Documentation about Android 13 behaviour changes to all apps doesn't seem to contain any changes of obvious relevance to this issue.

iOS in contrast works fine this time

This desperate attempt didn't work out of the box.

```<code>System.Diagnostics.Process.Start("http://www.c-sharpcorner.com/Default.aspx");
</code>```

My environment is quite fragile which is why I'm highly hesitant to try updating anything as a rule

Body:
I want to send users who press a button in my Uno Platform (Xamarin) Android mobile app to a pre-populated email with the body and subject passed as a parameter, so as to automate the process of sending a report.

The app uses the MVVM pattern, the button in the View is bound to a command in the ViewModel which puts together some strings and tries to send them along with the user to their email app of choice. Nothing overtly complex.

Since Android 13 the following piece of code causes the app to consistently crash (which it didn't do earlier)

var message = new Xamarin.Essentials.EmailMessage
{
    Subject = Report.SUBJECT,
    Body = Report.DATA
    To = new List<string> { Report.RECIPIENT }, // "example@example.com"
};
await Xamarin.Essentials.Email.ComposeAsync(message);

Stack trace yields the following

ApplicationActivity+<>c__DisplayClass29_0.<SetContentView>b__0 (System.Object s, Android.Views.View+ViewAttachedToWindowEventArgs e)
System.NullReferenceException: Object reference not set to an instance of an object

which is weird. The message is not null (seen in the debugger). Also, despite the app crashing, the message itself is correctly generated in the chosen email app (if I navigate there manually after my app crashed, that is)

Minimum Android version for the app is Android 9 (API level 28), target is 11 (API 30).
The newest .NET Core SDK is 6.0.101, and .NET Core Runtime is 6.0.1, as seen in the SDK manager.
I'm working in Visual Studio 2019 for Mac community edition version 8.10.22 (build 11)

How do I deal with this?

What I tried so far:

Replacing ComposeAsync with Launcher.OpenAsync results in the same failure.

var uri = $"mailto:{Report.RECIPIENT}?subject={Report.SUBJECT}&body={Report.DATA}";
await Xamarin.Essentials.Launcher.OpenAsync(uri);

In fact, even just going to some example website turns out to crash in the same way

var uri = "https://example.com";
await Xamarin.Essentials.Launcher.OpenAsync(uri);

Wrapping the whole method (regardless of launcher or email) in a try-catch statement fails to catch anything and app crashes nonetheless

private async void SendReport()
{
    try
    {
        // Do the thing
    }
    catch (Exception ex)
    {
        // Some exception occurred
    }
}

Elsewhere in the app, using a hyperlink button in the View (instead of a ViewModel method) surprisingly does work normally

<HyperlinkButton
    NavigateUri="mailto:example@example.com">
    <TextBlock Text="Contact via e-mail"/>
</HyperlinkButton>

which suggests that it is Xamarin.Essentials that isn't working for me, not just emails in Android.

I would much prefer solving the issue in the SendReport method in the ViewModel instead of resorting to that one weird trick that programmers hate (of switching to a hyperlink button in UI) to make it work.

Documentation about Android 13 behaviour changes to all apps doesn't seem to contain any changes of obvious relevance to this issue.

iOS in contrast works fine this time

This desperate attempt didn't work out of the box.

System.Diagnostics.Process.Start("http://www.c-sharpcorner.com/Default.aspx");

My environment is quite fragile which is why I'm highly hesitant to try updating anything as a rule


问:
Ansible SSH key mismatch
I wrote the following Ansible playbook:

```<code>---
- name: Create VLAN
  hosts: exos_device
  connection: ansible.netcommon.network_cli
  vars:
    ansible_user: admin
    ansible_password: password
    ansible_network_os: community.network.exos
  tasks:
  - name: Create VLAN 4050
    community.network.exos_config:
      lines:
        - create vlan TESTVLAN tag 4050
      match: exact
      save_when: always
</code>```

Where I'm trying to create a new vlan on an Extreme Networks machine (ExtremeXOS version 16.2.5.4). But when I execute it I keep getting the following error:

```<code>fatal: [10.12.2.10]: FAILED! => {
    "changed": false,
    "module_stderr": "ssh connection failed: ssh connect failed: kex error : no match for method server host key algo: server [ssh-rsa], client [rsa-sha2-512,rsa-sha2-256,ssh-ed25519,ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256]",
    "module_stdout": "",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error"
}
</code>```

I think this error indicates that there is a mismatch between the SSH key algorithms that the client (Ansible controller) and the server (the EXOS machine) support.

What is the best way to resolve this issue?

I've already tried specifying an algorithm inside the ansible.cfg file like this:

```<code>[defaults]
inventory = inventory.ini
ssh_args = -oKexAlgorithms=ssh-rsa
</code>```

But with no success.

Title: Ansible SSH key mismatch

Body:
I wrote the following Ansible playbook:

---
- name: Create VLAN
  hosts: exos_device
  connection: ansible.netcommon.network_cli
  vars:
    ansible_user: admin
    ansible_password: password
    ansible_network_os: community.network.exos
  tasks:
  - name: Create VLAN 4050
    community.network.exos_config:
      lines:
        - create vlan TESTVLAN tag 4050
      match: exact
      save_when: always

Where I'm trying to create a new vlan on an Extreme Networks machine (ExtremeXOS version 16.2.5.4). But when I execute it I keep getting the following error:

fatal: [10.12.2.10]: FAILED! => {
    "changed": false,
    "module_stderr": "ssh connection failed: ssh connect failed: kex error : no match for method server host key algo: server [ssh-rsa], client [rsa-sha2-512,rsa-sha2-256,ssh-ed25519,ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256]",
    "module_stdout": "",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error"
}

I think this error indicates that there is a mismatch between the SSH key algorithms that the client (Ansible controller) and the server (the EXOS machine) support.

What is the best way to resolve this issue?

I've already tried specifying an algorithm inside the ansible.cfg file like this:

[defaults]
inventory = inventory.ini
ssh_args = -oKexAlgorithms=ssh-rsa

But with no success.


问:
What are the differences between 'suspend fun main()' and 'fun main = runBlocking {}'?
The first example of using Kotlin Coroutines in the docs uses

fun main() = runBlocking {
  // ...
}
```
<p>However, when using Kotlin/JVM (but not Kotlin/Native), it is possible to make the main entry point a suspend function. This means there is no need for <code>runBlocking {}</code></p>
<pre class="lang-kotlin prettyprint-override"><code>import kotlinx.coroutines.*

suspend fun main() {
  doWorld()
}

// fun main() = runBlocking {
//   doWorld()
// }

suspend fun doWorld() = coroutineScope {
  launch {
    delay(1000L)
    println("World!")
  }
  println("Hello")
}
</code>```

Run example in Kotlin Playground

Are there any differences between the two approaches?

What are they?

How should I choose which approach to choose?

I'm using

Kotlin/Native v1.7.22

Kotlinx Coroutines 1.6.4

Body:
The first example of using Kotlin Coroutines in the docs uses

fun main() = runBlocking {
  // ...
}

However, when using Kotlin/JVM (but not Kotlin/Native), it is possible to make the main entry point a suspend function. This means there is no need for runBlocking {}

import kotlinx.coroutines.*

suspend fun main() {
  doWorld()
}

// fun main() = runBlocking {
//   doWorld()
// }

suspend fun doWorld() = coroutineScope {
  launch {
    delay(1000L)
    println("World!")
  }
  println("Hello")
}

Run example in Kotlin Playground

Are there any differences between the two approaches?

What are they?

How should I choose which approach to choose?

I'm using

Kotlin/Native v1.7.22

Kotlinx Coroutines 1.6.4


问:
Occasional System.AccessViolationException when copying memory from unsafe camera buffer to managed array
We observe a random and rare problem with our application.
When reading images via the DCAM-API of a Hamamatsu camera we occasionally get a System.AccessViolationException in the CopyMemory method after the system was running perfectly for hundreds of frames.
I thought I managed to eliminate these errors by using the GCHandle but somehow it still happens sometimes. We developed the application on Windows Server 2012 where I have not seen this error during development. On newer Windows 11 Machines it now happens much more frequently.

Any idea why this happens and what i could do to eliminate the error?

```<code>[DllImport("kernel32.dll", SetLastError = false)]
static extern void CopyMemory(IntPtr destination, IntPtr source, UIntPtr length);

public static void Copy<T>(IntPtr source, T[] destination, int startIndex, int length) where T : struct
{
    var gch = GCHandle.Alloc(destination, GCHandleType.Pinned);
    try
    {
        var targetPtr = Marshal.UnsafeAddrOfPinnedArrayElement(destination, startIndex);
        var bytesToCopy = Marshal.SizeOf(typeof(T)) * length;

        CopyMemory(targetPtr, source, (UIntPtr)bytesToCopy);
     }
     finally
     {
         gch.Free();
     }
}
</code>```

Body:
We observe a random and rare problem with our application.
When reading images via the DCAM-API of a Hamamatsu camera we occasionally get a System.AccessViolationException in the CopyMemory method after the system was running perfectly for hundreds of frames.
I thought I managed to eliminate these errors by using the GCHandle but somehow it still happens sometimes. We developed the application on Windows Server 2012 where I have not seen this error during development. On newer Windows 11 Machines it now happens much more frequently.

Any idea why this happens and what i could do to eliminate the error?

[DllImport("kernel32.dll", SetLastError = false)]
static extern void CopyMemory(IntPtr destination, IntPtr source, UIntPtr length);

public static void Copy<T>(IntPtr source, T[] destination, int startIndex, int length) where T : struct
{
    var gch = GCHandle.Alloc(destination, GCHandleType.Pinned);
    try
    {
        var targetPtr = Marshal.UnsafeAddrOfPinnedArrayElement(destination, startIndex);
        var bytesToCopy = Marshal.SizeOf(typeof(T)) * length;

        CopyMemory(targetPtr, source, (UIntPtr)bytesToCopy);
     }
     finally
     {
         gch.Free();
     }
}


问:
Error: "Creating the deployment 'xx-20221221-071859-a2d8' would exceed the quota of '800
We use Azure DevOps YAML pipeline for managed group scoped deployments. In the first stage we validate the ARM deployment via YAML task AzureResourceManagerTemplateDeployment@3 (validation mode). Since today it fails with the following error: Template validation failed. Error: "Creating the deployment 'xxx-20221221-071859-a2d8' would exceed the quota of '800'. The current deployment count is '800'. Please delete some deployments before creating a new one, or see https://aka.ms/800LimitFix for information on managing deployment limits.

The YAML code snippet:

```<code>    - task: AzureResourceManagerTemplateDeployment@3
      displayName: Validate ARM Template
      inputs:
        azureResourceManagerConnection: ${{ variables.TestAzureResourceManagerConnection }}
        deploymentScope: 'Management Group'
        location: $(location)
        templateLocation: 'Linked artifact'
        csmFile: '${{ variables.MainTemplateFilePath }}'
        overrideParameters: '-parTargetManagementGroupID $(managementGroupID)'
        deploymentMode: 'Validation'
</code>```

I already checked the deployments in the corresponding managementgroup and other managementgroups and deleted them without any success.

Body:
We use Azure DevOps YAML pipeline for managed group scoped deployments. In the first stage we validate the ARM deployment via YAML task AzureResourceManagerTemplateDeployment@3 (validation mode). Since today it fails with the following error: Template validation failed. Error: "Creating the deployment 'xxx-20221221-071859-a2d8' would exceed the quota of '800'. The current deployment count is '800'. Please delete some deployments before creating a new one, or see https://aka.ms/800LimitFix for information on managing deployment limits.

The YAML code snippet:

    - task: AzureResourceManagerTemplateDeployment@3
      displayName: Validate ARM Template
      inputs:
        azureResourceManagerConnection: ${{ variables.TestAzureResourceManagerConnection }}
        deploymentScope: 'Management Group'
        location: $(location)
        templateLocation: 'Linked artifact'
        csmFile: '${{ variables.MainTemplateFilePath }}'
        overrideParameters: '-parTargetManagementGroupID $(managementGroupID)'
        deploymentMode: 'Validation'

I already checked the deployments in the corresponding managementgroup and other managementgroups and deleted them without any success.


问:
How to train VAE to learn the distribution of 3 classes
I want to train a Variational Auto-Encoder for a simple task: learn 3-class dataset and generate new samples from it's latent space. The problem is that despite it seems like an easy task I can't make it work. I expect it to produce the same 3 clusters when generating new samples from decoder (2 image).

I played with different values for beta. It's doesn't make it better.

How I can fix it and get the desired output or there some restrictions? Thanks in advance.

It's the code below, you may easy copypast the 3 code pieces into 3 cells in notebook and run.

Imports:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import torch
from torch.utils.data import Dataset
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.datasets import make_classification
</code>```

Here's dataset:

```<code>class TrainDataset(Dataset):
    def __init__(self, X):
        self.data = X.astype('float32')

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        return self.data[idx], 0

X, y = make_classification(n_samples=100, n_features=3, n_informative=3, n_redundant=0, n_classes=3, n_clusters_per_class=1, class_sep=2, random_state=16)
train_ratio = 0.7
batch_size = 8
train_loader = torch.utils.data.DataLoader(TrainDataset(X[:int(train_ratio * len(X))]), batch_size=batch_size)
test_loader = torch.utils.data.DataLoader(TrainDataset(X[int(train_ratio * len(X)):]), batch_size=batch_size)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.show()
</code>```

Now the VAE:

```<code>class VAEmini(nn.Module):
    def __init__(self, latent_d=2):
        super().__init__()
        self.fc1 = nn.Linear(3, 3)
        self.fc21 = nn.Linear(3, latent_d)
        self.fc22 = nn.Linear(3, latent_d)
        self.fc3 = nn.Linear(latent_d, 3)
        self.fc4 = nn.Linear(3, 3)

    def encode(self, x):
        h1 = F.relu(self.fc1(x))
        return self.fc21(h1), self.fc22(h1)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5*logvar)
        eps = torch.randn_like(std)
        return mu + eps*std

    def decode(self, z):
        h3 = F.relu(self.fc3(z))
        return self.fc4(h3)

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

def loss_function(recon_x, x, mu, logvar, beta):
    BCE = F.mse_loss(recon_x, x, reduction='mean')
    KLD = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE +  beta * KLD

def train(epoch, beta):
    model_mini.train()
    train_loss = 0
    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.to(device)
        optimizer.zero_grad()
        recon_batch, mu, logvar = model_mini(data)
        loss = loss_function(recon_batch, data, mu, logvar, beta)
        loss.backward()
        train_loss += loss.item()
        optimizer.step()
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader),
                loss.item() / len(data)))

    print('====> Epoch: {} Average loss: {:.4f}'.format(
        epoch, train_loss / len(train_loader.dataset)))

def test(epoch, beta):
    model_mini.eval()
    test_loss = 0
    with torch.no_grad():
        for i, (data, _) in enumerate(test_loader):
            data = data.to(device)
            recon_batch, mu, logvar = model_mini(data)
            test_loss += loss_function(recon_batch, data, mu, logvar, beta).item()

    print('====> Test set loss: {:.4f}'.format(test_loss /  len(test_loader.dataset)))
    return test_loss /  len(test_loader.dataset)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_mini = VAEmini(latent_d=2).to(device)
log_interval = 5
epochs = 100
optimizer = optim.Adam(model_mini.parameters(), lr=1e-2)
beta=0.01

for epoch in range(1, epochs + 1):
    train(epoch, beta=beta)
    test(epoch, beta=beta)

with torch.no_grad():
    sample = torch.randn(1000, 2).to(device)
    sample = model_mini.decode(sample).cpu()

fig = plt.figure(figsize=(20, 20))
ax = fig.add_subplot(projection='3d')
ax.scatter(sample[:, 0], sample[:, 1], sample[:, 2])
plt.show()
</code>```

Body:
I want to train a Variational Auto-Encoder for a simple task: learn 3-class dataset and generate new samples from it's latent space. The problem is that despite it seems like an easy task I can't make it work. I expect it to produce the same 3 clusters when generating new samples from decoder (2 image).

I played with different values for beta. It's doesn't make it better.

How I can fix it and get the desired output or there some restrictions? Thanks in advance.

It's the code below, you may easy copypast the 3 code pieces into 3 cells in notebook and run.

Imports:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import torch
from torch.utils.data import Dataset
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.datasets import make_classification

Here's dataset:

class TrainDataset(Dataset):
    def __init__(self, X):
        self.data = X.astype('float32')

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        return self.data[idx], 0

X, y = make_classification(n_samples=100, n_features=3, n_informative=3, n_redundant=0, n_classes=3, n_clusters_per_class=1, class_sep=2, random_state=16)
train_ratio = 0.7
batch_size = 8
train_loader = torch.utils.data.DataLoader(TrainDataset(X[:int(train_ratio * len(X))]), batch_size=batch_size)
test_loader = torch.utils.data.DataLoader(TrainDataset(X[int(train_ratio * len(X)):]), batch_size=batch_size)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.show()

Now the VAE:

class VAEmini(nn.Module):
    def __init__(self, latent_d=2):
        super().__init__()
        self.fc1 = nn.Linear(3, 3)
        self.fc21 = nn.Linear(3, latent_d)
        self.fc22 = nn.Linear(3, latent_d)
        self.fc3 = nn.Linear(latent_d, 3)
        self.fc4 = nn.Linear(3, 3)

    def encode(self, x):
        h1 = F.relu(self.fc1(x))
        return self.fc21(h1), self.fc22(h1)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5*logvar)
        eps = torch.randn_like(std)
        return mu + eps*std

    def decode(self, z):
        h3 = F.relu(self.fc3(z))
        return self.fc4(h3)

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

def loss_function(recon_x, x, mu, logvar, beta):
    BCE = F.mse_loss(recon_x, x, reduction='mean')
    KLD = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE +  beta * KLD

def train(epoch, beta):
    model_mini.train()
    train_loss = 0
    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.to(device)
        optimizer.zero_grad()
        recon_batch, mu, logvar = model_mini(data)
        loss = loss_function(recon_batch, data, mu, logvar, beta)
        loss.backward()
        train_loss += loss.item()
        optimizer.step()
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader),
                loss.item() / len(data)))

    print('====> Epoch: {} Average loss: {:.4f}'.format(
        epoch, train_loss / len(train_loader.dataset)))

def test(epoch, beta):
    model_mini.eval()
    test_loss = 0
    with torch.no_grad():
        for i, (data, _) in enumerate(test_loader):
            data = data.to(device)
            recon_batch, mu, logvar = model_mini(data)
            test_loss += loss_function(recon_batch, data, mu, logvar, beta).item()

    print('====> Test set loss: {:.4f}'.format(test_loss /  len(test_loader.dataset)))
    return test_loss /  len(test_loader.dataset)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_mini = VAEmini(latent_d=2).to(device)
log_interval = 5
epochs = 100
optimizer = optim.Adam(model_mini.parameters(), lr=1e-2)
beta=0.01

for epoch in range(1, epochs + 1):
    train(epoch, beta=beta)
    test(epoch, beta=beta)

with torch.no_grad():
    sample = torch.randn(1000, 2).to(device)
    sample = model_mini.decode(sample).cpu()

fig = plt.figure(figsize=(20, 20))
ax = fig.add_subplot(projection='3d')
ax.scatter(sample[:, 0], sample[:, 1], sample[:, 2])
plt.show()


问:
Attribute not found when importing python module
I'm trying to import my own module into another ipynb Jupyter Notebook but I keep getting an error that the function I'm calling has no attribute. Both files are in the same location and are both ipynb files and I don't know why it's not pulling through.

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

input:

```<code>import import_ipynb
import user_interface as ui
import secondary_code as functions

def run():
    while True:
        option = ui.menu()
        if option == 1:
            functions.retrieve_record(df)
run()
</code>```

outcome:

```<code>AttributeError                            Traceback (most recent call last)
Input In [19], in <cell line: 30>()

---> 31     run()

Input In [19], in run()
     10 option = ui.menu()
     11 if option == 1:
---> 12     functions.retrieve_record(df)`

AttributeError: module 'secondary_code' has no attribute 'retrieve_record'
</code>```

Body:
I'm trying to import my own module into another ipynb Jupyter Notebook but I keep getting an error that the function I'm calling has no attribute. Both files are in the same location and are both ipynb files and I don't know why it's not pulling through.

input:

import import_ipynb
import user_interface as ui
import secondary_code as functions

def run():
    while True:
        option = ui.menu()
        if option == 1:
            functions.retrieve_record(df)
run()

outcome:

AttributeError                            Traceback (most recent call last)
Input In [19], in <cell line: 30>()

---> 31     run()

Input In [19], in run()
     10 option = ui.menu()
     11 if option == 1:
---> 12     functions.retrieve_record(df)`

AttributeError: module 'secondary_code' has no attribute 'retrieve_record'


问:
How to schedule a python script using Task scheduler by using Argument field in Task Scheduler
I have followed these steps to schedule python script using Task scheduler and using arguments option in task scheduler but not able to run the scripts:

```<code>1. Open the Task Scheduler by searching for it in the Start menu.
2. Click on the "Create Basic Task" option from the Actions panel on the right.
3. Enter a name and description for the task and click "Next".
4. Select the frequency at which you want the task to run and click "Next".
5. Select the "Start a program" option and click "Next".
6. In the "Program/script" field, enter the path to the Python interpreter (e.g.    "C:\Python36\python.exe").
7. In the "Add arguments" field, enter the path to your Python script followed by any required   arguments. For example: "C:\scripts\myscript.py arg1 arg2".
8. Click "Next" and then click "Finish" to create the task.
</code>```

Python Script to be scheduled:

```<code>import sys
print('Hello_1')
a = sys.argv[1]
print(a)
print('Hello_2')
</code>```

I am able to do it through Batch File method. But not when using Arguments field in the Task Schedule.

Body:
I have followed these steps to schedule python script using Task scheduler and using arguments option in task scheduler but not able to run the scripts:

1. Open the Task Scheduler by searching for it in the Start menu.
2. Click on the "Create Basic Task" option from the Actions panel on the right.
3. Enter a name and description for the task and click "Next".
4. Select the frequency at which you want the task to run and click "Next".
5. Select the "Start a program" option and click "Next".
6. In the "Program/script" field, enter the path to the Python interpreter (e.g.    "C:\Python36\python.exe").
7. In the "Add arguments" field, enter the path to your Python script followed by any required   arguments. For example: "C:\scripts\myscript.py arg1 arg2".
8. Click "Next" and then click "Finish" to create the task.

Python Script to be scheduled:

import sys
print('Hello_1')
a = sys.argv[1]
print(a)
print('Hello_2')

I am able to do it through Batch File method. But not when using Arguments field in the Task Schedule.


问:
Can Spark load a proto definition file similar to loading Avro schema?
Spark supports loading Avro schema files with the spark-avro module and the "avroSchema" property: https://spark.apache.org/docs/latest/sql-data-sources-avro.html#data-source-option. This makes it easy to convert an Avro schema into a Spark StructType.

Is there similar support for loading a .proto file containing Protobuf message definitions, and converting them to a Spark StructType?


问:
Maintain NodeJS Server on ec2 Instances
I have an issue and I am not sure how to create this one on AWS ec2. So I have a File (server.js) that runs a NodeJS (Express) Server. It is pretty straight forward.

My Idea is:

Create a custom Image with the NodeJS Server and use this Image (AMI) for my Auto Scaling Group. This works, but has a big downside. If I need to maintain the server.js File, I need to create a new Image and Maintain the server.js, this is somehow a downside.

So what would be for you best practice to (best case)

I have in Github a Repo with a server.js
After making a change, I want to deploy this server.js to all running ec2 Instances or replace them. But the traffic is really high (billions of invokes per month), so I need to avoid downtimes.

Any recommandations are welcome

Title: Maintain NodeJS Server on ec2 Instances


问:
Add dead code warning of C code to Visual Studio 2022
I use Visual Studio 2022 to build my C project and OpenCppCoverage to check the coverage.

With these tools, I don't find how to find C functions (static & public) that aren't called.
The /Zi option may not produce a PDB with the uncalled function and OpenCppCoverage is unable to detect it:

dead Code

As the goal is to detect dead code, one option is to add a warning to visual studio 2022 compilator or linker to raise an error in case of unused function as gcc or to produce a PDB that contain information about the uncalled function (The second option may not work).

Anyone have an idea to detect dead code with these tools?


问:
could not find an object to spy upon for navigate()
while running karma testing I was getting an error Error: <spyOn> : could not find an object to spy upon for navigate() here i have injected the Router below I will share my code

component.ts

```<code>onSubmit() {
const observer = this.landingService.addLandingPage(params).subscribe(
() => {
        this.isLoading = false;
        const message = this.globalTranslate.getTranslation('LANDINGPAGE.ADD.SUCCESSTOAST');
        this.toast.success(message);
        this.landingAddForm.reset();
        this.router.navigate(['/landing_pages']);
      }
)
}

</code>```

spec.ts

```<code> it('calls addDevice service', () => {
            const service = TestBed.inject(LandingService);
            spyOn(component.toast, 'success').and.callThrough();
            const router = TestBed.inject(Router);
            const routerSpy = spyOn(router, 'navigate'); // got error in this line
            component.onSubmit();

            expect(service.addLandingPage).toHaveBeenCalled();
            expect(component.toast.success).toHaveBeenCalled();
            expect(routerSpy).toHaveBeenCalledWith(['/landing_pages']);
          });

</code>```

can any one help me to fix this

Body:
while running karma testing I was getting an error Error: <spyOn> : could not find an object to spy upon for navigate() here i have injected the Router below I will share my code

component.ts

onSubmit() {
const observer = this.landingService.addLandingPage(params).subscribe(
() => {
        this.isLoading = false;
        const message = this.globalTranslate.getTranslation('LANDINGPAGE.ADD.SUCCESSTOAST');
        this.toast.success(message);
        this.landingAddForm.reset();
        this.router.navigate(['/landing_pages']);
      }
)
}

spec.ts

 it('calls addDevice service', () => {
            const service = TestBed.inject(LandingService);
            spyOn(component.toast, 'success').and.callThrough();
            const router = TestBed.inject(Router);
            const routerSpy = spyOn(router, 'navigate'); // got error in this line
            component.onSubmit();

            expect(service.addLandingPage).toHaveBeenCalled();
            expect(component.toast.success).toHaveBeenCalled();
            expect(routerSpy).toHaveBeenCalledWith(['/landing_pages']);
          });

can any one help me to fix this


问:
CASL - Vue 3 - Element not showing for role
I am having a bit of a challenge implementing CASL in my app.

I have created the following composable useAppAbility ("hook") that defines all the rules:

import { AbilityBuilder, createMongoAbility, subject } from "@casl/ability";
import { useAbility } from "@casl/vue";

const service = {};
const user = {};
const subscription = {};
const invoice = {};
const account = {};

const ability = createMongoAbility();

const ROLES = ["admin", "account_owner", "beneficiary", "super_admin"];

const defineAbilityFor = (role: Object) => {
  const { can, rules } = new AbilityBuilder(createMongoAbility);
  const is = (r: string) => {
    return ROLES.indexOf(r) >= ROLES.indexOf(role);
  };

  if (is("admin")) {
    can("add", subject("User", user));
    can("remove", subject("User", user));
  }

  return ability.update(rules);
};

export { defineAbilityFor, ability, subject };
export const useAppAbility = () => useAbility();
```
<p>Added the plugin to the <strong>main.ts</strong>:</p>
<pre class="lang-js prettyprint-override"><code>import { ability } from "@/composables/useAppAbility";
import { abilitiesPlugin } from "@casl/vue";
createApp(App)
  .use(abilitiesPlugin, ability, {
    useGlobalProperties: true,
  })
//stuff
.mount("#app");
</code>```

And then, I found that using the beforeEach hook in the router and passing in the user before each route was the simplest way to deal with page load and SPA routing.
I have therefore added the following to my router/index.ts:

import { ability, defineAbilityFor } from "@/composables/useAppAbility";
import useAuth from "@/composables/useAuth";

const {
  getUserByClaims,
} = useAuth();
// routes
router.beforeEach(async (to, _from, next) => {
  defineAbilityFor(getUserByClaims.value.roles)
})
```
<p>At this stage I can verify that the user is being passed properly to the <code>defineAbilityFor</code> function and when using the <code>ability.on("update")</code> hook to log the rules object, I have the following output:
<img src="https://i.stack.imgur.com/qZFMK.png" alt="enter image description here" /></p>
<p>Which seems to confirm that the rules for this user are built and updated correctly?</p>
<p>However, when trying to display a button for the said admin in a component, the button does not show.</p>
<p>MyComponent.vue:</p>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts">
import { useAppAbility, subject } from "@/composables/useAppAbility";
const { can } = useAppAbility();
</script>
<template>
<div v-if="can('add', subject('User', {}))">TEST FOR CASL</div> <!-- DOES NOT SHOW-->
</template>

</code>```

Not sure where to go from there, any help would be appreciated.

Thanks

Body:
I am having a bit of a challenge implementing CASL in my app.

I have created the following composable useAppAbility ("hook") that defines all the rules:

import { AbilityBuilder, createMongoAbility, subject } from "@casl/ability";
import { useAbility } from "@casl/vue";

const service = {};
const user = {};
const subscription = {};
const invoice = {};
const account = {};

const ability = createMongoAbility();

const ROLES = ["admin", "account_owner", "beneficiary", "super_admin"];

const defineAbilityFor = (role: Object) => {
  const { can, rules } = new AbilityBuilder(createMongoAbility);
  const is = (r: string) => {
    return ROLES.indexOf(r) >= ROLES.indexOf(role);
  };

  if (is("admin")) {
    can("add", subject("User", user));
    can("remove", subject("User", user));
  }

  return ability.update(rules);
};

export { defineAbilityFor, ability, subject };
export const useAppAbility = () => useAbility();

Added the plugin to the main.ts:

import { ability } from "@/composables/useAppAbility";
import { abilitiesPlugin } from "@casl/vue";
createApp(App)
  .use(abilitiesPlugin, ability, {
    useGlobalProperties: true,
  })
//stuff
.mount("#app");

And then, I found that using the beforeEach hook in the router and passing in the user before each route was the simplest way to deal with page load and SPA routing.
I have therefore added the following to my router/index.ts:

import { ability, defineAbilityFor } from "@/composables/useAppAbility";
import useAuth from "@/composables/useAuth";

const {
  getUserByClaims,
} = useAuth();
// routes
router.beforeEach(async (to, _from, next) => {
  defineAbilityFor(getUserByClaims.value.roles)
})

At this stage I can verify that the user is being passed properly to the defineAbilityFor function and when using the ability.on("update") hook to log the rules object, I have the following output:

Which seems to confirm that the rules for this user are built and updated correctly?

However, when trying to display a button for the said admin in a component, the button does not show.

MyComponent.vue:

<template>

TEST FOR CASL

</template>

Not sure where to go from there, any help would be appreciated.

Thanks