问:
How do I create separate buttons in a pygame loop?
I am trying to develop a Keno-style game within pygame but instead of creating 80 separate buttons, I was trying to make them in a loop.

I've attached the button loop as well as the button-generating loop.

```<code>def button(self, msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    # print(click)
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(self.gameDisplay, ac, (x, y, w, h))
        if click[0] == 1 and action is not None:
            action()
    else:
        pygame.draw.rect(self.gameDisplay, ic, (x, y, w, h))
    smallText = pygame.font.SysFont("calibri", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    self.gameDisplay.blit(textSurf, textRect)
</code>```
```<code>def button_gen(self):
    x_val = 100
    y_val = 100
    num = 1

    for i in range (100):
        while y_val <= 800:
            while x_val <= 1000:
                self.button(f"{num}", 100, 100, x_val, y_val, green, bright_green, self.exitGame)
                num += 1
                x_val += 100
            x_val = 100
            y_val += 100
</code>```

My code displays one giant 1000 x 800 (the width and height of the entire button grid) button labelled '80'. Instead, I wish the loop should create 80 separate different buttons (labelled 1 to 80), set up in a 1000 x 800 grid.

Body:
I am trying to develop a Keno-style game within pygame but instead of creating 80 separate buttons, I was trying to make them in a loop.

I've attached the button loop as well as the button-generating loop.

def button(self, msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    # print(click)
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(self.gameDisplay, ac, (x, y, w, h))
        if click[0] == 1 and action is not None:
            action()
    else:
        pygame.draw.rect(self.gameDisplay, ic, (x, y, w, h))
    smallText = pygame.font.SysFont("calibri", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    self.gameDisplay.blit(textSurf, textRect)

def button_gen(self):
    x_val = 100
    y_val = 100
    num = 1

    for i in range (100):
        while y_val <= 800:
            while x_val <= 1000:
                self.button(f"{num}", 100, 100, x_val, y_val, green, bright_green, self.exitGame)
                num += 1
                x_val += 100
            x_val = 100
            y_val += 100

My code displays one giant 1000 x 800 (the width and height of the entire button grid) button labelled '80'. Instead, I wish the loop should create 80 separate different buttons (labelled 1 to 80), set up in a 1000 x 800 grid.


来源: stackexchange

问:
How to call api in NotificationServiceExtension?
How to call api NotificationServiceExtension Android and similar in IOS ?

when notification is received i want to check the condition based on api call response

```<code>package com.example.app

import android.content.Context import com.onesignal.OSNotificationReceivedEvent import com.onesignal.OneSignal import android.app.Notification import android.R import androidx.core.app.NotificationCompat import android.content.SharedPreferences import android.util.Log

class NotificationServiceExtension : OneSignal.OSRemoteNotificationReceivedHandler {
    override fun remoteNotificationReceived( context: Context,notificationReceivedEvent: OSNotificationReceivedEvent
    ) {
        val notification = notificationReceivedEvent.notification
        val mutableNotification = notification.mutableCopy()

        //call api here and check condition

        notificationReceivedEvent.complete(mutableNotification)

    } }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to call api NotificationServiceExtension Android and similar in IOS ?

when notification is received i want to check the condition based on api call response

package com.example.app

import android.content.Context import com.onesignal.OSNotificationReceivedEvent import com.onesignal.OneSignal import android.app.Notification import android.R import androidx.core.app.NotificationCompat import android.content.SharedPreferences import android.util.Log

class NotificationServiceExtension : OneSignal.OSRemoteNotificationReceivedHandler {
    override fun remoteNotificationReceived( context: Context,notificationReceivedEvent: OSNotificationReceivedEvent
    ) {
        val notification = notificationReceivedEvent.notification
        val mutableNotification = notification.mutableCopy()

        //call api here and check condition

        notificationReceivedEvent.complete(mutableNotification)

    } }


问:
How to quit mobile driver session in parallel execution - testng in Browserstack
I am working on TestNG framework which is integrated with Browserstack for Mobile automation.
The framework behaved very well until we were running a single thread in browser stack for our test execution.
The problem actually started when we integrated parallel execution. Our framework has a json file where we define all the device capabilities and call them for execution. Example is given below:

```<code>  "about": {
    "project": "Demo-DexAutomation",
    "team": "QE",
    "environment": "QA",
    "releaseVersion": "1.0"
  },
  "gui": {
    "ss:remoteExecutor": {
      "browserstack": {
        "ss:remoteAddress": "http://hub-cloud.browserstack.com/wd/hub",
        "browserstack.user": “<Username>”,
        "browserstack.key": “<access key>“
      }
    },
    "defaultProfile": "browserstack-oneplus-7T",
    "multiProfile": [
      "browserstack-samsung-galaxy-s21-plus",
      "browserstack-oneplus-7T",
      "browserstack-google-pixel-4"
    ],
    "randomProfile": [
      "browserstack-samsung-galaxy-s21-plus",
      "browserstack-google-pixel-4",
      "browserstack-oneplus-7T"
    ],
   "browserstack-samsung-galaxy-s21-plus": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "Samsung Galaxy S21 Plus",
        "os_version": "11.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "Samsung Galaxy S21 Plus Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
      "browserstack-google-pixel-4": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "Google Pixel 4",
        "os_version": "10.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "Google Pixel 4 Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
      "browserstack-oneplus-7T": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "OnePlus 7T",
        "os_version": "10.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "One plus 7T Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
    }
  },
  "dashboard": {
    "url": "http://localhost:4000",
    "disabled": true
  }
}
</code>```

Now, We use RandomProfile from above json for running testcases. And the code will actually select random profile based on the availability of the device in the browserstack. We can also use Default profile and multiProfile.

Random profile -> selects differ devices for each test case picked for execution

Default profile -> calls the single device added to the profile for all testcases

multi profile -> runs each testcase in every device mentioned under the profile.

While running TestNG execution in Parallel, the driver quit does not work properly. Calling quit method after completing every test case inside @Test annotation, kills all the actively running session during parallel execution. Same behaviour observed when quit is called in @AfterMethod. Also tried calling driver.quit in @AfterTest and @AfterClass both does not work eventually end up in giving timeout session in browserstack.

Example of couple of testcases: - I have removed the driver.quit statement in the below code snippet, but have tried them as stated above.

```<code>    public void likeOrUnlikeAContent() {
        Profile deviceProfile = null;
        try {
            deviceProfile = singletonUtils.getUnusedRandomProfile(profile);
            SlingshotReporter.log("********************Test Case: Like or Unlike a Content Navigating from Home Page********************");
            DriverFactory.get().build(CommonUtils.setRunTimeCapability(deviceProfile, runTimeCapabilityUtils.getRuntimeCapabilities()));
            mobileDriver = DriverFactory.getDriver();
            CommonUtils.setSessionName(mobileDriver, "Like or Unlike a Content Navigating from Home Page");
            commonUtils.loginToAppWithSSO(mobileDriver, "username1", EMPLOYEE);
            HomePageFunctions homePageFunctions = new HomePageFunctions(mobileDriver);
            homePageFunctions.navigateToAltimetrikTab(CommonUtils.ScrollDirection.HORIZONTAL,CommonUtils.Direction.RIGHT);
            homePageFunctions.clickOnAltiverseCard();
            CommonUtils.scrollIntoViewIDWithDirection(mobileDriver,CommonUtils.ScrollDirection.VERTICAL,UP,"likeContent");
            Assert.assertTrue(homePageFunctions.verifyLikeButtonDisplayed());
            homePageFunctions.verifyLikeCount();
            CommonUtils.closeApp(mobileDriver);
            CommonUtils.setStatusForTestCase(mobileDriver, "Passed", "Test Execution Completed");
            singletonUtils.reAssignUsedDevices(deviceProfile.getProfileName());
        } catch (Exception e) {
            SlingshotReporter.log("-----------------Test case failed due to below error-----------------");
            CommonUtils.setStatusForTestCase(mobileDriver, "Failed", e.getMessage());
            singletonUtils.reAssignUsedDevices(Objects.requireNonNull(deviceProfile).getProfileName());
            Assert.fail(e.getMessage());
        }
    }

    @Test(groups = {"Smoke1"}, priority = 2)
    public void commentAndReplyToCommentOnAContent() {
        Profile deviceProfile = null;
        try {
            deviceProfile = singletonUtils.getUnusedRandomProfile(profile);
            SlingshotReporter.log("********************Test Case: Comment and Reply to a comment on a Content Navigating from Home "
                + "Page********************");
            DriverFactory.get().build(CommonUtils.setRunTimeCapability(deviceProfile, runTimeCapabilityUtils.getRuntimeCapabilities()));
            mobileDriver = DriverFactory.getDriver();
            CommonUtils.setSessionName(mobileDriver, "Comment and Reply to a comment on a Content Navigating from Home Page");
            commonUtils.loginToAppWithSSO(mobileDriver, "username1", EMPLOYEE);
            HomePageFunctions homePageFunctions = new HomePageFunctions(mobileDriver);
            homePageFunctions.navigateToAltimetrikTab(CommonUtils.ScrollDirection.HORIZONTAL,CommonUtils.Direction.RIGHT);
            homePageFunctions.clickOnAltiverseCard();
            CommonUtils.scrollIntoViewIDWithDirection(mobileDriver,CommonUtils.ScrollDirection.VERTICAL,UP,"commentCnt");
            homePageFunctions.commentOnAContent();
            Assert.assertTrue(homePageFunctions.verifyCommentOrReplyPosted());
            homePageFunctions.replyToAComment();
            Assert.assertTrue(homePageFunctions.verifyCommentOrReplyPosted());
            homePageFunctions.exitFromCommentDetailPage();
            CommonUtils.closeApp(mobileDriver);
            CommonUtils.setStatusForTestCase(mobileDriver, "Passed", "Test Execution Completed");
            singletonUtils.reAssignUsedDevices(deviceProfile.getProfileName());
        } catch (Exception e) {
            SlingshotReporter.log("-----------------Test case failed due to below error-----------------");
            CommonUtils.setStatusForTestCase(mobileDriver, "Failed", e.getMessage());
            singletonUtils.reAssignUsedDevices(Objects.requireNonNull(deviceProfile).getProfileName());
            Assert.fail(e.getMessage());
        }
    }
</code>```

Testng Xml looks like this:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Mobile Automation" verbose="1" thread-count="3" parallel="methods">
    <listeners>
        <listener class-name="com.altimetrik.qe.slingshot.reporter.SlingshotTestNGReporter"/>
        <listener class-name="com.altimetrik.qe.slingshot.testng.listeners.NeedsDriverListener"/>
    </listeners>

    <test name="DEX UI Tests">
        <classes>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.SmokeTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.SuccessStoryTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.EmployeeLandingTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.InnovateAndInspireTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.TweetTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.ContributorTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.ReviewerTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.CandidateLandingTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.JobOpportunitiesTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.JobDetailsPageTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.MySpaceTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.DiscoverDexTest"/>

        </classes>
    </test>
</suite>
</code>```

Kindly help me to resolve this issue, been trying every solution provided over internet, but nothing works.

Body:
I am working on TestNG framework which is integrated with Browserstack for Mobile automation.
The framework behaved very well until we were running a single thread in browser stack for our test execution.
The problem actually started when we integrated parallel execution. Our framework has a json file where we define all the device capabilities and call them for execution. Example is given below:

  "about": {
    "project": "Demo-DexAutomation",
    "team": "QE",
    "environment": "QA",
    "releaseVersion": "1.0"
  },
  "gui": {
    "ss:remoteExecutor": {
      "browserstack": {
        "ss:remoteAddress": "http://hub-cloud.browserstack.com/wd/hub",
        "browserstack.user": “<Username>”,
        "browserstack.key": “<access key>“
      }
    },
    "defaultProfile": "browserstack-oneplus-7T",
    "multiProfile": [
      "browserstack-samsung-galaxy-s21-plus",
      "browserstack-oneplus-7T",
      "browserstack-google-pixel-4"
    ],
    "randomProfile": [
      "browserstack-samsung-galaxy-s21-plus",
      "browserstack-google-pixel-4",
      "browserstack-oneplus-7T"
    ],
   "browserstack-samsung-galaxy-s21-plus": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "Samsung Galaxy S21 Plus",
        "os_version": "11.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "Samsung Galaxy S21 Plus Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
      "browserstack-google-pixel-4": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "Google Pixel 4",
        "os_version": "10.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "Google Pixel 4 Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
      "browserstack-oneplus-7T": {
        "ss:remoteExecutor": "browserstack",
        "platformName": "Android",
        "app": "bs://fbac93a34795331e12e3949ac65d120e73422217",
        "automationName": "UiAutomator2",
        "device": "OnePlus 7T",
        "os_version": "10.0",
        "project": "Android Automation",
        "build": "DEX Android Smoke Execution",
        "name": "One plus 7T Tests",
        "browserstack.networkLogs": true,
        "autoGrantPermissions": "true",
        "autoAcceptAlerts": "true",
        "acceptInsecureCerts": true,
        "acceptSslCert" : true
      },
    }
  },
  "dashboard": {
    "url": "http://localhost:4000",
    "disabled": true
  }
}

Now, We use RandomProfile from above json for running testcases. And the code will actually select random profile based on the availability of the device in the browserstack. We can also use Default profile and multiProfile.

Random profile -> selects differ devices for each test case picked for execution

Default profile -> calls the single device added to the profile for all testcases

multi profile -> runs each testcase in every device mentioned under the profile.

While running TestNG execution in Parallel, the driver quit does not work properly. Calling quit method after completing every test case inside @Test annotation, kills all the actively running session during parallel execution. Same behaviour observed when quit is called in @AfterMethod. Also tried calling driver.quit in @AfterTest and @AfterClass both does not work eventually end up in giving timeout session in browserstack.

Example of couple of testcases: - I have removed the driver.quit statement in the below code snippet, but have tried them as stated above.

    public void likeOrUnlikeAContent() {
        Profile deviceProfile = null;
        try {
            deviceProfile = singletonUtils.getUnusedRandomProfile(profile);
            SlingshotReporter.log("********************Test Case: Like or Unlike a Content Navigating from Home Page********************");
            DriverFactory.get().build(CommonUtils.setRunTimeCapability(deviceProfile, runTimeCapabilityUtils.getRuntimeCapabilities()));
            mobileDriver = DriverFactory.getDriver();
            CommonUtils.setSessionName(mobileDriver, "Like or Unlike a Content Navigating from Home Page");
            commonUtils.loginToAppWithSSO(mobileDriver, "username1", EMPLOYEE);
            HomePageFunctions homePageFunctions = new HomePageFunctions(mobileDriver);
            homePageFunctions.navigateToAltimetrikTab(CommonUtils.ScrollDirection.HORIZONTAL,CommonUtils.Direction.RIGHT);
            homePageFunctions.clickOnAltiverseCard();
            CommonUtils.scrollIntoViewIDWithDirection(mobileDriver,CommonUtils.ScrollDirection.VERTICAL,UP,"likeContent");
            Assert.assertTrue(homePageFunctions.verifyLikeButtonDisplayed());
            homePageFunctions.verifyLikeCount();
            CommonUtils.closeApp(mobileDriver);
            CommonUtils.setStatusForTestCase(mobileDriver, "Passed", "Test Execution Completed");
            singletonUtils.reAssignUsedDevices(deviceProfile.getProfileName());
        } catch (Exception e) {
            SlingshotReporter.log("-----------------Test case failed due to below error-----------------");
            CommonUtils.setStatusForTestCase(mobileDriver, "Failed", e.getMessage());
            singletonUtils.reAssignUsedDevices(Objects.requireNonNull(deviceProfile).getProfileName());
            Assert.fail(e.getMessage());
        }
    }

    @Test(groups = {"Smoke1"}, priority = 2)
    public void commentAndReplyToCommentOnAContent() {
        Profile deviceProfile = null;
        try {
            deviceProfile = singletonUtils.getUnusedRandomProfile(profile);
            SlingshotReporter.log("********************Test Case: Comment and Reply to a comment on a Content Navigating from Home "
                + "Page********************");
            DriverFactory.get().build(CommonUtils.setRunTimeCapability(deviceProfile, runTimeCapabilityUtils.getRuntimeCapabilities()));
            mobileDriver = DriverFactory.getDriver();
            CommonUtils.setSessionName(mobileDriver, "Comment and Reply to a comment on a Content Navigating from Home Page");
            commonUtils.loginToAppWithSSO(mobileDriver, "username1", EMPLOYEE);
            HomePageFunctions homePageFunctions = new HomePageFunctions(mobileDriver);
            homePageFunctions.navigateToAltimetrikTab(CommonUtils.ScrollDirection.HORIZONTAL,CommonUtils.Direction.RIGHT);
            homePageFunctions.clickOnAltiverseCard();
            CommonUtils.scrollIntoViewIDWithDirection(mobileDriver,CommonUtils.ScrollDirection.VERTICAL,UP,"commentCnt");
            homePageFunctions.commentOnAContent();
            Assert.assertTrue(homePageFunctions.verifyCommentOrReplyPosted());
            homePageFunctions.replyToAComment();
            Assert.assertTrue(homePageFunctions.verifyCommentOrReplyPosted());
            homePageFunctions.exitFromCommentDetailPage();
            CommonUtils.closeApp(mobileDriver);
            CommonUtils.setStatusForTestCase(mobileDriver, "Passed", "Test Execution Completed");
            singletonUtils.reAssignUsedDevices(deviceProfile.getProfileName());
        } catch (Exception e) {
            SlingshotReporter.log("-----------------Test case failed due to below error-----------------");
            CommonUtils.setStatusForTestCase(mobileDriver, "Failed", e.getMessage());
            singletonUtils.reAssignUsedDevices(Objects.requireNonNull(deviceProfile).getProfileName());
            Assert.fail(e.getMessage());
        }
    }

Testng Xml looks like this:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Mobile Automation" verbose="1" thread-count="3" parallel="methods">
    <listeners>
        <listener class-name="com.altimetrik.qe.slingshot.reporter.SlingshotTestNGReporter"/>
        <listener class-name="com.altimetrik.qe.slingshot.testng.listeners.NeedsDriverListener"/>
    </listeners>

    <test name="DEX UI Tests">
        <classes>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.SmokeTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.SuccessStoryTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.EmployeeLandingTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.InnovateAndInspireTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.TweetTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.ContributorTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.ReviewerTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.CandidateLandingTest"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.JobOpportunitiesTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.JobDetailsPageTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.MySpaceTests"/>
            <class name="com.altimetrik.pp.dexapp.mobileAutomation.DiscoverDexTest"/>

        </classes>
    </test>
</suite>

Kindly help me to resolve this issue, been trying every solution provided over internet, but nothing works.


问:
Is there a way to change data using SPARQL?
I want to change the data in my triple store using SPARQL. Is DELETE and INSERT the only way?</p>


问:
Node - Migrate postgres DB programmatically using jest globalsetup.js file
I am trying to use testcontainers(https://github.com/testcontainers/testcontainers-node/tree/master/src/modules/postgresql) to spin up a postgres db and use that to run my jest tests.
I used globalsetup.js file to run the container spinup code. The container is spinning successfully, no problem in that, but the issue arises when i try to migrate the db. For Migrating i use typeorm's connection.runMigrations function. Somehow the migration is not working.
All my files, except globalsetup.js is a typescript file.

My connection string looks like this:

```<code>createConnection({
    url: `postgres://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}`
    entities: process.env.TYPEORM_ENTITIES.split(‘,’),
    migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
    type: 'postgres,
  });
</code>```

TYPEORM_ENTITIES=src/db/entities/**/.ts
TYPEORM_MIGRATIONS=src/db/migrations/.ts

and in my jest.globalSetup.js:

```<code>const {createConnection} = require('typeorm')
module.exports = async () => {
/* Code for Container Startup */

   process.env.NODE_ENV = ‘test’;
   const connection = await createConnection({
     url: `postgres://uno-test:dia@localhost:${process.env.TYPEORM_PORT}/cart-test?sslmode=disable`,
     entities: process.env.TYPEORM_ENTITIES.split(‘,’),
     migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
     type: ‘postgres’,
   });

   await connection
     .runMigrations()
     .then((value) => console.log(‘Migration Done’, value))
    .catch((e) => console.log(e));

  await connection
           .close()
};
</code>```

Error Message is:

```<code>import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from ‘typeorm’;
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at /Users/webmaster/CART/cart-portal-service/node_modules/typeorm/util/ImportUtils.js:29:52
    at step (/Users/webmaster/CART/cart-portal-service/node_modules/tslib/tslib.js:144:27)
</code>```

I tried changing the entities and migrations constants to
TYPEORM_ENTITIES=src/db/entities/**/.{ts,js}
TYPEORM_MIGRATIONS=src/db/migrations/.{ts,js}

If i do above chagne, I no longer see the error, but my db is empty as in no tables are created.

Versions:
Node - 16.6.0
Typeorm - 0.2.45
typescript: 4.7.4
jest: 28.1.3

Body:
I am trying to use testcontainers(https://github.com/testcontainers/testcontainers-node/tree/master/src/modules/postgresql) to spin up a postgres db and use that to run my jest tests.
I used globalsetup.js file to run the container spinup code. The container is spinning successfully, no problem in that, but the issue arises when i try to migrate the db. For Migrating i use typeorm's connection.runMigrations function. Somehow the migration is not working.
All my files, except globalsetup.js is a typescript file.

My connection string looks like this:

createConnection({
    url: `postgres://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}`
    entities: process.env.TYPEORM_ENTITIES.split(‘,’),
    migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
    type: 'postgres,
  });

TYPEORM_ENTITIES=src/db/entities/**/.ts
TYPEORM_MIGRATIONS=src/db/migrations/.ts

and in my jest.globalSetup.js:

const {createConnection} = require('typeorm')
module.exports = async () => {
/* Code for Container Startup */

   process.env.NODE_ENV = ‘test’;
   const connection = await createConnection({
     url: `postgres://uno-test:dia@localhost:${process.env.TYPEORM_PORT}/cart-test?sslmode=disable`,
     entities: process.env.TYPEORM_ENTITIES.split(‘,’),
     migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
     type: ‘postgres’,
   });

   await connection
     .runMigrations()
     .then((value) => console.log(‘Migration Done’, value))
    .catch((e) => console.log(e));

  await connection
           .close()
};

Error Message is:

import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from ‘typeorm’;
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at /Users/webmaster/CART/cart-portal-service/node_modules/typeorm/util/ImportUtils.js:29:52
    at step (/Users/webmaster/CART/cart-portal-service/node_modules/tslib/tslib.js:144:27)

I tried changing the entities and migrations constants to
TYPEORM_ENTITIES=src/db/entities/**/.{ts,js}
TYPEORM_MIGRATIONS=src/db/migrations/.{ts,js}

If i do above chagne, I no longer see the error, but my db is empty as in no tables are created.

Versions:
Node - 16.6.0
Typeorm - 0.2.45
typescript: 4.7.4
jest: 28.1.3


问:
Vue-argon don't render any component
Browser's console image

I install and run npm run serve and running on local but the app just render nothing, in console, 'app' div doesn't contain any component. I followed the document but it's not working.

this is main.js file

```<code>import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import ArgonDashboard from './plugins/argon-dashboard';
import 'element-plus/lib/theme-chalk/index.css';

const app = createApp(App);
app.use(router);
app.use(ArgonDashboard);
app.mount('#app');
</code>```

and this is the router. file
router file image
what should i do or what can I fix for the issue

Title: Vue-argon don't render any component

Body:
Browser's console image

I install and run npm run serve and running on local but the app just render nothing, in console, 'app' div doesn't contain any component. I followed the document but it's not working.

this is main.js file

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import ArgonDashboard from './plugins/argon-dashboard';
import 'element-plus/lib/theme-chalk/index.css';

const app = createApp(App);
app.use(router);
app.use(ArgonDashboard);
app.mount('#app');

and this is the router. file
router file image
what should i do or what can I fix for the issue


问:
SignIn/SignOut with trustlogin and cognito problem
I have an app use trustlogin(https://portal.trustlogin.com/) to authenticate with amazon cognito user pool
I use this article to setup authentication: authorization-endpoint
and add it into trustlogin app
In my application, I use aws-amplify for authentication

the problem is: when I signout in my app, it work fine with aws-amplify configure, but when signout/change account in trustlogin portal, the account in my app still the previous account,even if I re-authenticate with the above endpoint(authorization-endpoint), it still doesn't work.

I have try to get accessToken after re-authenticate but user data not change


问:
Select randomly percent of datasets in each percent of epochs
I have a model that should train with 25000 data in 50000 epochs.
I want to train with the percentage of datasets for a percentage of periods
for example it trains for 10 first epochs only 1000 random data than for 10 next epochs, 1000 random data.....
My source code in part of datalogger is as follows.

```<code>class DataModule(pl.LightningDataModule):

  def __init__(self, train_dataset, val_dataset,  batch_size = 2):

    super(DataModule, self).__init__()
    self.train_dataset = train_dataset
    self.val_dataset = val_dataset
    self.batch_size = batch_size

  def train_dataloader(self):
    return DataLoader(self.train_dataset, batch_size = self.batch_size,
                      collate_fn = collate_fn, shuffle = True, num_workers = 2, pin_memory = True)

  def val_dataloader(self):
    return DataLoader(self.val_dataset, batch_size = self.batch_size,
                    collate_fn = collate_fn, shuffle = False, num_workers = 2, pin_memory = True)
</code>```

I understand below code could select random of dataset but I want to train the other data for next epochs too.

```<code>df_fraction= df_mydataset.sample(frac=0.04)
</code>```

And I understand below code could select a random dataset but I don't know how it works. Because I should change data for each 10 epochs

```<code>train_sampler = SubsetRandomSampler(train_indices)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=2, sampler=train_sampler)
</code>```

How can I do that with batch_size=2?

Body:
I have a model that should train with 25000 data in 50000 epochs.
I want to train with the percentage of datasets for a percentage of periods
for example it trains for 10 first epochs only 1000 random data than for 10 next epochs, 1000 random data.....
My source code in part of datalogger is as follows.

class DataModule(pl.LightningDataModule):

  def __init__(self, train_dataset, val_dataset,  batch_size = 2):

    super(DataModule, self).__init__()
    self.train_dataset = train_dataset
    self.val_dataset = val_dataset
    self.batch_size = batch_size

  def train_dataloader(self):
    return DataLoader(self.train_dataset, batch_size = self.batch_size,
                      collate_fn = collate_fn, shuffle = True, num_workers = 2, pin_memory = True)

  def val_dataloader(self):
    return DataLoader(self.val_dataset, batch_size = self.batch_size,
                    collate_fn = collate_fn, shuffle = False, num_workers = 2, pin_memory = True)

I understand below code could select random of dataset but I want to train the other data for next epochs too.

df_fraction= df_mydataset.sample(frac=0.04)

And I understand below code could select a random dataset but I don't know how it works. Because I should change data for each 10 epochs

train_sampler = SubsetRandomSampler(train_indices)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=2, sampler=train_sampler)

How can I do that with batch_size=2?


问:
How to create and call functions in different files using Slim resApi
I have a problem when I build resAPI from Slim. I want to separate the query that is usually written in the routes.php file, into module.php. When I split it, the function in module.php had an error when it was called in routes.php there was an error with the message ($this is undefined). is there any solution to create a separate module or model function from routes.php?

Example

//==== Model.php ====

```<code>class Stok{

    public function __construct(){
        $this->test_text = $eid;
        $this->db = $this->settings;
    }

    public function data_test($eid) {
        $sql = "SELECT * FROM `tb_barang` WHERE int_id_hidden=1 ORDER BY vc_nama_barang ASC";
        $stmt = $this->db->prepare($sql); //<= Error
        $stmt->execute(); //<= Error

        $array = array([
            'data' => $eid
        ]);
        return $array;
    }
}
</code>```

//==== Route.php ====

```<code>return function (App $app) {

    $app->get("/test", function (Request $request, Response $response, $args){
        $datanya = new Stok();
        $eid = 'contoh';

        $data = [
            'bulan' => $datanya->data_test($eid)
        ];

        return $response->withJson($data, 200);
    });
};
</code>```

Maybe there is a workaround so that route.php can call model.php which contains the query

Body:
I have a problem when I build resAPI from Slim. I want to separate the query that is usually written in the routes.php file, into module.php. When I split it, the function in module.php had an error when it was called in routes.php there was an error with the message ($this is undefined). is there any solution to create a separate module or model function from routes.php?

Example

//==== Model.php ====

class Stok{

    public function __construct(){
        $this->test_text = $eid;
        $this->db = $this->settings;
    }

    public function data_test($eid) {
        $sql = "SELECT * FROM `tb_barang` WHERE int_id_hidden=1 ORDER BY vc_nama_barang ASC";
        $stmt = $this->db->prepare($sql); //<= Error
        $stmt->execute(); //<= Error

        $array = array([
            'data' => $eid
        ]);
        return $array;
    }
}

//==== Route.php ====

return function (App $app) {

    $app->get("/test", function (Request $request, Response $response, $args){
        $datanya = new Stok();
        $eid = 'contoh';

        $data = [
            'bulan' => $datanya->data_test($eid)
        ];

        return $response->withJson($data, 200);
    });
};

Maybe there is a workaround so that route.php can call model.php which contains the query


问:
OpenAI Gym Observation Space for a list with unspecified size
I have an observation space that could be an array of any size (0,1,2,..., self.max_size) and all elements are anywhere from 1 to self.size. How can I implement this in code (which gym space can I use)?</p>


问:
CORS error occurs when accessing server-side wav file
I'm trying to load a wav file from the server but I get a CORS error. I've been wandering for 3 days without being able to solve it. Please help me..

This is the code I am trying to run. I am trying to convert wav file to blob.

```<code>var srcStr = "http://118.129.180.214:28934/campHistory/2022/12/13/14/wavFileName.wav";
fetch(srcStr)
    .then(response => response.blob())
    .then(console.log);
</code>```

http://118.129.180.214:28934/campHistory/2022/12/13/14/wavFileName.wav >> address to which the request is sent

```<code><Context path="/campHistory" docBase="/var/logs/recordings"></Context>
</code>```

The server side is using spring boot security, and the route mapping is done as follows in server.xml of tomcat, so the actually requested route is as follows.

http://118.129.180.214:28934/var/logs/recordings/2022/12/13/14/wavFileName.wav

How can I request a wav file from the server and convert it to a blob?

Access to fetch at 'http://118.129.180.214:28934/campHistory/2022/12/13/14/ymoons_20220106_171634_20221213_142729_01035510793_3747.wav' from origin 'http://localhost:8182' 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.

Since there was no Access-Control-Allow-Origin, I added the following filter on the server side and set it to allow everything.

```<code>@Component
@Order(Integer.MIN_VALUE)
public class CORSFilter implements Filter{

    private static final Logger log = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method","GET");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","*");

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
</code>```

Still getting the same error...
So, when I checked the network tab of the developer tools, the 'Access-Control-Allow-Origin' information was not included in the header despite the settings as above.

Why is that?... I don't know why there is no value in the response header when I request a wav file.

How can I request a wav file from the server and convert it to a blob?

Body:
I'm trying to load a wav file from the server but I get a CORS error. I've been wandering for 3 days without being able to solve it. Please help me..

This is the code I am trying to run. I am trying to convert wav file to blob.

var srcStr = "http://118.129.180.214:28934/campHistory/2022/12/13/14/wavFileName.wav";
fetch(srcStr)
    .then(response => response.blob())
    .then(console.log);

http://118.129.180.214:28934/campHistory/2022/12/13/14/wavFileName.wav >> address to which the request is sent

<Context path="/campHistory" docBase="/var/logs/recordings"></Context>

The server side is using spring boot security, and the route mapping is done as follows in server.xml of tomcat, so the actually requested route is as follows.

http://118.129.180.214:28934/var/logs/recordings/2022/12/13/14/wavFileName.wav

How can I request a wav file from the server and convert it to a blob?

Access to fetch at 'http://118.129.180.214:28934/campHistory/2022/12/13/14/ymoons_20220106_171634_20221213_142729_01035510793_3747.wav' from origin 'http://localhost:8182' 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.

Since there was no Access-Control-Allow-Origin, I added the following filter on the server side and set it to allow everything.

@Component
@Order(Integer.MIN_VALUE)
public class CORSFilter implements Filter{

    private static final Logger log = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method","GET");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","*");

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}

Still getting the same error...
So, when I checked the network tab of the developer tools, the 'Access-Control-Allow-Origin' information was not included in the header despite the settings as above.

Why is that?... I don't know why there is no value in the response header when I request a wav file.

How can I request a wav file from the server and convert it to a blob?


问:
How to match only property value in a nested structure using Elasticsearch 6.7
I have this structure:

and want to get the pricingbytrade for only the ones that the name matches hvac

Right now I am running this query:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "providerid": {
              "value": 13
            }
          }
        },
        {
          "nested": {
            "path": "pricingbytrade",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "pricingbytrade.name": "hvac"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "_source": {
    "includes": [
      "providerid",
      "pricingbytrade"
    ]
  }
}

```
<p>But that query returns all of them instead of only the ones with <code>hvac</code></p>
<p>I am using <strong>Elasticseach 6.7</strong> so the inner_hits does not work here.</p>
<p>And this is a section of the mapping where involve the structure:</p>
<pre class="lang-json prettyprint-override"><code> "pricingbytrade": {
            "type": "nested",
            "properties": {
              "name": {
                "type": "text",
                "fields": {
                  "analyzed": {
                    "type": "text",
                    "analyzer": "standard",
                    "search_analyzer": "synonym_analyzer"
                  },
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256,
                    "normalizer": "lowercase"
                  }
                }
              },
              "pricingbycbsa": {
                "type": "nested",
                "properties": {
                  "cbsaid": {
                    "type": "integer"
                  },
                  "cbsaname": {
                    "type": "text"
                  },
                  "pricingscore": {
                    "type": "float"
                  }
                }
              }
            }
          }
</code>```

Any suggestion??

Body:
I have this structure:

and want to get the pricingbytrade for only the ones that the name matches hvac

Right now I am running this query:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "providerid": {
              "value": 13
            }
          }
        },
        {
          "nested": {
            "path": "pricingbytrade",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "pricingbytrade.name": "hvac"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "_source": {
    "includes": [
      "providerid",
      "pricingbytrade"
    ]
  }
}

But that query returns all of them instead of only the ones with hvac

I am using Elasticseach 6.7 so the inner_hits does not work here.

And this is a section of the mapping where involve the structure:

 "pricingbytrade": {
            "type": "nested",
            "properties": {
              "name": {
                "type": "text",
                "fields": {
                  "analyzed": {
                    "type": "text",
                    "analyzer": "standard",
                    "search_analyzer": "synonym_analyzer"
                  },
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256,
                    "normalizer": "lowercase"
                  }
                }
              },
              "pricingbycbsa": {
                "type": "nested",
                "properties": {
                  "cbsaid": {
                    "type": "integer"
                  },
                  "cbsaname": {
                    "type": "text"
                  },
                  "pricingscore": {
                    "type": "float"
                  }
                }
              }
            }
          }

Any suggestion??


问:
I'm using Django to create an e-commerce website. While integrating payment into the project, I got a page not found (404) error
The error I got while I enter the customer detail and click on checkout:

This is my views.py of payment. Here I have imported stripe module using stripe api and created checkout session:

```<code>from django.shortcuts import render, redirect, reverse, get_object_or_404
from decimal import Decimal
import stripe
from django.conf import settings
from orders.models import Order

# Create your views here.

stripe.api_key = settings.STRIPE_SECRET_KEY
stripe.api_version = settings.STRIPE_API_VERSION

def payment_process(request):
    order_id = request.session.get('order_id', None)
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        success_url = request.build_absolute_uri(reverse('payment:completed'))
        cancel_url = request.build_absolute_uri(reverse('payment:canceled'))

        session_data = {
            'mode': 'payment',
            'client_reference_id': order_id,
            'success_url': success_url,
            'cancel_url': cancel_url,
            'line_items': []
        }

        for item in order.items.all():
            session_data['line_items'].append({
                'price_data': {
                    'unit_amount': int(item.price * Decimal(100)),
                    'currency': 'usd',
                    'product_data': {
                        'name': item.product.name,
                    },
                },
                'quantity': item.quantity,
            })

        session = stripe.checkout.Session.create(**session_data)
        return redirect(session.url, code=303)

    else:
        return render(request, 'payment/process.html', locals())

def payment_completed(request):
    return render(request, 'payment/completed.html')

def payment_canceled(request):
    return render(request, 'payment/canceled.html')
</code>```

This is urls.py of payment where I have created URL patterns for process where the order summary is displayed, stripe checkout session. completed for the successfull payment and canceled for payment cancelation. :

```<code>    from django.urls import path
    from . import views

    app_name = 'payment'

    urlpatterns = [
        path('canceled/', views.payment_canceled, name='canceled'),
        path('completed/', views.payment_completed, name='completed'),
        path('process/', views.payment_process, name='process'),
    ]
</code>```

This is djangoProject urls.py:

```<code>from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('cart/', include('cart.urls', namespace='cart')),
    path('orders/', include('orders.urls', namespace='orders')),
    path('payment/', include('payment.urls', namespace='payment')),
    path('', include('ecommerce.urls', namespace='ecommerce')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Body:
The error I got while I enter the customer detail and click on checkout:

This is my views.py of payment. Here I have imported stripe module using stripe api and created checkout session:

from django.shortcuts import render, redirect, reverse, get_object_or_404
from decimal import Decimal
import stripe
from django.conf import settings
from orders.models import Order

# Create your views here.

stripe.api_key = settings.STRIPE_SECRET_KEY
stripe.api_version = settings.STRIPE_API_VERSION

def payment_process(request):
    order_id = request.session.get('order_id', None)
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        success_url = request.build_absolute_uri(reverse('payment:completed'))
        cancel_url = request.build_absolute_uri(reverse('payment:canceled'))

        session_data = {
            'mode': 'payment',
            'client_reference_id': order_id,
            'success_url': success_url,
            'cancel_url': cancel_url,
            'line_items': []
        }

        for item in order.items.all():
            session_data['line_items'].append({
                'price_data': {
                    'unit_amount': int(item.price * Decimal(100)),
                    'currency': 'usd',
                    'product_data': {
                        'name': item.product.name,
                    },
                },
                'quantity': item.quantity,
            })

        session = stripe.checkout.Session.create(**session_data)
        return redirect(session.url, code=303)

    else:
        return render(request, 'payment/process.html', locals())

def payment_completed(request):
    return render(request, 'payment/completed.html')

def payment_canceled(request):
    return render(request, 'payment/canceled.html')

This is urls.py of payment where I have created URL patterns for process where the order summary is displayed, stripe checkout session. completed for the successfull payment and canceled for payment cancelation. :

    from django.urls import path
    from . import views

    app_name = 'payment'

    urlpatterns = [
        path('canceled/', views.payment_canceled, name='canceled'),
        path('completed/', views.payment_completed, name='completed'),
        path('process/', views.payment_process, name='process'),
    ]

This is djangoProject urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('cart/', include('cart.urls', namespace='cart')),
    path('orders/', include('orders.urls', namespace='orders')),
    path('payment/', include('payment.urls', namespace='payment')),
    path('', include('ecommerce.urls', namespace='ecommerce')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


问:
How to Integrate Python API in Wordpress?
I'm building a website that allows users to input a prompt and generate an essay using an API. I have the following Python code that makes a POST request to the API with the prompt and receives the generated essay in the response:

```<code>import requests
import json

def generate_essay(prompt):
    # Make a POST request to the essay generator API with the prompt
    data = {"prompt": prompt}
    headers = {"Content-Type": "application/json"}
    response = requests.post("https://example.com/essay-generator-api", data=json.dumps(data), headers=headers)

    # Check if the request was successful
    if response.status_code == 200:
        # Extract the generated essay from the response
        essay = response.json()["essay"]
        return essay
    else:
        return "Error generating essay"

# Example usage:
generated_essay = generate_essay("Write an essay about the importance of education")
print(generated_essay)
</code>```

How can I integrate this code into my website so that it generates an essay on a submit request?

For example, when a user clicks a button, the generate_essay function should be called and the generated essay should be displayed on the page. Can you provide an example of the code I would need to do this?

Body:
I'm building a website that allows users to input a prompt and generate an essay using an API. I have the following Python code that makes a POST request to the API with the prompt and receives the generated essay in the response:

import requests
import json

def generate_essay(prompt):
    # Make a POST request to the essay generator API with the prompt
    data = {"prompt": prompt}
    headers = {"Content-Type": "application/json"}
    response = requests.post("https://example.com/essay-generator-api", data=json.dumps(data), headers=headers)

    # Check if the request was successful
    if response.status_code == 200:
        # Extract the generated essay from the response
        essay = response.json()["essay"]
        return essay
    else:
        return "Error generating essay"

# Example usage:
generated_essay = generate_essay("Write an essay about the importance of education")
print(generated_essay)

How can I integrate this code into my website so that it generates an essay on a submit request?

For example, when a user clicks a button, the generate_essay function should be called and the generated essay should be displayed on the page. Can you provide an example of the code I would need to do this?


问:
How to pass the data from Flutter inappwebview while function call in flutter?
I need to pass some data to Inappwebview at the function call. I tried in the below way it's not working.

```<code>  sendResponseData() {
print("Response Function called Flutter");
_controller.addJavaScriptHandler(
    handlerName: 'handler_blockly_response',
    callback: (args) {
      // return data to the JavaScript side!
      print("The call send to the javascript%%%%%%%%%%%%%");
      return {'response': "The Data from the Flutter Side"};
    });
</code>```

}

It's not working.

Note: what is the use of this I need to pass my API response to the inappwebview.

Body:
I need to pass some data to Inappwebview at the function call. I tried in the below way it's not working.

  sendResponseData() {
print("Response Function called Flutter");
_controller.addJavaScriptHandler(
    handlerName: 'handler_blockly_response',
    callback: (args) {
      // return data to the JavaScript side!
      print("The call send to the javascript%%%%%%%%%%%%%");
      return {'response': "The Data from the Flutter Side"};
    });

}

It's not working.

Note: what is the use of this I need to pass my API response to the inappwebview.


问:
Laravel 9: Redirect page window.location in javascript doesn't work when updating data
I am trying to update data in modals/pop-ups using jquery ajax. when I click the UPDATE Button, a page appears containing json data and the data has been successfully updated to the database.

{"success":true,"message":"Data Berhasil Diudapte!","data":{"id":6,"id_karyawan":"3","id_settingalokasi":"8","id_jeniscuti":"6","durasi":"3","mode_alokasi":"Berdasarkan Karyawan","tgl_masuk":null,"tgl_sekarang":null,"aktif_dari":"2022-01-02","sampai":"2022-12-31","created_at":"2022-12-15T06:21:04.000000Z","updated_at":"2022-12-21T04:09:04.000000Z"}}```
</div>
</div>
</p>
<p>with status 200 on the network
display on the network</p>
<p>but when double click on the data id on that network, an error appears like the following:</p>
<p>error when double click I don't know which url is meant in the error, so I'm quite confused about this error</p>
<p>this is my controller for function edit and update leave data:</p>
``` //get data alokascuti
public function edit($id)
{
    $alokasicuti = Alokasicuti::find($id);

    return response()->json([
        'success' => true,
        'message' => 'Data Alokasi cuti',
        'data'    => $alokasicuti
    ]);
    // dd($alokasicuti);
}

public function update(Request $request, $id)
{
    $alokasicuti = Alokasicuti::find($id);
    if($request->id_jeniscuti == 1)
    {
        $validate = $request->validate([
            'id_karyawan'  => 'required',
            'id_settingalokasi'=> 'required',
            'id_jeniscuti' => 'required',
            'tgl_masuk'    => 'required',
            'tgl_sekarang' => 'required',
            'aktif_dari'   => 'required',
            'sampai'       => 'required',
        ]);
        $alokasicuti->update([
            'id_karyawan'  =>$request->id_karyawan,
            'id_settingalokasi'=> $request->id_settingalokasi,
            'id_jeniscuti' =>$request->id_jeniscuti,
            'durasi'       =>$request->durasi,
            'mode_alokasi' =>$request->mode_alokasi,
            'tgl_masuk'    => Carbon::parse($request->tgl_masuk)->format('Y-m-d'),
            'tgl_sekarang' => Carbon::parse($request->tgl_sekarang)->format('Y-m-d'),
            'aktif_dari'   => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
            'sampai'       => Carbon::parse($request->sampai)->format('Y-m-d'),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Data Berhasil Diudapte!',
            'data'    => $alokasicuti
        ]);
    }else
    {
        $validate = $request->validate([
            'id_karyawan'  => 'required',
            'id_settingalokasi'=> 'required',
            'id_jeniscuti' => 'required',
            'aktif_dari'   => 'required',
            'sampai'       => 'required',
        ]);
        $alokasicuti->update([
            'id_karyawan'  =>$request->id_karyawan,
            'id_settingalokasi'=> $request->id_settingalokasi,
            'id_jeniscuti' =>$request->id_jeniscuti,
            'durasi'       =>$request->durasi,
            'mode_alokasi' =>$request->mode_alokasi,
            'tgl_masuk'    =>NULL,
            'tgl_sekarang' =>NULL,
            'aktif_dari'   => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
            'sampai'       => Carbon::parse($request->sampai)->format('Y-m-d'),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Data Berhasil Diudapte!',
            'data'    => $alokasicuti
        ]);

    }
}
```
<p>this is the code in editallocation.blade.php along with the script:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!-- script untuk mengambil data alokasi cuti  -->
<script type="text/javascript">
    $('body').on('click','.btn-editalokasi',function()
    {
        var id_alokasi =$(this).data('alokasi');

        // console.log(id_alokasi);
        $.ajaxSetup({
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
                        .attr('content')
                    }
        });
        $.ajax({
            url: "/edit-alokasi/"+id_alokasi,
            type: "GET",
            cache: false,
            success: function (response) {
                // console.log(response);
                $('#id_alokasi').val(response.data.id);
                $("#idjeniscuti").val(response.data.id_jeniscuti);
                $("#idsettingalokasi").val(response.data.id_settingalokasi);
                $("#id_karyawan").val(response.data.id_karyawan);
                $("#duration").val(response.data.durasi);
                $("#modealokasi").val(response.data.mode_alokasi);
                // $("#tglmasuk").val(response.data.tgl_masuk);
                // $("#tglsekarang").val(response.data.tgl_sekarang);
                $("#datepicker-autoclosea3").val(response.data.aktif_dari);
                $("#datepicker-autoclosea4").val(response.data.sampai);
            }
        });

    });
</script>

<!-- script untuk menyimpan data update-->
<script type="text/javascript">
    $(".input").click(function(e) {
        e.preventDefault();
        //nama variabel | id field pada form | value
        var id_alokasi       = $("#id_alokasi").val();
        var id_settingalokasi= $("idsettingalokasi").val();
        var id_jeniscuti     = $("#idjeniscuti").val();
        var id_karyawan      = $("#id_karyawan").val();
        var durasi           = $("#duration").val();
        var mode_alokasi     = $("#modealokasi").val();
        var tgl_masuk        = $("#tglmasuk").val();
        var tgl_sekarang     = $("#tglsekarang").val();
        var aktif_dari       = $("#datepicker-autoclosea3").val();
        var sampai           = $("#datepicker-autoclosea4").val();
        var token            = $('meta[name="csrf-token"]').attr('content');
    });
    $.ajax({
        url: "/updatealokasi/{$id_alokasi}",
        type:"PUT",
        data: {
            "id":id_alokasi,
            "id_settingalokasi": id_settingalokasi,
            "id_jeniscuti": id_jeniscuti,
            "id_karyawan": id_karyawan,
            "durasi": durasi,
            "mode_alokasi": mode_alokasi,
            "tgl_masuk": tgl_masuk,
            "tgl_sekarang": tgl_sekarang,
            "aktif_dari":aktif_dari,
            "sampai": sampai,
            "_token": token,
        },
        success: function(response) {
            window.location = "http://127.0.0.1:8000/alokasicuti";

            $('#aid'+ response.id +' td:nth-child(1)').text(response.id_karyawan);
            $('#aid'+ response.id +' td:nth-child(2)').text(response.id_jeniscuti);
            $('#aid'+ response.id +' td:nth-child(3)').text(response.durasi);
            $('#aid'+ response.id +' td:nth-child(4)').text(response.mode_alokasi);
            $('#aid'+ response.id +' td:nth-child(5)').text(response.aktif_dari);
            $('#aid'+ response.id +' td:nth-child(6)').text(response.sampai);

            $(".input")[0].reset();

            // $('#aid'+ response.id +' td:nth-child(1)').text(response.id_settingalokasi);
            // $('#aid'+ response.id +' td:nth-child(6)').text(response.tgl_masuk);
            // $('#aid'+ response.id +' td:nth-child(7)').text(response.tgl_sekarang);
        },
    });
</script>

         </code>```

id}}" id="editalokasi" tabindex="-1" role="dialog" aria-labelledby="editalokasi" aria-hidden="true">

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Alokasi Cuti

                <form class="input" action="/updatealokasi/{{$data->id}}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')

                            <input type="hidden" id="id_alokasi" name="id" value="{{$data->id}}">
                            <input type="hidden" name="id_settingalokasi" id="idsettingalokasi" value="{{$data->id_settingalokasi}}">

                                Kategori Cuti
                                <select name="id_jeniscuti" id="idjeniscuti" class="form-control">
                                    <option value="{{$data->id_jeniscuti}}" selected>{{$data->jeniscutis->jenis_cuti}}</option>
                                    @foreach ($jeniscuti as $jenis)
                                        <option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}</option>
                                    @endforeach
                                </select>

                                Karyawan
                                <select name="id_karyawan" id="id_karyawan" class="form-control">
                                    <option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
                                    @foreach ($karyawan as $data)
                                        <option value="{{ $data->id }}">{{ $data->nama }}</option>
                                    @endforeach
                                </select>

                                Durasi (Hari)
                                <input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" readonly>

                                Mode Alokasi
                                <input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" id="modealokasi" readonly>

                                    Tanggal Masuk

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>

                                    Tanggal Sekarang

                                        <input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>

                                    Aktif Dari

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" autocomplete="off">

                                    Sampai

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" autocomplete="off">

                        <button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-info" name="submit" value="save" id="update">Update</button>

                </form>

```

please help me solve this problem, because I'm still new to jquery ajax and I don't know much about jquery ajax yet.

Body:
I am trying to update data in modals/pop-ups using jquery ajax. when I click the UPDATE Button, a page appears containing json data and the data has been successfully updated to the database.

{"success":true,"message":"Data Berhasil Diudapte!","data":{"id":6,"id_karyawan":"3","id_settingalokasi":"8","id_jeniscuti":"6","durasi":"3","mode_alokasi":"Berdasarkan Karyawan","tgl_masuk":null,"tgl_sekarang":null,"aktif_dari":"2022-01-02","sampai":"2022-12-31","created_at":"2022-12-15T06:21:04.000000Z","updated_at":"2022-12-21T04:09:04.000000Z"}}

with status 200 on the network
display on the network

but when double click on the data id on that network, an error appears like the following:

error when double click I don't know which url is meant in the error, so I'm quite confused about this error

this is my controller for function edit and update leave data:

 //get data alokascuti
public function edit($id)
{
    $alokasicuti = Alokasicuti::find($id);

    return response()->json([
        'success' => true,
        'message' => 'Data Alokasi cuti',
        'data'    => $alokasicuti
    ]);
    // dd($alokasicuti);
}

public function update(Request $request, $id)
{
    $alokasicuti = Alokasicuti::find($id);
    if($request->id_jeniscuti == 1)
    {
        $validate = $request->validate([
            'id_karyawan'  => 'required',
            'id_settingalokasi'=> 'required',
            'id_jeniscuti' => 'required',
            'tgl_masuk'    => 'required',
            'tgl_sekarang' => 'required',
            'aktif_dari'   => 'required',
            'sampai'       => 'required',
        ]);
        $alokasicuti->update([
            'id_karyawan'  =>$request->id_karyawan,
            'id_settingalokasi'=> $request->id_settingalokasi,
            'id_jeniscuti' =>$request->id_jeniscuti,
            'durasi'       =>$request->durasi,
            'mode_alokasi' =>$request->mode_alokasi,
            'tgl_masuk'    => Carbon::parse($request->tgl_masuk)->format('Y-m-d'),
            'tgl_sekarang' => Carbon::parse($request->tgl_sekarang)->format('Y-m-d'),
            'aktif_dari'   => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
            'sampai'       => Carbon::parse($request->sampai)->format('Y-m-d'),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Data Berhasil Diudapte!',
            'data'    => $alokasicuti
        ]);
    }else
    {
        $validate = $request->validate([
            'id_karyawan'  => 'required',
            'id_settingalokasi'=> 'required',
            'id_jeniscuti' => 'required',
            'aktif_dari'   => 'required',
            'sampai'       => 'required',
        ]);
        $alokasicuti->update([
            'id_karyawan'  =>$request->id_karyawan,
            'id_settingalokasi'=> $request->id_settingalokasi,
            'id_jeniscuti' =>$request->id_jeniscuti,
            'durasi'       =>$request->durasi,
            'mode_alokasi' =>$request->mode_alokasi,
            'tgl_masuk'    =>NULL,
            'tgl_sekarang' =>NULL,
            'aktif_dari'   => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
            'sampai'       => Carbon::parse($request->sampai)->format('Y-m-d'),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Data Berhasil Diudapte!',
            'data'    => $alokasicuti
        ]);

    }
}

this is the code in editallocation.blade.php along with the script:

id}}" id="editalokasi" tabindex="-1" role="dialog" aria-labelledby="editalokasi" aria-hidden="true">

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Alokasi Cuti

                <form class="input" action="/updatealokasi/{{$data->id}}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')

                            <input type="hidden" id="id_alokasi" name="id" value="{{$data->id}}">
                            <input type="hidden" name="id_settingalokasi" id="idsettingalokasi" value="{{$data->id_settingalokasi}}">

                                Kategori Cuti
                                <select name="id_jeniscuti" id="idjeniscuti" class="form-control">
                                    <option value="{{$data->id_jeniscuti}}" selected>{{$data->jeniscutis->jenis_cuti}}</option>
                                    @foreach ($jeniscuti as $jenis)
                                        <option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}</option>
                                    @endforeach
                                </select>

                                Karyawan
                                <select name="id_karyawan" id="id_karyawan" class="form-control">
                                    <option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
                                    @foreach ($karyawan as $data)
                                        <option value="{{ $data->id }}">{{ $data->nama }}</option>
                                    @endforeach
                                </select>

                                Durasi (Hari)
                                <input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" readonly>

                                Mode Alokasi
                                <input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" id="modealokasi" readonly>

                                    Tanggal Masuk

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>

                                    Tanggal Sekarang

                                        <input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>

                                    Aktif Dari

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" autocomplete="off">

                                    Sampai

                                        <input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" autocomplete="off">

                        <button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-info" name="submit" value="save" id="update">Update</button>

                </form>

please help me solve this problem, because I'm still new to jquery ajax and I don't know much about jquery ajax yet.


问:
java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver(log in closed testing)
Received this error in log of closed testing eventhough i'm not using instant app library

java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{15d773b u0a190 TRNB bg:+11m51s747ms idle change:uncached procs:4 seq(0,0,0)}


问:
COMException while accessing .NET WebBrowser (SHDocVw)
What is the reason for the following exception ?

System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

It occurs when I make a COM call, trying to manipulate InternetExplorer in a Windows XP machine running c# code. It raises when I try to read a property like .IsBusy.

Exception message: Unable to cast COM object of type 'System.__ComObject' interface type 'SHDocVw.IWebBrowser2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{-D30C1661 CDAF-11D0-8A3E-00C04FC9E26E}' failed due to following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

ContentLicense: CC BY-SA 3.0


问:
ReactJS export excel with xlxs-populate nested array of object how
I'm looking for a way to export excel file for nested array of object using xlxs-populate library, language is reactjs. I don't see this get mention in the official document, i make sure to check thoroughly (or perhap i'm missing please be kindly leave a comment), or perhap this feature hasn't been implemented yet? I'm looking forward for your insight. For an easier depiction, here's how the data should look like:</p>
```<code>[
  {
    title: "title1",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Campaigns",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Events",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "General",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  },
  {
    title: "title2",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  }
];
</code>```

Body:
I'm looking for a way to export excel file for nested array of object using xlxs-populate library, language is reactjs. I don't see this get mention in the official document, i make sure to check thoroughly (or perhap i'm missing please be kindly leave a comment), or perhap this feature hasn't been implemented yet? I'm looking forward for your insight. For an easier depiction, here's how the data should look like:

[
  {
    title: "title1",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Campaigns",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Events",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "General",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  },
  {
    title: "title2",
    content: [
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      },
      {
        imageUrl: "http://placehold.it/300x300",
        title: "Video Template A",
        description:
          "Short description explaining the use of this design in a single sentence."
      }
    ]
  }
];


问:
Share env across GitHub Actions workflows
I have a GitHub Action (test-python.yml) intended to test a Django application. It utilizes the env tag like so towards the top of the file:

```<code>env:
  SECRET_KEY: test
  DEBUG: False
...
</code>```

I want to make another workflow - not a job in the same workflow - that is reliant on the same variables. I could obviously just make another file for said workflow and copy the env however this seems slightly flaky, I'd rather somehow share the env variables across numerous workflows so I only have to keep it up to date in one place.

Is there a way to do this? Thank you in advance!

Body:
I have a GitHub Action (test-python.yml) intended to test a Django application. It utilizes the env tag like so towards the top of the file:

env:
  SECRET_KEY: test
  DEBUG: False
...

I want to make another workflow - not a job in the same workflow - that is reliant on the same variables. I could obviously just make another file for said workflow and copy the env however this seems slightly flaky, I'd rather somehow share the env variables across numerous workflows so I only have to keep it up to date in one place.

Is there a way to do this? Thank you in advance!


问:
how do I write good marble tests for NGRX effects with service calls?
I have the following effect:

```<code>createListConfirm$ = createEffect(() =>
    this.actions$.pipe(
      ofType(listActions.createListConfirm),
      withLatestFrom(this.store.select(projectSelectors.getCurrentProjectId)),
      switchMap(([action, projectId]) => this.listService.createList(action.payload, projectId)),
      switchMap(result => of(listActions.createListSuccess({ payload: result }))),
      catchError(() => of(listActions.createListFailed())),
    ),
  );
</code>```

and have written the following unit tests:

```<code>
  describe('createListConfirm$', () => {
    it('dispatches createListSuccess', () => {
      action = hot('a', { a: listActions.createListConfirm({ payload: createListReq }) });
      const response = cold('a|', { a: payload })
      const expected = cold('-b|', { b: listActions.createListSuccess({ payload }) });
      expect(effects.createListConfirm$).toBeObservable(expected);
    })
    it('dispatches createListFailed', () => {
      action = hot('a', { a: listActions.createListConfirm({ payload: createListReq }) });
      const error = cold('#');
      listService.createList.mockReturnValue(throwError(error));
      const expected = cold('(b|', { b: listActions.createListFailed() });
      expect(effects.createListConfirm$).toBeObservable(expected);
    });
  });
</code>```

The issue I'm having is that the test returns an error @ frame 0 for both test cases and I don't know enough about unit tests or NgRx to tell if there is an issue with the test I've provided or the effect.

Config:

```<code>  const createListReq: CreateListRequest<BaseListConfig> = { ...createListReq };
  const payload: SubjectSummary = { ...payload };
  const list: CreateListRequest<BaseListConfig> = { ...list };

  let action: Observable<Action>;
  let effects: ListEffects;
  let mockStore: MockStore;
  let listService: jest.Mocked<ListService>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [AngularTestingModule],
        providers: [
          ListEffects,
          HttpClientTestingModule,
          BrowserAnimationsModule,
          Store,
          provideMockActions(() => action),
          provideMockStore({
            initialState: {
              loaded: false,
              loading: false,
              listId: null,
              config: null,
              showFilterRow: false,
              features: null,
            },
          }),
          { provide: ApiService, useValue: mockAndSpyOn(ApiService) },
          {
            provide: ListService, useValue: {
              createList: jest.fn().mockReturnValue(cold('-a|',{ id: '123' }))
          }, },

        ],
      });
      effects = TestBed.inject(ListEffects);
      mockStore = TestBed.inject(MockStore);
      action = TestBed.inject(Actions);
      listService = TestBed.inject(ListService) as jest.Mocked<ListService>;
    }),
  );
</code>```

Body:
I have the following effect:

createListConfirm$ = createEffect(() =>
    this.actions$.pipe(
      ofType(listActions.createListConfirm),
      withLatestFrom(this.store.select(projectSelectors.getCurrentProjectId)),
      switchMap(([action, projectId]) => this.listService.createList(action.payload, projectId)),
      switchMap(result => of(listActions.createListSuccess({ payload: result }))),
      catchError(() => of(listActions.createListFailed())),
    ),
  );

and have written the following unit tests:

  describe('createListConfirm$', () => {
    it('dispatches createListSuccess', () => {
      action = hot('a', { a: listActions.createListConfirm({ payload: createListReq }) });
      const response = cold('a|', { a: payload })
      const expected = cold('-b|', { b: listActions.createListSuccess({ payload }) });
      expect(effects.createListConfirm$).toBeObservable(expected);
    })
    it('dispatches createListFailed', () => {
      action = hot('a', { a: listActions.createListConfirm({ payload: createListReq }) });
      const error = cold('#');
      listService.createList.mockReturnValue(throwError(error));
      const expected = cold('(b|', { b: listActions.createListFailed() });
      expect(effects.createListConfirm$).toBeObservable(expected);
    });
  });

The issue I'm having is that the test returns an error @ frame 0 for both test cases and I don't know enough about unit tests or NgRx to tell if there is an issue with the test I've provided or the effect.

Config:

  const createListReq: CreateListRequest<BaseListConfig> = { ...createListReq };
  const payload: SubjectSummary = { ...payload };
  const list: CreateListRequest<BaseListConfig> = { ...list };

  let action: Observable<Action>;
  let effects: ListEffects;
  let mockStore: MockStore;
  let listService: jest.Mocked<ListService>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [AngularTestingModule],
        providers: [
          ListEffects,
          HttpClientTestingModule,
          BrowserAnimationsModule,
          Store,
          provideMockActions(() => action),
          provideMockStore({
            initialState: {
              loaded: false,
              loading: false,
              listId: null,
              config: null,
              showFilterRow: false,
              features: null,
            },
          }),
          { provide: ApiService, useValue: mockAndSpyOn(ApiService) },
          {
            provide: ListService, useValue: {
              createList: jest.fn().mockReturnValue(cold('-a|',{ id: '123' }))
          }, },

        ],
      });
      effects = TestBed.inject(ListEffects);
      mockStore = TestBed.inject(MockStore);
      action = TestBed.inject(Actions);
      listService = TestBed.inject(ListService) as jest.Mocked<ListService>;
    }),
  );