问:
Using CLion to develop SDL2 programs, worked well in the IDE but got 0xc000007b error when opening it in the cmd/file explorer
I'm following Lazy Foo's tutorials, using CLion to develop SDL2 programs. When I build executable files in CLion, it worked well and ran correctly. But when I tried to run the exe file in the cmd, it showed me an 0xc000007b error. The same error occurred when i double-clicked it in the file explorer.

Im using windows10 21H2 64bit, CLion 2022.3.1 64bit with mingw 64bit,
The SDL release is 2.26.2, I copied the 64bit version to the mingw directory.

I've tried several methods to solve the problem, including but not limited to revise my CMakeLists.txt file:

```<code>cmake_minimum_required(VERSION 3.24)
project(SDL_project)
set(CMAKE_CXX_STANDARD 17)

include_directories(SDL)

add_executable(SDL_project main.cpp)

target_link_libraries(SDL_project mingw32 SDL2 SDL2main)

#link_directories(${SDL2_DIR})
#set(SDL2_DIR E:/programming/SDL_project/SDL2-2.26.2/x86_64-w64-mingw32)
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64")
#set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
</code>```

The lines i commented out were those i tried.

I've also read the questions about this issue on stackoverflow. Most of the answers suggest checking the lib or dll to ensure using the correct bit version (64bit or 32bit). I did checked, only to find that my SDL2/mingw/clion/OS are all 64bit.

I've tried using the Dependency Walker. After analysis, it reported that my
LIBGCC_S_DW2-1.DLL LIBSTDC++-6.DLL LIBWINPTHREAD-1.DLL SDL2.DLL
are 32bit. I'm sure that i copied the 64bit version SDL2.dll to the mingw directory, but other dlls - how can i change them to 64bit version?

Is my installation method of SDL2 incorrect? Or is my mingw settings incorrect? Another confusing detail is that it worked pretty well in the CLion IDE, but failed in the cmd/file explorer. By the way, im just using SDL2.h, not using SDL_Image or other expand libs.

Body:
I'm following Lazy Foo's tutorials, using CLion to develop SDL2 programs. When I build executable files in CLion, it worked well and ran correctly. But when I tried to run the exe file in the cmd, it showed me an 0xc000007b error. The same error occurred when i double-clicked it in the file explorer.

Im using windows10 21H2 64bit, CLion 2022.3.1 64bit with mingw 64bit,
The SDL release is 2.26.2, I copied the 64bit version to the mingw directory.

I've tried several methods to solve the problem, including but not limited to revise my CMakeLists.txt file:

cmake_minimum_required(VERSION 3.24)
project(SDL_project)
set(CMAKE_CXX_STANDARD 17)

include_directories(SDL)

add_executable(SDL_project main.cpp)

target_link_libraries(SDL_project mingw32 SDL2 SDL2main)

#link_directories(${SDL2_DIR})
#set(SDL2_DIR E:/programming/SDL_project/SDL2-2.26.2/x86_64-w64-mingw32)
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64")
#set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")

The lines i commented out were those i tried.

I've also read the questions about this issue on stackoverflow. Most of the answers suggest checking the lib or dll to ensure using the correct bit version (64bit or 32bit). I did checked, only to find that my SDL2/mingw/clion/OS are all 64bit.

I've tried using the Dependency Walker. After analysis, it reported that my
LIBGCC_S_DW2-1.DLL LIBSTDC++-6.DLL LIBWINPTHREAD-1.DLL SDL2.DLL
are 32bit. I'm sure that i copied the 64bit version SDL2.dll to the mingw directory, but other dlls - how can i change them to 64bit version?

Is my installation method of SDL2 incorrect? Or is my mingw settings incorrect? Another confusing detail is that it worked pretty well in the CLion IDE, but failed in the cmd/file explorer. By the way, im just using SDL2.h, not using SDL_Image or other expand libs.


来源: stackexchange

问:
Shortcut focus mouse in Filter of widget box in Qt Designer?
I don't know if there is a shortcut that can focus the mouse on the Filter box in the Widget box?
I want to quickly focus mouse to the Filter box to find widgets quickly
The straining to find widgets really tire me out.

I've tried looking in the manual but can't find it mentioned? (link: [https://doc.qt.io/qt-6/qtdesigner-manual.html])
Can someone help me?

ContentLicense: CC BY-SA 4.0


问:
Is it possible to create a Docker image from two base images?
I use MariaDB and Adminer. Both of them have their official images.

For the purpose of consistency, our team has these custom-built images:

company/site

company/api

company/panel

We want to have our company/database. We want to have an image that has both MariaDB and Adminer inside it.

Is there a way for us to merge these two images into one image?


问:
How do I make torch.cuda.is_available() be True?
I am trying to get whisper.ai to run on my GPU and so I installed pyTorch and cuda but torch.cuda.is_available() is still showing as False.

I installed nvidia CUDA 11.6 and I added cudnn to path. I also installed pytorch for cuda 11.6. I don't think I am missing any other steps but I am still getting false when I print(torch.cuda.is_available()) and I am not sure why.

ALSO: I am using an RTX 3070


问:
What is the keyboard shortcut to apply Reset on all actions in Google Data Studio Report?
Google Data Studio offers a Reset button that can be clicked to reset all actions on the report. This button is good to be used but when in full screen mode or presentation mode, this button is not visible, thus making it necessary to turn off the presentation mode, then apply reset and then turn on the presentation mode again. Do we have a keyboard shortcut instead of the Reset button? Thanks in advance for clarification.

I tried pressing F5 but it doesn't help.


问:
Save .xlsx file from st.download_button (Streamlit) using PySide6
I created a dashboard with Streamlit as a standalone application with the PySide6 library, however, I need to download a file generated in Streamlit through a button (st.download_button), but when it is clicked, nothing happens. Could you help on how to download Streamlit files with PySide6?

Here's my code:

app.py (PySide6 connector)

```<code>import atexit
import subprocess as sp
import os
from PySide6 import QtCore, QtWebEngineWidgets, QtWidgets
from PySide6.QtGui import QIcon

def kill_server(s):
    if os.name == 'nt':
        sp.call(['taskkill', '/F', '/T', '/PID', str(s.pid)])
    elif os.name == 'posix':
        s.taskkill()
    else:
        pass

if __name__ == '__main__':
    cmd = f'streamlit run rpbr.py --server.headless=True'
    p = sp.Popen(cmd.split(), stdout=sp.DEVNULL)
    atexit.register(kill_server, p)

    hostname = 'localhost'
    port = 8501

    app = QtWidgets.QApplication()
    my_icon = QIcon()
    my_icon.addFile('app.ico')

    app.setWindowIcon(my_icon)

    view = QtWebEngineWidgets.QWebEngineView()
    view.setWindowTitle("Plataform")
    view.load(QtCore.QUrl(f'http://{hostname}:{port}'))

    view.show()
    app.exec()
</code>```

rpbr.py (Streamlit - code area with download button)

```<code>run = st.download_button(label="Download", data=stats_rpbr(typ, pa, fab, brand, apr, start, end),
           file_name='Statistics.xlsx')
</code>```

I tried to find solutions by flagging the file download directly in PySide6, but nothing.

Body:
I created a dashboard with Streamlit as a standalone application with the PySide6 library, however, I need to download a file generated in Streamlit through a button (st.download_button), but when it is clicked, nothing happens. Could you help on how to download Streamlit files with PySide6?

Here's my code:

app.py (PySide6 connector)

import atexit
import subprocess as sp
import os
from PySide6 import QtCore, QtWebEngineWidgets, QtWidgets
from PySide6.QtGui import QIcon

def kill_server(s):
    if os.name == 'nt':
        sp.call(['taskkill', '/F', '/T', '/PID', str(s.pid)])
    elif os.name == 'posix':
        s.taskkill()
    else:
        pass

if __name__ == '__main__':
    cmd = f'streamlit run rpbr.py --server.headless=True'
    p = sp.Popen(cmd.split(), stdout=sp.DEVNULL)
    atexit.register(kill_server, p)

    hostname = 'localhost'
    port = 8501

    app = QtWidgets.QApplication()
    my_icon = QIcon()
    my_icon.addFile('app.ico')

    app.setWindowIcon(my_icon)

    view = QtWebEngineWidgets.QWebEngineView()
    view.setWindowTitle("Plataform")
    view.load(QtCore.QUrl(f'http://{hostname}:{port}'))

    view.show()
    app.exec()

rpbr.py (Streamlit - code area with download button)

run = st.download_button(label="Download", data=stats_rpbr(typ, pa, fab, brand, apr, start, end),
           file_name='Statistics.xlsx')

I tried to find solutions by flagging the file download directly in PySide6, but nothing.


问:
Detailed Step by Step for Installing Docker on Synology DS120j (aarch64)?
I have scrubbed the internet for detailed instructions on how to install Docker specifically on a Synology DS120j (aarch64, running DSM 7.1.4) and still need some help.
For confirmation I checked,

```<code>uname -m
</code>```

aarch64

I'm seeing that it looks to be possible to in stall Docker on this non-Intel machine but so far the instructions I've read are not as specific (step by step) as I apparently need them to be because something's not quite working.

End use is installing and running Home Assistant on this machine (which requires Docker) as an alternative to Raspberry Pi 4 because they are so hard to find and the DS120j seems to be an economic alternative (I have Homebridge successfully running on it and it's working great).

Though it looks like I was able to (sort of) install Docker, I can not access the Docker GUI / it does not show up in my package center. I'm not sure how I can install Home Assistant without the Docker GUI.

So I'm not sure if what I've done right and wrong along the way but have tried multiple methods  (from 4 post on Stackoverflow) to get to this point but I might need to start from scratch, which I'm completely prepared to do!

I have tried steps  1 - 6 from this Stackoverflow post including trying the automatic script (and also a second automatic script from a link that was posted further down the in the post replies).
Can I install Docker on arm8 based Synology Nas

Any detailed step by step instructions or insigts would be greatly appreciated.
I have held off for two weeks posting about this but am doing so now because there seems to be a lot of people buying these cheap DS120j NAS machines to run Homebridge / Home Assistant and other servers in place of Raspberry Pi's.

Thank you!
M

This is one script that I have tried:

```<code>#!/bin/sh
#/bin/wget -O - https://raw.githubusercontent.com/wdmomoxx/catdriver/master/install-docker.sh | /bin/sh
/bin/wget https://raw.githubusercontent.com/wdmomoxx/catdriver/master/catdsm-docker.tgz
tar -xvpzf catdsm-docker.tgz -C /
rm catdsm-docker.tgz
PATH=/opt/sbin:/opt/bin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/opt/etc/init.d/S60dockerd
sudo docker run -d --network=host -v "/run/docker.sock:/var/run/docker.sock"  portainer/portainer:linux-arm64
echo "猫盘群晖Docker安装完成"
echo "浏览器输入群晖IP:9000进入Docker UI"
</code>```

also

```<code>sudo mkdir -p /volume1/@Docker/lib
</code>```
```<code>sudo mkdir /docker
</code>```
```<code>sudo mount -o bind "/volume1/@Docker/lib" /docker
</code>```

This tip from comments in the above Stackoverflow post, I do not understand though,

"Then set the data-root in /etc/docker/daemon.json: { "data-root": "/docker" }"

I have also created a docker user group and added my name to the group but I'm not sure if docker is set to associate the two.

However when I currently ssh into the Diskstation and

```<code>docker --version"
</code>```

I do get,

Docker version 20.10.0, build 7287ab3

but I can not seem to see or launch the Docker GUI.

I see there is talk on the next about using Portainer but I'm not sure how to get that running as well.

Body:
I have scrubbed the internet for detailed instructions on how to install Docker specifically on a Synology DS120j (aarch64, running DSM 7.1.4) and still need some help.
For confirmation I checked,

uname -m

aarch64

I'm seeing that it looks to be possible to in stall Docker on this non-Intel machine but so far the instructions I've read are not as specific (step by step) as I apparently need them to be because something's not quite working.

End use is installing and running Home Assistant on this machine (which requires Docker) as an alternative to Raspberry Pi 4 because they are so hard to find and the DS120j seems to be an economic alternative (I have Homebridge successfully running on it and it's working great).

Though it looks like I was able to (sort of) install Docker, I can not access the Docker GUI / it does not show up in my package center. I'm not sure how I can install Home Assistant without the Docker GUI.

So I'm not sure if what I've done right and wrong along the way but have tried multiple methods  (from 4 post on Stackoverflow) to get to this point but I might need to start from scratch, which I'm completely prepared to do!

I have tried steps  1 - 6 from this Stackoverflow post including trying the automatic script (and also a second automatic script from a link that was posted further down the in the post replies).
Can I install Docker on arm8 based Synology Nas

Any detailed step by step instructions or insigts would be greatly appreciated.
I have held off for two weeks posting about this but am doing so now because there seems to be a lot of people buying these cheap DS120j NAS machines to run Homebridge / Home Assistant and other servers in place of Raspberry Pi's.

Thank you!
M

This is one script that I have tried:

#!/bin/sh
#/bin/wget -O - https://raw.githubusercontent.com/wdmomoxx/catdriver/master/install-docker.sh | /bin/sh
/bin/wget https://raw.githubusercontent.com/wdmomoxx/catdriver/master/catdsm-docker.tgz
tar -xvpzf catdsm-docker.tgz -C /
rm catdsm-docker.tgz
PATH=/opt/sbin:/opt/bin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/opt/etc/init.d/S60dockerd
sudo docker run -d --network=host -v "/run/docker.sock:/var/run/docker.sock"  portainer/portainer:linux-arm64
echo "猫盘群晖Docker安装完成"
echo "浏览器输入群晖IP:9000进入Docker UI"

also

sudo mkdir -p /volume1/@Docker/lib

sudo mkdir /docker

sudo mount -o bind "/volume1/@Docker/lib" /docker

This tip from comments in the above Stackoverflow post, I do not understand though,

"Then set the data-root in /etc/docker/daemon.json: { "data-root": "/docker" }"

I have also created a docker user group and added my name to the group but I'm not sure if docker is set to associate the two.

However when I currently ssh into the Diskstation and

docker --version"

I do get,

Docker version 20.10.0, build 7287ab3

but I can not seem to see or launch the Docker GUI.

I see there is talk on the next about using Portainer but I'm not sure how to get that running as well.


问:
airflow.exceptions.AirflowException: 403:Forbidden
```<code>from datetime import datetime
from airflow import DAG
from airflow.providers.sqlite.operators.sqlite import SqliteOperator
from airflow.providers.http.sensors.http import HttpSensor

default_args= {
    'start_date': datetime(2022, 1, 1)
}

# DAG skeleton
with DAG(dag_id='nft-pipeline',
         schedule='@daily',
         default_args=default_args,
         tags=['nft'],
         catchup=False) as dag:

    creating_table = SqliteOperator(
        task_id='creating_table',
        sqlite_conn_id='db_sqlite',
        sql='''
            CREATE TABLE IF NOT EXISTS nfts (
                token_id TEXT PRIMARY KEY,
                name TEST NOT NULL,
                image_url TEXT NOT NULL
            )
        '''
    )

    is_api_available = HttpSensor(
        task_id='is_api_available',
        http_conn_id='opensea_api',
        endpoint='api/v1/assets?collection=doodles-official&limit=1'
    )
</code>```

When I execute "$ airflow tasks test nft-pipeline is_api_available 2022-01-01" command, I got an "airflow.exceptions.AirflowException: 403:Forbidden" error message.

Body:
from datetime import datetime
from airflow import DAG
from airflow.providers.sqlite.operators.sqlite import SqliteOperator
from airflow.providers.http.sensors.http import HttpSensor

default_args= {
    'start_date': datetime(2022, 1, 1)
}

# DAG skeleton
with DAG(dag_id='nft-pipeline',
         schedule='@daily',
         default_args=default_args,
         tags=['nft'],
         catchup=False) as dag:

    creating_table = SqliteOperator(
        task_id='creating_table',
        sqlite_conn_id='db_sqlite',
        sql='''
            CREATE TABLE IF NOT EXISTS nfts (
                token_id TEXT PRIMARY KEY,
                name TEST NOT NULL,
                image_url TEXT NOT NULL
            )
        '''
    )

    is_api_available = HttpSensor(
        task_id='is_api_available',
        http_conn_id='opensea_api',
        endpoint='api/v1/assets?collection=doodles-official&limit=1'
    )

When I execute "$ airflow tasks test nft-pipeline is_api_available 2022-01-01" command, I got an "airflow.exceptions.AirflowException: 403:Forbidden" error message.


问:
How should the factorGraph object function factorTwoPoseSE3 in matlab use relative measurements correctly?
I tried to add relative pose measurements of 2 adjacent nodes using factorGraph's object function factorTwoPoseSE3, but no matter how much I should modify the relative angle “relT” variable(i.e. the number of quaternions), the optimized result graph remains the same, which is apparently a big problem?

If this is not the case, how do I modify the code to achieve the correct optimisation result that I want?

Design a plane rectangle, its observed 4 absolute coordinate points (0,0), (1,0), (1,1), (0,1), (0,1), node (node) number 1,2,3,4, respectively, in the last node 4 observed node 1 relative coordinates for (0.8,0), that is, closed loop , you can see that the last node error is 0.2. that is, this pose graph contains 4 edges, The first 3 of these are odometers and the last one is a closed loop edge.

% Since factorTwoPoseSE2 cannot specify a starting point for the time being, se3 is used for this purpose.

abspos = [0,0,0,eul2quat([0,0,0],"ZYX"); % rotate 0 about Z axis
    1,0,0,eul2quat([pi/2,0,0],"ZYX");    % rotate 90*pi/180 about Z axis
    1,1,0,eul2quat([pi,0,0],"ZYX");      % rotate 180*pi/180 about Z axis
    0,1,0,eul2quat([3*pi/2,0,0],"ZYX")]; % rotate 270*pi/180 about Z axis

relT = pi/2; % no matter how much I should modify this value, the result does't change???
relPose = [1,0,0,eul2quat([relT,0,0]);
    1,0,0,eul2quat([relT,0,0]);
    1,0,0,eul2quat([relT,0,0]);
    0.8,0,0,eul2quat([relT,0,0])];

fg = factorGraph();

pf = factorPoseSE3Prior(1,Measurement=[0,0,0, 1,0,0,0]);
addFactor(fg,pf);

nodeID = [1 2];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(1,:));% odometry
addFactor(fg,f);

nodeID = [2 3];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(2,:));% odometry
addFactor(fg,f);

nodeID = [3 4];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(3,:));% odometry
addFactor(fg,f);

nodeID = [4 1];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(end,:));% loop closure
addFactor(fg,f);

% optimize
optns = factorGraphSolverOptions();
optimize(fg,optns);

newNodes = [fg.nodeState(1);
    fg.nodeState(2);
    fg.nodeState(3);
    fg.nodeState(4)]

figure;
plot(newNodes(:,1),newNodes(:,2),'b-',Marker='.')
hold on;grid on;
plot(newNodes([4,1],1),newNodes([4,1],2),'r-',Marker='.')
text(newNodes(:,1),newNodes(:,2),string(1:4))
title('after factorGraph(3D) optimize')
```
<p><img src="https://i.stack.imgur.com/pwPeN.png" alt="enter image description here" /></p>
<p>Additionly, according to the  factorTwoPoseSE3 official documentation <strong>"Measured relative pose, specified as a seven-element row vector of the form [dx dy dz dqw dqx dqy dqz]. dx, dy, and dz are the change in position in x, y, and z respectively. dqw, dqx, dqy, and dqz are the change in quaternion rotation in w, x, y, and z respectively."</strong></p>
<p>So,  I have made the following changes to the relpos and it seems that the optimisation graphs are not correct, which is very confusing!</p>
<pre class="lang-matlab prettyprint-override"><code>relPose = diff(abspos);
relPose = [relPose;
    abspos(1,:)-abspos(end,:)];
</code>```

run in MATLAB R2022b.

Body:
I tried to add relative pose measurements of 2 adjacent nodes using factorGraph's object function factorTwoPoseSE3, but no matter how much I should modify the relative angle “relT” variable(i.e. the number of quaternions), the optimized result graph remains the same, which is apparently a big problem?

If this is not the case, how do I modify the code to achieve the correct optimisation result that I want?

Design a plane rectangle, its observed 4 absolute coordinate points (0,0), (1,0), (1,1), (0,1), (0,1), node (node) number 1,2,3,4, respectively, in the last node 4 observed node 1 relative coordinates for (0.8,0), that is, closed loop , you can see that the last node error is 0.2. that is, this pose graph contains 4 edges, The first 3 of these are odometers and the last one is a closed loop edge.

% Since factorTwoPoseSE2 cannot specify a starting point for the time being, se3 is used for this purpose.

abspos = [0,0,0,eul2quat([0,0,0],"ZYX"); % rotate 0 about Z axis
    1,0,0,eul2quat([pi/2,0,0],"ZYX");    % rotate 90*pi/180 about Z axis
    1,1,0,eul2quat([pi,0,0],"ZYX");      % rotate 180*pi/180 about Z axis
    0,1,0,eul2quat([3*pi/2,0,0],"ZYX")]; % rotate 270*pi/180 about Z axis

relT = pi/2; % no matter how much I should modify this value, the result does't change???
relPose = [1,0,0,eul2quat([relT,0,0]);
    1,0,0,eul2quat([relT,0,0]);
    1,0,0,eul2quat([relT,0,0]);
    0.8,0,0,eul2quat([relT,0,0])];

fg = factorGraph();

pf = factorPoseSE3Prior(1,Measurement=[0,0,0, 1,0,0,0]);
addFactor(fg,pf);

nodeID = [1 2];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(1,:));% odometry
addFactor(fg,f);

nodeID = [2 3];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(2,:));% odometry
addFactor(fg,f);

nodeID = [3 4];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(3,:));% odometry
addFactor(fg,f);

nodeID = [4 1];
f = factorTwoPoseSE3(nodeID,Measurement=relPose(end,:));% loop closure
addFactor(fg,f);

% optimize
optns = factorGraphSolverOptions();
optimize(fg,optns);

newNodes = [fg.nodeState(1);
    fg.nodeState(2);
    fg.nodeState(3);
    fg.nodeState(4)]

figure;
plot(newNodes(:,1),newNodes(:,2),'b-',Marker='.')
hold on;grid on;
plot(newNodes([4,1],1),newNodes([4,1],2),'r-',Marker='.')
text(newNodes(:,1),newNodes(:,2),string(1:4))
title('after factorGraph(3D) optimize')

Additionly, according to the  factorTwoPoseSE3 official documentation "Measured relative pose, specified as a seven-element row vector of the form [dx dy dz dqw dqx dqy dqz]. dx, dy, and dz are the change in position in x, y, and z respectively. dqw, dqx, dqy, and dqz are the change in quaternion rotation in w, x, y, and z respectively."

So,  I have made the following changes to the relpos and it seems that the optimisation graphs are not correct, which is very confusing!

relPose = diff(abspos);
relPose = [relPose;
    abspos(1,:)-abspos(end,:)];

run in MATLAB R2022b.


问:
Google Maps does not animate to user's location
I am trying to get my google maps map to center on my user's location. The user's location updates properly and shows the blue dot indicating their location. However, the camera, also set to the same coordinate locations, instead places itself at (0, 0). I have modified the program below so that it does move to the proper location after it loads. However, since my Bool is a state variable, it gives me a warning that I cannot update State variables during view updates. See the code below:

```<code>import SwiftUI
import GoogleMaps
import GoogleMapsUtils

struct GoogleMapsView: UIViewRepresentable {

@ObservedObject var locationManager = LocationManager()

var marker: GMSMarker = GMSMarker()

@Binding var heatmapWeightedData: [GMUWeightedLatLng]
@State var heatmapLayer = GMUHeatmapTileLayer()

@State var isCenteredOnCamera = false

func makeUIView(context: Context) -> GMSMapView {
    let camera = GMSCameraPosition.camera(withLatitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

    heatmapLayer.radius = 75
    heatmapLayer.weightedData = heatmapWeightedData
    heatmapLayer.map = mapView

    mapView.isMyLocationEnabled = true

    return mapView
}

func updateUIView(_ mapView: GMSMapView, context: UIViewRepresentableContext<GoogleMapsView>) {

    if self.isCenteredOnCamera == false {
        mapView.animate(to: GMSCameraPosition(latitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15))
        self.isCenteredOnCamera = true                            //Gives me the error
    }

    heatmapLayer.weightedData = heatmapWeightedData
    heatmapLayer.map = mapView

}

}
</code>```

Here is the locationManager code:

```<code>import Foundation
import CoreLocation

class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()

@Published var location: CLLocation? {
    willSet { objectWillChange.send() }
}

var latitude: CLLocationDegrees {
    return location?.coordinate.latitude ?? 0
}

var longitude: CLLocationDegrees {
    return location?.coordinate.longitude ?? 0
}

override init() {
    super.init()

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}
}

extension LocationManager: CLLocationManagerDelegate {

func locationManager( manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print(status)
}

func locationManager( manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else {
        return
    }

    self.location = location
}
}
</code>```

Presumably, the camera is just reading the optional longitude and latitude variables and setting them to 0, for reasons I do not know.

Is there a way for me to update the camera location just once so that it does not infinitely update the camera location? If so, what should I do?

Body:
I am trying to get my google maps map to center on my user's location. The user's location updates properly and shows the blue dot indicating their location. However, the camera, also set to the same coordinate locations, instead places itself at (0, 0). I have modified the program below so that it does move to the proper location after it loads. However, since my Bool is a state variable, it gives me a warning that I cannot update State variables during view updates. See the code below:

import SwiftUI
import GoogleMaps
import GoogleMapsUtils

struct GoogleMapsView: UIViewRepresentable {

@ObservedObject var locationManager = LocationManager()

var marker: GMSMarker = GMSMarker()

@Binding var heatmapWeightedData: [GMUWeightedLatLng]
@State var heatmapLayer = GMUHeatmapTileLayer()

@State var isCenteredOnCamera = false

func makeUIView(context: Context) -> GMSMapView {
    let camera = GMSCameraPosition.camera(withLatitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

    heatmapLayer.radius = 75
    heatmapLayer.weightedData = heatmapWeightedData
    heatmapLayer.map = mapView

    mapView.isMyLocationEnabled = true

    return mapView
}

func updateUIView(_ mapView: GMSMapView, context: UIViewRepresentableContext<GoogleMapsView>) {

    if self.isCenteredOnCamera == false {
        mapView.animate(to: GMSCameraPosition(latitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15))
        self.isCenteredOnCamera = true                            //Gives me the error
    }

    heatmapLayer.weightedData = heatmapWeightedData
    heatmapLayer.map = mapView

}

}

Here is the locationManager code:

import Foundation
import CoreLocation

class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()

@Published var location: CLLocation? {
    willSet { objectWillChange.send() }
}

var latitude: CLLocationDegrees {
    return location?.coordinate.latitude ?? 0
}

var longitude: CLLocationDegrees {
    return location?.coordinate.longitude ?? 0
}

override init() {
    super.init()

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}
}

extension LocationManager: CLLocationManagerDelegate {

func locationManager( manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print(status)
}

func locationManager( manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else {
        return
    }

    self.location = location
}
}

Presumably, the camera is just reading the optional longitude and latitude variables and setting them to 0, for reasons I do not know.

Is there a way for me to update the camera location just once so that it does not infinitely update the camera location? If so, what should I do?


问:
How to make binocular rivalry effect filter in Unity with AR Camera
As what the title mentioned, I wanna know does it possible to make binocular rivalry/anaglyph single-lens filter in Unity either using Post-Processing or just image panel?

If it is possible, then how?

I've tried adding post-processing to my AR Camera with red filter from Color-grading effect but it seems like I can't hide the red color object and make blue/cyan color object visible on my book.


问:
Proper way to branch iOS & Android AdMob App ID Development & Production settings in Flutter
I'm using AdMob in Flutter, and I can branch the Ad Unit ID via kDebugMode. However, the AdMob App ID is hardcoded into AndroidManifest.xml (Android) and Info.plist (iOS) respectively. I cannot apply the checking of debug mode in these files.

How can I switch between debug and production modes to use different AdMob App IDs? Thanks.

I heard I can use Product Flavors, but I'm unsure it's the right way to do so.

in iOS, I add an user-defined settings in Build Settings named ADMOB_APPID, then in Info.plist, I use the value $(ADMOB_APPID) in GADApplicationIdentifier property.

But I have no clue how I can do it in Android.


问:
MongoDB NodeJS driver : why is the MongoDB "cursor" not an asynchronous task?
I'm new to MongoDB and JS. I was just getting started with trying to connect a NodeJS app with MongoDB, when I encountered this thing called a "cursor". Could not fully understand what it exactly is.

For example my code look like this.

```<code>const db = client.db("playground").collection("cartoons");

async function readDocument() {
  const cursor = await db.find();    // VS code says await has not effect here
  cursor.forEach((doc) => console.log(doc));
}

readDocument();  // this works, it returns the docs in from the collection
</code>```

I wanted to know why the db.find(); which is fetching all the docs from a MongoDB server not an asynchronous task ?

Body:
I'm new to MongoDB and JS. I was just getting started with trying to connect a NodeJS app with MongoDB, when I encountered this thing called a "cursor". Could not fully understand what it exactly is.

For example my code look like this.

const db = client.db("playground").collection("cartoons");

async function readDocument() {
  const cursor = await db.find();    // VS code says await has not effect here
  cursor.forEach((doc) => console.log(doc));
}

readDocument();  // this works, it returns the docs in from the collection

I wanted to know why the db.find(); which is fetching all the docs from a MongoDB server not an asynchronous task ?


问:
The arguments object must be serializable via the StandardMessageCodec in restorablePush
I am trying to pass a map to the arguments parameter in the restorablePush method in flutter. Nonetheless, I keep getting an erro stating that the object I pass as a parameter should be serialized.

Error:
'debugIsSerializableForRestoration(arguments)': The arguments object must be serializable via the StandardMessageCodec.

This is my code

```<code>Navigator.restorablePush(context, _buildRoute,
  arguments: <String, dynamic>{
    'latitude': latitudeVisit,
    'longitude': longitudeVisit,
    'uid': widget.user.userUID,
    'user': widget.user,
  });
</code>```

I thought a map was a serializable object

Body:
I am trying to pass a map to the arguments parameter in the restorablePush method in flutter. Nonetheless, I keep getting an erro stating that the object I pass as a parameter should be serialized.

Error:
'debugIsSerializableForRestoration(arguments)': The arguments object must be serializable via the StandardMessageCodec.

This is my code

Navigator.restorablePush(context, _buildRoute,
  arguments: <String, dynamic>{
    'latitude': latitudeVisit,
    'longitude': longitudeVisit,
    'uid': widget.user.userUID,
    'user': widget.user,
  });

I thought a map was a serializable object


问:
If I could use SIMD process ProtoBuf RepeatedField data directly,or is there a way to parse RepeatedField to vector efficiently?
I use ProtoBuf RepeatedField<uint32_t> store my 64 bit uint vector.Now I want to get the sum or product of two RepeatedField,and I want to use SIMD to accelerate the speed.

If I could access the RepeatedField's memory,just like a vector,to finish it?
is there  a efficient way to copy the data from RepeatedField to vector.Then I will use SIMD at vectors.

My code report a heap-buffer-overflow at first iteration of  _mm256_loadu_si256.

Parameter papply(Parameter& a, Parameter& b) {
    Parameter ret;

    std::vector<uint32_t> tmp(8);

    for(int i = 0;i Mutable(i));
        __m256i mb = _mm256_loadu_si256((__m256i*) b.mutable_datas()->Mutable(i));

        _mm256_add_epi32(ma,mb);
        _mm256_storeu_si256((__m256i*) &tmp[0], ma);
        ret.mutable_datas()->Add(tmp.begin(),tmp.end());
    }
}
```

If I could access the RepeatedField's memory,just like a vector,to finish it? is there  a efficient way to copy the data from RepeatedField to vector.Then I will use SIMD at vectors.

Body:
I use ProtoBuf RepeatedField<uint32_t> store my 64 bit uint vector.Now I want to get the sum or product of two RepeatedField,and I want to use SIMD to accelerate the speed.

If I could access the RepeatedField's memory,just like a vector,to finish it?
is there  a efficient way to copy the data from RepeatedField to vector.Then I will use SIMD at vectors.

My code report a heap-buffer-overflow at first iteration of  _mm256_loadu_si256.

Parameter papply(Parameter& a, Parameter& b) {
    Parameter ret;

    std::vector<uint32_t> tmp(8);

    for(int i = 0;i Mutable(i));
        __m256i mb = _mm256_loadu_si256((__m256i*) b.mutable_datas()->Mutable(i));

        _mm256_add_epi32(ma,mb);
        _mm256_storeu_si256((__m256i*) &tmp[0], ma);
        ret.mutable_datas()->Add(tmp.begin(),tmp.end());
    }
}

If I could access the RepeatedField's memory,just like a vector,to finish it? is there  a efficient way to copy the data from RepeatedField to vector.Then I will use SIMD at vectors.


问:
Individual Account Verify and Flatform section in App Review
I have 2 question in app review process. Can you give my some advice?

I want to create a single App within Facebook that is solely for my own use and not intended to be sold or shared with anyone. This application will be used to manage and post content on my pages (https://www.facebook.com/ntdepcom - I sell interior-exterior products) or groups (of which I am the admin).
In Setting Basic Section, I already verified Individual Account; do I need to verify Business Account as well?

When it comes to the verification process, in the 'Add Platform' section I chose the 'Website' option.
I assume that I should fill this cell with a URL that the reviewer will use to access my app; is this correct?
Since this app is only for my own use, I don't need to create a 'beautiful user interface'. Would it be possible for me to create a simple interface with Google Spreadsheet for the Facebook review? (Front-end: Google Spreadsheet, back-end: Google App Script).

I developed a rudimentary application of my own, and I am in the process of constructing its user interface. I need more information about it, because I am not good at interface.

Thank you.


问:
One embedded excel for multiple charts in PowerPoint
I have a ppt with 80+ charts in 50+ slides.

When I get the data, I've to go into each chart -> right click -> Edit data -> Update the data in the embedded excel.

This process I'm repeating 80+ times for each chart which is time consuming.

I'm aware that the ppt can be transformed into a complete excel pack where we can have all the data in one single sheet and link to multiple charts in different tabs.

But, Is there a possibility in ppt itself to keep all the data in one embedded excel and refer it to all the 80+ charts?

Really appreciate any help on this!!

Please let me know if you have any questions..

Thanks..


问:
Sending GZipped data to SQL Server
I understand that SQL Server uses GZip for COMPRESS/DECOMPRESS. I've read, that the data is stored in SQL Server as hex and adds extra characters to the beginning.

It must be possible to send and receive compressed data to and from SQL Server. My case relates to large JSON payloads, however this would be applicable to importing large amounts of structured data from CSV/XML as well.

Stored procedure:

```<code>CREATE OR ALTER PROCEDURE gzipTest
    @compressed VARBINARY(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    SELECT CAST(DECOMPRESS(@compressed) as VARCHAR(MAX)) as json
END;
</code>```

Example Code:

```<code>mssql.exec({
    data: {
        compressed: {
            type: Datalayer.sql.VarBinary(Datalayer.sql.MAX),
            value: deflateSync(json),
        },
    },
    spName: 'gzipTest',
})
</code>```

A co-worker found this example code, for receiving compressed data:

https://jsfiddle.net/58mgsy9a/

However iterating over the zip file buffer array.map(pair => parseInt(pair, 16)) seems like way too much processing for something that should adhere to standards on both sides.

Title: Sending GZipped data to SQL Server

Body:
I understand that SQL Server uses GZip for COMPRESS/DECOMPRESS. I've read, that the data is stored in SQL Server as hex and adds extra characters to the beginning.

It must be possible to send and receive compressed data to and from SQL Server. My case relates to large JSON payloads, however this would be applicable to importing large amounts of structured data from CSV/XML as well.

Stored procedure:

CREATE OR ALTER PROCEDURE gzipTest
    @compressed VARBINARY(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    SELECT CAST(DECOMPRESS(@compressed) as VARCHAR(MAX)) as json
END;

Example Code:

mssql.exec({
    data: {
        compressed: {
            type: Datalayer.sql.VarBinary(Datalayer.sql.MAX),
            value: deflateSync(json),
        },
    },
    spName: 'gzipTest',
})

A co-worker found this example code, for receiving compressed data:

https://jsfiddle.net/58mgsy9a/

However iterating over the zip file buffer array.map(pair => parseInt(pair, 16)) seems like way too much processing for something that should adhere to standards on both sides.


问:
How to use Latex with Matplotlib on Mac?
This is the error:

```<code>RuntimeError: Failed to process string with tex because latex could not be found.
</code>```

I have already installed MacTex. I also installed dvipng and ghostscript using Mac Ports, but it's still not working. I also tried pip install latex.

The exact same code can run on another linux computer, so it's not the problem of the code.

It outputs a blank figure while I am expecting a figure with plotted data.

Is there any way to solve this? Thank you so much!!!

Body:
This is the error:

RuntimeError: Failed to process string with tex because latex could not be found.

I have already installed MacTex. I also installed dvipng and ghostscript using Mac Ports, but it's still not working. I also tried pip install latex.

The exact same code can run on another linux computer, so it's not the problem of the code.

It outputs a blank figure while I am expecting a figure with plotted data.

Is there any way to solve this? Thank you so much!!!


问:
How to List with objects, split into List.s of different Java objects)

I have a CsvToGame class, this is a model for parsing a CSV file.

```<code>import com.opencsv.bean.CsvBindByPosition;

import java.util.Objects;

public class CsvToGame {
    @CsvBindByPosition(position = 0)
    private String rank;

    @CsvBindByPosition(position = 1)
    private String name;

    @CsvBindByPosition(position = 2)
    private String platform;

    @CsvBindByPosition(position = 3)
    private String year;

    @CsvBindByPosition(position = 4)
    private String Genre;

    @CsvBindByPosition(position = 5)
    private String publisher;

    @CsvBindByPosition(position = 6)
    private String NASales;

    @CsvBindByPosition(position = 7)
    private String EUSales;

    @CsvBindByPosition(position = 8)
    private String JPSales;

    @CsvBindByPosition(position = 9)
    private String otherSales;

    @CsvBindByPosition(position = 10)
    private String globalSales;

    //set and get
    //equals and hashcode

</code>```

There is a parser.

```<code>import com.opencsv.bean.CsvToBeanBuilder;
import alex.gusev.Parser.model.CsvToGame;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ParserCsv {
    public static ArrayList<CsvToGame> parser(String path) {
        try (FileReader fileReader = new FileReader(path)) {
            ArrayList<CsvToGame> all = new ArrayList<>();
            List<CsvToGame> beans = new CsvToBeanBuilder(fileReader)
                    .withType(CsvToGame.class)
                    .build()
                    .parse();
            all.addAll(beans);
            return all;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
</code>```

**I need a parsed Csv file, I need to upload it to the database.

According to the database structure.**

enter image description here

**
How to implement it?
Sample code please!**

I created a set of classes, according to the structure of the database, but I can not help but connect it all.
enter image description here

Body:
I have a CsvToGame class, this is a model for parsing a CSV file.

import com.opencsv.bean.CsvBindByPosition;

import java.util.Objects;

public class CsvToGame {
    @CsvBindByPosition(position = 0)
    private String rank;

    @CsvBindByPosition(position = 1)
    private String name;

    @CsvBindByPosition(position = 2)
    private String platform;

    @CsvBindByPosition(position = 3)
    private String year;

    @CsvBindByPosition(position = 4)
    private String Genre;

    @CsvBindByPosition(position = 5)
    private String publisher;

    @CsvBindByPosition(position = 6)
    private String NASales;

    @CsvBindByPosition(position = 7)
    private String EUSales;

    @CsvBindByPosition(position = 8)
    private String JPSales;

    @CsvBindByPosition(position = 9)
    private String otherSales;

    @CsvBindByPosition(position = 10)
    private String globalSales;

    //set and get
    //equals and hashcode

There is a parser.

import com.opencsv.bean.CsvToBeanBuilder;
import alex.gusev.Parser.model.CsvToGame;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ParserCsv {
    public static ArrayList<CsvToGame> parser(String path) {
        try (FileReader fileReader = new FileReader(path)) {
            ArrayList<CsvToGame> all = new ArrayList<>();
            List<CsvToGame> beans = new CsvToBeanBuilder(fileReader)
                    .withType(CsvToGame.class)
                    .build()
                    .parse();
            all.addAll(beans);
            return all;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

**I need a parsed Csv file, I need to upload it to the database.

According to the database structure.**

enter image description here

**
How to implement it?
Sample code please!**

I created a set of classes, according to the structure of the database, but I can not help but connect it all.
enter image description here


问:
Delete data using on CASCADE DELETE but delete the records from the child tables in batches
I have just tried using delete statement but it will delete all the records of the child tables at once. but I have to delete them in batches

Suppose I have a parent table with user information like userid, username, age etc.. and in the child table there are million messages for a particular user, how I can delete the messages from the second table in batches using on cascade delete?


问:
How to update a record in Hive table using Informatica powercenter
I'm trying to update a record based on ID field in Hive table using informtica cloud data integration. But the problem is Instead of updating the existing record it is creating new record. Can anyone please suggest better approach</p>


问:
Why does my UseLoaderData return an added '3' in front of my parameter?
screen cap of debugger

My params.contactId is listed as 'int' when I call the useLoaderData function. However no matter what the int that is parsed in is ALWAYS prefixed by a 3?  all while still displaying the correct int I parsed in on the json string.

Has anyone else encountered this issue before?

I was expecting it to return just my contact id


问:
How to add a different DOMAIN ADDRESS to my Google Sheet Add-On?
Our app is designed to be used by our internal users most of the time. However, we have a partner company that we are planning to give access to our app. In other words, some users are outside of our domain but within our partner company's domain.

Would it be possible if we deploy the app internally and add OUR PARTNER'S DOMAIN in the allowed list?


问:
Webpack doesn't build and displays image
I'm having some problems with Webpack 5, which are:

It is not building the pro dist image.

In development mode when reloading the page, the image link is lost and it breaks.

The HTML does not find the image link.

This is my folder hierarchy:

WEBPACK CODE:

```<code>module.exports = {
    entry: './src/index.js',
    mode: 'production',
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
            chunkFilename: '[id].[contenthash].css',
        }),
        new CopyPlugin({
            patterns: [{ from: path.resolve(__dirname, 'src/*.txt'), to: path.resolve(__dirname, 'dist') }],
        }),
    ],
    devServer: {
        static: path.resolve(__dirname, 'dist'),
        port: 8080,
        hot: false,
        liveReload: true,
    },
    optimization: {
        runtimeChunk: 'single',
        minimizer: [
            new CssMinimizerPlugin({
                parallel: true,
                minify: CssMinimizerPlugin.cleanCssMinify,
            }),
            new TerserPlugin({
                test: /\.js(\?.*)?$/i,
                parallel: true,
                minify: TerserPlugin.uglifyJsMinify,
            }),
            new ImageMinimizerPlugin({
                minimizer: {
                    implementation: ImageMinimizerPlugin.imageminMinify,
                    options: {
                        plugins: [
                            ['gifsicle', { interlaced: true }],
                            ['jpegtran', { progressive: true }],
                            ['optipng', { optimizationLevel: 5 }],
                            [
                                'svgo',
                                {
                                    plugins: [
                                        {
                                            name: 'preset-default',
                                            params: {
                                                overrides: {
                                                    removeViewBox: false,
                                                    addAttributesToSVGElement: {
                                                        params: {
                                                            attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
                                                        },
                                                    },
                                                },
                                            },
                                        },
                                    ],
                                },
                            ],
                        ],
                    },
                },
            }),
        ],
    },
    output: {
        clean: true,
        filename: '[name].[contenthash].js',
        chunkFilename: '[id].[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.html$/i,
                loader: 'html-loader',
            },
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                        cacheCompression: true,
                        presets: ['@babel/preset-env'],
                        plugins: ['@babel/plugin-transform-runtime'],
                    },
                },
            },
            {
                mimetype: 'image/svg+xml',
                scheme: 'data',
                type: 'asset/resource',
                generator: {
                    filename: 'icons/[hash].svg',
                },
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]',
                    publicPath: 'assets/imgs',
                    outputPath: 'assets/imgs/',
                },
            },
            {
                test: /\.(sa|sc|c)ss$/, // SASS AND CSS
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    {
                        loader: 'css-loader',
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: () => [AutoPrefixer()],
                            },
                        },
                    },
                    {
                        loader: 'sass-loader',
                    },
                ],
            },
        ],
    },
};
</code>```

I've tried all possible configurations, with file-loader, url-loader etc, but none work.

Body:
I'm having some problems with Webpack 5, which are:

It is not building the pro dist image.

In development mode when reloading the page, the image link is lost and it breaks.

The HTML does not find the image link.

This is my folder hierarchy:

WEBPACK CODE:

module.exports = {
    entry: './src/index.js',
    mode: 'production',
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
            chunkFilename: '[id].[contenthash].css',
        }),
        new CopyPlugin({
            patterns: [{ from: path.resolve(__dirname, 'src/*.txt'), to: path.resolve(__dirname, 'dist') }],
        }),
    ],
    devServer: {
        static: path.resolve(__dirname, 'dist'),
        port: 8080,
        hot: false,
        liveReload: true,
    },
    optimization: {
        runtimeChunk: 'single',
        minimizer: [
            new CssMinimizerPlugin({
                parallel: true,
                minify: CssMinimizerPlugin.cleanCssMinify,
            }),
            new TerserPlugin({
                test: /\.js(\?.*)?$/i,
                parallel: true,
                minify: TerserPlugin.uglifyJsMinify,
            }),
            new ImageMinimizerPlugin({
                minimizer: {
                    implementation: ImageMinimizerPlugin.imageminMinify,
                    options: {
                        plugins: [
                            ['gifsicle', { interlaced: true }],
                            ['jpegtran', { progressive: true }],
                            ['optipng', { optimizationLevel: 5 }],
                            [
                                'svgo',
                                {
                                    plugins: [
                                        {
                                            name: 'preset-default',
                                            params: {
                                                overrides: {
                                                    removeViewBox: false,
                                                    addAttributesToSVGElement: {
                                                        params: {
                                                            attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
                                                        },
                                                    },
                                                },
                                            },
                                        },
                                    ],
                                },
                            ],
                        ],
                    },
                },
            }),
        ],
    },
    output: {
        clean: true,
        filename: '[name].[contenthash].js',
        chunkFilename: '[id].[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.html$/i,
                loader: 'html-loader',
            },
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                        cacheCompression: true,
                        presets: ['@babel/preset-env'],
                        plugins: ['@babel/plugin-transform-runtime'],
                    },
                },
            },
            {
                mimetype: 'image/svg+xml',
                scheme: 'data',
                type: 'asset/resource',
                generator: {
                    filename: 'icons/[hash].svg',
                },
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]',
                    publicPath: 'assets/imgs',
                    outputPath: 'assets/imgs/',
                },
            },
            {
                test: /\.(sa|sc|c)ss$/, // SASS AND CSS
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    {
                        loader: 'css-loader',
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: () => [AutoPrefixer()],
                            },
                        },
                    },
                    {
                        loader: 'sass-loader',
                    },
                ],
            },
        ],
    },
};

I've tried all possible configurations, with file-loader, url-loader etc, but none work.


问:
Collection View is reloaded then why wrong item disappears
I was seeing a code where a collection view is made and we can mark some items as favorite. Also there is a filter button on top if we select that only favorite items will be visible.

Now is favorite filter is applied, then any random item is unfavourated then from the collection view, the last item disappears (which is wrong, but the bussiness logic going on is right I have tested multiple times using breakpoints) and now if I go back and come to favorites page again then the wrong item which disappeared is in the list and the correct item which was unfavorited is not present because the businesses logic was right and the data source has correct elements so the collection view made is correct (what i think).

Now I guess after tapping favorite button something wrong is hapenning, that the collection view reloading has some problem.

Also second question is is always mandatory to call

```<code>collectionView.reloadData()
</code>```

and

```<code>collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
</code>```

in main thread using DispatchQueue.main.async

I am new to swift, can you help out what could be the case that the reload is happening is wrong but in data source correct element is removed.

Problem gif: View Here

I was not able to add in this post

UPDATE: added code snippets:

On tapping heart symbol this function is invoked:

```<code>func editFavouriteChannelList(with viewModel: MyChannelViewModel?, index: Int) {
        guard var viewModel = viewModel,
              viewModel.isFavouriteEnabled,
              var channel = viewModel.channels?[safe: index],
              !channel.state.isChangingStateInProgress() else {
                  return
              }
        // Some working
        // Calls updateCell fn with same viewModel but updated channel state
        self.updateCell(with: viewModel, channelCellModel: channel)

        // This makes API call then again we call on it's success updateCell fn with viewModel have removed that updated channel
        interactor.editFavouriteChannelList(with: channel, isMarkingFavourite: isMarkingFavourite)

    }
</code>```

This presenter's updateCell is called twice,
first when only channelCellModel is updated
and second time after making an API call that time viewModel will have that channel removed from it.

In presenter:

    private func updateCell(with viewModel: MyChannelViewModel, channelCellModel: MyChannelCellModel) {
         DispatchQueue.main.async { [weak self] in
            self.interface?.updateCell(with: viewModel, channelCellModel: channelCellModel)
         }
    }
```
<p>In ViewController:</p>
<pre class="lang-swift prettyprint-override"><code>    func updateCell(with viewModel: MyChannelViewModel, channelCellModel: MyChannelCellModel) {
        if myChannelVM?.channels?.count != viewModel.channels?.count {
            self.myChannelVM = viewModel
            collectionView.reloadData()
        } else {
            guard let index = myChannelVM?.channels?.firstIndex(of: channelCellModel) else {
                return
            }
            myChannelVM?.channels?[index] = channelCellModel
            print(" Like: updateCell local : \(myChannelVM?.channels?[index])")
            collectionView.reloadItems(at: [indexPath])
        }
    }
</code>```

In View Controller logic going on is like this first call to updateCell is made where viewModel is same as myChannelVM but channelCellModel is a channel with updated state.

Then second time call to updateCell is made where viewModel is same as myChannelVM but not having that channel which was earlier marked unfavorite.

Now if I remove collectionView.reloadItems(at: [indexPath]) from else block and use collectionView.reloadData() in place of it then collection view updates correctly otherwise not.

So updateCell(at:) is interfereing with reloadData() of when made in next call.

So there is issue like Why is a call to reloadItems(at:) stopping/breaking call to reloadData() in Collection View?

What is the reason for this in my case?

Body:
I was seeing a code where a collection view is made and we can mark some items as favorite. Also there is a filter button on top if we select that only favorite items will be visible.

Now is favorite filter is applied, then any random item is unfavourated then from the collection view, the last item disappears (which is wrong, but the bussiness logic going on is right I have tested multiple times using breakpoints) and now if I go back and come to favorites page again then the wrong item which disappeared is in the list and the correct item which was unfavorited is not present because the businesses logic was right and the data source has correct elements so the collection view made is correct (what i think).

Now I guess after tapping favorite button something wrong is hapenning, that the collection view reloading has some problem.

Also second question is is always mandatory to call

collectionView.reloadData()

and

collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])

in main thread using DispatchQueue.main.async

I am new to swift, can you help out what could be the case that the reload is happening is wrong but in data source correct element is removed.

Problem gif: View Here

I was not able to add in this post

UPDATE: added code snippets:

On tapping heart symbol this function is invoked:

func editFavouriteChannelList(with viewModel: MyChannelViewModel?, index: Int) {
        guard var viewModel = viewModel,
              viewModel.isFavouriteEnabled,
              var channel = viewModel.channels?[safe: index],
              !channel.state.isChangingStateInProgress() else {
                  return
              }
        // Some working
        // Calls updateCell fn with same viewModel but updated channel state
        self.updateCell(with: viewModel, channelCellModel: channel)

        // This makes API call then again we call on it's success updateCell fn with viewModel have removed that updated channel
        interactor.editFavouriteChannelList(with: channel, isMarkingFavourite: isMarkingFavourite)

    }

This presenter's updateCell is called twice,
first when only channelCellModel is updated
and second time after making an API call that time viewModel will have that channel removed from it.

In presenter:

    private func updateCell(with viewModel: MyChannelViewModel, channelCellModel: MyChannelCellModel) {
         DispatchQueue.main.async { [weak self] in
            self.interface?.updateCell(with: viewModel, channelCellModel: channelCellModel)
         }
    }

In ViewController:

    func updateCell(with viewModel: MyChannelViewModel, channelCellModel: MyChannelCellModel) {
        if myChannelVM?.channels?.count != viewModel.channels?.count {
            self.myChannelVM = viewModel
            collectionView.reloadData()
        } else {
            guard let index = myChannelVM?.channels?.firstIndex(of: channelCellModel) else {
                return
            }
            myChannelVM?.channels?[index] = channelCellModel
            print(" Like: updateCell local : \(myChannelVM?.channels?[index])")
            collectionView.reloadItems(at: [indexPath])
        }
    }

In View Controller logic going on is like this first call to updateCell is made where viewModel is same as myChannelVM but channelCellModel is a channel with updated state.

Then second time call to updateCell is made where viewModel is same as myChannelVM but not having that channel which was earlier marked unfavorite.

Now if I remove collectionView.reloadItems(at: [indexPath]) from else block and use collectionView.reloadData() in place of it then collection view updates correctly otherwise not.

So updateCell(at:) is interfereing with reloadData() of when made in next call.

So there is issue like Why is a call to reloadItems(at:) stopping/breaking call to reloadData() in Collection View?

What is the reason for this in my case?


问:
PowerMock private void method with arguments
I'm looking for a unit test for Controllers using Mockito and PowerMock. Every controller has only private void methods with a single argument and a @Autowired service dependency:

```<code>    public class ProjectController {

    private ProjectServiceImpl service;
    @Autowired
    public void setInjectedBean(ProjectServiceImpl service) {
        this.service = service;
    }

    private void createProject(String someString) {
        // do stuff by calling service.doSomething(someString)
    }
}
</code>```

ProjectServiceImpl is annotated with @Service and has only a public void method with a String as argument. As it is too simple, I didn't bother providing the code.
My last attempt to accomplish that test looks like this:

```<code>@RunWith(PowerMockRunner.class)
@ExtendWith(MockitoExtension.class)
@PrepareForTest({ProjectController.class, ProjectServiceImpl.class})
class ProjectControllerTest {

    @InjectMocks
    private ProjectController controller;
    @Mock
    private ProjectServiceImplservice;

    @Test
    void createProject() throws Exception {
        controller = PowerMockito.spy(new ProjectController());

        PowerMockito.doNothing().when(controller, "createProject", new String(""));
    }
}
</code>```

Question 1: is it possible to make PowerMock work aside of Mockito?

Question 2: using PowerMock, what's the most appropriate way of calling for a private void method with argument?

IMPORTANT: Before marking this post as a duplicate, I personally challenge you finding any content how to do so. It seems like there is just no content showing not only how to make both work together, but make PowerMockito calls for a private void method with one or more arguments.

dependencies used for PowerMock:

```<code><dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.3.0</version>
    </dependency>
</code>```

Body:
I'm looking for a unit test for Controllers using Mockito and PowerMock. Every controller has only private void methods with a single argument and a @Autowired service dependency:

    public class ProjectController {

    private ProjectServiceImpl service;
    @Autowired
    public void setInjectedBean(ProjectServiceImpl service) {
        this.service = service;
    }

    private void createProject(String someString) {
        // do stuff by calling service.doSomething(someString)
    }
}

ProjectServiceImpl is annotated with @Service and has only a public void method with a String as argument. As it is too simple, I didn't bother providing the code.
My last attempt to accomplish that test looks like this:

@RunWith(PowerMockRunner.class)
@ExtendWith(MockitoExtension.class)
@PrepareForTest({ProjectController.class, ProjectServiceImpl.class})
class ProjectControllerTest {

    @InjectMocks
    private ProjectController controller;
    @Mock
    private ProjectServiceImplservice;

    @Test
    void createProject() throws Exception {
        controller = PowerMockito.spy(new ProjectController());

        PowerMockito.doNothing().when(controller, "createProject", new String(""));
    }
}

Question 1: is it possible to make PowerMock work aside of Mockito?

Question 2: using PowerMock, what's the most appropriate way of calling for a private void method with argument?

IMPORTANT: Before marking this post as a duplicate, I personally challenge you finding any content how to do so. It seems like there is just no content showing not only how to make both work together, but make PowerMockito calls for a private void method with one or more arguments.

dependencies used for PowerMock:

<dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.3.0</version>
    </dependency>


问:
Upload Manifest.xml file to Microsoft Centralized Deployment cmdlets using power shell in ubuntu environment
I need to install O365CentralizedAddInDeployment module to continue my development related to microsoft365 add-in development. For that I already installed powershell in ubuntu and executed following command,

Install-Module -Name O365CentralizedAddInDeployment -RequiredVersion 1.5.0.2

then import using Import-Module -Name O365CentralizedAddInDeployment
but it gives me following error.

Import-Module: Could not load file or assembly 'microsoft.identitymodel.clients.activedirectory, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Is there any way to install this "O365CentralizedAddInDeployment" module to uduntu environment and use for the development?


问:
Is there a way to send the feature file annotations in Karate via Jenkins
We have a lot of feature files in our karate framework. We want to set up the ability to run any required feature file from Jenkins. Currently we are able to run the whole set of Feature files via Jenkins, but need to set up an ability to dynamically the required feature file annotation from JENKINS as part of a job.</p>


问:
something is changing .htaccess file periodically
The content of .htaccess file get changed from the typical content made by WordPress to this :

```<code># Apache 2.4+
<IfModule authz_core_module>
Require all denied
</IfModule>

# Apache 2.2
<IfModule !authz_core_module>
Deny from all
</IfModule>
</code>```

This causes the site to stop working with a 403 error message. The site returns to work when I return the content of the file (.htaccess) to what it was (from a previous backup), but after periods that may be long or short, the same thing happens and all the content of the file (.htaccess) is erased and replaced with the text written above.

I am using Jelastic Paas + Lightspeed Web Server, I checked all the site files using BitNinja, I use Wordfense and Sucuri, so I don't know where the error is and how the file is replaced automatically and periodically. Any ideas in particular?

I tried scanning the files and i expected to find some malware, even after deleting some suspicious files nothing improved.

Edit1: installed plugins are :

Checkout Files Upload for WooCommerce

Code Snippets

Contact Form 7

Content for multiple Courses in LearnPress

Cool Integration for LearnPress & WooCommerce

Elementor

Essential Addons for Elementor

Facebook Chat Plugin - Live Chat Plugin for WordPress

Flamingo

LearnPress

LearnPress - WooCommerce Payment Methods Integration

Limit Max IPs Per User

LiteSpeed Cache

LoginPress - Customizing the WordPress Login Screen.

LoginWP (Formerly Peter's Login Redirect)

Nextend Social Login

Password Strength Settings for WooCommerce

Quiz Maker

reCaptcha by BestWebSoft

Redirection

Redirection for Contact Form 7

Simple History

Sucuri Security - Auditing, Malware Scanner and Hardening

TeraWallet

UpdraftPlus - Backup/Restore

User Switching

VdoCipher

WooCommerce

WooCommerce Checkout Manager

WooCommerce Checkout Manager PRO

WooCommerce Wallet Coupons

Wordfence Security

WordPress Persistent Login

Wordpress Special Characters in Usernames

WP Mail SMTP

WP Ultimate CSV Importer

WP Ultimate Exporter

WPC Fly Cart for WooCommerce

WPC Product Bundles for WooCommerce

WPFront Notification Bar

Body:
The content of .htaccess file get changed from the typical content made by WordPress to this :

# Apache 2.4+
<IfModule authz_core_module>
Require all denied
</IfModule>

# Apache 2.2
<IfModule !authz_core_module>
Deny from all
</IfModule>

This causes the site to stop working with a 403 error message. The site returns to work when I return the content of the file (.htaccess) to what it was (from a previous backup), but after periods that may be long or short, the same thing happens and all the content of the file (.htaccess) is erased and replaced with the text written above.

I am using Jelastic Paas + Lightspeed Web Server, I checked all the site files using BitNinja, I use Wordfense and Sucuri, so I don't know where the error is and how the file is replaced automatically and periodically. Any ideas in particular?

I tried scanning the files and i expected to find some malware, even after deleting some suspicious files nothing improved.

Edit1: installed plugins are :

Checkout Files Upload for WooCommerce

Code Snippets

Contact Form 7

Content for multiple Courses in LearnPress

Cool Integration for LearnPress & WooCommerce

Elementor

Essential Addons for Elementor

Facebook Chat Plugin - Live Chat Plugin for WordPress

Flamingo

LearnPress

LearnPress - WooCommerce Payment Methods Integration

Limit Max IPs Per User

LiteSpeed Cache

LoginPress - Customizing the WordPress Login Screen.

LoginWP (Formerly Peter's Login Redirect)

Nextend Social Login

Password Strength Settings for WooCommerce

Quiz Maker

reCaptcha by BestWebSoft

Redirection

Redirection for Contact Form 7

Simple History

Sucuri Security - Auditing, Malware Scanner and Hardening

TeraWallet

UpdraftPlus - Backup/Restore

User Switching

VdoCipher

WooCommerce

WooCommerce Checkout Manager

WooCommerce Checkout Manager PRO

WooCommerce Wallet Coupons

Wordfence Security

WordPress Persistent Login

Wordpress Special Characters in Usernames

WP Mail SMTP

WP Ultimate CSV Importer

WP Ultimate Exporter

WPC Fly Cart for WooCommerce

WPC Product Bundles for WooCommerce

WPFront Notification Bar


问:
Need to run schedulers internally
I have a public website, which processes the data and run different schedulers for that data to process i.e. save data into db, send notifications to users

All these processes are running independently through the schedulers, and these processes are running concurrently

I am trying to run these schedulers using http, but using http the problem was up of available tcp ports into the system, because I have to process huge amount of data which will run millions of schedulers at a certain time, I have implemented the rate limiting also.

I have tried to run the schedulers using curl also, but it starts giving error

too much open files

even I have increased the open file limit in my system to 1 million ,and curl occupies too much resources, so I am avoiding to go with curl

For more clarification on data, let's say I have 10,000 schedulers are running concurrently, and inside these schedulers, 10-20 schedulers(for each scheduler) are running in parallel for sending notifications, I am thinking to run these internal schedulers by another method rather than http or curl.

Note:- I have to pass different data to each scheduler.

I am thinking to run these schedulers internally, can I do that?

Is there any better solution to run schedulers, by not using http or curl?

Title: Need to run schedulers internally


问:
[Unity][Android] BetterStreamingAssets Initialize failed with unauthorized access exception

Platform:

Unity： Unity 2021.3.11f1 Personal - Window 11

Visual Studio: Microsoft Visual Studio Enterprise 2022 (64-bit) - LTSC 17.2

Android Phone: Mi 10s

Code:

BetterStreamingAssets.Initialize();
```
<ul>
<li><strong>Exception</strong>:</li>
</ul>
```System.UnauthorizedAccessException:
Access to the path \'/data/data/{appName}/pram-shadow-files\' is denied.\n
```

I found the code of GetStreamingAssetsInfoFromJar with File.OpenRead in ApkImp.

And the Project link

Body:
Platform:

Unity： Unity 2021.3.11f1 Personal - Window 11

Visual Studio: Microsoft Visual Studio Enterprise 2022 (64-bit) - LTSC 17.2

Android Phone: Mi 10s

Code:

BetterStreamingAssets.Initialize();

Exception:

System.UnauthorizedAccessException:
Access to the path \'/data/data/{appName}/pram-shadow-files\' is denied.\n

I found the code of GetStreamingAssetsInfoFromJar with File.OpenRead in ApkImp.

And the Project link


问:
Can't create an app or a script using Whisper from OpenAi
I have a simple Python code that I can't export as an app using py2app nor as an executable script with pyinstaller...I get "RecursionError: maximum recursion depth exceeded". Pyinstaller tells me to use the .spec file and to add "import sys ; sys.setrecursionlimit(sys.getrecursionlimit() * 5)" in it but that solution doesn't work either once the script is created...</p>
```<code>import whisper
import tkinter as tk
import tkinter.filedialog as filedialog

# Create the main window
root = tk.Tk()

# Define a function to be called when the user selects a file
def select_file():
    # Display the file selection dialog and get the selected file
    filepath = filedialog.askopenfilename()

    # Transcribe the selected file
    model = whisper.load_model("base")
    result = model.transcribe(filepath, fp16=False)

    # Update the label with the transcription text
    label.config(text=result["text"])

# Create a button that will display the file selection dialog when clicked
button = tk.Button(root, text="Select file", command=select_file)
button.pack()

# Set the maximum width of the label to 400 pixels
max_width = 400

# Create a label to display the transcription text, with a maximum width of 400 pixels
label = tk.Label(root, wraplength=max_width)
label.pack()

# Run the tkinter event loop
root.mainloop()
</code>```

Body:
I have a simple Python code that I can't export as an app using py2app nor as an executable script with pyinstaller...I get "RecursionError: maximum recursion depth exceeded". Pyinstaller tells me to use the .spec file and to add "import sys ; sys.setrecursionlimit(sys.getrecursionlimit() * 5)" in it but that solution doesn't work either once the script is created...

import whisper
import tkinter as tk
import tkinter.filedialog as filedialog

# Create the main window
root = tk.Tk()

# Define a function to be called when the user selects a file
def select_file():
    # Display the file selection dialog and get the selected file
    filepath = filedialog.askopenfilename()

    # Transcribe the selected file
    model = whisper.load_model("base")
    result = model.transcribe(filepath, fp16=False)

    # Update the label with the transcription text
    label.config(text=result["text"])

# Create a button that will display the file selection dialog when clicked
button = tk.Button(root, text="Select file", command=select_file)
button.pack()

# Set the maximum width of the label to 400 pixels
max_width = 400

# Create a label to display the transcription text, with a maximum width of 400 pixels
label = tk.Label(root, wraplength=max_width)
label.pack()

# Run the tkinter event loop
root.mainloop()


问:
How to use Kubernetes kubeConfig to perform API calls in Karate Framework
I have kube config having client-certificate-data and client-key-data, how can I use this in karate to make api calls?

Is there a way to use these pem certificate in karate to configure ssl keystore ?
Any example for doing this ?


问:
Binance API: I can't fetch open order's stopLimit
Binance API: I can't fetch open order's stopLimit

All I get is zero, i've tried different libraries for this but still doesnt work, i still get 0.

i've tried different libraries and also tried raw request for this but still doesnt work, i still get 0.


问:
Wait for incoming video call with minimal power consumption
A bit of background on my project: I am doing a robot which can be controlled through the internet with live video feed. For that I have a raspberry pi as an on-board computer that handles the internet connection, video streaming, motor controlling etc. I've been successful with controlling it through a socket connection on python and a public VPS to relay commands (for NAT traversal).

Now I want to implement some sort of "idle state" like you would have on a mobile phone: The robot would stays idle and consume almost no power, and when I initiate a call on my computer it would wake up, stream the video etc. and when I hang up the call it would go to sleep again. Essentially, I want some version of Apple's Facetime and tweak it to my liking. The emphasis is on consuming as little energy as possible, since the robot is battery powered.

I can find almost no information on the internet for such an implementation (or maybe I just don't know the correct keyword). Can anyone point me in the correct direction?


问:
RSI higher then rsiMA by a specific value?
Thanks in advance.

How can I code that rsi is greater than rsiMA by a specific number in pine5?

I can only make it higher by the current ma value


问:
Unable to RE-navigate through SwiftUI app
I’m writing a workout app for Apple Watch but am running into issues with navigation. I have a version which includes the behaviour I’m looking for but am trying to simplify the navigation through the app which is leading to issues.

The “working” version of the app (code below) has the user select a workout from a launch page. When the workout is started, a tabbed view is displayed which contains controls on one page and metrics on another, cut down here for the purpose of demonstration. When End on the controls page is pressed, a boolean is set to true forcing a summary view to be displayed. When Done is pressed here, the view is dismissed returning the user to the launch page. A new workout can then be initiated.

As mentioned above, I’m trying to simplify the app, doing away with the workout selection and immediately leading to a start page. From there the functionality is basically the same. However, when I return to the start page, I am unable to initiate another workout without re-launching the app.

I’m just starting out on my SwiftUI journey so can only presume I’m misusing the NavigationStack or misunderstanding the concepts behind it but have not been able to see the issue.

Any assistance would be greatly appreciated.

Thanks much.

```<code>struct ContentView: View {
    @StateObject private var workoutManager = WorkoutManager()

    var body: some View {
        NavigationStack {
            List(Workout.workouts) { workout in
                NavigationLink(value: workout) {
                    Text(workout.shortName)
                }
            }
            .navigationDestination(for: Workout.self) { workout in
                WorkoutSetupView()
            }
            .navigationDestination(isPresented: $workoutManager.showingSummaryView) {
                SummaryView()
            }
        }
        .environmentObject(workoutManager)
    }
}

struct Workout: Identifiable, Hashable {
    var id: String
    var shortName: String

    static var workouts: [Workout] {
        [
            Workout(id: "WORKOUT1", shortName: "Workout 1"),
            Workout(id: "WORKOUT2", shortName: "Workout 2")
        ]
    }
}

class WorkoutManager: NSObject, ObservableObject {
    @Published var showingSummaryView: Bool = false

    func endWorkout() {
        showingSummaryView = true
    }
}

struct SummaryView: View {
    @Environment(\.dismiss) var dismiss

    var body: some View {
            ScrollView {
                VStack{
                    Text("Results: 2")

                    Button("Done") {
                        dismiss()
                    }
                }
            }
            .navigationTitle("Summary")
            .navigationBarBackButtonHidden(true)
    }
}

struct WorkoutSetupView: View {
    var body: some View {
        NavigationLink(
            destination: SessionPagingView()) {
                Image(systemName: "play")
            }
    }
}

struct SessionPagingView: View {
    @EnvironmentObject var workoutManager: WorkoutManager
    @State private var selection: Tab = .session

    enum Tab {
        case controls, session
    }

    var body: some View {
        TabView(selection: $selection) {
            Button {
                workoutManager.endWorkout()
            } label: {
                Text("End")
            }.tag(Tab.controls)

            Text("0:10").tag(Tab.session)
        }
        .navigationBarBackButtonHidden(true)
    }
}

</code>```

If I replace the NavigationStack block in ContentView with the code below, the app works in a simplified way as expected but a new workout cannot be initiated without relaunching the app.

```<code>        NavigationStack {
            NavigationLink(
                destination: SessionPagingView()) {
                    Image(systemName: "play")
                }
                .navigationDestination(isPresented: $workoutManager.showingSummaryView) {
                    SummaryView()
                }
        }
</code>```

I've tried resetting showingSummaryView to false on pressing Done in SummaryView and also tried using a NavigationPath but neither had any noticeable effect.

Thanks

Body:
I’m writing a workout app for Apple Watch but am running into issues with navigation. I have a version which includes the behaviour I’m looking for but am trying to simplify the navigation through the app which is leading to issues.

The “working” version of the app (code below) has the user select a workout from a launch page. When the workout is started, a tabbed view is displayed which contains controls on one page and metrics on another, cut down here for the purpose of demonstration. When End on the controls page is pressed, a boolean is set to true forcing a summary view to be displayed. When Done is pressed here, the view is dismissed returning the user to the launch page. A new workout can then be initiated.

As mentioned above, I’m trying to simplify the app, doing away with the workout selection and immediately leading to a start page. From there the functionality is basically the same. However, when I return to the start page, I am unable to initiate another workout without re-launching the app.

I’m just starting out on my SwiftUI journey so can only presume I’m misusing the NavigationStack or misunderstanding the concepts behind it but have not been able to see the issue.

Any assistance would be greatly appreciated.

Thanks much.

struct ContentView: View {
    @StateObject private var workoutManager = WorkoutManager()

    var body: some View {
        NavigationStack {
            List(Workout.workouts) { workout in
                NavigationLink(value: workout) {
                    Text(workout.shortName)
                }
            }
            .navigationDestination(for: Workout.self) { workout in
                WorkoutSetupView()
            }
            .navigationDestination(isPresented: $workoutManager.showingSummaryView) {
                SummaryView()
            }
        }
        .environmentObject(workoutManager)
    }
}

struct Workout: Identifiable, Hashable {
    var id: String
    var shortName: String

    static var workouts: [Workout] {
        [
            Workout(id: "WORKOUT1", shortName: "Workout 1"),
            Workout(id: "WORKOUT2", shortName: "Workout 2")
        ]
    }
}

class WorkoutManager: NSObject, ObservableObject {
    @Published var showingSummaryView: Bool = false

    func endWorkout() {
        showingSummaryView = true
    }
}

struct SummaryView: View {
    @Environment(\.dismiss) var dismiss

    var body: some View {
            ScrollView {
                VStack{
                    Text("Results: 2")

                    Button("Done") {
                        dismiss()
                    }
                }
            }
            .navigationTitle("Summary")
            .navigationBarBackButtonHidden(true)
    }
}

struct WorkoutSetupView: View {
    var body: some View {
        NavigationLink(
            destination: SessionPagingView()) {
                Image(systemName: "play")
            }
    }
}

struct SessionPagingView: View {
    @EnvironmentObject var workoutManager: WorkoutManager
    @State private var selection: Tab = .session

    enum Tab {
        case controls, session
    }

    var body: some View {
        TabView(selection: $selection) {
            Button {
                workoutManager.endWorkout()
            } label: {
                Text("End")
            }.tag(Tab.controls)

            Text("0:10").tag(Tab.session)
        }
        .navigationBarBackButtonHidden(true)
    }
}

If I replace the NavigationStack block in ContentView with the code below, the app works in a simplified way as expected but a new workout cannot be initiated without relaunching the app.

        NavigationStack {
            NavigationLink(
                destination: SessionPagingView()) {
                    Image(systemName: "play")
                }
                .navigationDestination(isPresented: $workoutManager.showingSummaryView) {
                    SummaryView()
                }
        }

I've tried resetting showingSummaryView to false on pressing Done in SummaryView and also tried using a NavigationPath but neither had any noticeable effect.

Thanks


问:
Scalling Socket.IO using Postgre Adapter, one server cannot send message to another server
Using postgres adapter not receive message from another server, but successfully with redis adapter,
here my code..
Postgresql Code

Anyone can fix this ??

Expect for close my problem


问:
Set seaborn diverging cmap palette's center/middle parameter to 0
I am trying to create a diverging red-green formatting for my pandas dataframe. Specifically, I want any value below 0 to be red, and any value above 0 to be green (& the higher the value, the darker green the cell ... and vice versa).

Currently, I cannot find a way to center this around 0. See below for a quick example of my code and a screenshot of my current output.

Thanks!

```<code>rdgn = sns.diverging_palette(h_neg=0, h_pos=112, s=68, l=50, sep=10,n=9, as_cmap=True)
s = test.style.background_gradient(rdgn).set_precision(2)
</code>```

Body:
I am trying to create a diverging red-green formatting for my pandas dataframe. Specifically, I want any value below 0 to be red, and any value above 0 to be green (& the higher the value, the darker green the cell ... and vice versa).

Currently, I cannot find a way to center this around 0. See below for a quick example of my code and a screenshot of my current output.

Thanks!

rdgn = sns.diverging_palette(h_neg=0, h_pos=112, s=68, l=50, sep=10,n=9, as_cmap=True)
s = test.style.background_gradient(rdgn).set_precision(2)


问:
Initialize values in ViewModel with Proto Datastore on Jetpack Compose
I am trying to initialize String values in ViewModel and cannot find proper solutions for this situation. The intended operation is as follows:

There is a string value on ViewModel and real value on Proto Datastore.

Initialize a string value with existing value saved at Proto Datastore.

Change a string value on ViewModel. (NOT applying change to Proto Datastore in this step!)

If changing string value completed, request Proto Datastore to apply string values on real values.

class MainViewModel(private val repository: DataRepository) : ViewMode() {
    private val _stringValue = MutableStateFlow("") // trying to initialize this value

    fun setStringValue(value: String) {
        viewModelScope.launch {
            repository.setStringValue(value)
        }
    }
}
```
```message Data {
    string stringValue = 1;
}
```

I tried initializing string value on Composable, because currently I am using Flow and Flow.collectAsState() method is only avaliable on @Composable annotated function. But it has critical problem that when every recomposition happens, string value is initialized with unintended values, too.

So I changed the way and trying to initialize it on ViewModel. But cannot find proper way on Google to do this.

Body:
I am trying to initialize String values in ViewModel and cannot find proper solutions for this situation. The intended operation is as follows:

There is a string value on ViewModel and real value on Proto Datastore.

Initialize a string value with existing value saved at Proto Datastore.

Change a string value on ViewModel. (NOT applying change to Proto Datastore in this step!)

If changing string value completed, request Proto Datastore to apply string values on real values.

class MainViewModel(private val repository: DataRepository) : ViewMode() {
    private val _stringValue = MutableStateFlow("") // trying to initialize this value

    fun setStringValue(value: String) {
        viewModelScope.launch {
            repository.setStringValue(value)
        }
    }
}

message Data {
    string stringValue = 1;
}

I tried initializing string value on Composable, because currently I am using Flow and Flow.collectAsState() method is only avaliable on @Composable annotated function. But it has critical problem that when every recomposition happens, string value is initialized with unintended values, too.

So I changed the way and trying to initialize it on ViewModel. But cannot find proper way on Google to do this.


问:
Bash: Issue when iterating string with lines
I have a issue when iterating string with lines. Check the following code:

file='[
    {"name" : "a b"},
    {
        "name" : "c"
    },
    {
        "name" : "d"
    }
]'

lines=$(jq -c '.[]' <<< "$file")
echo "lines $lines"

echo "\niterating #1:"
for i in ${lines//\\n/ }; do
  echo "item: $i"
done

echo "\niterating #2:"
while read -r line; do
  echo "item: $line"
done <<< $lines
```
<p>And the result is note expected. It breaks a line into two because there is a space in a field value.</p>
```lines {"name":"a b"}
{"name":"c"}
{"name":"d"}

iterating #1:
item: {"name":"a
item: b"}           # <-- don't want break here
item: {"name":"c"}
item: {"name":"d"}

iterating #2:
item: {"name":"a b"} {"name":"c"} {"name":"d"} # <-- seems no new line?
```

Body:
I have a issue when iterating string with lines. Check the following code:

file='[
    {"name" : "a b"},
    {
        "name" : "c"
    },
    {
        "name" : "d"
    }
]'

lines=$(jq -c '.[]' <<< "$file")
echo "lines $lines"

echo "\niterating #1:"
for i in ${lines//\\n/ }; do
  echo "item: $i"
done

echo "\niterating #2:"
while read -r line; do
  echo "item: $line"
done <<< $lines

And the result is note expected. It breaks a line into two because there is a space in a field value.

lines {"name":"a b"}
{"name":"c"}
{"name":"d"}

iterating #1:
item: {"name":"a
item: b"}           # <-- don't want break here
item: {"name":"c"}
item: {"name":"d"}

iterating #2:
item: {"name":"a b"} {"name":"c"} {"name":"d"} # <-- seems no new line?