问:
Bytecompilation is done with /usr/bin/python and not /usr/bin/python3
I have a python project and I use maven to create an rpm file, using rpm-maven-plugin v2.1.3.
My project is written using python3.
When I create the rpm file, as part of a larger process of ms creation (with mvn install) I get syntax error on specific python3 syntax.
I can see that bytecompilation is done during the process, using /usr/bin/python which points to python2.7.
How can I force the bytecompile to use /usr/bin/python3?
I cannot change the global env variable since other ms are using python2.7
Also I cannot change the way mvn install is revoked since it's also used for all ms together.
I'm looking for somathing in the project itself I can define or change to force it to use python3.
I don't use a cmake file and I don't write my spec file (it is created as part of the rpm build)

Thank you!

spec file creation:

```<code>[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/BUILD
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/RPMS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SOURCES
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SPECS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SRPMS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/buildroot
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Creating spec file /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SPECS/ms-yael.spec
</code>```

Exception Trace:

```<code>[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/check-buildroot
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-compress
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip /usr/bin/strip
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip-comment-note /usr/bin/strip /usr/bin/objdump
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip-static-archive /usr/bin/strip
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/brp-python-bytecompile /usr/bin/python 1
[2023-01-03T16:22:00.773Z] [INFO] Compiling /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/buildroot/usr/share/yael/yael/yaelFramework/yael1.py ...
[2023-01-03T16:22:00.773Z] [INFO]   File "/usr/share/yael/yael/yaelFramework/yael1.py", line 33
[2023-01-03T16:22:00.773Z] [INFO]     def send_response(self, response: Response, metadata: ResponseMetadata) -> None:
[2023-01-03T16:22:00.773Z] [INFO]                                     ^
[2023-01-03T16:22:00.773Z] [INFO] SyntaxError: invalid syntax
</code>```

POM plugins:

```<code>                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>rpm-maven-plugin</artifactId>
                        <version>2.1.3</version>
                        <inherited>false</inherited>
                        <executions>
                            <execution>
                                <inherited>false</inherited>
                                <phase>install</phase>
                                <goals>
                                    <goal>rpm</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <group>Networking/Admin</group>
                            <name>myProject</name>
                            <packager>Yael</packager>
                            <prefix>/usr/share</prefix>
                            <version>0</version>
                            <release>0</release>
                            <needarch>x86_64</needarch>
                            <mappings>
                                <mapping>
                                    <directory>myProjectDir/</directory>
                                    <filemode>777</filemode>
                                    <sources>
                                        <source>
                                            <location>../yaelDir/</location>
                                        </source>
                                    </sources>
                                </mapping>
                            </mappings>
                        </configuration>
                    </plugin>
                     <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>build-helper-maven-plugin</artifactId>
                        <version>3.0.0</version>
                        <executions>
                            <execution>
                                <id>attach-artifacts</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>attach-artifact</goal>
                                </goals>
                                <configuration>
                                    <artifacts>
                                        <artifact>
                                            <file>target/rpm/ms-yael/RPMS/x86_64/yaelRPM-0-0.x86_64.rpm</file>
                                            <type>rpm</type>
                                        </artifact>
                                        <artifact>
                                            <file>../git-commit.txt</file>
                                            <classifier>git-commit</classifier>
                                            <type>txt</type>
                                        </artifact>
                                    </artifacts>
                                </configuration>
                            </execution>
                        </executions>

                    </plugin>
                </plugins>
</code>```

I am trying to build my project using mvn install.

Body:
I have a python project and I use maven to create an rpm file, using rpm-maven-plugin v2.1.3.
My project is written using python3.
When I create the rpm file, as part of a larger process of ms creation (with mvn install) I get syntax error on specific python3 syntax.
I can see that bytecompilation is done during the process, using /usr/bin/python which points to python2.7.
How can I force the bytecompile to use /usr/bin/python3?
I cannot change the global env variable since other ms are using python2.7
Also I cannot change the way mvn install is revoked since it's also used for all ms together.
I'm looking for somathing in the project itself I can define or change to force it to use python3.
I don't use a cmake file and I don't write my spec file (it is created as part of the rpm build)

Thank you!

spec file creation:

[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/BUILD
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/RPMS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SOURCES
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SPECS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SRPMS
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot
[2023-01-03T16:22:00.431Z] [INFO] Creating directory /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/buildroot
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Copying files to /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/tmp-buildroot/usr/share/yael
[2023-01-03T16:22:00.431Z] [INFO] Creating spec file /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/SPECS/ms-yael.spec

Exception Trace:

[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/check-buildroot
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-compress
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip /usr/bin/strip
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip-comment-note /usr/bin/strip /usr/bin/objdump
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/redhat/brp-strip-static-archive /usr/bin/strip
[2023-01-03T16:22:00.773Z] [INFO] + /usr/lib/rpm/brp-python-bytecompile /usr/bin/python 1
[2023-01-03T16:22:00.773Z] [INFO] Compiling /home/jenkins/workspace/ms_side-pipeline/yael-packer/target/rpm/ms-yael/buildroot/usr/share/yael/yael/yaelFramework/yael1.py ...
[2023-01-03T16:22:00.773Z] [INFO]   File "/usr/share/yael/yael/yaelFramework/yael1.py", line 33
[2023-01-03T16:22:00.773Z] [INFO]     def send_response(self, response: Response, metadata: ResponseMetadata) -> None:
[2023-01-03T16:22:00.773Z] [INFO]                                     ^
[2023-01-03T16:22:00.773Z] [INFO] SyntaxError: invalid syntax

POM plugins:

                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>rpm-maven-plugin</artifactId>
                        <version>2.1.3</version>
                        <inherited>false</inherited>
                        <executions>
                            <execution>
                                <inherited>false</inherited>
                                <phase>install</phase>
                                <goals>
                                    <goal>rpm</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <group>Networking/Admin</group>
                            <name>myProject</name>
                            <packager>Yael</packager>
                            <prefix>/usr/share</prefix>
                            <version>0</version>
                            <release>0</release>
                            <needarch>x86_64</needarch>
                            <mappings>
                                <mapping>
                                    <directory>myProjectDir/</directory>
                                    <filemode>777</filemode>
                                    <sources>
                                        <source>
                                            <location>../yaelDir/</location>
                                        </source>
                                    </sources>
                                </mapping>
                            </mappings>
                        </configuration>
                    </plugin>
                     <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>build-helper-maven-plugin</artifactId>
                        <version>3.0.0</version>
                        <executions>
                            <execution>
                                <id>attach-artifacts</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>attach-artifact</goal>
                                </goals>
                                <configuration>
                                    <artifacts>
                                        <artifact>
                                            <file>target/rpm/ms-yael/RPMS/x86_64/yaelRPM-0-0.x86_64.rpm</file>
                                            <type>rpm</type>
                                        </artifact>
                                        <artifact>
                                            <file>../git-commit.txt</file>
                                            <classifier>git-commit</classifier>
                                            <type>txt</type>
                                        </artifact>
                                    </artifacts>
                                </configuration>
                            </execution>
                        </executions>

                    </plugin>
                </plugins>

I am trying to build my project using mvn install.


来源: stackexchange

问:
How to Create Screen, Attach and run commands with inputs in the screen without attaching it?
I have the following set of ubuntu commands which i am currently running in multiple steps. How do i run these commands in one step without attaching the screen and passing the inputs and commands one by one in the screen and finally detaching it?

```<code>screen -dmS screen_1
screen -d -r screen_1
cd User/Myfolder/
python3 myscript.py    #(Here myscript.py demands an input for which value 1 or 2 needs to be provided)
input:1
Ctrl + a + d            #(to detach the screen after running the python script with the given input 1 or 2)
</code>```

Tried the below mentioned command. But not working properly. It's not running the script in the created screen. And also the given input 1 is not accounted anywhere. Again the python script is asking for the input.

```<code>screen -dmS screen_1; screen -d -r screen_1; cd User/Myfolder/; python3 myscript.py; 1; exit;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following set of ubuntu commands which i am currently running in multiple steps. How do i run these commands in one step without attaching the screen and passing the inputs and commands one by one in the screen and finally detaching it?

screen -dmS screen_1
screen -d -r screen_1
cd User/Myfolder/
python3 myscript.py    #(Here myscript.py demands an input for which value 1 or 2 needs to be provided)
input:1
Ctrl + a + d            #(to detach the screen after running the python script with the given input 1 or 2)

Tried the below mentioned command. But not working properly. It's not running the script in the created screen. And also the given input 1 is not accounted anywhere. Again the python script is asking for the input.

screen -dmS screen_1; screen -d -r screen_1; cd User/Myfolder/; python3 myscript.py; 1; exit;


问:
How to index through dynamic generated nested objects in Python?
```<code>import tkinter as tk
import tksheet
import json
import pickle

class Treino(object):
    class config(object):
        _list = []
        def __init__(self, name, value):
            self.name = name
            self.value = value
            self._list.append(self)
    class CategoriaTreino(object):
        _list = []
        def __init__(self, name):
            self.name = name
            self._list.append(self)
            self.config = {'RNG': 0}
        class SubCategoriaTreino(object):
            _list = []
            def __init__(self, name, repet):
                self.name = name
                self.repetição = repet
                self._list.append(self)
        pass
def returnCat():
     for cat in TreinoMain.CategoriaTreino._list:
         yield cat
def returnSubCat():
    for subcat in TreinoMain.CategoriaTreino.SubCategoriaTreino._list:
        yield subcat
def savefile():
    with open('treinos.pkl', 'wb') as file:
        for cat in returnCat():
            pickle.dump(cat, file, pickle.HIGHEST_PROTOCOL)
def loadfile():
    data = []
    with open('treinos.pkl', 'wb') as file:
        while True:
            try:
                data.append(pickle.load(file))
            except EOFError:
                break
    for d in data:
        #iterate through objs
        pass
if __name__ == "__main__":
    TreinoMain = Treino()
    ca1 = TreinoMain.CategoriaTreino("Braço")
    subca1 = ca1.SubCategoriaTreino('Biceps', '2x10')
</code>```

So, code is obviously far from done, my issue though is, i was hoping that creating an instance of the parent object, and then an instance of the child object would allow me to easily return attributes from the child object through it's parent object (and save/load from pickle). but apparently that's not the case (can't reefer to the childobj as parentobj.childobj), any ideas on how to do it in a simple way, or a better way to dynamically generate an object inside another object?
Also i'm almost pretty sure the _list will be useless after i load the objs with pickle and iterate through them...

The idea: Make a GUI so that the user can add/remove categories and subcategories of a data structure on the fly

Why i didn't go with nested data types? I figured it would be easier to implement with objects when i'm actually going to use them for what my goal is (randomize exercise schedules) and to write the add/remove functions.

So far what i've tried was to return attributes with:

```<code>ca1.subca1.name
</code>```

That doesn't work.

Body:
import tkinter as tk
import tksheet
import json
import pickle

class Treino(object):
    class config(object):
        _list = []
        def __init__(self, name, value):
            self.name = name
            self.value = value
            self._list.append(self)
    class CategoriaTreino(object):
        _list = []
        def __init__(self, name):
            self.name = name
            self._list.append(self)
            self.config = {'RNG': 0}
        class SubCategoriaTreino(object):
            _list = []
            def __init__(self, name, repet):
                self.name = name
                self.repetição = repet
                self._list.append(self)
        pass
def returnCat():
     for cat in TreinoMain.CategoriaTreino._list:
         yield cat
def returnSubCat():
    for subcat in TreinoMain.CategoriaTreino.SubCategoriaTreino._list:
        yield subcat
def savefile():
    with open('treinos.pkl', 'wb') as file:
        for cat in returnCat():
            pickle.dump(cat, file, pickle.HIGHEST_PROTOCOL)
def loadfile():
    data = []
    with open('treinos.pkl', 'wb') as file:
        while True:
            try:
                data.append(pickle.load(file))
            except EOFError:
                break
    for d in data:
        #iterate through objs
        pass
if __name__ == "__main__":
    TreinoMain = Treino()
    ca1 = TreinoMain.CategoriaTreino("Braço")
    subca1 = ca1.SubCategoriaTreino('Biceps', '2x10')

So, code is obviously far from done, my issue though is, i was hoping that creating an instance of the parent object, and then an instance of the child object would allow me to easily return attributes from the child object through it's parent object (and save/load from pickle). but apparently that's not the case (can't reefer to the childobj as parentobj.childobj), any ideas on how to do it in a simple way, or a better way to dynamically generate an object inside another object?
Also i'm almost pretty sure the _list will be useless after i load the objs with pickle and iterate through them...

The idea: Make a GUI so that the user can add/remove categories and subcategories of a data structure on the fly

Why i didn't go with nested data types? I figured it would be easier to implement with objects when i'm actually going to use them for what my goal is (randomize exercise schedules) and to write the add/remove functions.

So far what i've tried was to return attributes with:

ca1.subca1.name

That doesn't work.


问:
AndroidAlarmManager does not call a function from Getx Controller
i spent almost a whole day on this logical error

I am using Android Alarm Manager plus and trying to call a function after 3 seconds for example.
here is the code

```<code> AndroidAlarmManager.oneShot(
                  Duration(seconds: 3), 1, testfromclass);
</code>```

testfromclass function

```<code>testfromclass() {
  print("testFromclass");
}
</code>```

it works fine

but when i use function that is inside controller  and try to call it. it wont be called.

```<code>  AndroidAlarmManager.oneShot(
                      Duration(seconds: 3), 1, controller.testFromController);
</code>```

testFromController function:

```<code> testFromController() {
    print("testFromController");
  }
</code>```

this does not print "testFromController" it means it did not call it

i use controller from Getx package.
any idea why is this happening?

Body:
i spent almost a whole day on this logical error

I am using Android Alarm Manager plus and trying to call a function after 3 seconds for example.
here is the code

 AndroidAlarmManager.oneShot(
                  Duration(seconds: 3), 1, testfromclass);

testfromclass function

testfromclass() {
  print("testFromclass");
}

it works fine

but when i use function that is inside controller  and try to call it. it wont be called.

  AndroidAlarmManager.oneShot(
                      Duration(seconds: 3), 1, controller.testFromController);

testFromController function:

 testFromController() {
    print("testFromController");
  }

this does not print "testFromController" it means it did not call it

i use controller from Getx package.
any idea why is this happening?


问:
PostgreSQL UTF-8 data loading with double encoding
We have a PostgreSQL database encoded in UTF-8, into which we load CSV files.

As these files are using Latin 1 encoding, we are using "iconv" command line tool to convert them to UTF-8 before loading.

But one of our files has been incorrectly provided in UTF-8, so after UTF-8 conversion and loading, we have badly encoded data in PostgreSQL, like "CHLOÃ\u0089" instead of "CHLOÉ".

As we can't reload these data files, is there a way to convert these strings with correct UTF-8 encoding?

Best regards,

Thierry


问:
Opening notification with ADB and notification ID on Android
I am trying to open a notification on my Android device using ADB and the notification ID, but I am getting the following error message:

Starting: Intent { act=android.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=24 } Error: Activity not started, unable to resolve Intent { act=android.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=24 flg=0x10000000 }

I have used the following command to try to open the notification:

adb shell am start -a android.intent.action.VIEW -c android.intent.category.DEFAULT -d 24

I am sure that I have entered the correct notification ID and that the app that sent the notification is installed on my device. What could be the cause of this error and how can I fix it?

I have tried the following steps to troubleshoot the issue, but I am still getting the error message:

I have checked to make sure that I have entered the correct notification ID. I have used the adb shell dumpsys notification command to get a list of open notification IDs and made sure that the ID I have entered is valid.

I have made sure that the app that sent the notification is installed on my device.


问:
Domain not working properly for automated action
I have an automated action that send me an email warning me when a subscription will be renew in 30 days.
I have a domain that's suppose to stop subscription that are already closed from sending me an email but I sometimes have those in my email box and I don't understand why.

I have:

Trigger: Based on time condition

Apply on: [Step: "Closed"] [Suspriction model: Annual]

Trigger date: Next bill date (Subscription)

Delay after trigger date: -30 days

I try to see if I made a typo or if I forgot something but no there is nothing
What have I done wrong?


问:
Angular: Cors error when sending a particular request to my PHP server. But the same requests works everywhere else
Hi all I have the following request in angular:

```<code>public async getPdfFromServer(format: any, numberOfPage: any, signatureString: any, filterObject: any = "") {
    const token: string = localStorage.getItem('token') || '';

    let data = {
      format, numberOfPage, signatureString, filterObject
    }
    try {
      return fetch('https://www.testenpoint.com/applicationApis/getPdfReport.php',
        {
          method: 'POST',
          headers: {
            'Authorization': token
          },
          body: JSON.stringify(data)
        }
      ).then((response) => {
        if (response) {
          // @ts-ignore
          return response.blob({headers: {'Content-Type': 'application/pdf'}});
        }
        return;
      }).catch((err) => {
        console.log(err);
      });
    } catch (e) {
      console.log(e);
      return false;
    }
  }
</code>```

the problem I am having is if filterObject is empty or null the request works fine. However if populated it doesn't work and I get the following error:

```<code>Access to fetch at 'https://www.testenpoint.com/applicationApis/getPdfReport.php' from origin 'https://testenpoint.com/applicationApis/getPdfReport.php' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
polyfills.js:9560
POST https://www.testenpoint.com/applicationApis/getPdfReport.php net::ERR_FAILED 404

</code>```

However my confusion is that if I replicate the code on my other instance and it works with the filter. Also using via postman with the exact same request also works.

Here is my cors checker at the top of my php script:

```<code>
function cors(): void
{
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Encoding, Content-Type, Accept");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

// Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: Origin, Authorization,Content-Encoding, X-Requested-With, Content-Type, Accept");

        exit(0);
    }
}

</code>```

Additionally I know the code works and runs because my logs have outputted it all the way to completion. But i get the 404 instead of the response.

Here is my nginx config as well just incase:

```<code>server {
  listen       443 ssl;
  root         /var/www/angular/dist/testenpoint-website-angular;
  index        index.htm index.html;
  server_name  www.testenpoint.com;
  client_max_body_size 100m;

  location / {
  try_files $uri $uri/ /index.html;
}

location /applicationApis/ {
  root /var/www/html;
  try_files $uri $uri/ =404;
  include fastcgi_params;
  fastcgi_pass unix:/run/php-fpm/www.sock;
  fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}

ssl_certificate /etc/letsencrypt/live/testenpoint-all/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/testenpoint-all/privkey.pem; # managed by Certbot
}

server {
if ($host = testenpoint.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

if ($host = www.testenpoint.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen      80;   #listen for all the HTTP requests
server_name testenpoint.com www.testenpoint.com;
return      301         https://www.testenpoint.com$request_uri;

}

server {
if ($host = testenpoint.co.uk) {
return 301 https://www.testenpoint.com$request_uri;
} # managed by Certbot

if ($host = www.testenpoint.co.uk) {
return 301 https://www.testenpoint.com$request_uri;
} # managed by Certbot

listen      80;
server_name testenpoint.co.uk *.testenpoint.co.uk;
return      301         https://www.testenpoint.com$request_uri;

}
server {
listen       443;
server_name  testenpoint.co.uk *.testenpoint.co.uk;
return       301         https://www.testenpoint.com$request_uri;
}

</code>```

Thanks for any help

Body:
Hi all I have the following request in angular:

public async getPdfFromServer(format: any, numberOfPage: any, signatureString: any, filterObject: any = "") {
    const token: string = localStorage.getItem('token') || '';

    let data = {
      format, numberOfPage, signatureString, filterObject
    }
    try {
      return fetch('https://www.testenpoint.com/applicationApis/getPdfReport.php',
        {
          method: 'POST',
          headers: {
            'Authorization': token
          },
          body: JSON.stringify(data)
        }
      ).then((response) => {
        if (response) {
          // @ts-ignore
          return response.blob({headers: {'Content-Type': 'application/pdf'}});
        }
        return;
      }).catch((err) => {
        console.log(err);
      });
    } catch (e) {
      console.log(e);
      return false;
    }
  }

the problem I am having is if filterObject is empty or null the request works fine. However if populated it doesn't work and I get the following error:

Access to fetch at 'https://www.testenpoint.com/applicationApis/getPdfReport.php' from origin 'https://testenpoint.com/applicationApis/getPdfReport.php' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
polyfills.js:9560
POST https://www.testenpoint.com/applicationApis/getPdfReport.php net::ERR_FAILED 404

However my confusion is that if I replicate the code on my other instance and it works with the filter. Also using via postman with the exact same request also works.

Here is my cors checker at the top of my php script:

function cors(): void
{
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Encoding, Content-Type, Accept");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

// Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: Origin, Authorization,Content-Encoding, X-Requested-With, Content-Type, Accept");

        exit(0);
    }
}

Additionally I know the code works and runs because my logs have outputted it all the way to completion. But i get the 404 instead of the response.

Here is my nginx config as well just incase:

server {
  listen       443 ssl;
  root         /var/www/angular/dist/testenpoint-website-angular;
  index        index.htm index.html;
  server_name  www.testenpoint.com;
  client_max_body_size 100m;

  location / {
  try_files $uri $uri/ /index.html;
}

location /applicationApis/ {
  root /var/www/html;
  try_files $uri $uri/ =404;
  include fastcgi_params;
  fastcgi_pass unix:/run/php-fpm/www.sock;
  fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}

ssl_certificate /etc/letsencrypt/live/testenpoint-all/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/testenpoint-all/privkey.pem; # managed by Certbot
}

server {
if ($host = testenpoint.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

if ($host = www.testenpoint.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen      80;   #listen for all the HTTP requests
server_name testenpoint.com www.testenpoint.com;
return      301         https://www.testenpoint.com$request_uri;

}

server {
if ($host = testenpoint.co.uk) {
return 301 https://www.testenpoint.com$request_uri;
} # managed by Certbot

if ($host = www.testenpoint.co.uk) {
return 301 https://www.testenpoint.com$request_uri;
} # managed by Certbot

listen      80;
server_name testenpoint.co.uk *.testenpoint.co.uk;
return      301         https://www.testenpoint.com$request_uri;

}
server {
listen       443;
server_name  testenpoint.co.uk *.testenpoint.co.uk;
return       301         https://www.testenpoint.com$request_uri;
}

Thanks for any help


问:
Spring + Hibernate + Oracle StoredProcedure with commit
I have a Spring project, with Hibernate as ORM and Oracle as DB.

Transaction management works as expected, though I found that use case:

Transactional service:

1.1 Calls oJpaRepositoryX.save(oEntity01HibernateObject) (Entity01)

1.2 Calls oJpaRepositoryZ.callDbStoredProcedure()

Insert a row in Entity02

Executes a COMMIT; (still in StoredProdure)

Insert another row in Entity02

1.3 Extra Java code executes on the service, and an Exception is thrown

Due to the rollback, I didn't expect to find anything on Entity01/Entity02, BUT:

First row inserted into Entity02 is there

Rollback only affected to Entity01 row and the second insert into Entity02

It is like the commit on the PL keeps out of the main transaction, and it doesn't allow the rollback of the first row inserted in the SP

Perhaps I was wrong, and this is OK... Or am I missing something?

What do you think? Is it working fine?

I made this tests also:

If I comment out the commit on the SP, a full rollback is executed (as expected)

This makes me bear that the StoredProcedure is running under the same Tx that the Java service...

If no exception is thrown, all rows are in the DB (commit OK)

Any help/insight/comment is welcome

Thanks in advance

P.S.: No autonomous transaction defined on SP (PRAGMA)

Application configuration (xml):

```<code>    <!-- Db config -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="${database.driverClassName}"
        p:url="${database.url}"
        p:username="${database.username}"
        p:password="${database.password}" />

    <!--  El entity manager factory  -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:persistence-xml-location="classpath:test_persistence.xml"
        p:data-source-ref="dataSource" >
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                p:showSql="true"
                p:generateDdl="false">
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
               <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.hbm2ddl.import_files">${hibernate.hbm2ddl.import_files}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.order_inserts">true</prop>
                <prop key="hibernate.order_updates">true</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- Enable transaction demarcation with annotations -->
    <tx:annotation-driven />

    <!-- Services -->
    <context:component-scan base-package="com.myapp.srv"/>

   <!--  Spring Data Repositories -->
    <data:repositories base-package="com.myapp.srv" transaction-manager-ref="transactionManager" />

</code>```

New info / Explanation to this behaviour

OK, thats what I've discovered with new tests:

COMMIT/ROLLBACK on SP falls apart from Java TransactionManager, and affects some previous SQL commands executed (inserts/updates/deletes)

Some? What will affected by the SP inner commit/rollback?

Operations performed througth custom JpaRepositories functions annotated with:

@Query with nativeQuery=true
because they are sent directly to the DB (1), and DB is aware of the operation

(1) Usual JPA operations performed in the Java application layer throught JpaRepositories or the EntityManager, are not sent to DB until outer @Transactional function/procedure ends its execution. So, DB doesn't know anything about them since then

So, the explanation of the behaviour detected in the use case documented above is that:

Insert on step "1.1" is done throught CrudRepository.save() over a Hibernate model entity, so it won't be sent to the DB until Service "1.-" ends

COMMIT on StoredProcedure (step "1.2") only sees Entity02 insert, performed on same PL. So, commits it

Second insert done in SP needs a commit to persist on DB

When Java service throws an exception, @Transactional demarcation finishes and Spring executes a rollback

Result: Though Java executed a rollback, first record inserted in 'Entity02' is there

Just to check it, I did two extra tests:

Test1:

Changed insert done on step "1.1" with a call to that custom Repository funcion:

```<code>    @Transactional
    @Modifying
    @Query(value = "INSERT INTO Entity01(code, description) SELECT :code, :description FROM Entity01")
    public void insertUsingSqlAnnotatedInRepository(@Param("code") String code, @Param("description") String description);
</code>```

Results?

The same as the other, because it is performed througth JPA (standard SQL), and won't be sent to DB until last @Transactional service executes succesfully. And, as a service exception arise, a rollback is executed
Only first insert is there due to then commit into the SP

Test2:

Changed insert done on step "1.1" with a call to that custom Repository funcion:

```<code>    @Transactional
    @Modifying
    @Query(value = "INSERT INTO Entity01(code, description) VALUES(:code, :description)", nativeQuery = true)
    public void insertUsingSqlAnnotatedInRepository_NativeQuery(@Param("code") String code, @Param("description") String description);
</code>```

Results?

As Entity01 insert is performed through a "nativeQuery", it will be affected by the commit inside the PL, so:
Two rows are in the DB: Entity01, and first insert on Entity02
Second insert done inside the SP will be rolled back when Java exception arises

Body:
I have a Spring project, with Hibernate as ORM and Oracle as DB.

Transaction management works as expected, though I found that use case:

Transactional service:

1.1 Calls oJpaRepositoryX.save(oEntity01HibernateObject) (Entity01)

1.2 Calls oJpaRepositoryZ.callDbStoredProcedure()

Insert a row in Entity02

Executes a COMMIT; (still in StoredProdure)

Insert another row in Entity02

1.3 Extra Java code executes on the service, and an Exception is thrown

Due to the rollback, I didn't expect to find anything on Entity01/Entity02, BUT:

First row inserted into Entity02 is there

Rollback only affected to Entity01 row and the second insert into Entity02

It is like the commit on the PL keeps out of the main transaction, and it doesn't allow the rollback of the first row inserted in the SP

Perhaps I was wrong, and this is OK... Or am I missing something?

What do you think? Is it working fine?

I made this tests also:

If I comment out the commit on the SP, a full rollback is executed (as expected)

This makes me bear that the StoredProcedure is running under the same Tx that the Java service...

If no exception is thrown, all rows are in the DB (commit OK)

Any help/insight/comment is welcome

Thanks in advance

P.S.: No autonomous transaction defined on SP (PRAGMA)

Application configuration (xml):

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="${database.driverClassName}"
        p:url="${database.url}"
        p:username="${database.username}"
        p:password="${database.password}" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:persistence-xml-location="classpath:test_persistence.xml"
        p:data-source-ref="dataSource" >
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                p:showSql="true"
                p:generateDdl="false">
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
               <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.hbm2ddl.import_files">${hibernate.hbm2ddl.import_files}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.order_inserts">true</prop>
                <prop key="hibernate.order_updates">true</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven />

    <context:component-scan base-package="com.myapp.srv"/>

    <data:repositories base-package="com.myapp.srv" transaction-manager-ref="transactionManager" />

New info / Explanation to this behaviour

OK, thats what I've discovered with new tests:

COMMIT/ROLLBACK on SP falls apart from Java TransactionManager, and affects some previous SQL commands executed (inserts/updates/deletes)

Some? What will affected by the SP inner commit/rollback?

Operations performed througth custom JpaRepositories functions annotated with:

@Query with nativeQuery=true
because they are sent directly to the DB (1), and DB is aware of the operation

(1) Usual JPA operations performed in the Java application layer throught JpaRepositories or the EntityManager, are not sent to DB until outer @Transactional function/procedure ends its execution. So, DB doesn't know anything about them since then

So, the explanation of the behaviour detected in the use case documented above is that:

Insert on step "1.1" is done throught CrudRepository.save() over a Hibernate model entity, so it won't be sent to the DB until Service "1.-" ends

COMMIT on StoredProcedure (step "1.2") only sees Entity02 insert, performed on same PL. So, commits it

Second insert done in SP needs a commit to persist on DB

When Java service throws an exception, @Transactional demarcation finishes and Spring executes a rollback

Result: Though Java executed a rollback, first record inserted in 'Entity02' is there

Just to check it, I did two extra tests:

Test1:

Changed insert done on step "1.1" with a call to that custom Repository funcion:

    @Transactional
    @Modifying
    @Query(value = "INSERT INTO Entity01(code, description) SELECT :code, :description FROM Entity01")
    public void insertUsingSqlAnnotatedInRepository(@Param("code") String code, @Param("description") String description);

Results?

The same as the other, because it is performed througth JPA (standard SQL), and won't be sent to DB until last @Transactional service executes succesfully. And, as a service exception arise, a rollback is executed
Only first insert is there due to then commit into the SP

Test2:

Changed insert done on step "1.1" with a call to that custom Repository funcion:

    @Transactional
    @Modifying
    @Query(value = "INSERT INTO Entity01(code, description) VALUES(:code, :description)", nativeQuery = true)
    public void insertUsingSqlAnnotatedInRepository_NativeQuery(@Param("code") String code, @Param("description") String description);

Results?

As Entity01 insert is performed through a "nativeQuery", it will be affected by the commit inside the PL, so:
Two rows are in the DB: Entity01, and first insert on Entity02
Second insert done inside the SP will be rolled back when Java exception arises


问:
Kafka Consumer doesn't poll any messages
I have an external topic.
And an application under test which sends messages to that topic.

My goal is to consume sent event from that topic.

What I do:

Call an API of application that triggers a message to get sent to the topic.

Use my consumer to poll the message and ensure it posted.

Problem: When I poll messages - nothing is polled and test fails with timeout.

Consumer config:

```<code>public Properties consumerProperties() {
    Properties properties = new Properties();

    properties.setProperty("group.id", "test-consumer-group");
    properties.setProperty("bootstrap.servers", "my_server");
    properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    properties.setProperty("value.deserializer", "io.confluent.kafka.serializers.KafkaAvroDeserializer");
    properties.setProperty("schema.registry.url", "my_url");
    properties.setProperty("max.poll.records", "1000");
    properties.setProperty("retries", "5");
    properties.setProperty("default.api.timeout.ms", "240000");
    properties.setProperty("auto.offset.reset", "latest");
    properties.setProperty("auto.commit", "false");
    properties.setProperty("specific.avro.reader", "true");
    properties.setProperty("ssl.endpoint.identification.algorithm", "");
    properties.setProperty("basic.auth.credentials.source", "SASL_INHERIT");
    properties.setProperty("sasl.mechanism", "SCRAM-SHA-512");
    properties.setProperty("security.protocol", "SASL_SSL");
    properties.setProperty(
            "sasl.jaas.config",
            "org.apache.kafka.common.security.scram.ScramLoginModule required username=\""
                    + user
                    + "\" password=\""
                    + password
                    + "\";");

    return properties;
}
</code>```

TestConsumer:

```<code>public class TestConsumer<T> {

private final String topic;
private final Consumer<String, T> consumer;

public TestConsumer(String topic, Properties properties) {
    this.topic = topic;
    this.consumer = new KafkaConsumer<>(properties);
    consumer.subscribe(List.of(topic));
    consumer.poll(Duration.ofMillis(0));
}

public T consumeEvent(Predicate<T> expectedEvent) {
    ConsumerRecords<String, T> records = consumer.poll(Duration.ofMillis(100000));
    consumer.commitSync();
    for (ConsumerRecord<String, T> record : records.records(topic)) {
        if (expectedEvent.test(record.value()))
            return record.value();
    }
    return null;
}
</code>```

}

Usage:

```<code>T message = new TestConsumer<>("my_topic", consumerProperties).consumeEvent(m -> m != null);
</code>```

And I always get null because nothing is polled. What can be a reason?

I have tried to change properties with different combinations including auto.offset.reset, max.poll.records, group.id and others however nothing helped.

Appreciate any solutions!

Body:
I have an external topic.
And an application under test which sends messages to that topic.

My goal is to consume sent event from that topic.

What I do:

Call an API of application that triggers a message to get sent to the topic.

Use my consumer to poll the message and ensure it posted.

Problem: When I poll messages - nothing is polled and test fails with timeout.

Consumer config:

public Properties consumerProperties() {
    Properties properties = new Properties();

    properties.setProperty("group.id", "test-consumer-group");
    properties.setProperty("bootstrap.servers", "my_server");
    properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    properties.setProperty("value.deserializer", "io.confluent.kafka.serializers.KafkaAvroDeserializer");
    properties.setProperty("schema.registry.url", "my_url");
    properties.setProperty("max.poll.records", "1000");
    properties.setProperty("retries", "5");
    properties.setProperty("default.api.timeout.ms", "240000");
    properties.setProperty("auto.offset.reset", "latest");
    properties.setProperty("auto.commit", "false");
    properties.setProperty("specific.avro.reader", "true");
    properties.setProperty("ssl.endpoint.identification.algorithm", "");
    properties.setProperty("basic.auth.credentials.source", "SASL_INHERIT");
    properties.setProperty("sasl.mechanism", "SCRAM-SHA-512");
    properties.setProperty("security.protocol", "SASL_SSL");
    properties.setProperty(
            "sasl.jaas.config",
            "org.apache.kafka.common.security.scram.ScramLoginModule required username=\""
                    + user
                    + "\" password=\""
                    + password
                    + "\";");

    return properties;
}

TestConsumer:

public class TestConsumer<T> {

private final String topic;
private final Consumer<String, T> consumer;

public TestConsumer(String topic, Properties properties) {
    this.topic = topic;
    this.consumer = new KafkaConsumer<>(properties);
    consumer.subscribe(List.of(topic));
    consumer.poll(Duration.ofMillis(0));
}

public T consumeEvent(Predicate<T> expectedEvent) {
    ConsumerRecords<String, T> records = consumer.poll(Duration.ofMillis(100000));
    consumer.commitSync();
    for (ConsumerRecord<String, T> record : records.records(topic)) {
        if (expectedEvent.test(record.value()))
            return record.value();
    }
    return null;
}

}

Usage:

T message = new TestConsumer<>("my_topic", consumerProperties).consumeEvent(m -> m != null);

And I always get null because nothing is polled. What can be a reason?

I have tried to change properties with different combinations including auto.offset.reset, max.poll.records, group.id and others however nothing helped.

Appreciate any solutions!


问:
Fatal Error AFTER text change listener executed

SOLVED

I have an app that searches through an arraylist whenever the search string is updated in an EditText.
I have a text change listener added to the EditText. It usually works but randomly I've been getting a Fatal error with no reference to a line number in my app (I'm Using Eclipse Logcat)
I've put log outputs in my code to find the last line that is executed. Unexpectedly this turned out to be AFTER the text change listener had executed all it's code, and presumably after the thread had been handed back to the UI?
I'd be grateful of any help.

Here's the full code in my text Listener. I'm getting the log output saying it Finished this function though. So where does the thread go after this?

```<code> public void afterTextChanged(Editable s) {
            if (("" + inputField.getText()).length() > 0) {
                fullSearchString += ("" + inputField.getText()).trim();
                inputField.setText("");
                searchArray(fullSearchString);
                out("FINISHED Text change Listener");
            }
        }
</code>```

Here's the stack trace

```<code>09-21 13:05:24.146: ERROR/AndroidRuntime(7660): FATAL EXCEPTION: main
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.util.ArrayList.get(ArrayList.java:311)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.widget.TextView.sendAfterTextChanged(TextView.java:6194)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:6377)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.sendTextHasChanged(SpannableStringBuilder.java:897)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:353)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.os.Looper.loop(Looper.java:123)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.lang.reflect.Method.invoke(Method.java:521)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at dalvik.system.NativeStart.main(Native Method)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SOLVED

I have an app that searches through an arraylist whenever the search string is updated in an EditText.
I have a text change listener added to the EditText. It usually works but randomly I've been getting a Fatal error with no reference to a line number in my app (I'm Using Eclipse Logcat)
I've put log outputs in my code to find the last line that is executed. Unexpectedly this turned out to be AFTER the text change listener had executed all it's code, and presumably after the thread had been handed back to the UI?
I'd be grateful of any help.

Here's the full code in my text Listener. I'm getting the log output saying it Finished this function though. So where does the thread go after this?

 public void afterTextChanged(Editable s) {
            if (("" + inputField.getText()).length() > 0) {
                fullSearchString += ("" + inputField.getText()).trim();
                inputField.setText("");
                searchArray(fullSearchString);
                out("FINISHED Text change Listener");
            }
        }

Here's the stack trace

09-21 13:05:24.146: ERROR/AndroidRuntime(7660): FATAL EXCEPTION: main
09-21 13:05:24.146: ERROR/AndroidRuntime(7660): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.util.ArrayList.get(ArrayList.java:311)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.widget.TextView.sendAfterTextChanged(TextView.java:6194)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:6377)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.sendTextHasChanged(SpannableStringBuilder.java:897)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:353)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.os.Looper.loop(Looper.java:123)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at java.lang.reflect.Method.invoke(Method.java:521)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
09-21 13:05:24.146: ERROR/AndroidRuntime(7660):     at dalvik.system.NativeStart.main(Native Method)


问:
How to use Auth api from AWS amplify without refreshing and redirecting application to different URL?
```<code>export default function Home() {
  const [user, setUser] = useState("");

  useEffect(() => {
    Auth.currentAuthenticatedUser().then((user) => {
      setUser(user.username);
    });

    Hub.listen("auth", (data) => {
      switch (data.payload.event) {
        case "signIn":
          return setUser(data.payload.data.username);
        case "signOut":
          return setUser("");
      }
    });
  }, [setUser]);

  const handleGoogleLogin = () => {
    Auth.federatedSignIn({
      provider: CognitoHostedUIIdentityProvider.Google,
    });
  };

  const handleSignOut = () => {
    Auth.signOut({
      global: true,
    }).then(() => {});
  };

  return (
    <>
      {!user && <button onClick={handleGoogleLogin}>Google</button>}
      {user && (
        <button onClick={handleSignOut}>LogOut</button>
      )}
      <h1>Hello {user}, this is my app</h1>
    </>
  );
}
</code>```

In this react component, i am using the AWS api to sign in with google and to sign out when users is logged. The problem is that Auth.federatedSignIn use the same tab of my application to open google login form, and Auth.signOut refresh my application. How can I use this API only relying on Hub.listen to send auth events to my app?

Body:
export default function Home() {
  const [user, setUser] = useState("");

  useEffect(() => {
    Auth.currentAuthenticatedUser().then((user) => {
      setUser(user.username);
    });

    Hub.listen("auth", (data) => {
      switch (data.payload.event) {
        case "signIn":
          return setUser(data.payload.data.username);
        case "signOut":
          return setUser("");
      }
    });
  }, [setUser]);

  const handleGoogleLogin = () => {
    Auth.federatedSignIn({
      provider: CognitoHostedUIIdentityProvider.Google,
    });
  };

  const handleSignOut = () => {
    Auth.signOut({
      global: true,
    }).then(() => {});
  };

  return (
    <>
      {!user && <button onClick={handleGoogleLogin}>Google</button>}
      {user && (
        <button onClick={handleSignOut}>LogOut</button>
      )}

Hello {user}, this is my app

    </>
  );
}

In this react component, i am using the AWS api to sign in with google and to sign out when users is logged. The problem is that Auth.federatedSignIn use the same tab of my application to open google login form, and Auth.signOut refresh my application. How can I use this API only relying on Hub.listen to send auth events to my app?


问:
i'm not succeeding to use kalend component in my project
i try using kalend in my project but i'm not succeeding. i dont know why but my kalend dont show a full calendar with days, times and shcedulers. When a import and use a component in my project show only the topbar.
enter image description here
like this picture. Please i need help.

Thank you

i try use the component like a documentation and i expected it work, but not.

This usage it seems simple, but not working. The kalend have a documentation here.

https://docs.kalend.org/docs/intro


问:
Compiling JS failed error in react native
I am trying to solve this error
in my react native application.

Some people reported getting a similar error when they use asynchronous calls incorrectly but I tried rewriting all my async code to promises and even commenting out all of this async code and still get the error.
Any ideas?


问:
How can I use setDefaultMemberPermissions for only certain subcommands discord.js
I am using the discord.js module for javascript, and am creating a /roles command. Within this /roles command, I have 4 subcommands, create, delete, add, and remove. I am planning to add a list subcommand as well, but there is one issue, which is that I used setDefaultMemberPermissions() on the SlashCommandBuilder, but I only want to set those for the first 4 subcommands, not the list subcommand. Do I need to create a new command or is there a different way to do this?

This is my code right now.
`

```<code>const {
  SlashCommandBuilder,
  EmbedBuilder,
  PermissionFlagsBits,
} = require("discord.js");
module.exports = {
  data: new SlashCommandBuilder()
    .setName("roles")
    .setDescription("Manage roles for your guild!")
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
    .addSubcommand((subcommand) =>
      subcommand
        .setName("create")
        .setDescription("Create a role")
        .addStringOption((option) =>
          option
            .setName("name")
            .setDescription("Name of the role you want to add")
            .setRequired(true)
        )
        .addStringOption((option) =>
          option
            .setName("color")
            .setDescription("Set a color for your role")
            .addChoices(
              { name: "RED", value: "RED" },
              { name: "BLUE", value: "BLUE" },
              { name: "GREEN", value: "GREEN" },
              { name: "YELLOW", value: "YELLOW" },
              { name: "PURPLE", value: "PURPLE" },
              { name: "GREY", value: "GREY" }
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("mentionable")
            .setDescription("Enter whether this role should be mentionable")
        )
        .addBooleanOption((option) =>
          option
            .setName("send_messages")
            .setDescription(
              "Enter whether members of this role can send messages"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("add_reactions")
            .setDescription(
              "Enter whether members of this role can add reactions"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("attach_files")
            .setDescription(
              "Enter whether members of this role can attach files"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("connect")
            .setDescription(
              "Enter whether members of this role can connect to vc"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("change_nickname")
            .setDescription(
              "Enter whether members of this role can change their nickname"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("administrator")
            .setDescription("Enter whether this role should have administrator")
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("delete")
        .setDescription("Delete a role")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Enter the name of the role you want to delete")
            .setRequired(true)
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("add")
        .setDescription("Add a role to a user")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Enter the name of the role you want to add")
            .setRequired(true)
        )
        .addUserOption((option) =>
          option
            .setName("user")
            .setDescription("Enter the user you want to add")
            .setRequired(true)
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("remove")
        .setDescription("Remove a role from a user")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Role to remove from user")
            .setRequired(true)
        )
        .addUserOption((option) =>
          option
            .setName("user")
            .setDescription("Enter the user you want to remove")
            .setRequired(true)
        )
    ),
</code>```

`

Body:
I am using the discord.js module for javascript, and am creating a /roles command. Within this /roles command, I have 4 subcommands, create, delete, add, and remove. I am planning to add a list subcommand as well, but there is one issue, which is that I used setDefaultMemberPermissions() on the SlashCommandBuilder, but I only want to set those for the first 4 subcommands, not the list subcommand. Do I need to create a new command or is there a different way to do this?

This is my code right now.
`

const {
  SlashCommandBuilder,
  EmbedBuilder,
  PermissionFlagsBits,
} = require("discord.js");
module.exports = {
  data: new SlashCommandBuilder()
    .setName("roles")
    .setDescription("Manage roles for your guild!")
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
    .addSubcommand((subcommand) =>
      subcommand
        .setName("create")
        .setDescription("Create a role")
        .addStringOption((option) =>
          option
            .setName("name")
            .setDescription("Name of the role you want to add")
            .setRequired(true)
        )
        .addStringOption((option) =>
          option
            .setName("color")
            .setDescription("Set a color for your role")
            .addChoices(
              { name: "RED", value: "RED" },
              { name: "BLUE", value: "BLUE" },
              { name: "GREEN", value: "GREEN" },
              { name: "YELLOW", value: "YELLOW" },
              { name: "PURPLE", value: "PURPLE" },
              { name: "GREY", value: "GREY" }
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("mentionable")
            .setDescription("Enter whether this role should be mentionable")
        )
        .addBooleanOption((option) =>
          option
            .setName("send_messages")
            .setDescription(
              "Enter whether members of this role can send messages"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("add_reactions")
            .setDescription(
              "Enter whether members of this role can add reactions"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("attach_files")
            .setDescription(
              "Enter whether members of this role can attach files"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("connect")
            .setDescription(
              "Enter whether members of this role can connect to vc"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("change_nickname")
            .setDescription(
              "Enter whether members of this role can change their nickname"
            )
        )
        .addBooleanOption((option) =>
          option
            .setName("administrator")
            .setDescription("Enter whether this role should have administrator")
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("delete")
        .setDescription("Delete a role")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Enter the name of the role you want to delete")
            .setRequired(true)
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("add")
        .setDescription("Add a role to a user")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Enter the name of the role you want to add")
            .setRequired(true)
        )
        .addUserOption((option) =>
          option
            .setName("user")
            .setDescription("Enter the user you want to add")
            .setRequired(true)
        )
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName("remove")
        .setDescription("Remove a role from a user")
        .addRoleOption((option) =>
          option
            .setName("role")
            .setDescription("Role to remove from user")
            .setRequired(true)
        )
        .addUserOption((option) =>
          option
            .setName("user")
            .setDescription("Enter the user you want to remove")
            .setRequired(true)
        )
    ),

`


问:
Questions about strange output of hexo page.date variable
In hexo, there is a page variable called page.date which refers to the date that the file is created. But when I tried it by using

```<code><%- page.date %>
</code>```

in the post.ejs file, this variable is always a series a number displayed in the site rather than the expected date. For example:

```<code>date: 2022-12-10 20:32:47
</code>```
```<code>page.date: 1672598362227
</code>```

why this happen, and how to solve it?

I found the same problem also happen in other variable display related the date, such as page.updated.

Body:
In hexo, there is a page variable called page.date which refers to the date that the file is created. But when I tried it by using

<%- page.date %>

in the post.ejs file, this variable is always a series a number displayed in the site rather than the expected date. For example:

date: 2022-12-10 20:32:47

page.date: 1672598362227

why this happen, and how to solve it?

I found the same problem also happen in other variable display related the date, such as page.updated.


问:
Gradient boosting provides constant forecast values
I am trying to forecast a time series using the machine learning method gradient boosting in R but I am facing an issue.

I have separated the data into a training set (75 obs) and a test set (17 obs) and fitted a XGB model using the caret package. When I compare the plots of my predicted values against real values, I obtain something I would say acceptable. However, the issue happens when I try to forecast for the next 12 quarters, the model keeps returning me constant forecast values, which is basically a perfectly horizontal line when plotting.

First of all, I am totally aware that I should not expect great results as I only have 92 observations and 10 independent variables but that is what we were provided with for this work. Is it normal to only have a constant value though?

Here is my code to see if I did something wrong:

```<code>#Load data
a = diff(log(UnempRate$LRUN64TTBEQ156S))
b = diff(log(GDP$CPMNACSCAB1GQBE))
c = diff(log(URateUS$UNRATE))
d = diff(log(AirT$PCU481481))
e = diff(log(DGoods$PITGCD02BEQ661N))
f = diff(log(GCredit$QBEGAMUSDA))
g = diff(log(HWage$LCWRMN01BEQ661N))
h = diff(log(Sales$SLRTTO02BEQ661S))
i = diff(log(ActRate$LRAC64TTBEQ156S))
j = diff(log(Imports$Imports))
k = diff(log(Exports$XTEXVA01BEM667S))

dset2 = data.frame(a,b,c, d,e,f,g,h,i,j,k)
</code>```

Then I did this to create a partition

```<code>#Split data
train = head(dset2,75)
test = dset2[76:92, ]
</code>```

I tuned my XGB model, I am trying to forecast the variable a

```<code>#XGBoost
grid_tune = expand.grid(nrounds = 1000, max_depth = 8, eta = 0.1, gamma = 0.00, colsample_bytree = 1, min_child_weight = 1, subsample = 1)

train_control = trainControl(method = "cv", number = 3, verboseIter = TRUE, allowParallel = TRUE)

xgb_tune = caret::train(x = train[, -1], y = train[,1], trControl = train_control, tuneGrid = grid_tune, method = "xgbTree", verbose = TRUE)
</code>```

And then I run my test on the test set

```<code>xgb_pred = predict(xgb_tune, test)
ts.plot(test$a, xlab = "Quarters 76 to 92", ylab = "Diff(log()) value", main = "XGB predictions on testing data", col = "#009999")
lines(xgb_pred, col = "red")
</code>```

For which I obtain something, as I said, acceptable but not great:

Where the blue line is the actual values and the red line the predicted ones

What I did then to forecast is that I added 12 empty rows to my current data frame to use them as newdata for predict() function and I put my whole 92 observations as a training set:

```<code>empty_df <- data.frame(matrix(nrow = 12, ncol = 11))
colnames(empty_df) <- c("a","b","c","d","e","f","g","h","i","j","k")
dset3 = rbind(dset2, empty_df)
train2 = head(dset3, 92)
test2 = dset3[93: 104, ]
newtime <- data.frame(Time = seq(93,104, by = 1))
</code>```

I tuned the model:

```<code>grid_tune = expand.grid(nrounds = 1000, max_depth = 8, eta = 0.1, gamma = 0.00, colsample_bytree = 1, min_child_weight = 1, subsample = 1)

train_control = trainControl(method = "cv", number = 3, verboseIter = TRUE, allowParallel = TRUE)

xgb_tune = caret::train(x = train2[, -1], y = train2[,1], trControl = train_control, tuneGrid = grid_tune, method = "xgbTree", verbose = TRUE)
</code>```

And when I predict the 12 empty rows I get the following:

```<code>xgb_pred = predict(xgb_tune, test2)
</code>```

Results:

```<code>[1] 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851
</code>```

What did I do wrong? I know that my code is certainly not optimised as I am only a beginner but I really don't understand why I get a constant value. Thanks !

Body:
I am trying to forecast a time series using the machine learning method gradient boosting in R but I am facing an issue.

I have separated the data into a training set (75 obs) and a test set (17 obs) and fitted a XGB model using the caret package. When I compare the plots of my predicted values against real values, I obtain something I would say acceptable. However, the issue happens when I try to forecast for the next 12 quarters, the model keeps returning me constant forecast values, which is basically a perfectly horizontal line when plotting.

First of all, I am totally aware that I should not expect great results as I only have 92 observations and 10 independent variables but that is what we were provided with for this work. Is it normal to only have a constant value though?

Here is my code to see if I did something wrong:

#Load data
a = diff(log(UnempRate$LRUN64TTBEQ156S))
b = diff(log(GDP$CPMNACSCAB1GQBE))
c = diff(log(URateUS$UNRATE))
d = diff(log(AirT$PCU481481))
e = diff(log(DGoods$PITGCD02BEQ661N))
f = diff(log(GCredit$QBEGAMUSDA))
g = diff(log(HWage$LCWRMN01BEQ661N))
h = diff(log(Sales$SLRTTO02BEQ661S))
i = diff(log(ActRate$LRAC64TTBEQ156S))
j = diff(log(Imports$Imports))
k = diff(log(Exports$XTEXVA01BEM667S))

dset2 = data.frame(a,b,c, d,e,f,g,h,i,j,k)

Then I did this to create a partition

#Split data
train = head(dset2,75)
test = dset2[76:92, ]

I tuned my XGB model, I am trying to forecast the variable a

#XGBoost
grid_tune = expand.grid(nrounds = 1000, max_depth = 8, eta = 0.1, gamma = 0.00, colsample_bytree = 1, min_child_weight = 1, subsample = 1)

train_control = trainControl(method = "cv", number = 3, verboseIter = TRUE, allowParallel = TRUE)

xgb_tune = caret::train(x = train[, -1], y = train[,1], trControl = train_control, tuneGrid = grid_tune, method = "xgbTree", verbose = TRUE)

And then I run my test on the test set

xgb_pred = predict(xgb_tune, test)
ts.plot(test$a, xlab = "Quarters 76 to 92", ylab = "Diff(log()) value", main = "XGB predictions on testing data", col = "#009999")
lines(xgb_pred, col = "red")

For which I obtain something, as I said, acceptable but not great:

Where the blue line is the actual values and the red line the predicted ones

What I did then to forecast is that I added 12 empty rows to my current data frame to use them as newdata for predict() function and I put my whole 92 observations as a training set:

empty_df <- data.frame(matrix(nrow = 12, ncol = 11))
colnames(empty_df) <- c("a","b","c","d","e","f","g","h","i","j","k")
dset3 = rbind(dset2, empty_df)
train2 = head(dset3, 92)
test2 = dset3[93: 104, ]
newtime <- data.frame(Time = seq(93,104, by = 1))

I tuned the model:

grid_tune = expand.grid(nrounds = 1000, max_depth = 8, eta = 0.1, gamma = 0.00, colsample_bytree = 1, min_child_weight = 1, subsample = 1)

train_control = trainControl(method = "cv", number = 3, verboseIter = TRUE, allowParallel = TRUE)

xgb_tune = caret::train(x = train2[, -1], y = train2[,1], trControl = train_control, tuneGrid = grid_tune, method = "xgbTree", verbose = TRUE)

And when I predict the 12 empty rows I get the following:

xgb_pred = predict(xgb_tune, test2)

Results:

[1] 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851 0.0709851

What did I do wrong? I know that my code is certainly not optimised as I am only a beginner but I really don't understand why I get a constant value. Thanks !


问:
Database Schema Design for Chat Application using Cassandra (Private and Group Messaging)
I am currently learning Cassandra, and I am having difficulty coming up with a good database design that allows for private and group messaging and a message inbox.

In terms of domain, I suppose it should work closely with how chat applications do; an inbox shows a list of available chats where a user has exchanged messages (either with a different user or a group of users). To keep things simple, when a user joins a group, they should be able to view the whole chat history.

For these use cases, I have the following access patterns:

Find all inboxes by user_id ORDERED by TIMEUUID

Find all messages between two users; or a user and a group ORDERED by TIMEUUID

Find all groups by user_id

I have designed the following tables to support these:

-- Query find messages between two users or between a user and a group
-- SELECT * FROM chat.messages WHERE from = "1234" and to = "4321";
CREATE TABLE IF NOT EXISTS chat.messages (
  message_id TIMEUUID,
  from UUID, // user_id
  to UUID, // user_id or group_id
  message TEXT,
  created_at TIMESTAMP,
  PRIMARY KEY ((from, to), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

-- Query to find all groups by user_id
-- SELECT * FROM chat.groups_by_user WHERE user_id = "1234";
CREATE TABLE IF NOT EXISTS chat.groups_by_user_id (
  user_id UUID,
  group_id UUID,
  group_name TEXT,
  created_at TIMESTAMP,
  PRIMARY KEY ((user_id, group_id))
);

// Query to find all inboxes by user_id
CREATE TABLE IF NOT EXISTS chat.inbox_by_user_id (
    user_id UUID,
    inbox_id UUID, // Can be user_id or group_id
    name TEXT, // Can be concatenation of user first_name and last_name; or group_name
    last_message TEXT, // To show the last message thumbnail
    last_message_created_at TIMEUUID, // To sort the inbox
    PRIMARY KEY ((user_id, inbox_id), last_message_created_at)
) WITH CLUSTERING ORDER BY (last_message_created_at DESC);
```

I have thought about creating a group_messages table that could be queried by group_id, but I was wondering if I could get away from it with the design above.

I have looked up some possible solutions in StackOverflow. Still, most use cases only support private and not group messaging or are relational.

I appreciate any help you can provide.

Body:
I am currently learning Cassandra, and I am having difficulty coming up with a good database design that allows for private and group messaging and a message inbox.

In terms of domain, I suppose it should work closely with how chat applications do; an inbox shows a list of available chats where a user has exchanged messages (either with a different user or a group of users). To keep things simple, when a user joins a group, they should be able to view the whole chat history.

For these use cases, I have the following access patterns:

Find all inboxes by user_id ORDERED by TIMEUUID

Find all messages between two users; or a user and a group ORDERED by TIMEUUID

Find all groups by user_id

I have designed the following tables to support these:

-- Query find messages between two users or between a user and a group
-- SELECT * FROM chat.messages WHERE from = "1234" and to = "4321";
CREATE TABLE IF NOT EXISTS chat.messages (
  message_id TIMEUUID,
  from UUID, // user_id
  to UUID, // user_id or group_id
  message TEXT,
  created_at TIMESTAMP,
  PRIMARY KEY ((from, to), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

-- Query to find all groups by user_id
-- SELECT * FROM chat.groups_by_user WHERE user_id = "1234";
CREATE TABLE IF NOT EXISTS chat.groups_by_user_id (
  user_id UUID,
  group_id UUID,
  group_name TEXT,
  created_at TIMESTAMP,
  PRIMARY KEY ((user_id, group_id))
);

// Query to find all inboxes by user_id
CREATE TABLE IF NOT EXISTS chat.inbox_by_user_id (
    user_id UUID,
    inbox_id UUID, // Can be user_id or group_id
    name TEXT, // Can be concatenation of user first_name and last_name; or group_name
    last_message TEXT, // To show the last message thumbnail
    last_message_created_at TIMEUUID, // To sort the inbox
    PRIMARY KEY ((user_id, inbox_id), last_message_created_at)
) WITH CLUSTERING ORDER BY (last_message_created_at DESC);

I have thought about creating a group_messages table that could be queried by group_id, but I was wondering if I could get away from it with the design above.

I have looked up some possible solutions in StackOverflow. Still, most use cases only support private and not group messaging or are relational.

I appreciate any help you can provide.


问:
Compare 2 large excel spreadsheets for changes
I receive a large Excel spreadsheet (10K rows) weekly and need to compare the previous with the new to identify any changes and/or new data.  What is the easiest way to do this?  I do not have Spreadsheet Compare from Excel Professional.</p>


问:
Is there a way to use R Fable with Spark?
I've successfully built a pipeline for hierarchial time-series forecasting using the fable package. For now I've used multicore function from the future pacakge (in Databricks). And, for ~1k time series the runtime isn't too bad. Below is the code I have for that.

```<code>plan(multicore, workers = 14)
model_multicore_log_exts <- data_for_modeling %>%
    model(
          prophetML_additive_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "additive")),
          prophetML_multiplicative_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "multiplicative")),
          nn = NNETAR(log(dependent_variable) ~ trend() + season() + exogenous_var1 + exogenous_var2 + exogenous_var3, n_networks = 50)
          )
</code>```

But, I have the need for increasing that number substantially.

So, I'm wondering if there is a way to distribute with sparkr. I cannot find anything in the fable CRAN documentation nor anything with a google search, so I am asking here.

Any suggestions/advice appreciated.

Thank you,
Brian

Body:
I've successfully built a pipeline for hierarchial time-series forecasting using the fable package. For now I've used multicore function from the future pacakge (in Databricks). And, for ~1k time series the runtime isn't too bad. Below is the code I have for that.

plan(multicore, workers = 14)
model_multicore_log_exts <- data_for_modeling %>%
    model(
          prophetML_additive_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "additive")),
          prophetML_multiplicative_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "multiplicative")),
          nn = NNETAR(log(dependent_variable) ~ trend() + season() + exogenous_var1 + exogenous_var2 + exogenous_var3, n_networks = 50)
          )

But, I have the need for increasing that number substantially.

So, I'm wondering if there is a way to distribute with sparkr. I cannot find anything in the fable CRAN documentation nor anything with a google search, so I am asking here.

Any suggestions/advice appreciated.

Thank you,
Brian


问:
How can we submit multi-node jobs?
I want to submit a job on multi-node.

I was using qsub -pe <some-parallel-environment> <slots-number> jobsleep.sh

Not sure that it's the correct way.

Title: How can we submit multi-node jobs?


问:
VSCode - StandardJs - GitIgnore
as I well understand, StandardJs automatically excludes folders whose are in the .gitignore file.
Is-it possible to change that ? Or force standardjs to include certain directories ?

My project is composed by multiples git projects, so at the root folder I have a gitignore file that permits to only watch for the root projet and each sub project has its own gitignore file.
But with standardjs, it's impossible to format my subproject ! This is due to the .gitignore at the root folder.

Best regards
Sylvain

Title: VSCode - StandardJs - GitIgnore


问:
Transformers BERT model from_pt_True error with from_pt=True in code
I'm trying to get someone else's code to run on my machine (new to machine learning too) and running into an issue where this code

```<code>import transformers as trf
bert = trf.TFBertModel.from_pretrained('BERT Model/possip_model', from_pt=True)
</code>```

is generating this error

```<code>OSError: Error no file named tf_model.h5 found in directory BERT Model/possip_model but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those weights.
</code>```

There is a .json file in the folder it is referencing with PyTorch weights so I don't know why there is an error saying from_pt=True is needed when it is being used in the code. Nothing I've found online has been helpful.

Body:
I'm trying to get someone else's code to run on my machine (new to machine learning too) and running into an issue where this code

import transformers as trf
bert = trf.TFBertModel.from_pretrained('BERT Model/possip_model', from_pt=True)

is generating this error

OSError: Error no file named tf_model.h5 found in directory BERT Model/possip_model but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those weights.

There is a .json file in the folder it is referencing with PyTorch weights so I don't know why there is an error saying from_pt=True is needed when it is being used in the code. Nothing I've found online has been helpful.


问:
Why object required error is showing in vbscript?
I am using vbscript for automating excel. I know to use excel i need to create object of Excel application.
I have created an object of Excel but still its throwing an error Object required.

Error picture
Object required Error

Here's my code :

```<code>setInputPath = "C:\Users\pr.ch\Desktop\Blank_Process\Data\"
'setInputPath = Wscript.Arguments(0)

'YESTERDAY DATE -------------------------------------------------------------------------
yesterday = DateAdd("d", -1, Date())
sp = split(yesterday,"/")

d = sp(1)
m = sp(0)
y = sp(2)
if Len(d)= 1 Then
    d = "0" & d
End if

m = MonthName(m, True)

todayDateAsFolder = d & "-" & m & "-" & y

FileName = setInputPath & "Output\" & todayDateAsFolder & ".xlsx"
pathCBS = setInputPath & "Input\Makuri\" & todayDateAsFolder & ".xlsx"
pathIB = setInputPath & "Input\iBank\" & todayDateAsFolder & ".xlsx"
pathMM = setInputPath & "Input\MobileMoney\" & todayDateAsFolder & ".xlsx"
Set xl = CreateObject("Excel.Application")

xl.Visible = True
Set wb = xl.Workbooks.Open(FileName)
Set ws = wb.WorkSheets("CBS")
Set wsiBank = wb.WorkSheets("iBank")
Set wsMobM = wb.WorkSheets("MM")

Set zz = xl.Workbooks.Open(pathCBS)
Set wsCBS = zz.Worksheets(1)

Set wbIB = xl.Workbooks.open(pathIB)
Set wsIB = wbIB.worksheets(1)

Set wbMM = xl.Workbooks.open(pathMM)
Set wsMM = wbMM.worksheets(1)

'Count CBS totalRows and totalColumn-------------------------------------------------------------
totalRowsCBS = wsCBS.UsedRange.Rows.Count
totalColCBS = wsCBS.usedRange.Columns.Count
wsCBS.Range("A1:" & Chr(totalColCBS + 64) & totalRowsCBS).Copy
ws.Range("A1").PasteSpecial

'Count IBANK toalRows and totalColumn ----------------------------------------------------------
totalRowsIB = wsIB.UsedRange.Rows.Count
totalColIB = wsIB.usedRange.Columns.Count
wsIB.Range("A1:" & Chr(totalColIB + 64) & totalRowsIB).Copy
wsiBank.Range("A1").PasteSpecial

'Count MM toalRows and totalColumn --------------------------------------------------------------
totalRowsMM = wsMM.UsedRange.Rows.Count
totalColMM = wsMM.usedRange.Columns.Count
wsMM.Range("A1:" & Chr(totalColMM + 64) & totalRowsMM).Copy
wsMobM.Range("A1").PasteSpecial

wb.Save
wb.Close
xl.Quit

'msgbox "Completed 06"
</code>```

I tried creating new excel object for every sheets that i am working on which is working but not as expected. I am using VBs from 3 months never ever i encountered this error.

Body:
I am using vbscript for automating excel. I know to use excel i need to create object of Excel application.
I have created an object of Excel but still its throwing an error Object required.

Error picture
Object required Error

Here's my code :

setInputPath = "C:\Users\pr.ch\Desktop\Blank_Process\Data\"
'setInputPath = Wscript.Arguments(0)

'YESTERDAY DATE -------------------------------------------------------------------------
yesterday = DateAdd("d", -1, Date())
sp = split(yesterday,"/")

d = sp(1)
m = sp(0)
y = sp(2)
if Len(d)= 1 Then
    d = "0" & d
End if

m = MonthName(m, True)

todayDateAsFolder = d & "-" & m & "-" & y

FileName = setInputPath & "Output\" & todayDateAsFolder & ".xlsx"
pathCBS = setInputPath & "Input\Makuri\" & todayDateAsFolder & ".xlsx"
pathIB = setInputPath & "Input\iBank\" & todayDateAsFolder & ".xlsx"
pathMM = setInputPath & "Input\MobileMoney\" & todayDateAsFolder & ".xlsx"
Set xl = CreateObject("Excel.Application")

xl.Visible = True
Set wb = xl.Workbooks.Open(FileName)
Set ws = wb.WorkSheets("CBS")
Set wsiBank = wb.WorkSheets("iBank")
Set wsMobM = wb.WorkSheets("MM")

Set zz = xl.Workbooks.Open(pathCBS)
Set wsCBS = zz.Worksheets(1)

Set wbIB = xl.Workbooks.open(pathIB)
Set wsIB = wbIB.worksheets(1)

Set wbMM = xl.Workbooks.open(pathMM)
Set wsMM = wbMM.worksheets(1)

'Count CBS totalRows and totalColumn-------------------------------------------------------------
totalRowsCBS = wsCBS.UsedRange.Rows.Count
totalColCBS = wsCBS.usedRange.Columns.Count
wsCBS.Range("A1:" & Chr(totalColCBS + 64) & totalRowsCBS).Copy
ws.Range("A1").PasteSpecial

'Count IBANK toalRows and totalColumn ----------------------------------------------------------
totalRowsIB = wsIB.UsedRange.Rows.Count
totalColIB = wsIB.usedRange.Columns.Count
wsIB.Range("A1:" & Chr(totalColIB + 64) & totalRowsIB).Copy
wsiBank.Range("A1").PasteSpecial

'Count MM toalRows and totalColumn --------------------------------------------------------------
totalRowsMM = wsMM.UsedRange.Rows.Count
totalColMM = wsMM.usedRange.Columns.Count
wsMM.Range("A1:" & Chr(totalColMM + 64) & totalRowsMM).Copy
wsMobM.Range("A1").PasteSpecial

wb.Save
wb.Close
xl.Quit

'msgbox "Completed 06"

I tried creating new excel object for every sheets that i am working on which is working but not as expected. I am using VBs from 3 months never ever i encountered this error.