问:
Firebase Cloud Messaging (FCM) - Data messages are CANCELED by iOS device after restart until app is opened for the first time after device restart
I am using pure data messages from FCM to display notifications locally on my app devices. For some reason, on iOS devices only, the data messages are CANCELED by iOS whenever the device is restarted up until my app is opened for the first time.  This leads to my app not receiving any data messages and thus not being able to display notifications and process them accordingly.  I am using React Native / Expo to build my app.

This below log lines show iOS cancellations, which continue to retry until the app is opened for the first time following the restart.

iOS Logs:

```<code>default 16:57:19.114198+0100    dasd    Submitted Activity: com.apple.pushLaunch.XXXXXXXXXXXXXX at priority 5 (Fri Dec 30 16:57:19 2022 - Sat Dec 31 16:57:19 2022)
default 16:57:19.118067+0100    dasd    Daemon Canceling Activities: {(
    com.apple.pushLaunch.XXXXXXXXXXXXXX
)}
default 16:57:19.118227+0100    dasd    CANCELED: com.apple.pushLaunch.XXXXXXXXXXXXXX at priority 5 <private>!
default 17:16:58.004240+0100    dasd    com.apple.pushLaunch.XXXXXXXXXXXXXX:[
    {name: ApplicationPolicy, policyWeight: 50.000, response: {Decision: Absolutely Must Not Proceed, Score: 0.00, Rationale: [{[pushDisallowed]: Required:0.00, Observed:1.00},]}}
 ], FinalDecision: Absolutely Must Not Proceed}
</code>```

Once the app is started for the first time, the data messages are received by my app. Following this, the issue does not take place once the app has been started the first time, even if it is is subsequently killed. However, on the next restart, the same issue will take place once again.

The following data message is sent using firebase admin sdk:

```<code>       Message firebaseMessage = Message.builder()
                .putData("notificationId", notificationId)
                .putData("title", title)
                .putData("body", message)
                .putData("imageUrl", imageUrl)
                .putData("channelImageUrl", channelImageUrl)
                .putData("channelId", "channel-notifications")
                .setApnsConfig(ApnsConfig.builder()
                        .setAps(Aps.builder()
                                .setContentAvailable(true).build())
                        .putHeader("apns-push-type", "background")
                        .putHeader("apns-priority", "5")
                        .putHeader("apns-topic", <my-app-bundle-id>)
                        .build())
                .setAndroidConfig(AndroidConfig.builder()
                        .setPriority(AndroidConfig.Priority.HIGH)
                        .build())
                .setToken(recipient)
                .build();
</code>```

The issue does not occur on Android.

Does anyone know what could be wrong and how to fix for my app to start receiving data messages even after a restart on iOS?

Body:
I am using pure data messages from FCM to display notifications locally on my app devices. For some reason, on iOS devices only, the data messages are CANCELED by iOS whenever the device is restarted up until my app is opened for the first time.  This leads to my app not receiving any data messages and thus not being able to display notifications and process them accordingly.  I am using React Native / Expo to build my app.

This below log lines show iOS cancellations, which continue to retry until the app is opened for the first time following the restart.

iOS Logs:

default 16:57:19.114198+0100    dasd    Submitted Activity: com.apple.pushLaunch.XXXXXXXXXXXXXX at priority 5 (Fri Dec 30 16:57:19 2022 - Sat Dec 31 16:57:19 2022)
default 16:57:19.118067+0100    dasd    Daemon Canceling Activities: {(
    com.apple.pushLaunch.XXXXXXXXXXXXXX
)}
default 16:57:19.118227+0100    dasd    CANCELED: com.apple.pushLaunch.XXXXXXXXXXXXXX at priority 5 <private>!
default 17:16:58.004240+0100    dasd    com.apple.pushLaunch.XXXXXXXXXXXXXX:[
    {name: ApplicationPolicy, policyWeight: 50.000, response: {Decision: Absolutely Must Not Proceed, Score: 0.00, Rationale: [{[pushDisallowed]: Required:0.00, Observed:1.00},]}}
 ], FinalDecision: Absolutely Must Not Proceed}

Once the app is started for the first time, the data messages are received by my app. Following this, the issue does not take place once the app has been started the first time, even if it is is subsequently killed. However, on the next restart, the same issue will take place once again.

The following data message is sent using firebase admin sdk:

       Message firebaseMessage = Message.builder()
                .putData("notificationId", notificationId)
                .putData("title", title)
                .putData("body", message)
                .putData("imageUrl", imageUrl)
                .putData("channelImageUrl", channelImageUrl)
                .putData("channelId", "channel-notifications")
                .setApnsConfig(ApnsConfig.builder()
                        .setAps(Aps.builder()
                                .setContentAvailable(true).build())
                        .putHeader("apns-push-type", "background")
                        .putHeader("apns-priority", "5")
                        .putHeader("apns-topic", <my-app-bundle-id>)
                        .build())
                .setAndroidConfig(AndroidConfig.builder()
                        .setPriority(AndroidConfig.Priority.HIGH)
                        .build())
                .setToken(recipient)
                .build();

The issue does not occur on Android.

Does anyone know what could be wrong and how to fix for my app to start receiving data messages even after a restart on iOS?


来源: stackexchange

问:
UnInstall is deleting all path variables INstallSHield
I trying to add a path variable using InstallShield 2014 (InstallScript project)

I managed to append add path variable using this code:

```<code>sRegKey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
szKey="Environment";
RegDBSetDefaultRoot(HKEY_CURRENT_USER);
GetEnvVar("PATH", svEnvVar);
sNewPath= svEnvVar + "My Path";
nResult1 = RegDBSetKeyValueEx(szKey,"PATH",REGDB_STRING,sNewPath,-1);
</code>```

The problem is that when unINstalling the exe file the all Path variables are deleted.
Is there another way to add the path variable without deleting it on uninstall?

Thanks,

ContentLicense: CC BY-SA 4.0

Body:
I trying to add a path variable using InstallShield 2014 (InstallScript project)

I managed to append add path variable using this code:

sRegKey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
szKey="Environment";
RegDBSetDefaultRoot(HKEY_CURRENT_USER);
GetEnvVar("PATH", svEnvVar);
sNewPath= svEnvVar + "My Path";
nResult1 = RegDBSetKeyValueEx(szKey,"PATH",REGDB_STRING,sNewPath,-1);

The problem is that when unINstalling the exe file the all Path variables are deleted.
Is there another way to add the path variable without deleting it on uninstall?

Thanks,


问:
PyQt5 Button dont work when I import it, but works when main
I use PyQt5 Designer to create two windows. My idea is to change first(main) window when I press button and this works fine. So now I have second window that has other button with function to show hidden label. But when I press that button nothing happens. When I open second window as main, button works perfectly. Here is my first window:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
from SecondWindow import *

class Ui_FirstWindow(object):
    def setupUi(self, FirstWindow):
        FirstWindow.setObjectName("FirstWindow")
        FirstWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(FirstWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_ChangeWindow = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_ChangeWindow.setGeometry(QtCore.QRect(280, 330, 281, 91))
        self.pushButton_ChangeWindow.setObjectName("pushButton_ChangeWindow")
        self.pushButton_ChangeWindow.clicked.connect(self.change_window)   # Link button with funcion
        FirstWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(FirstWindow)
        QtCore.QMetaObject.connectSlotsByName(FirstWindow)

    def retranslateUi(self, FirstWindow):
        _translate = QtCore.QCoreApplication.translate
        FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
        self.pushButton_ChangeWindow.setText(_translate("FirstWindow", "Change Window"))

    def change_window(self):
        ui = Ui_SecondWindow()
        ui.setupUi(FirstWindow)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    FirstWindow = QtWidgets.QMainWindow()
    ui = Ui_FirstWindow()
    ui.setupUi(FirstWindow)
    FirstWindow.show()
    sys.exit(app.exec_())

</code>```

Here everything works fine. When I click button it shows me second window. Code for second window:

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

class Ui_SecondWindow(object):
    def setupUi(self, SecondWindow):
        SecondWindow.setObjectName("SecondWindow")
        SecondWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(SecondWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_ShowLabel = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_ShowLabel.setGeometry(QtCore.QRect(270, 260, 241, 81))
        self.pushButton_ShowLabel.setObjectName("pushButton_ShowLabel")
        self.pushButton_ShowLabel.clicked.connect(self.show_hidden_label)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(320, 130, 121, 51))
        self.label.setObjectName("label")

        # Hide label
        self.label.hide()
        SecondWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(SecondWindow)
        QtCore.QMetaObject.connectSlotsByName(SecondWindow)

    def retranslateUi(self, SecondWindow):
        _translate = QtCore.QCoreApplication.translate
        SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
        self.pushButton_ShowLabel.setText(_translate("SecondWindow", "Show Label"))
        self.label.setText(_translate("SecondWindow", "Hello"))

    def show_hidden_label(self):
        self.label.show()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    SecondWindow = QtWidgets.QMainWindow()
    ui = Ui_SecondWindow()
    ui.setupUi(SecondWindow)
    SecondWindow.show()
    sys.exit(app.exec_())
</code>```

Now I click button on new window but it does nothing. When I start this code as main, everything works fine.

I started coding about 1 month ago so sorry if code is confusing or something. I appriciate any help and advice

Body:
I use PyQt5 Designer to create two windows. My idea is to change first(main) window when I press button and this works fine. So now I have second window that has other button with function to show hidden label. But when I press that button nothing happens. When I open second window as main, button works perfectly. Here is my first window:

from PyQt5 import QtCore, QtGui, QtWidgets
from SecondWindow import *

class Ui_FirstWindow(object):
    def setupUi(self, FirstWindow):
        FirstWindow.setObjectName("FirstWindow")
        FirstWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(FirstWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_ChangeWindow = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_ChangeWindow.setGeometry(QtCore.QRect(280, 330, 281, 91))
        self.pushButton_ChangeWindow.setObjectName("pushButton_ChangeWindow")
        self.pushButton_ChangeWindow.clicked.connect(self.change_window)   # Link button with funcion
        FirstWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(FirstWindow)
        QtCore.QMetaObject.connectSlotsByName(FirstWindow)

    def retranslateUi(self, FirstWindow):
        _translate = QtCore.QCoreApplication.translate
        FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
        self.pushButton_ChangeWindow.setText(_translate("FirstWindow", "Change Window"))

    def change_window(self):
        ui = Ui_SecondWindow()
        ui.setupUi(FirstWindow)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    FirstWindow = QtWidgets.QMainWindow()
    ui = Ui_FirstWindow()
    ui.setupUi(FirstWindow)
    FirstWindow.show()
    sys.exit(app.exec_())

Here everything works fine. When I click button it shows me second window. Code for second window:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_SecondWindow(object):
    def setupUi(self, SecondWindow):
        SecondWindow.setObjectName("SecondWindow")
        SecondWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(SecondWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_ShowLabel = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_ShowLabel.setGeometry(QtCore.QRect(270, 260, 241, 81))
        self.pushButton_ShowLabel.setObjectName("pushButton_ShowLabel")
        self.pushButton_ShowLabel.clicked.connect(self.show_hidden_label)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(320, 130, 121, 51))
        self.label.setObjectName("label")

        # Hide label
        self.label.hide()
        SecondWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(SecondWindow)
        QtCore.QMetaObject.connectSlotsByName(SecondWindow)

    def retranslateUi(self, SecondWindow):
        _translate = QtCore.QCoreApplication.translate
        SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
        self.pushButton_ShowLabel.setText(_translate("SecondWindow", "Show Label"))
        self.label.setText(_translate("SecondWindow", "Hello"))

    def show_hidden_label(self):
        self.label.show()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    SecondWindow = QtWidgets.QMainWindow()
    ui = Ui_SecondWindow()
    ui.setupUi(SecondWindow)
    SecondWindow.show()
    sys.exit(app.exec_())

Now I click button on new window but it does nothing. When I start this code as main, everything works fine.

I started coding about 1 month ago so sorry if code is confusing or something. I appriciate any help and advice


问:
Soap-server responds with error 12030 after requests over HTTPS
My Delphi 10.4 application uses a HTTPRIO-component to communicates with SOAP REST Server over HTTPS.
It is installed on more then 100 PC's, and it works fine almost everywhere.
However, I now have 2 clients that get the following error:

"Error sending data: (12030). De verbinding met de server is niet normaal beëindigd"
(--> The connection to the server did not end normally )

The user has a Windows 7 Home Premium machine (I have Windows 10 Pro).
Firewall was disabled.

If I copy the complete application-dirctory with all the dll's to my machine everything works fine.

Where should I start looking for a solution?
Which properties of the HTTPRIO-component could have an effect on this behaviour? Or which dll's?

I checked the article Peter Wolf suggested but without succes. (The register-settings should be OK). All the registers are present with the right values, but the windows update could not be installed. Also downloading the stand-alone update KB3140245 fails. It juist says "failed".

any hints are welcome!

kind regards,

Dirk Janssens


问:
Apply optim() function to each row then cbind result for corresponding row to new or existing data frame
EDIT: I'm going to EDIT this post to streamline my question to hopefully make it clearer. -- CalebPicker

I'm trying to use apply() or a for...loop to optimize a custom function on each row, and for each completed optimization, I want the output parameters to bind to the corresponding row.  For example, if I have 10 rows in my dataframe called df_conf, then I want optim() to run 10 times and bind the 10 sets of outputs next to the corresponding row.

I want to apply the optim() function to row 1, spit out par1:par3 and bind it to this data frame, then move onto row 2 and do the same thing for all rows.

```<code>df5<-data.frame(H1=c(1,5),H2=c(4,7),H3=c(12,17),H4=c(21,32),H5=c(25,41),H6=c(52,64),

F1=c(2,8),F2=c(9,10),F3=c(18,21),F4=c(21,32),F5=c(31,49),F6=c(59,68))

# Create optim() function to minimize sse for a line for one subject
lm_sse5<-function(dat,par,i){
  b0<-par[1]
  b1<-par[2]

  # Convert wide to long inside of function
  lm_df5<-data.frame(x=c(dat[["H1"]],dat[["H2"]],dat[["H3"]],dat[["H4"]],dat[["H5"]],dat[["H6"]]), y=c(dat[["F1"]], dat[["F2"]], dat[["F3"]], dat[["F4"]], dat[["F5"]], dat[["F6"]]))`

  yhat<-b0 + b1*lm_df5[["x"]]
  sse<- sum((yhat-lm_df5[["y"]])**2)
  sse_sqrt<-sqrt(sse)

  # How to get sse and sse_sqrt into dataframe?
  #  This seemed to work but seems tedious.  This replaces the dataframe with a new value for each iteration
  # but because it's being overwritten each time, I end up with the last value in the output dataframe.
  output<<-data.frame("sse"="","sse_sqrt"="")
  output[["sse"]]<<-sse
  output[["sse_sqrt"]]<<-sse_sqrt

 print(paste0("sse is: ",sse))
 print(paste0("sse_sqrt is: ", sse_sqrt))

  return(sse)
}

# Define parameter start values
param_start<-c(b0=0,b1=0)

# Run minimization function on return value in function, which is sse

# try to use apply function
# I could not get this to work
# result5a<-apply(1:nrow(df5),1,function(x){
#       optim(param_start,
#             fn=lm_sse5,
#             dat=df5[x,])
#   }
#       )

# # The for loop works but this does not save the values appropriately
for(x in 1:nrow(df5)){
result5b<-optim(param_start,
           fn=lm_sse5,
           dat=df5[x,],
           i=x)
}

# append results to original dataframe
# This works but is very manual
 df5$b0<-result$par["b0"]
 df5$b1<-result$par["b1"]
 df5$sse<-output$sse
 df5$sse_sqrt<-output$sse_sqrt
</code>```

Body:
EDIT: I'm going to EDIT this post to streamline my question to hopefully make it clearer. -- CalebPicker

I'm trying to use apply() or a for...loop to optimize a custom function on each row, and for each completed optimization, I want the output parameters to bind to the corresponding row.  For example, if I have 10 rows in my dataframe called df_conf, then I want optim() to run 10 times and bind the 10 sets of outputs next to the corresponding row.

I want to apply the optim() function to row 1, spit out par1:par3 and bind it to this data frame, then move onto row 2 and do the same thing for all rows.

df5<-data.frame(H1=c(1,5),H2=c(4,7),H3=c(12,17),H4=c(21,32),H5=c(25,41),H6=c(52,64),

F1=c(2,8),F2=c(9,10),F3=c(18,21),F4=c(21,32),F5=c(31,49),F6=c(59,68))

# Create optim() function to minimize sse for a line for one subject
lm_sse5<-function(dat,par,i){
  b0<-par[1]
  b1<-par[2]

  # Convert wide to long inside of function
  lm_df5<-data.frame(x=c(dat[["H1"]],dat[["H2"]],dat[["H3"]],dat[["H4"]],dat[["H5"]],dat[["H6"]]), y=c(dat[["F1"]], dat[["F2"]], dat[["F3"]], dat[["F4"]], dat[["F5"]], dat[["F6"]]))`

  yhat<-b0 + b1*lm_df5[["x"]]
  sse<- sum((yhat-lm_df5[["y"]])**2)
  sse_sqrt<-sqrt(sse)

  # How to get sse and sse_sqrt into dataframe?
  #  This seemed to work but seems tedious.  This replaces the dataframe with a new value for each iteration
  # but because it's being overwritten each time, I end up with the last value in the output dataframe.
  output<<-data.frame("sse"="","sse_sqrt"="")
  output[["sse"]]<<-sse
  output[["sse_sqrt"]]<<-sse_sqrt

 print(paste0("sse is: ",sse))
 print(paste0("sse_sqrt is: ", sse_sqrt))

  return(sse)
}

# Define parameter start values
param_start<-c(b0=0,b1=0)

# Run minimization function on return value in function, which is sse

# try to use apply function
# I could not get this to work
# result5a<-apply(1:nrow(df5),1,function(x){
#       optim(param_start,
#             fn=lm_sse5,
#             dat=df5[x,])
#   }
#       )

# # The for loop works but this does not save the values appropriately
for(x in 1:nrow(df5)){
result5b<-optim(param_start,
           fn=lm_sse5,
           dat=df5[x,],
           i=x)
}

# append results to original dataframe
# This works but is very manual
 df5$b0<-result$par["b0"]
 df5$b1<-result$par["b1"]
 df5$sse<-output$sse
 df5$sse_sqrt<-output$sse_sqrt


问:
Can I have an assertion that applies throughout an entire test instead of having an assertion at a particular instance/ after a particular action?
I am testing a website and I have this error message that shows up every once in a while when I'm executing the automation for the tests due to the websites load issues. The error message shows up only some of the times in random locations during the test. Sometimes it shows after I click on button x. The next time it'll happen when I click on button y. So it is hard to predict exactly when the error message will show. I do not want to have to write an assertion after every single action in my script (such as having the same assertion after every page.locator.click()) How can I do something like "If an error message with locator x shows up at any point during this entire test, fail the test and display this message"? The assertion I am currently using is await expect(locator,"Error Message").not.tobeVisible(), which is using a locator only visible in the error message. So the words "Error Message" is displayed and the test is failed, indicating that the failed test was a result of the error message. (The error message is occurring due to db load issues).

I can do an assertion such as

```<code>await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible()
await page.locator.click();
await page.locator.click();
await page.locator.click();
</code>```

but the assertion here only applies to checking for the error message after the first click. Sometimes it occurs after the 2nd click, 3rd click, etc. It's an error message from the website indicating load issues. So the test will fail eventually but I'd like to have the assertion of await expect(locator,"Error Message").not.tobeVisible() apply throughout the test and not have to do something like putting the assertion after every single action like this:

```<code>await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();

await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
</code>```

await expect(locator,"Error Message").not.tobeVisible() only checks for a particular instance when explicitly stated, and not constantly checking throughout the entire test.

It would be great to do be able to write an assertion of await expect(locator,"Error Message").not.tobeVisible() once so that it applies throughout the entire test, and not having to write it multiple times after each click/action due to the error messages unpredictable nature.

Body:
I am testing a website and I have this error message that shows up every once in a while when I'm executing the automation for the tests due to the websites load issues. The error message shows up only some of the times in random locations during the test. Sometimes it shows after I click on button x. The next time it'll happen when I click on button y. So it is hard to predict exactly when the error message will show. I do not want to have to write an assertion after every single action in my script (such as having the same assertion after every page.locator.click()) How can I do something like "If an error message with locator x shows up at any point during this entire test, fail the test and display this message"? The assertion I am currently using is await expect(locator,"Error Message").not.tobeVisible(), which is using a locator only visible in the error message. So the words "Error Message" is displayed and the test is failed, indicating that the failed test was a result of the error message. (The error message is occurring due to db load issues).

I can do an assertion such as

await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible()
await page.locator.click();
await page.locator.click();
await page.locator.click();

but the assertion here only applies to checking for the error message after the first click. Sometimes it occurs after the 2nd click, 3rd click, etc. It's an error message from the website indicating load issues. So the test will fail eventually but I'd like to have the assertion of await expect(locator,"Error Message").not.tobeVisible() apply throughout the test and not have to do something like putting the assertion after every single action like this:

await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();

await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();

await expect(locator,"Error Message").not.tobeVisible() only checks for a particular instance when explicitly stated, and not constantly checking throughout the entire test.

It would be great to do be able to write an assertion of await expect(locator,"Error Message").not.tobeVisible() once so that it applies throughout the entire test, and not having to write it multiple times after each click/action due to the error messages unpredictable nature.


问:
CountDownTimer been decreses by 2, which should be just 1 sec
I'm creating a quiz game, and there is a countdown timer. But, the countdown decreases by two seconds, which should be just one second. My code is working okay sometimes, but when I install it again, it decreases again in 2 seconds.</p>
```<code>countDownTimer = new CountDownTimer(timer, 1200) {
            @Override
            public void onTick(long l) {
                timeText.setText(String.valueOf(timeValue));

                timeValue = timeValue - 1;
                if (timeValue == -1){
                    FLAG = 3;
                    playAudio.setAudioforEvent(FLAG);
                    timerDialog.timerDialog();
                }
            }
            @Override
            public void onFinish() {

                // timerDialog.timerDialog();

            }
        }.start();
</code>```

Body:
I'm creating a quiz game, and there is a countdown timer. But, the countdown decreases by two seconds, which should be just one second. My code is working okay sometimes, but when I install it again, it decreases again in 2 seconds.

countDownTimer = new CountDownTimer(timer, 1200) {
            @Override
            public void onTick(long l) {
                timeText.setText(String.valueOf(timeValue));

                timeValue = timeValue - 1;
                if (timeValue == -1){
                    FLAG = 3;
                    playAudio.setAudioforEvent(FLAG);
                    timerDialog.timerDialog();
                }
            }
            @Override
            public void onFinish() {

                // timerDialog.timerDialog();

            }
        }.start();


问:
pg_dump: missing pg_catalog.pg_roles relation
I had created a DB testDb1 on a postgres server. After adding some data to this DB, I created a dump of this data and restored that to a new DB testDb2. After that data was added to second DB for quite some time.
Now, I want to dump data of testDb2 using following command:

```<code>pg_dump -U "postgres" --no-privileges -Fd -j 4 -f dump_20230102_db2 testDb2
</code>```

But this gives me below error:

```<code>pg_dump: error: query failed: ERROR:  relation "pg_catalog.pg_roles" does not exist
LINE 1: ....tableoid, n.oid, n.nspname, (SELECT rolname FROM pg_catalog...
                                                             ^
pg_dump: error: query was: SELECT n.tableoid, n.oid, n.nspname, (SELECT rolname FROM pg_catalog.pg_roles WHERE oid = nspowner) AS rolname, (SELECT pg_catalog.array_agg(acl ORDER BY row_n) FROM (SELECT acl, row_n FROM pg_catalog.unnest(coalesce(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) WITH ORDINALITY AS perm(acl,row_n) WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.unnest(coalesce(pip.initprivs,pg_catalog.acldefault('n',n.nspowner))) AS init(init_acl) WHERE acl = init_acl)) as foo) as nspacl, (SELECT pg_catalog.array_agg(acl ORDER BY row_n) FROM (SELECT acl, row_n FROM pg_catalog.unnest(coalesce(pip.initprivs,pg_catalog.acldefault('n',n.nspowner))) WITH ORDINALITY AS initp(acl,row_n) WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.unnest(coalesce(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) AS permp(orig_acl) WHERE acl = orig_acl)) as foo) as rnspacl, NULL as initnspacl, NULL as initrnspacl FROM pg_namespace n LEFT JOIN pg_init_privs pip ON (n.oid = pip.objoid AND pip.classoid = 'pg_namespace'::regclass AND pip.objsubid = 0)
</code>```

I checked the original DB testDb1, results are generated for above query but not for testDb2.

I also changed the owner of testDb2 to postgres but no luck there.

What can I do to restore or generate pg_catalog.pg_roles for testDb2 ?

Update:

Both DB are on same version 14.4

Output of \d *pg_roles* in testDb2 is:

```<code>testDb2-# \d *pg_roles*
Did not find any relation named "*pg_roles*".
</code>```

Body:
I had created a DB testDb1 on a postgres server. After adding some data to this DB, I created a dump of this data and restored that to a new DB testDb2. After that data was added to second DB for quite some time.
Now, I want to dump data of testDb2 using following command:

pg_dump -U "postgres" --no-privileges -Fd -j 4 -f dump_20230102_db2 testDb2

But this gives me below error:

pg_dump: error: query failed: ERROR:  relation "pg_catalog.pg_roles" does not exist
LINE 1: ....tableoid, n.oid, n.nspname, (SELECT rolname FROM pg_catalog...
                                                             ^
pg_dump: error: query was: SELECT n.tableoid, n.oid, n.nspname, (SELECT rolname FROM pg_catalog.pg_roles WHERE oid = nspowner) AS rolname, (SELECT pg_catalog.array_agg(acl ORDER BY row_n) FROM (SELECT acl, row_n FROM pg_catalog.unnest(coalesce(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) WITH ORDINALITY AS perm(acl,row_n) WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.unnest(coalesce(pip.initprivs,pg_catalog.acldefault('n',n.nspowner))) AS init(init_acl) WHERE acl = init_acl)) as foo) as nspacl, (SELECT pg_catalog.array_agg(acl ORDER BY row_n) FROM (SELECT acl, row_n FROM pg_catalog.unnest(coalesce(pip.initprivs,pg_catalog.acldefault('n',n.nspowner))) WITH ORDINALITY AS initp(acl,row_n) WHERE NOT EXISTS ( SELECT 1 FROM pg_catalog.unnest(coalesce(n.nspacl,pg_catalog.acldefault('n',n.nspowner))) AS permp(orig_acl) WHERE acl = orig_acl)) as foo) as rnspacl, NULL as initnspacl, NULL as initrnspacl FROM pg_namespace n LEFT JOIN pg_init_privs pip ON (n.oid = pip.objoid AND pip.classoid = 'pg_namespace'::regclass AND pip.objsubid = 0)

I checked the original DB testDb1, results are generated for above query but not for testDb2.

I also changed the owner of testDb2 to postgres but no luck there.

What can I do to restore or generate pg_catalog.pg_roles for testDb2 ?

Update:

Both DB are on same version 14.4

Output of \d *pg_roles* in testDb2 is:

testDb2-# \d *pg_roles*
Did not find any relation named "*pg_roles*".


问:
Implementing reordering of Sections
I made some code which is representing View and two Sections in it:

```<code>@State var firstCases: FirstTestCases = .first
@State var secondCases: SecondTestCases = .newFirst

var body: some View {
    Section(
        header: Text("First header"),
        footer: Text("First footer"),
        content: {
            Picker("", selection: $firstCases) {
                Text("First case").tag(FirstTestCases.first)
                Text("Second case").tag(FirstTestCases.second)
                Text("Third case").tag(FirstTestCases.third)
            }
            .onChange(of: firstCases) { _ in print("Do something") }
            .pickerStyle(.segmented)
            .padding(.vertical, 4)
        }
    )

    Section(
        header: Text("Second header"),
        footer: Text("Second footer"),
        content: {
            Picker("", selection: $secondCases) {
                Text("New first case").tag(SecondTestCases.newFirst)
                Text("New second case").tag(SecondTestCases.newSecond)
                Text("New third case").tag(SecondTestCases.newThird)
            }
            .onChange(of: secondCases) { _ in print("Do something") }
            .pickerStyle(.segmented)
            .padding(.vertical, 4)

            if secondCases == .newThird {
                Button("First button") {
                    print("Do something")
                }
            }

            Button("Second button", action: {
                print("Do something")
            })
        }
    )
}

enum FirstTestCases: Equatable {
    case first
    case second
    case third
}

enum SecondTestCases: Equatable {
    case newFirst
    case newSecond
    case newThird
}
</code>```

I want to implement option of sorting these sections (I made only 2 here, I will have 7+ sections and section can be different (one section can have few buttons and some sections dont have buttons)). To have option of sorting, I need to have some data in array. So I wanted to create array of Sections.

```<code>@State var data: [Section] = []
</code>```

I was getting error Generic parameter 'Content' could not be inferred., so I made it like this

```<code>@State var data: [Section<AnyView, AnyView, AnyView>] = []
</code>```

I created function, which will append data to array. (Appending already created sections, so later I can use ForEach and use modifier .move)

```<code>private func prepareData() {
    data
        .append(
            contentsOf: Section(
                header: Text("Second header"),
                footer: Text("Second footer"),
                content: {
                    Picker("", selection: $secondCases) {
                        Text("New first case").tag(SecondTestCases.newFirst)
                        Text("New second case").tag(SecondTestCases.newSecond)
                        Text("New third case").tag(SecondTestCases.newThird)
                    }
                    .onChange(of: secondCases) { _ in print("Do something") }
                    .pickerStyle(.segmented)
                    .padding(.vertical, 4)

                    if secondCases == .newThird {
                        Button("First button") {
                            print("Do something")
                        }
                    }

                    Button("Second button", action: {
                        print("Do something")
                    })
                }
            )
        )
}
</code>```

But problem I am getting is -

Instance method 'append(contentsOf:)' requires that 'Section<Text, TupleView<(some View, Button?, Button)>, Text>' conform to 'Sequence'

Why is this problem occuring? Is this good approach of implementing Section sorting, or is there some better?

Title: Implementing reordering of Sections

Body:
I made some code which is representing View and two Sections in it:

@State var firstCases: FirstTestCases = .first
@State var secondCases: SecondTestCases = .newFirst

var body: some View {
    Section(
        header: Text("First header"),
        footer: Text("First footer"),
        content: {
            Picker("", selection: $firstCases) {
                Text("First case").tag(FirstTestCases.first)
                Text("Second case").tag(FirstTestCases.second)
                Text("Third case").tag(FirstTestCases.third)
            }
            .onChange(of: firstCases) { _ in print("Do something") }
            .pickerStyle(.segmented)
            .padding(.vertical, 4)
        }
    )

    Section(
        header: Text("Second header"),
        footer: Text("Second footer"),
        content: {
            Picker("", selection: $secondCases) {
                Text("New first case").tag(SecondTestCases.newFirst)
                Text("New second case").tag(SecondTestCases.newSecond)
                Text("New third case").tag(SecondTestCases.newThird)
            }
            .onChange(of: secondCases) { _ in print("Do something") }
            .pickerStyle(.segmented)
            .padding(.vertical, 4)

            if secondCases == .newThird {
                Button("First button") {
                    print("Do something")
                }
            }

            Button("Second button", action: {
                print("Do something")
            })
        }
    )
}

enum FirstTestCases: Equatable {
    case first
    case second
    case third
}

enum SecondTestCases: Equatable {
    case newFirst
    case newSecond
    case newThird
}

I want to implement option of sorting these sections (I made only 2 here, I will have 7+ sections and section can be different (one section can have few buttons and some sections dont have buttons)). To have option of sorting, I need to have some data in array. So I wanted to create array of Sections.

@State var data: [Section] = []

I was getting error Generic parameter 'Content' could not be inferred., so I made it like this

@State var data: [Section<AnyView, AnyView, AnyView>] = []

I created function, which will append data to array. (Appending already created sections, so later I can use ForEach and use modifier .move)

private func prepareData() {
    data
        .append(
            contentsOf: Section(
                header: Text("Second header"),
                footer: Text("Second footer"),
                content: {
                    Picker("", selection: $secondCases) {
                        Text("New first case").tag(SecondTestCases.newFirst)
                        Text("New second case").tag(SecondTestCases.newSecond)
                        Text("New third case").tag(SecondTestCases.newThird)
                    }
                    .onChange(of: secondCases) { _ in print("Do something") }
                    .pickerStyle(.segmented)
                    .padding(.vertical, 4)

                    if secondCases == .newThird {
                        Button("First button") {
                            print("Do something")
                        }
                    }

                    Button("Second button", action: {
                        print("Do something")
                    })
                }
            )
        )
}

But problem I am getting is -

Instance method 'append(contentsOf:)' requires that 'Section<Text, TupleView<(some View, Button?, Button)>, Text>' conform to 'Sequence'

Why is this problem occuring? Is this good approach of implementing Section sorting, or is there some better?


问:
write a python code to print multiplication table till user's input
Create a multiplication table application where user will enter a sentinel value n and the application will display the mathematical multiplication tables till given sentinel value n.
For example, if user enters n = 4 then application will display the multiplication tables of 2, 3, and 4.
Constraint:
•   Make use of oop concepts class methods and attributes</p>


问:
How do I remove the opacity from an input field in Bootstrap 5.3?
I want to make an input field (for a search bar) not translucent. I am using bootstrap 5.3. How can I achieve this result?

```<code> <div class="input-group d-sm-none d-md-block">
  <div class="form-outline">
    <input type="search" class="form-control" id="searchbar"  placeholder="Search..."/>
  </div>
</div>
</code>```

I have tried to, first off, make the opacity 1 and declared that as important. Like so:

```<code>#searchbar {
 opacity:1 !important;
}
</code>```
```<code> <div class="input-group d-sm-none d-md-block">
  <div class="form-outline">
    <input type="search" class="form-control" id="searchbar"  placeholder="Search..."/>
  </div>
</div>
</code>```

Obviously, that has not worked.

I then tried to set the background color.

```<code>#searchbar {
  background-color:#ffff;
}
</code>```

That worked, but not in the way I expected. I had hoped giving the input a background color would remove the opacity, which it didn’t.

Is there a way to get rid of the transparency on the input?

Body:
I want to make an input field (for a search bar) not translucent. I am using bootstrap 5.3. How can I achieve this result?

    <input type="search" class="form-control" id="searchbar"  placeholder="Search..."/>

I have tried to, first off, make the opacity 1 and declared that as important. Like so:

#searchbar {
 opacity:1 !important;
}

    <input type="search" class="form-control" id="searchbar"  placeholder="Search..."/>

Obviously, that has not worked.

I then tried to set the background color.

#searchbar {
  background-color:#ffff;
}

That worked, but not in the way I expected. I had hoped giving the input a background color would remove the opacity, which it didn’t.

Is there a way to get rid of the transparency on the input?


问:
How to get BlueStacks 5's front camera to work in applications?
BlueStacks 5's back camera is now connected to my webcam, but the problem is that I want to use an application that has to verify my identity by taking a picture from the front camera. How do I get the front camera to work?

I've searched many places, adb or fake camera doesn't work at all. But sometimes I see they use Android studio, it can be set to choose that What will the front camera use and what will the rear camera use?

enter image description here

I want apps that require authentication to move to my back camera or my webcam.


问:
How can I Upload File to Google Drive in Flutter
I was trying to integrate Google drive in Flutter,
for getting user files,
But I can't find a complete solution for this.
Can someone provide me a Solution?

I've generated Client for Google Drive in https://console.cloud.google.com/,
but after that I don't know what to do.


问:
Updating Lettuce Connection Factory Dynamically
We are using Spring Data Redis and AWS Elastic cache in a clustered mode.

We are using the AWS Elastic Cache cluster URL to connect to Redis.

We are configuring the LettuceConnectionFactory like this . We are using TopologyRefreshOptions to take care of the failover and slot movement scenarios.

```<code>ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                //.timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(60L)))
                .topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
                        .enablePeriodicRefresh(Duration.ofSeconds(10L))
                        .enableAllAdaptiveRefreshTriggers()
                        .dynamicRefreshSources(false)
                        .build())
                .autoReconnect(true)
                .cancelCommandsOnReconnectFailure(true)
                .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
                .build();
        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .clientOptions(clusterClientOptions)
                .build();
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        redisClusterConfiguration.addClusterNode(new RedisNode(redisHost, redisPort));
        redisClusterConfiguration.setPassword(redisPassword);
        return new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);
</code>```

With this configuration also we are facing "moved" issues which typically comes from the hash slot movement across the nodes.
Sometimes after the restart of the app , the app starts working fine.

i was thinking if we can proactively update the LettuceConnectionFactory by updating the CLusterNodes on the LettuceClientConfiguration on receiving the Moved exception ?

Best Regards,

Saurav

Body:
We are using Spring Data Redis and AWS Elastic cache in a clustered mode.

We are using the AWS Elastic Cache cluster URL to connect to Redis.

We are configuring the LettuceConnectionFactory like this . We are using TopologyRefreshOptions to take care of the failover and slot movement scenarios.

ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                //.timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(60L)))
                .topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
                        .enablePeriodicRefresh(Duration.ofSeconds(10L))
                        .enableAllAdaptiveRefreshTriggers()
                        .dynamicRefreshSources(false)
                        .build())
                .autoReconnect(true)
                .cancelCommandsOnReconnectFailure(true)
                .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
                .build();
        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .clientOptions(clusterClientOptions)
                .build();
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        redisClusterConfiguration.addClusterNode(new RedisNode(redisHost, redisPort));
        redisClusterConfiguration.setPassword(redisPassword);
        return new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);

With this configuration also we are facing "moved" issues which typically comes from the hash slot movement across the nodes.
Sometimes after the restart of the app , the app starts working fine.

i was thinking if we can proactively update the LettuceConnectionFactory by updating the CLusterNodes on the LettuceClientConfiguration on receiving the Moved exception ?

Best Regards,

Saurav


问:
How to raise our own custom SQLExceptions?
```<code>DECLARE
   c_id customers.id%type := 8;
   c_name  customers.name%type;
   c_addr customers.address%type;
BEGIN
   SELECT  name, address INTO  c_name, c_addr
   FROM customers
   WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);
 DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
   WHEN no_data_found THEN
      dbms_output.put_line('No such customer!');
   WHEN others THEN
      dbms_output.put_line('Error!');
END;
</code>```

After the execution of above code at SQL Prompt, it produces the following result:

```<code>No such customer!
PL/SQL procedure successfully completed.
</code>```

Here the exception is captured by the exception block

I tried handling inbuilt exception using exception block, I am expecting a way to raise my own custom SQLEXCEPTION

Body:
DECLARE
   c_id customers.id%type := 8;
   c_name  customers.name%type;
   c_addr customers.address%type;
BEGIN
   SELECT  name, address INTO  c_name, c_addr
   FROM customers
   WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);
 DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
   WHEN no_data_found THEN
      dbms_output.put_line('No such customer!');
   WHEN others THEN
      dbms_output.put_line('Error!');
END;

After the execution of above code at SQL Prompt, it produces the following result:

No such customer!
PL/SQL procedure successfully completed.

Here the exception is captured by the exception block

I tried handling inbuilt exception using exception block, I am expecting a way to raise my own custom SQLEXCEPTION


问:
Use an id for insert but it must be found from the cross values between the columns being inserted and those of another table
I have a project that I am doing for the courses where I have to use the open DATA SNCF (train in France). I have a problem that I've been stuck on for a while, I put my CSV file in a table (sncf_csv_tarifsterparod with different columns), everything works fine, I created my project tables (sncf.tarif, sncf. ligne). Where I block it is in the INSERT I explain:

```<code>INSERT INTO sncf.ligne(gareDepart, gareArrivee, typeTrain) SELECT DISTINCT Origine, Destination, 'TER' FROM sncf_csv.tarifsterparod;
</code>```

sncf.ligne

Here I come to fill my table sncf.ligne with the column sncf_csv.Origine and sncf_csv.Destination, in addition to that there is an id which is auto incremented at each table (idLigne), the "distinct" is necessary because I don't want two lines with the same "Origine"/"Destination".

sncf_csv.tarifsterparod

Then, I want to fill my "tarif" table, so I want to insert (two constants), "LabelTarif", "TypeTarif", "Prix" from my table sncf_csv.tarifsterparod, where it gets stuck is that I have to add an "idLigne" associated with this "tarif" (a "tarif" is associated with a line, it's the foreign key). So you have to add the idLigne which corresponds to the Origin and the Destination of the line that I am adding. I tried many things but nothing worked, anyone have any idea ?

I tried to make a join but I have an "infinite fetching" (first I want to look with the select if it works before making an insert)

```<code>SELECT t.LibelleTarif, t.TypeTarif, t.Prix, l.idLigne
FROM sncf_csv.tarifsterparod AS t
LEFT JOIN sncf.ligne AS l
ON (t.Origine = l.gareDepart
AND t.Destination = l.gareArrivee);
</code>```

mysqlworkbench

Body:
I have a project that I am doing for the courses where I have to use the open DATA SNCF (train in France). I have a problem that I've been stuck on for a while, I put my CSV file in a table (sncf_csv_tarifsterparod with different columns), everything works fine, I created my project tables (sncf.tarif, sncf. ligne). Where I block it is in the INSERT I explain:

INSERT INTO sncf.ligne(gareDepart, gareArrivee, typeTrain) SELECT DISTINCT Origine, Destination, 'TER' FROM sncf_csv.tarifsterparod;

sncf.ligne

Here I come to fill my table sncf.ligne with the column sncf_csv.Origine and sncf_csv.Destination, in addition to that there is an id which is auto incremented at each table (idLigne), the "distinct" is necessary because I don't want two lines with the same "Origine"/"Destination".

sncf_csv.tarifsterparod

Then, I want to fill my "tarif" table, so I want to insert (two constants), "LabelTarif", "TypeTarif", "Prix" from my table sncf_csv.tarifsterparod, where it gets stuck is that I have to add an "idLigne" associated with this "tarif" (a "tarif" is associated with a line, it's the foreign key). So you have to add the idLigne which corresponds to the Origin and the Destination of the line that I am adding. I tried many things but nothing worked, anyone have any idea ?

I tried to make a join but I have an "infinite fetching" (first I want to look with the select if it works before making an insert)

SELECT t.LibelleTarif, t.TypeTarif, t.Prix, l.idLigne
FROM sncf_csv.tarifsterparod AS t
LEFT JOIN sncf.ligne AS l
ON (t.Origine = l.gareDepart
AND t.Destination = l.gareArrivee);

mysqlworkbench


问:
'docker' unable to calculate disk image size
it my first time to work on docker, I just installed it and got an error unable to calculate image disk size. and docker desktop get stopped.

my computer has enough space, with few applications on it. I tried to re install docker several time and restarted my computer and still got the same error as i was trying.


问:
Kotlin: SensorManager in ForegroundService killed when Application is off
I put sensor manager in foreground service not to be killed when app is off.

```<code>class MyService : Service(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private lateinit var step_sensor: Sensor

    private val db = Firebase.firestore
    private val userDB = Firebase.firestore.collection("users")
    private val diaryDB = Firebase.firestore.collection("diary")
    private val userId = Firebase.auth.currentUser?.uid

    companion object {
        var todayTotalStepCount: MutableLiveData<Int>? = MutableLiveData()
    }

    override fun onCreate() {
        super.onCreate()

        // 오늘 걸음수 초기화
        userDB.document("$userId").get().addOnSuccessListener { document ->
            var todayStepCountFromDB = document.getLong("todayStepCount") ?: 0
            todayTotalStepCount?.value = todayStepCountFromDB.toInt()
        }

        sensorManager =
            applicationContext?.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        step_sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)

        sensorManager.registerListener(this, step_sensor, SensorManager.SENSOR_DELAY_UI)

    }

    override fun onBind(p0: Intent?): IBinder? {
//        TODO("Not yet implemented")
        throw UnsupportedOperationException("Not yet implemented")
    }

    override fun onSensorChanged(stepEvent: SensorEvent?) {
        Log.d("결과", "$stepEvent")

}
</code>```

And I link this service to fragment.

```<code>    var startService = Intent(activity, MyService::class.java)
    activity?.startService(startService)
</code>```

It works well in foreground and background either. However when I kill app, it stops. I'm a newbie in Kotlin.

Please help me with detail code.

Thank you!

Body:
I put sensor manager in foreground service not to be killed when app is off.

class MyService : Service(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private lateinit var step_sensor: Sensor

    private val db = Firebase.firestore
    private val userDB = Firebase.firestore.collection("users")
    private val diaryDB = Firebase.firestore.collection("diary")
    private val userId = Firebase.auth.currentUser?.uid

    companion object {
        var todayTotalStepCount: MutableLiveData<Int>? = MutableLiveData()
    }

    override fun onCreate() {
        super.onCreate()

        // 오늘 걸음수 초기화
        userDB.document("$userId").get().addOnSuccessListener { document ->
            var todayStepCountFromDB = document.getLong("todayStepCount") ?: 0
            todayTotalStepCount?.value = todayStepCountFromDB.toInt()
        }

        sensorManager =
            applicationContext?.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        step_sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)

        sensorManager.registerListener(this, step_sensor, SensorManager.SENSOR_DELAY_UI)

    }

    override fun onBind(p0: Intent?): IBinder? {
//        TODO("Not yet implemented")
        throw UnsupportedOperationException("Not yet implemented")
    }

    override fun onSensorChanged(stepEvent: SensorEvent?) {
        Log.d("결과", "$stepEvent")

}

And I link this service to fragment.

    var startService = Intent(activity, MyService::class.java)
    activity?.startService(startService)

It works well in foreground and background either. However when I kill app, it stops. I'm a newbie in Kotlin.

Please help me with detail code.

Thank you!


问:
How can i define a job in gitlab-ci.yaml which gets triggerd when deleting an environment?
I have a gitlab-ci.yaml file which creates an environment. Within the environment i defined an on_stop-action which will be triggered as soon as i manually stop the environment in the GitLab User Interface.

My config looks similar to this:

```<code>stop_review_app:
  when: manual
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    on_stop: stop

stop:
  extends: .delete
  stage: stop
  script:
    - kubectl scale -n $NAMESPACE deployment app-name --replicas=0

</code>```

Basically everything works fine. Now i want to run a different script if i actually delete my environment in the Gitlab UI. So i was looking for an option named on_delete which works the same way as on_stop does. But it doesn't exist. Shouldn't something exist like that? How can i achive my requirements using gitlab-ci.yaml?

I'm running GitLab Community Edition 15.2.2

Body:
I have a gitlab-ci.yaml file which creates an environment. Within the environment i defined an on_stop-action which will be triggered as soon as i manually stop the environment in the GitLab User Interface.

My config looks similar to this:

stop_review_app:
  when: manual
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    on_stop: stop

stop:
  extends: .delete
  stage: stop
  script:
    - kubectl scale -n $NAMESPACE deployment app-name --replicas=0

Basically everything works fine. Now i want to run a different script if i actually delete my environment in the Gitlab UI. So i was looking for an option named on_delete which works the same way as on_stop does. But it doesn't exist. Shouldn't something exist like that? How can i achive my requirements using gitlab-ci.yaml?

I'm running GitLab Community Edition 15.2.2


问:
output depth must be evenly divisible by number of groups: 64 vs 3
I'm trying to make a CNN model in Python with Tensorflow Keras to train these images.
bitwise images
This is how the images have been prepared for which worked, the code managed to find all the images:

```<code>training_datagen = ImageDataGenerator(
  rescale = 1./255,
  horizontal_flip=True,
  vertical_flip=True,
  fill_mode='nearest')

train_generator = training_datagen.flow_from_dataframe(
        dataframe=df_train_dominance,
        x_col="Filename",
        y_col="Dominance",
        target_size=(512, 512),
        class_mode='other')

validation_datagen = ImageDataGenerator(rescale = 1./255)

val_generator = validation_datagen.flow_from_dataframe(
        dataframe=df_test_dominance,
        x_col="Filename",
        y_col="Dominance",
        target_size=(512, 512),
        class_mode='other')
</code>```

Then I try to make the following model:

```<code>model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu',
        input_shape=(512, 512, 1)),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(20, activation='relu'),
    tf.keras.layers.Dense(11, activation='softmax')
])

model.summary()
epoch_steps = 250
validation_steps = len(df_test_dominance)
model.compile(loss = 'mean_squared_error', optimizer='adam', metrics=['accuracy'])
monitor = EarlyStopping(monitor='val_loss', min_delta=0,
        patience=5, verbose=1, mode='auto',
        restore_best_weights=True)

start_time = time.time()
history = model.fit(train_generator,
  verbose = 1,
  validation_data=val_generator, callbacks=[monitor], epochs=25)
</code>```

However, when I try to run this, I get the error "output depth must be evenly divisible by number of groups: 64 vs 3" So it won't allow me to make a convolutional layer with more than 3 filters. Why is this and what do I need to change to use more filters? The code does run fine with 3 filters.

I tried adding padding but that does not help. I also tried to invert the color of the images, but it also didn't solve the problem

Body:
I'm trying to make a CNN model in Python with Tensorflow Keras to train these images.
bitwise images
This is how the images have been prepared for which worked, the code managed to find all the images:

training_datagen = ImageDataGenerator(
  rescale = 1./255,
  horizontal_flip=True,
  vertical_flip=True,
  fill_mode='nearest')

train_generator = training_datagen.flow_from_dataframe(
        dataframe=df_train_dominance,
        x_col="Filename",
        y_col="Dominance",
        target_size=(512, 512),
        class_mode='other')

validation_datagen = ImageDataGenerator(rescale = 1./255)

val_generator = validation_datagen.flow_from_dataframe(
        dataframe=df_test_dominance,
        x_col="Filename",
        y_col="Dominance",
        target_size=(512, 512),
        class_mode='other')

Then I try to make the following model:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu',
        input_shape=(512, 512, 1)),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(20, activation='relu'),
    tf.keras.layers.Dense(11, activation='softmax')
])

model.summary()
epoch_steps = 250
validation_steps = len(df_test_dominance)
model.compile(loss = 'mean_squared_error', optimizer='adam', metrics=['accuracy'])
monitor = EarlyStopping(monitor='val_loss', min_delta=0,
        patience=5, verbose=1, mode='auto',
        restore_best_weights=True)

start_time = time.time()
history = model.fit(train_generator,
  verbose = 1,
  validation_data=val_generator, callbacks=[monitor], epochs=25)

However, when I try to run this, I get the error "output depth must be evenly divisible by number of groups: 64 vs 3" So it won't allow me to make a convolutional layer with more than 3 filters. Why is this and what do I need to change to use more filters? The code does run fine with 3 filters.

I tried adding padding but that does not help. I also tried to invert the color of the images, but it also didn't solve the problem


问:
Multiprocessing for multiple cameras in Python
I have multiple cameras that I'd like to read images from and do some image processing.

I tried using multithreading and created a class that manages these threads and stores data.

I want to pass these images into an image processing function. Should I use multithreading or multiprocessing or a mix?

For this example code:

```<code>
if __name__ == '__main__':
    img_proc = ImgProc()
    stream0 = Stream(0,args)
    stream1 = Stream(1,args)
    streams = [stream0,stream1]
    stream_manager = StreamManager(streams,img_proc)
    stream_manager.start_streams()

    while True:
        stream_manager.process_images()
</code>```

The img_proc obj is a class containing functions of the image processing

The start_streams() spawns multiple Thread objects that capture image frames from the streams list and stores the data in an array of queues in StreamManager.

Q1: Is the ImgProc class functions running on a process or a thread if I were to loop through the array of queues and process each of them?

Q2: should I use multiprocessing to stream each camera instead and have a multiprocessing.Array of collections.deque to share data with a separate img processing Process?

Q3: if i initialize another object in Stream class constructor, say x = DummyList. then I append a 1 to x. will stream0 and stream1 both share DummyList since threads share the same memory space? Or would they just be separate objects with only 1 of them having x = [1] and the other having x = []

Body:
I have multiple cameras that I'd like to read images from and do some image processing.

I tried using multithreading and created a class that manages these threads and stores data.

I want to pass these images into an image processing function. Should I use multithreading or multiprocessing or a mix?

For this example code:

if __name__ == '__main__':
    img_proc = ImgProc()
    stream0 = Stream(0,args)
    stream1 = Stream(1,args)
    streams = [stream0,stream1]
    stream_manager = StreamManager(streams,img_proc)
    stream_manager.start_streams()

    while True:
        stream_manager.process_images()

The img_proc obj is a class containing functions of the image processing

The start_streams() spawns multiple Thread objects that capture image frames from the streams list and stores the data in an array of queues in StreamManager.

Q1: Is the ImgProc class functions running on a process or a thread if I were to loop through the array of queues and process each of them?

Q2: should I use multiprocessing to stream each camera instead and have a multiprocessing.Array of collections.deque to share data with a separate img processing Process?

Q3: if i initialize another object in Stream class constructor, say x = DummyList. then I append a 1 to x. will stream0 and stream1 both share DummyList since threads share the same memory space? Or would they just be separate objects with only 1 of them having x = [1] and the other having x = []


问:
Go run greeter_server/main.go
I don't know how to access the server which is listent at [::]:50051

BELOW IS THE DISCRIPTION

```<code>$ go run greeter_client/main.go
Greeting: Hello world
</code>```

I'm a new bie to the world of programming!

I try the below code on the same laptop listening from aforementioned server!

```<code>$ go run greeter_client/main.go
Greeting: Hello world
</code>```

Title: Go run greeter_server/main.go

Body:
I don't know how to access the server which is listent at [::]:50051

BELOW IS THE DISCRIPTION

$ go run greeter_client/main.go
Greeting: Hello world

I'm a new bie to the world of programming!

I try the below code on the same laptop listening from aforementioned server!

$ go run greeter_client/main.go
Greeting: Hello world


问:
Fatal error: Uncaught Google_Auth_Exception: Invalid token format in ...google\apiclient\src\Google\Auth\OAuth2.php:189 Stack trace: #0
I am tying to integrate google sign in service (OAuth 2.0) within a web application without success.
I bump into this issue after using a "token" in a json file (token.json for simplicity).

Fatal error: Uncaught Google_Auth_Exception: Invalid token format in [DIR]\phpgmailapi\vendor\google\apiclient\src\Google\Auth\OAuth2.php:189 Stack trace: #0

the script:

```<code>    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_encode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }
</code>```

token.json looks like this:

```<code>{"access_token" : "XXXXXXXXXX"}
</code>```

Assuming the error comes from invalid format I tried also save it as a string by editing the json file or calling the string from the array.

$client->setAccessToken($accessToken['access_token']);
yet, no success.

The setAccessToken isn't seem to be messed with (located in OAuth2.php)

```<code>public function setAccessToken($token)
 {
    $token = json_decode($token, true);
    if ($token == null) {
        throw new Google_Auth_Exception('Could not json decode the token');
    }
    if (! isset($token['access_token'])) {
        throw new Google_Auth_Exception("Invalid token format");
    }
    $this->token = $token;
 }
</code>```

I wonder what leads to this bug in the system.

Body:
I am tying to integrate google sign in service (OAuth 2.0) within a web application without success.
I bump into this issue after using a "token" in a json file (token.json for simplicity).

Fatal error: Uncaught Google_Auth_Exception: Invalid token format in [DIR]\phpgmailapi\vendor\google\apiclient\src\Google\Auth\OAuth2.php:189 Stack trace: #0

the script:

    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_encode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

token.json looks like this:

{"access_token" : "XXXXXXXXXX"}

Assuming the error comes from invalid format I tried also save it as a string by editing the json file or calling the string from the array.

$client->setAccessToken($accessToken['access_token']);
yet, no success.

The setAccessToken isn't seem to be messed with (located in OAuth2.php)

public function setAccessToken($token)
 {
    $token = json_decode($token, true);
    if ($token == null) {
        throw new Google_Auth_Exception('Could not json decode the token');
    }
    if (! isset($token['access_token'])) {
        throw new Google_Auth_Exception("Invalid token format");
    }
    $this->token = $token;
 }

I wonder what leads to this bug in the system.


问:
Why my rsync scripts do no work on the new mac?
Good evening. I have a new mac and a backup script that I found and adapted from the web does not work anymore (it works on my old mac).

it is a simple script for backing up the whole home dir on an external drive

```<code>    #!/bin/bash

    # A script to perform incremental backups using rsync

    set -o errexit
    set -o nounset
    set -o pipefail

    readonly SOURCE_DIR="/Users/username"
    readonly BACKUP_DIR="link to folder in external drive"
    readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
    readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
    readonly LATEST_LINK="${BACKUP_DIR}/latest"

    mkdir -p "${BACKUP_DIR}"

    rsync -av --delete \
      "${SOURCE_DIR}/" \
      --link-dest "${LATEST_LINK}" \
      --exclude=".cache" \
      "${BACKUP_PATH}"

    rm -rf "${LATEST_LINK}"
    ln -s "${BACKUP_PATH}" "${LATEST_LINK}"

</code>```

The first part of the error output is

```<code>: command not found
: command not found
: command not found
: invalid option namet: errexit
: invalid option namet: nounset
: invalid option namet: pipefail
: command not found
: command not found
: command not found
sending incremental file list
</code>```

echo $path output is

/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin

but sudo nano /etc/paths feedback is

```<code>/usr/local/bin
/System/Cryptexes/App/usr/bin
/usr/bin
/bin
/usr/sbin
/sbin
</code>```

Body:
Good evening. I have a new mac and a backup script that I found and adapted from the web does not work anymore (it works on my old mac).

it is a simple script for backing up the whole home dir on an external drive

    #!/bin/bash

    # A script to perform incremental backups using rsync

    set -o errexit
    set -o nounset
    set -o pipefail

    readonly SOURCE_DIR="/Users/username"
    readonly BACKUP_DIR="link to folder in external drive"
    readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
    readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
    readonly LATEST_LINK="${BACKUP_DIR}/latest"

    mkdir -p "${BACKUP_DIR}"

    rsync -av --delete \
      "${SOURCE_DIR}/" \
      --link-dest "${LATEST_LINK}" \
      --exclude=".cache" \
      "${BACKUP_PATH}"

    rm -rf "${LATEST_LINK}"
    ln -s "${BACKUP_PATH}" "${LATEST_LINK}"

The first part of the error output is

: command not found
: command not found
: command not found
: invalid option namet: errexit
: invalid option namet: nounset
: invalid option namet: pipefail
: command not found
: command not found
: command not found
sending incremental file list

echo $path output is

/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin

but sudo nano /etc/paths feedback is

/usr/local/bin
/System/Cryptexes/App/usr/bin
/usr/bin
/bin
/usr/sbin
/sbin


问:
GraphQL pass array of object as argument
Here i am trying to send array of object as parameter. i have tried both type and input but both case giving some error.

```<code>    const VERIFY_ASSESSMENT = gql`
        type questionWiseMarks {
            questionId : ID!
            mark : Int
        }
        mutation verifyAssessment($userRef : ID!, $assessment_id :String!, $remarks : String!, $questionWiseMarks : [questionWiseMarks]){
            verifyAssessment(
                userRef : $userRef,
                assessment_id : $assessment_id,
                remarks : $remarks
                questionWiseMarks : $questionWiseMarks
                ){
                success
                msg
            }
        }
    `

    const [verifyAssessment, { data: __data, loading: __loading, error: __error }] = useMutation(VERIFY_ASSESSMENT)
    const onSubmit = () => {
        let questionWiseMarks = [];
        assessmentDetails.questionRef.map((item,i) => {
            questionWiseMarks.push({ questionId : item.id, mark : item.given_marks== '' ? 0 : JSON.parse(item.given_marks)})
        })
        verifyAssessment({
            variables: {
                userRef: selectedUser,
                assessment_id: assessmentDetails.id,
                remarks: remarks,
                questionWiseMarks
            }
        })
    }
</code>```

Please take a look i have attached the error message.
error message screenshot

Body:
Here i am trying to send array of object as parameter. i have tried both type and input but both case giving some error.

    const VERIFY_ASSESSMENT = gql`
        type questionWiseMarks {
            questionId : ID!
            mark : Int
        }
        mutation verifyAssessment($userRef : ID!, $assessment_id :String!, $remarks : String!, $questionWiseMarks : [questionWiseMarks]){
            verifyAssessment(
                userRef : $userRef,
                assessment_id : $assessment_id,
                remarks : $remarks
                questionWiseMarks : $questionWiseMarks
                ){
                success
                msg
            }
        }
    `

    const [verifyAssessment, { data: __data, loading: __loading, error: __error }] = useMutation(VERIFY_ASSESSMENT)
    const onSubmit = () => {
        let questionWiseMarks = [];
        assessmentDetails.questionRef.map((item,i) => {
            questionWiseMarks.push({ questionId : item.id, mark : item.given_marks== '' ? 0 : JSON.parse(item.given_marks)})
        })
        verifyAssessment({
            variables: {
                userRef: selectedUser,
                assessment_id: assessmentDetails.id,
                remarks: remarks,
                questionWiseMarks
            }
        })
    }

Please take a look i have attached the error message.
error message screenshot


问:
I cannot import and use SwingFxUtils
I am using Intelj with Maven, my version is 19.

I tried almost everything, but i cannot figure it out.

i tried to add the dependecies to my pom.xml;

i tried to add library to my project;

i tried to requires javafx.swing in the module-info;

i tried to install the file jar.

This is what happen when i try to add it on my file maven:

Title: I cannot import and use SwingFxUtils


问:
How do I resize <Canvas> from React-Three-Fibre
I am using React, ThreeJS, React-Three-Fibre

Here is the boilerplate from there website:

```<code>function App() {

  const Box = (props) => {
      // This reference gives us direct access to the THREE.Mesh object
      const ref = useRef()

      // Hold state for hovered and clicked events
      const [hovered, setHovered] = useState(false)
      const [clicked, setClicked] = useState(false)

      // Subscribe this component to the render-loop, rotate the mesh every frame
      useFrame((state, delta) => (ref.current.rotation.x += delta))

      // Return the view, these are regular Threejs elements expressed in JSX
      return (
        <mesh
          {...props}
          ref={ref}
          scale={clicked ? 1.5 : 1}
          onClick={(event) => setClicked(!clicked)}
          onPointerOver={(event) => setHovered(true)}
          onPointerOut={(event) => setHovered(false)}>
          <boxGeometry args={[1, 1, 1]} />
          <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
        </mesh>
      )
  }
  return (
    <Canvas>
        <ambientLight intensity={0.5} />
        <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} />
        <pointLight position={[-10, -10, -10]} />
        <Box position={[-1.2, 0, 0]} />
        <Box position={[1.2, 0, 0]} />
        <OrbitControls />
    </Canvas>
  )
}

export default App
</code>```

I have tried using MUI and CSS to try and resize either the canvas element or some parent div but I didn't figure it out. Does anyone with experience in ThreeJS and the Fibre library know how I can go about resizing their  element?

From the docs an alternate approach is to do the following but I'm still trying to make sense of it:

```<code>import * as THREE from 'three'
import { extend, createRoot, events } from '@react-three/fiber'

// Register the THREE namespace as native JSX elements.
// See below for notes on tree-shaking
extend(THREE)

// Create a react root
const root = createRoot(document.querySelector('canvas'))

// Configure the root, inject events optionally, set camera, etc
root.configure({ events, camera: { position: [0, 0, 50] } })

// createRoot by design is not responsive, you have to take care of resize yourself
window.addEventListener('resize', () => {
  root.configure({ size: { width: window.innerWidth, height: window.innerHeight } })
})

// Trigger resize
window.dispatchEvent(new Event('resize'))

// Render entry point
root.render(<App />)

// Unmount and dispose of memory
// root.unmount()

</code>```

EDIT:

Forgot to add that I want to make the canvas be the size of the browser window, but atm it is 780px by 150px and these numbers are not mentioned anywhere explicitly

EDIT2:

As a further edit I noticed that the  tag puts a  with a  inside of it with the 780x150 dimensions. I did the following in css to overwrite the old rules, but in general I am curious how I can use the  tag with my own custom values from the getgo

```<code>canvas{
  width: 100vw !important;
  height: 100vh !important;
}
</code>```

Body:
I am using React, ThreeJS, React-Three-Fibre

Here is the boilerplate from there website:

function App() {

  const Box = (props) => {
      // This reference gives us direct access to the THREE.Mesh object
      const ref = useRef()

      // Hold state for hovered and clicked events
      const [hovered, setHovered] = useState(false)
      const [clicked, setClicked] = useState(false)

      // Subscribe this component to the render-loop, rotate the mesh every frame
      useFrame((state, delta) => (ref.current.rotation.x += delta))

      // Return the view, these are regular Threejs elements expressed in JSX
      return (
        <mesh
          {...props}
          ref={ref}
          scale={clicked ? 1.5 : 1}
          onClick={(event) => setClicked(!clicked)}
          onPointerOver={(event) => setHovered(true)}
          onPointerOut={(event) => setHovered(false)}>
          <boxGeometry args={[1, 1, 1]} />
          <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
        </mesh>
      )
  }
  return (
    <Canvas>
        <ambientLight intensity={0.5} />
        <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} />
        <pointLight position={[-10, -10, -10]} />
        <Box position={[-1.2, 0, 0]} />
        <Box position={[1.2, 0, 0]} />
        <OrbitControls />
    </Canvas>
  )
}

export default App

I have tried using MUI and CSS to try and resize either the canvas element or some parent div but I didn't figure it out. Does anyone with experience in ThreeJS and the Fibre library know how I can go about resizing their  element?

From the docs an alternate approach is to do the following but I'm still trying to make sense of it:

import * as THREE from 'three'
import { extend, createRoot, events } from '@react-three/fiber'

// Register the THREE namespace as native JSX elements.
// See below for notes on tree-shaking
extend(THREE)

// Create a react root
const root = createRoot(document.querySelector('canvas'))

// Configure the root, inject events optionally, set camera, etc
root.configure({ events, camera: { position: [0, 0, 50] } })

// createRoot by design is not responsive, you have to take care of resize yourself
window.addEventListener('resize', () => {
  root.configure({ size: { width: window.innerWidth, height: window.innerHeight } })
})

// Trigger resize
window.dispatchEvent(new Event('resize'))

// Render entry point
root.render(<App />)

// Unmount and dispose of memory
// root.unmount()

EDIT:

Forgot to add that I want to make the canvas be the size of the browser window, but atm it is 780px by 150px and these numbers are not mentioned anywhere explicitly

EDIT2:

As a further edit I noticed that the  tag puts a  with a  inside of it with the 780x150 dimensions. I did the following in css to overwrite the old rules, but in general I am curious how I can use the  tag with my own custom values from the getgo

canvas{
  width: 100vw !important;
  height: 100vh !important;
}


问:
Load flat file data to SQL - when calling from a job, no or few records commit without error, when running manually from solution, it works
I'm perplexed and would appreciate any help. My SQL setup works by jobs running throughout the day that will upload flat file information if the flat file exists. This is setup using variables and loops and 90% of the jobs run without issue daily.

About six weeks ago, we changed where our flat files were being saved and this caused issues with the formatting that required me to rewrite many of the flat file managers to ensure all records worked correctly. This has been resolved and works perfectly when I'm running all of these jobs manually through Visual Studio.

Now, when a handful of these packages are called from the SQL job, they either do not write any records, or only write a handful of them, and no error is thrown. When I go back into Visual Studio and run them manually, they work without error.

Details on two of the flat files:

SHIPPED.TXT - size: 2.13 MB; 2,342 rows; rows committed when loading from SQL job: 85

WIP.TXT - size: 11.3 MB; 29,479 rows; rows committed when loading from SQL job: 11,057

I have tried turning off fast load, reorganizing the order they are called in the SQL jobs, thinning out the SQL jobs when they are called, all to no avail.

I'm stuck. Has anyone ever experienced anything like this before?


问:
React Server Components and Webpack unexpected token when server launch
I'm making tests on React Server Components with a co-worker's project, and I'm blocking on an error which is providing from react-bootstrap.

I can build the project, webpack made it good, with no errors, but when I'm starting the server, I have this error in the terminal here is the full return :

assets by path ../build/components/*.ts 2.21 KiB
  asset ../build/components/EncryptButton.d.ts 364 bytes [emitted]
  asset ../build/components/DecryptContent.d.ts 355 bytes [emitted]
  asset ../build/components/Footer.d.ts 339 bytes [emitted]
  + 4 assets
assets by path ../build/pages/*.ts 1.5 KiB
  asset ../build/pages/Decrypted.d.ts 339 bytes [emitted]
  asset ../build/pages/Encrypted.d.ts 339 bytes [emitted]
  asset ../build/pages/Error.d.ts 339 bytes [emitted]
  + 2 assets
assets by path ../build/*.ts 155 bytes
  asset ../build/App.d.ts 89 bytes [emitted]
  asset ../build/i18n.d.ts 49 bytes [emitted]
  asset ../build/index.d.ts 17 bytes [emitted]
asset index.js 74.4 KiB [compared for emit] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 44.8 KiB
  modules by path ./src/components/*.tsx 11.8 KiB 7 modules
  modules by path ./src/pages/*.tsx 7.87 KiB 5 modules
  ./server/index.js 849 bytes [built] [code generated]
  ./src/App.tsx 1.5 KiB [built] [code generated]
  ./src/ressources/LogoWhite.png 22.8 KiB [built] [code generated]
modules by path external "react-bootstrap/ 84 bytes
  external "react-bootstrap/esm" 42 bytes [built] [code generated]
  external "react-bootstrap/esm/Button" 42 bytes [built] [code generated]
+ 8 modules
webpack 5.75.0 compiled successfully in 2785 ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./server-build/index.js`
Compiled successfully.

File sizes after gzip:

[nodemon] restarting due to changes...
[nodemon] starting `node ./server-build/index.js`
  82.01 kB  build/static/js/main.4e82a657.js

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.
You may serve it with a static server:

  npm install -g serve
  serve -s build

Find out more about deployment here:

  https://cra.link/deployment

/src/node_modules/react-bootstrap/esm/index.js:1
export { default as Accordion } from './Accordion';
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at react-bootstrap/esm (/src/server-build/index.js:199:18)
    at __webpack_require__ (/src/server-build/index.js:283:41)

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...
```
<p>I thought that was a transpile problem, so I include the react-bootstrap's folder in the build. But nothing more ( however I see that the folder is well build in the terminal )!</p>
<p>I tested lots of things and readed lots of topics, but I can't found out.</p>
<h3>server/index.js</h3>
<pre class="lang-js prettyprint-override"><code>import path from 'path';
import fs from 'fs';
import React from 'react';
import express from 'express';
import ReactDOMServer from 'react-dom/server';
import App from '../src/App.tsx';

const PORT = process.env.REACT_APP_SERVER_PORT || 8000;
const app = express();

app.get('/', (req,res) => {
    const app = ReactDOMServer.renderToString(<App />);

    const indexFile = path.resolve('./build/index.html');
    fs.readFile(indexFile, 'utf-8', ( err, data ) => {
        if(err) {
            console.error('Erreur: ', err);
            return res.status(500).send('Oops, plus de chance la prochaine fois!')
        }

        return res.send(
            data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
        );
    });
});

app.use(express.static('/build'));

app.listen(PORT, () => {
    console.log(`Serveur en écoute sur le port ${PORT}`)
});
</code>```

webpack.config.js

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './server/index.js',

    target: 'node',

    externals: [nodeExternals({
      allowlist: ['react-bootstrap','/^Accordion/']
    })],

    output: {
        path: path.resolve('server-build'),
        filename: 'index.js'
    },

    resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: [".ts", ".tsx", ".js"],
      // Add support for TypeScripts fully qualified ESM imports.
      extensionAlias: {
        ".js": [".js", ".ts", ".tsx"],
        ".cjs": [".cjs", ".cts"],
        ".mjs": [".mjs", ".mts"]
      }
    },
    module: {
        rules: [
            {
              test: /\.([cm]?js|jsx)$/,
              use: "babel-loader",

            },
            {
              test: /\.([cm]?ts|tsx)$/,
              use: [
                {
                  loader: 'babel-loader',
                  options: {
                    presets: ['@babel/preset-env'],
                  },
                },
                {
                  loader: 'ts-loader',
                  options: {
                    compilerOptions: {
                      noEmit: false,
                    },
                  },
                },

              ]
            },
            {
              test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
              use: 'url-loader?limit=100000'
            },
            {
              test: /\.css$/,
              use: [
                  "style-loader",
                  "css-loader"
                ]
            }
        ]
    }
};
```
<h3>.babelrc</h3>
<pre class="lang-json prettyprint-override"><code>{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react",
        "@babel/preset-typescript"
    ]
}
</code>```

package.json

{
  "name": "flashpaper_front",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/jest": "^29.2.5",
    "@types/node": "^18.11.18",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.10",
    "axios": "^1.2.2",
    "bootstrap": "^5.2.3",
    "express": "^4.18.2",
    "i18next": "^22.4.6",
    "install": "^0.13.0",
    "npm": "^9.2.0",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.0",
    "react-dom": "^18.2.0",
    "react-i18next": "^12.1.1",
    "react-router-dom": "^6.6.1",
    "react-scripts": "5.0.1",
    "typescript": "^4.9.4",
    "web-vitals": "^3.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "dev:build-server": "NODE_ENV=development webpack --mode=development -w",
    "dev:start": "nodemon ./server-build/index.js",
    "dev": "npm-run-all --parallel build dev:* ",
    "update": "ncu -u"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.18.6",
    "babel-loader": "^9.1.0",
    "css-loader": "^6.7.3",
    "file-loader": "^6.2.0",
    "nodemon": "^2.0.20",
    "npm-run-all": "^4.1.5",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.4.2",
    "url-loader": "^4.1.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-node-externals": "^3.0.0"
  }
}
```
<p>I even put the SSRProvider from <code>react-bootstrap</code> wrapping the App in case</p>
<h3>index.tsx</h3>
<pre class="lang-js prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom';
import './i18n';
import App from './App';
import i18next from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { SSRProvider } from 'react-bootstrap';

ReactDOM.hydrate(
  <I18nextProvider i18n={i18next}>
    <SSRProvider>
        <App />
    </SSRProvider>
  </I18nextProvider>,
  document.getElementById('root')
);

</code>```

Body:
I'm making tests on React Server Components with a co-worker's project, and I'm blocking on an error which is providing from react-bootstrap.

I can build the project, webpack made it good, with no errors, but when I'm starting the server, I have this error in the terminal here is the full return :

assets by path ../build/components/*.ts 2.21 KiB
  asset ../build/components/EncryptButton.d.ts 364 bytes [emitted]
  asset ../build/components/DecryptContent.d.ts 355 bytes [emitted]
  asset ../build/components/Footer.d.ts 339 bytes [emitted]
  + 4 assets
assets by path ../build/pages/*.ts 1.5 KiB
  asset ../build/pages/Decrypted.d.ts 339 bytes [emitted]
  asset ../build/pages/Encrypted.d.ts 339 bytes [emitted]
  asset ../build/pages/Error.d.ts 339 bytes [emitted]
  + 2 assets
assets by path ../build/*.ts 155 bytes
  asset ../build/App.d.ts 89 bytes [emitted]
  asset ../build/i18n.d.ts 49 bytes [emitted]
  asset ../build/index.d.ts 17 bytes [emitted]
asset index.js 74.4 KiB [compared for emit] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 44.8 KiB
  modules by path ./src/components/*.tsx 11.8 KiB 7 modules
  modules by path ./src/pages/*.tsx 7.87 KiB 5 modules
  ./server/index.js 849 bytes [built] [code generated]
  ./src/App.tsx 1.5 KiB [built] [code generated]
  ./src/ressources/LogoWhite.png 22.8 KiB [built] [code generated]
modules by path external "react-bootstrap/ 84 bytes
  external "react-bootstrap/esm" 42 bytes [built] [code generated]
  external "react-bootstrap/esm/Button" 42 bytes [built] [code generated]
+ 8 modules
webpack 5.75.0 compiled successfully in 2785 ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./server-build/index.js`
Compiled successfully.

File sizes after gzip:

[nodemon] restarting due to changes...
[nodemon] starting `node ./server-build/index.js`
  82.01 kB  build/static/js/main.4e82a657.js

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.
You may serve it with a static server:

  npm install -g serve
  serve -s build

Find out more about deployment here:

  https://cra.link/deployment

/src/node_modules/react-bootstrap/esm/index.js:1
export { default as Accordion } from './Accordion';
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at react-bootstrap/esm (/src/server-build/index.js:199:18)
    at __webpack_require__ (/src/server-build/index.js:283:41)

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...

I thought that was a transpile problem, so I include the react-bootstrap's folder in the build. But nothing more ( however I see that the folder is well build in the terminal )!

I tested lots of things and readed lots of topics, but I can't found out.

server/index.js

import path from 'path';
import fs from 'fs';
import React from 'react';
import express from 'express';
import ReactDOMServer from 'react-dom/server';
import App from '../src/App.tsx';

const PORT = process.env.REACT_APP_SERVER_PORT || 8000;
const app = express();

app.get('/', (req,res) => {
    const app = ReactDOMServer.renderToString(<App />);

    const indexFile = path.resolve('./build/index.html');
    fs.readFile(indexFile, 'utf-8', ( err, data ) => {
        if(err) {
            console.error('Erreur: ', err);
            return res.status(500).send('Oops, plus de chance la prochaine fois!')
        }

        return res.send(
            data.replace('

', `<div id="root">${app}</div>`)
        );
    });
});

app.use(express.static('/build'));

app.listen(PORT, () => {
    console.log(`Serveur en écoute sur le port ${PORT}`)
});

webpack.config.js

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './server/index.js',

    target: 'node',

    externals: [nodeExternals({
      allowlist: ['react-bootstrap','/^Accordion/']
    })],

    output: {
        path: path.resolve('server-build'),
        filename: 'index.js'
    },

    resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: [".ts", ".tsx", ".js"],
      // Add support for TypeScripts fully qualified ESM imports.
      extensionAlias: {
        ".js": [".js", ".ts", ".tsx"],
        ".cjs": [".cjs", ".cts"],
        ".mjs": [".mjs", ".mts"]
      }
    },
    module: {
        rules: [
            {
              test: /\.([cm]?js|jsx)$/,
              use: "babel-loader",

            },
            {
              test: /\.([cm]?ts|tsx)$/,
              use: [
                {
                  loader: 'babel-loader',
                  options: {
                    presets: ['@babel/preset-env'],
                  },
                },
                {
                  loader: 'ts-loader',
                  options: {
                    compilerOptions: {
                      noEmit: false,
                    },
                  },
                },

              ]
            },
            {
              test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
              use: 'url-loader?limit=100000'
            },
            {
              test: /\.css$/,
              use: [
                  "style-loader",
                  "css-loader"
                ]
            }
        ]
    }
};

.babelrc

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react",
        "@babel/preset-typescript"
    ]
}

package.json

{
  "name": "flashpaper_front",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/jest": "^29.2.5",
    "@types/node": "^18.11.18",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.10",
    "axios": "^1.2.2",
    "bootstrap": "^5.2.3",
    "express": "^4.18.2",
    "i18next": "^22.4.6",
    "install": "^0.13.0",
    "npm": "^9.2.0",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.0",
    "react-dom": "^18.2.0",
    "react-i18next": "^12.1.1",
    "react-router-dom": "^6.6.1",
    "react-scripts": "5.0.1",
    "typescript": "^4.9.4",
    "web-vitals": "^3.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "dev:build-server": "NODE_ENV=development webpack --mode=development -w",
    "dev:start": "nodemon ./server-build/index.js",
    "dev": "npm-run-all --parallel build dev:* ",
    "update": "ncu -u"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.18.6",
    "babel-loader": "^9.1.0",
    "css-loader": "^6.7.3",
    "file-loader": "^6.2.0",
    "nodemon": "^2.0.20",
    "npm-run-all": "^4.1.5",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.4.2",
    "url-loader": "^4.1.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-node-externals": "^3.0.0"
  }
}

I even put the SSRProvider from react-bootstrap wrapping the App in case

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './i18n';
import App from './App';
import i18next from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { SSRProvider } from 'react-bootstrap';

ReactDOM.hydrate(
  <I18nextProvider i18n={i18next}>
    <SSRProvider>
        <App />
    </SSRProvider>
  </I18nextProvider>,
  document.getElementById('root')
);