问:
data not getting displayed on the reusable component in the vuejs application
```<code>In my laravel vue application I'm trying to fetch total number of orders for the current day for a shopify store sing Shopify's admin REST API and display that on my vue component.

Following is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyOrderController extends Controller
{
    public function fetchOrders()
    {
        // Set up cURL request
        $access_token = 'shpat_XXXXXXXXXXXXXXXXXXXXXXXX';
        $today = Carbon::today()->toIso8601String();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STORE_NAME.myshopify.com/admin/orders/count.json?status=any&created_at_min={$today}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "X-Shopify-Access-Token: {$access_token}"
        ));

       // Make cURL request
        $response = curl_exec($ch);
        $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        //dd($response);die;

        // Check for empty or null response
        if (empty($response) || is_null($response)) {
            return 0;
        } else {
            // Return the response from the API
            return $response;
        }
    }

}
</code>```

when I dd($response);die; it correctly gives me out put as count:1 for today.

And then I have a reusable vue comonent called, ShopifyOrdersScoreCard.vue and following is it's code

```<code><template>
    <div data-aos="fade-up" class="col-md-12 mx-1 border bg-white rounded rounded-lg w-100 h-100 py-2 px-3">
        <table class="w-100 h-100">
            <tr>
                <td class="align-top" style="height:10px">
                    <dashboard-widget-header
                        image="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png"
                        width="32"
                        height="32"
                        title="Shopify"
                        imageAlt="Shopify">
                    </dashboard-widget-header>
                </td>
            </tr>
            <tr>
                <td class="align-middle text-center">
                    <div class="row">
                        <div class="col-12">
                            <div class="row">
                                <div class="col-12">
                                    <h6 class="m-b-5 custom-non-comparison-score-card-title">
                                        Orders
                                    </h6>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <h5 class="mb-0 custom-non-comparison-score-card-value">
                                        <p
                                            v-if="orders"
                                        >
                                            {{ orders }}
                                        </p>
                                        <p
                                            v-else
                                        >
                                            Loading...
                                        </p>
                                    </h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
export default {
    props: ['orders'],

    created() {
        console.log('Shopify 343434 Orders:', this.orders);
    }
}
</script>
</code>```

Here my console log giving me Undefined as the out put (that's my problem, can't figure out why it's happening)

And I use this component on my index.vue. Following is my index.vue.

```<code><template>
    <div>
        <draggable v-model="items" :options="{ group: 'shared' }" class="d-flex">
            <div v-for="item in items" :key="item.id" class="col-md-2 col-sm-2 col-lg-2" >
                <component :is="item.component" :item="item" />
            </div>
        </draggable>
    </div>
</template>

<script>
import ShopifyOrdersScoreCard from './ShopifyOrdersScoreCard.vue';

export default {
    data() {
        return {
            items: [
                { id: 1, component: ShopifyOrdersScoreCard, orders: null }
            ]
        }
    },
    methods: {
        fetchOrders() {
            // Make a request to the Laravel server to fetch the orders data
            axios.get('/orders').then(response => {
                console.log('Response:', response);
                console.log('Orders:', response.data);
                // Update the orders prop in the ShopifyOrdersScoreCard component
                this.items[0].orders = response.data;
                console.log('Items:', this.items);
            });
        }
    },
    created() {
        this.fetchOrders();
    }
}
</script>
</code>```

These console logs giving me the correct out put. but

console.log('Shopify 343434 Orders:', this.orders); in my ShopifyOrdersScoreCard.vue giving me undefined....

because of that the order count is not getting displayed on my index.vue..

Body:
In my laravel vue application I'm trying to fetch total number of orders for the current day for a shopify store sing Shopify's admin REST API and display that on my vue component.

Following is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyOrderController extends Controller
{
    public function fetchOrders()
    {
        // Set up cURL request
        $access_token = 'shpat_XXXXXXXXXXXXXXXXXXXXXXXX';
        $today = Carbon::today()->toIso8601String();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STORE_NAME.myshopify.com/admin/orders/count.json?status=any&created_at_min={$today}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "X-Shopify-Access-Token: {$access_token}"
        ));

       // Make cURL request
        $response = curl_exec($ch);
        $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        //dd($response);die;

        // Check for empty or null response
        if (empty($response) || is_null($response)) {
            return 0;
        } else {
            // Return the response from the API
            return $response;
        }
    }

}

when I dd($response);die; it correctly gives me out put as count:1 for today.

And then I have a reusable vue comonent called, ShopifyOrdersScoreCard.vue and following is it's code

<template>

                    <dashboard-widget-header
                        image="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png"
                        width="32"
                        height="32"
                        title="Shopify"
                        imageAlt="Shopify">
                    </dashboard-widget-header>

                                        Orders

                                            {{ orders }}

                                            Loading...

</template>

Here my console log giving me Undefined as the out put (that's my problem, can't figure out why it's happening)

And I use this component on my index.vue. Following is my index.vue.

<template>

        <draggable v-model="items" :options="{ group: 'shared' }" class="d-flex">

                <component :is="item.component" :item="item" />

        </draggable>

</template>

These console logs giving me the correct out put. but

console.log('Shopify 343434 Orders:', this.orders); in my ShopifyOrdersScoreCard.vue giving me undefined....

because of that the order count is not getting displayed on my index.vue..


来源: stackexchange

问:
Video plays fine in VideoView, but I cannot save it to Gallery
I am using a library CameraView to manage the Camera - I'm not sure that particularly matters here, but it offers some unique functionality I need for my application, and does record some video to a file on my device.

I can then take this VideoResult object and view it through a native VideoView. This works fine:

```<code>videoView.setVideoURI(Uri.fromFile(videoResult!!.file))
</code>```

However when I try and save the Video to the gallery, it ends up with a "Can't play video" error. My code looks like this:

```<code>        private fun saveVideo(result: VideoResult) {
            val videoFile = result.file

            val contentValues = ContentValues()
            contentValues.put(Video.Media.DISPLAY_NAME, System.currentTimeMillis().toString())
            contentValues.put(Video.Media.MIME_TYPE, "video/mp4")
            contentValues.put(Video.Media.DATA, videoFile.absolutePath)
            contentValues.put(Video.Media.RELATIVE_PATH, "Movies/ShaderCam")
            val uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues)
        }
</code>```

It seems that whatever file gets saved here is indeed invalid, because when I try and pass that uri to the VideoView, it also shows the same "Can't play video" error.

This is really confusing because pretty much the same code works fine for photos; I can view these in the Gallery as expected:

```<code>    fun saveImage(bmp: Bitmap, path: String, activity: CameraActivity) {
        ByteArrayOutputStream().apply {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, this)
        }
        val imageFile = File(path)
        val contentResolver = ContentValues().apply {
            put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis())
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.DATA, imageFile.absolutePath)
        }

        activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentResolver).apply {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, activity.contentResolver.openOutputStream(this!!))
        }
    }
</code>```

So I am really stumped here; I have no idea what is different about videos that it won't play them from the gallery. In the meantime, I can save the video to the device through Intent.ACTION_SEND, but it'd be nice to save directly to the device when recording is done.

ContentLicense: CC BY-SA 4.0

Body:
I am using a library CameraView to manage the Camera - I'm not sure that particularly matters here, but it offers some unique functionality I need for my application, and does record some video to a file on my device.

I can then take this VideoResult object and view it through a native VideoView. This works fine:

videoView.setVideoURI(Uri.fromFile(videoResult!!.file))

However when I try and save the Video to the gallery, it ends up with a "Can't play video" error. My code looks like this:

        private fun saveVideo(result: VideoResult) {
            val videoFile = result.file

            val contentValues = ContentValues()
            contentValues.put(Video.Media.DISPLAY_NAME, System.currentTimeMillis().toString())
            contentValues.put(Video.Media.MIME_TYPE, "video/mp4")
            contentValues.put(Video.Media.DATA, videoFile.absolutePath)
            contentValues.put(Video.Media.RELATIVE_PATH, "Movies/ShaderCam")
            val uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues)
        }

It seems that whatever file gets saved here is indeed invalid, because when I try and pass that uri to the VideoView, it also shows the same "Can't play video" error.

This is really confusing because pretty much the same code works fine for photos; I can view these in the Gallery as expected:

    fun saveImage(bmp: Bitmap, path: String, activity: CameraActivity) {
        ByteArrayOutputStream().apply {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, this)
        }
        val imageFile = File(path)
        val contentResolver = ContentValues().apply {
            put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis())
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.DATA, imageFile.absolutePath)
        }

        activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentResolver).apply {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, activity.contentResolver.openOutputStream(this!!))
        }
    }

So I am really stumped here; I have no idea what is different about videos that it won't play them from the gallery. In the meantime, I can save the video to the device through Intent.ACTION_SEND, but it'd be nice to save directly to the device when recording is done.


问:
How to start localhost with https in vite reactapp
I am building a react app that needs to talk a backend server and is able to do a SSL handshake. For this purpose I need to use https on my local host. Running https on vite has become extreme pain in a**. There are no clear tutorials on youtube and nothing clear in vite docs.

Following is my vite.config.js

`    import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

```<code>// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
  /* https option must be turned on,so that you can use h2 */
https: {
  key: "./config/cert/local-client-key.pem",
  cert: "./config/cert/local-client-csr.pem",
   },
 }
</code>```

})`

and then tried running npm run dev --https. But I am not able to run the otherwise fine working code.

Body:
I am building a react app that needs to talk a backend server and is able to do a SSL handshake. For this purpose I need to use https on my local host. Running https on vite has become extreme pain in a**. There are no clear tutorials on youtube and nothing clear in vite docs.

Following is my vite.config.js

`    import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
  /* https option must be turned on,so that you can use h2 */
https: {
  key: "./config/cert/local-client-key.pem",
  cert: "./config/cert/local-client-csr.pem",
   },
 }

})`

and then tried running npm run dev --https. But I am not able to run the otherwise fine working code.


问:
Can I send a fetch request after waiting for target to load?
I am trying to build an extension that displays the open cases of an entire company when one of their staff writes in. I'm using Zendesk, but it doesn't support GraphQL for tickets, which means the data I get back is way too much to work with. Instead, I want to send a fetch request to Zendesk's search, then parse the response. I want to delay the data that is fetched until after the search runs, which may be done using an iFrame is not possible by fetching the URL directly.

The question is NOT about running another function after a fetch request has been completed.

The issue is that I need the search to run so that the tickets are included in the response. Is there any way to send the request, wait for load and then get back the response?

Here is the code:

```<code>fetchCompanyOpenTickets = async (companyId) => {
      await fetch(
        `https://mycompany.zendesk.com/agent/search/1?type=ticket&q=${companyId}%20status%3Aopen`,
        {
          method: "GET",
        }
      )
        .then((res) => res.text())
        .then((data) => {
          const parser = new DOMParser();
          const doc = parser.parseFromString(data, "text/html");
          console.log(doc);
        });
    },
</code>```

What I get is the document, but the body tag only holds the search skeleton as opposed to the generated content.

Body:
I am trying to build an extension that displays the open cases of an entire company when one of their staff writes in. I'm using Zendesk, but it doesn't support GraphQL for tickets, which means the data I get back is way too much to work with. Instead, I want to send a fetch request to Zendesk's search, then parse the response. I want to delay the data that is fetched until after the search runs, which may be done using an iFrame is not possible by fetching the URL directly.

The question is NOT about running another function after a fetch request has been completed.

The issue is that I need the search to run so that the tickets are included in the response. Is there any way to send the request, wait for load and then get back the response?

Here is the code:

fetchCompanyOpenTickets = async (companyId) => {
      await fetch(
        `https://mycompany.zendesk.com/agent/search/1?type=ticket&q=${companyId}%20status%3Aopen`,
        {
          method: "GET",
        }
      )
        .then((res) => res.text())
        .then((data) => {
          const parser = new DOMParser();
          const doc = parser.parseFromString(data, "text/html");
          console.log(doc);
        });
    },

What I get is the document, but the body tag only holds the search skeleton as opposed to the generated content.


问:
Debezium Kafka connector does not support autoscaling to multiple workers. But the worker count is shown as increased when monitoring from CloudWatch
As per the note on November 10, 2022 - The Debezium connector supports only 1 task per connector, hence it can use just use one worker per connector. Autoscaling workers per connector will not work with this specific connector. If you’re following this blog to set up Debezium with MSK Connect, choose the Provisioned capacity type and increase the MCUs as needed to scale up.

https://aws.amazon.com/blogs/aws/introducing-amazon-msk-connect-stream-data-to-and-from-your-apache-kafka-clusters-using-managed-connectors/

According to the above note, multiple workers should not be supported for a Debezium connector, and the worker count should not be increased while autoscaling the connector.

To verify this, I created a Debezium connector with the configs below and a CloudWatch dashboard to monitor the worker count while autoscaling. When the CPU utilization exceeded the scale_out_cpu_utilization_percentage (11%), we could verify that the worker count is increased to the maximum count as configured. (max_worker_count - 3).

Any idea about how this works?

CloudWatch dashboard

You can see the autoscaled worker count from the attached images of the CloudWatch dashboard here.

CloudWatch dashboard1

CloudWatch dashboard2

Please find the configurations below.

Connector plugin - debezium-connector-postgresql-1.9.2.zip

Apache Kafka version - 2.7.1

Connector Capacity

Autoscaled    mcu_count - 1

min_worker_count -1

max_worker_count - 3

scale_in_cpu_utilization_percentage - 1%

scale_out_cpu_utilization_percentage - 11%

Connector Capacity

Connector configuration

connector.class=io.debezium.connector.postgresql.PostgresConnector

slot.name=debezium _test

tasks.max=1

database.server.name=test_db_dev

database.hostname=<>

database.port=5432

database.dbname=test_db

database.user=<>

database.password=<>

table.include.list=public.test_outbox

plugin.name=pgoutput

topic.creation.enable=true

transforms.outbox.type=io.debezium.transforms.outbox.EventRouter

transforms=outbox

transforms.outbox.table.expand.json.payload=true

transforms.outbox.route.topic.replacement=test.dev.${routedByValue}_outbox

transforms.outbox.table.op.invalid.behavior=error

key.converter.schemas.enable=false

value.converter=org.apache.kafka.connect.json.JsonConverter

key.converter=org.apache.kafka.connect.json.JsonConverter


问:
How to call google map API inside a javascript file in Sitecore SXA
I wanted to create a custom map via scriban in sxa, but I can't access the google api inside a javascript file.

I try this code:

```<code>(function ($) {
    $(document).ready(function () {
        if ($(".property-map").length > 0) {
            // Initialize and add the map
            // The location of Uluru
            const uluru = { lat: -25.344, lng: 131.031 };
            // The map, centered at Uluru
            const map = new google.maps.Map(document.getElementById("property-map"), {
            zoom: 4,
            center: uluru,
            });
        }
    });
})(jQuery);
</code>```

this results in google not defined in the sxa cli.

Body:
I wanted to create a custom map via scriban in sxa, but I can't access the google api inside a javascript file.

I try this code:

(function ($) {
    $(document).ready(function () {
        if ($(".property-map").length > 0) {
            // Initialize and add the map
            // The location of Uluru
            const uluru = { lat: -25.344, lng: 131.031 };
            // The map, centered at Uluru
            const map = new google.maps.Map(document.getElementById("property-map"), {
            zoom: 4,
            center: uluru,
            });
        }
    });
})(jQuery);

this results in google not defined in the sxa cli.


问:
Parse YAML List in Golang
I'm trying to parse such a YAML:

a:
  - opt:
    f1: "lol"
  - opt:
    f1: "lul"
```
<p>Using such structures:</p>
<pre class="lang-golang prettyprint-override"><code>package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

var data = `
a:
  - opt:
    f1: "lol"
  - opt:
    f1: "lul"
`

type T struct {
    As []A `yaml:"a"`
}

type A struct {
    Opts []Opt `yaml:"opt"`
}

type Opt struct {
    F1 string `yaml:"f1"`
}

func main() {
    t := T{}

    err := yaml.Unmarshal([]byte(data), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    fmt.Printf("--- t:\n%v\n\n", t)
}
</code>```

But it gives me only empty lists:

```<code>--- t:
{[{[]} {[]}]}
</code>```

What's wrong with this code? Playground

Title: Parse YAML List in Golang

Body:
I'm trying to parse such a YAML:

a:
  - opt:
    f1: "lol"
  - opt:
    f1: "lul"

Using such structures:

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

var data = `
a:
  - opt:
    f1: "lol"
  - opt:
    f1: "lul"
`

type T struct {
    As []A `yaml:"a"`
}

type A struct {
    Opts []Opt `yaml:"opt"`
}

type Opt struct {
    F1 string `yaml:"f1"`
}

func main() {
    t := T{}

    err := yaml.Unmarshal([]byte(data), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    fmt.Printf("--- t:\n%v\n\n", t)
}

But it gives me only empty lists:

--- t:
{[{[]} {[]}]}

What's wrong with this code? Playground


问:
Where to find documentation of kivymd MDDataTable ViewAdapter?
No documentation found for ViewAdapter class in MDDataTable in KivyMD. Any help is appreciated.


问:
How to get list of JSON navigations of a EF Core 7 entity?
I have some models that are created in a DBContext. Some of them may have some navigation properties.
I get IEntityType of those models using this method:

```<code>var entityType = context.Model.FindEntityType(typeof(TEntity));
</code>```

When I call entityType.GetProperties() it returns none of navigation fields of the entity.
Also when I call entityType.GetNavigations() it returns all navigation fields of the entity.
Some of those navigation fields are JSON fields and I wanna detect them in some of my practices.
I check all methods and properties of the returned type INavigation, but I can't find any related property or method that can specify JSON navigation filed.
In configuration of DBContext I used this code for configuring JSON field:

```<code>builder.OwnsOne(e => e.MyPropName, ownedNavigationBuilder => ownedNavigationBuilder.ToJson());
</code>```

This config works well to storing or querying purposes, but the main problem is "How can I find list of JSON navigation fields of an entity in EF Core 7"?

Body:
I have some models that are created in a DBContext. Some of them may have some navigation properties.
I get IEntityType of those models using this method:

var entityType = context.Model.FindEntityType(typeof(TEntity));

When I call entityType.GetProperties() it returns none of navigation fields of the entity.
Also when I call entityType.GetNavigations() it returns all navigation fields of the entity.
Some of those navigation fields are JSON fields and I wanna detect them in some of my practices.
I check all methods and properties of the returned type INavigation, but I can't find any related property or method that can specify JSON navigation filed.
In configuration of DBContext I used this code for configuring JSON field:

builder.OwnsOne(e => e.MyPropName, ownedNavigationBuilder => ownedNavigationBuilder.ToJson());

This config works well to storing or querying purposes, but the main problem is "How can I find list of JSON navigation fields of an entity in EF Core 7"?


问:
Invalid URL appears while testing an asyn function in Vitest
I want to write a unit test for a async function inside of a composable.
Here is the composable :

```<code>// Composable/useData.ts
export function useData(){

    async function handlerPromise(req:IHezarpa){

        return await getList(req)
            }

    return { handlerPromise }
}

</code>```

At this composable, the helper function of "getList" is defined as follows:

```<code>// util/getList.ts
interface IData{
 page:number
}

export const getList = (reqData:IData) => {
    return ApiInstance.get(URLS.suffix, {
        params: {
            page:reqData.page
        }
    })
}
</code>```

I wrote the following test for above function in Vitest+Vue3

```<code>import {useData} from "./Composabels/useData.ts"

it("Should resolve a value ",async()=>{

    const reqData:IData = {page:1}
    const {handlerPromise} = useData()

        const response = await handlerPromise(reqData)
        expect(response).toBeDefined()

})

</code>```

When i run the above test, the following error appears:

TypeError: Invalid URL

I should say that the above composable works correctly and just fails when running its test.

Body:
I want to write a unit test for a async function inside of a composable.
Here is the composable :

// Composable/useData.ts
export function useData(){

    async function handlerPromise(req:IHezarpa){

        return await getList(req)
            }

    return { handlerPromise }
}

At this composable, the helper function of "getList" is defined as follows:

// util/getList.ts
interface IData{
 page:number
}

export const getList = (reqData:IData) => {
    return ApiInstance.get(URLS.suffix, {
        params: {
            page:reqData.page
        }
    })
}

I wrote the following test for above function in Vitest+Vue3

import {useData} from "./Composabels/useData.ts"

it("Should resolve a value ",async()=>{

    const reqData:IData = {page:1}
    const {handlerPromise} = useData()

        const response = await handlerPromise(reqData)
        expect(response).toBeDefined()

})

When i run the above test, the following error appears:

TypeError: Invalid URL

I should say that the above composable works correctly and just fails when running its test.


问:
How to detect Browser Tab close and Browser Reload
How to detect Tab close in web browser and Browser Reload in Angular?

My problem is , I need to remove a key in local storage when the browser tab is closed.

I used Host Listener with 'window:beforeunload' ,

```<code>@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
  // remove local storage key here
}
</code>```

But , When tab is Reload it clear the key in local storage. In my problem session storage cannot be used.

Body:
How to detect Tab close in web browser and Browser Reload in Angular?

My problem is , I need to remove a key in local storage when the browser tab is closed.

I used Host Listener with 'window:beforeunload' ,

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
  // remove local storage key here
}

But , When tab is Reload it clear the key in local storage. In my problem session storage cannot be used.


问:
Jakarta XML Schema is not present when updating to Java 17 and JAXB 3
I'm currently updating our application to Java 17 and JAXB 3.

I switched to the jaxb30-maven-plugin for this

```<code><groupId>com.evolvedbinary.maven.jvnet</groupId>
<artifactId>jaxb30-maven-plugin</artifactId>
<version>0.15.0</version>
</code>```

Now I'm getting the error when I try to generate anything:

[WARNING] Error injecting: org.jvnet.mjiip.v_3_0.XJC30Mojo
java.lang.TypeNotPresentException: Type jakarta.xml.bind.annotation.XmlSchema not present
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType

here is my pom.xml:

```<code>    <plugin>
        <groupId>com.evolvedbinary.maven.jvnet</groupId>
        <artifactId>jaxb30-maven-plugin</artifactId>
        <version>0.15.0</version>
        <configuration>
            <locale>en</locale>
            <extension>true</extension>
        </configuration>
        <executions>
            <execution>
                <id>Generate Import Sources</id>
                <goals>
                    <goal>generate</goal>
                </goals>
                <phase>generate-sources</phase>
                <configuration>
                    <schemaLanguage>XMLSCHEMA</schemaLanguage>
                    <schemaDirectory>${basedir}/src/main/resources/xsd</schemaDirectory>
                    <schemaIncludes>
                        <include>/Import_v1.xsd</include>
                    </schemaIncludes>
                    <generatePackage>com.company.project.v1</generatePackage>
                    <generateDirectory>${basedir}/target/jaxb</generateDirectory>
                    <bindingIncludes>
                        <bindingInclude>Import_v1.xjb</bindingInclude>
                    </bindingIncludes>
                </configuration>
            </execution>
        </executions>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jaxb</groupId>
                <artifactId>jaxb-runtime</artifactId>
                <version>2.3.3</version>
            </dependency>
            <dependency>
                <groupId>com.sun.activation</groupId>
                <artifactId>jakarta.activation</artifactId>
                <version>1.2.1</version>
            </dependency>
        </dependencies>

    </plugin>
</code>```

Can you probably help me and see what the problem is?

Body:
I'm currently updating our application to Java 17 and JAXB 3.

I switched to the jaxb30-maven-plugin for this

<groupId>com.evolvedbinary.maven.jvnet</groupId>
<artifactId>jaxb30-maven-plugin</artifactId>
<version>0.15.0</version>

Now I'm getting the error when I try to generate anything:

[WARNING] Error injecting: org.jvnet.mjiip.v_3_0.XJC30Mojo
java.lang.TypeNotPresentException: Type jakarta.xml.bind.annotation.XmlSchema not present
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType

here is my pom.xml:

    <plugin>
        <groupId>com.evolvedbinary.maven.jvnet</groupId>
        <artifactId>jaxb30-maven-plugin</artifactId>
        <version>0.15.0</version>
        <configuration>
            <locale>en</locale>
            <extension>true</extension>
        </configuration>
        <executions>
            <execution>
                <id>Generate Import Sources</id>
                <goals>
                    <goal>generate</goal>
                </goals>
                <phase>generate-sources</phase>
                <configuration>
                    <schemaLanguage>XMLSCHEMA</schemaLanguage>
                    <schemaDirectory>${basedir}/src/main/resources/xsd</schemaDirectory>
                    <schemaIncludes>
                        <include>/Import_v1.xsd</include>
                    </schemaIncludes>
                    <generatePackage>com.company.project.v1</generatePackage>
                    <generateDirectory>${basedir}/target/jaxb</generateDirectory>
                    <bindingIncludes>
                        <bindingInclude>Import_v1.xjb</bindingInclude>
                    </bindingIncludes>
                </configuration>
            </execution>
        </executions>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jaxb</groupId>
                <artifactId>jaxb-runtime</artifactId>
                <version>2.3.3</version>
            </dependency>
            <dependency>
                <groupId>com.sun.activation</groupId>
                <artifactId>jakarta.activation</artifactId>
                <version>1.2.1</version>
            </dependency>
        </dependencies>

    </plugin>

Can you probably help me and see what the problem is?


问:
How to set default values with Easyadmin useEntryCrudForm?
I have crud form that has a CollectionField:

```<code>  if (Crud::PAGE_EDIT === $pageName) {
            return [

                CollectionField::new('elements')
                    ->useEntryCrudForm(TemplateElementCrudController::class)
                    ->setFormTypeOptions([
                        'block_name' => 'template_elements',
                    ])
                    ->setColumns('col-md-12 col-xxl-12')
                    ->setEntryIsComplex()
                    ->renderExpanded()
            ];

  }
</code>```

And my TemplateElementCrudController creates a subform.
There are a lot of values inside configureFields but some fields require to have a default value.

But i can't seem to set those default values.
I've tried several things like settings:

set default values in Entity (ignored)

set default values in Field, e.g. :  BooleanField::new('...')->setValue(true) -> ignored

set default values with  public function createEntity(string $entityFqcn) -> function not called in this case

As i see it, it's only possible to set these values with javascript (but i would rather not do that).

An other solution is that i use setEntryType with a symfony form and set the default values there.

But i was just wondering why can't i just simply set the default values when using the useEntryCrudForm, or am i missing something?

https://symfony.com/bundles/EasyAdminBundle/current/fields/CollectionField.html#useentrycrudform

Body:
I have crud form that has a CollectionField:

  if (Crud::PAGE_EDIT === $pageName) {
            return [

                CollectionField::new('elements')
                    ->useEntryCrudForm(TemplateElementCrudController::class)
                    ->setFormTypeOptions([
                        'block_name' => 'template_elements',
                    ])
                    ->setColumns('col-md-12 col-xxl-12')
                    ->setEntryIsComplex()
                    ->renderExpanded()
            ];

  }

And my TemplateElementCrudController creates a subform.
There are a lot of values inside configureFields but some fields require to have a default value.

But i can't seem to set those default values.
I've tried several things like settings:

set default values in Entity (ignored)

set default values in Field, e.g. :  BooleanField::new('...')->setValue(true) -> ignored

set default values with  public function createEntity(string $entityFqcn) -> function not called in this case

As i see it, it's only possible to set these values with javascript (but i would rather not do that).

An other solution is that i use setEntryType with a symfony form and set the default values there.

But i was just wondering why can't i just simply set the default values when using the useEntryCrudForm, or am i missing something?

https://symfony.com/bundles/EasyAdminBundle/current/fields/CollectionField.html#useentrycrudform


问:
$map query returning Boolean value instead of data in mongodb aggregation pipeline
I have data:

```<code>{
        "_id": "63b6c24fa14b7a7762f053f5",
        "question": [
            {
                "type": "single",
                "optional": false,
                "options": null,
                "is_disable": false,
                "is_deleted": true,
                "draggable": false,
                "choice": null,
                "updated_by": "6360e17547fbf84e159a3777",
                "deleted_by": null,
                "_id": "63b6c3789f67afe5a4c6140d",
                "category_option": [
                    {
                        "name": {
                            "en": "bb",
                            "ar": "الخبرة الشاملة"
                        },
                        "optional": false,
                        "editable": false,
                        "sequence": 0,
                        "draggable": true,
                        "is_deleted": true,
                        "updated_by": "6360e17547fbf84e159a3777",
                        "deleted_by": null,
                        "_id": "63b6ce9674af1e81317ef2ff"
                    }
                ],
                "name": {
                    "en": "Please rate the following items c",
                    "ar": "يرجى تقييم العناصر التالية"
                },
                "sequence": 0
            }
        ]
    }
</code>```

i want to apply sort here and want to filter data by is_deleted. if is_deleted:true then i want data for particular question and particular category_question but whenever i run $map query it is returning me Boolean value.

code i have written:

```<code>const getSurvey = await SurveyQuestions.aggregate([
      {
        $match: {
          brand_id: brand_id,
          experience_type_id: experience_type,
          is_deleted: FALSE,
        },
      },
      {
        $addFields: {
          question: {
            $map: {
              input: "$question",
              as: "q",
              in: {
                $eq: ["$$q.is_deleted", true],
              },
            },
          },
        },
      },
)]
</code>```

i am getting result as belove,

```<code>{
        "_id": "63b6c24fa14b7a7762f053f5",
        "question": [
            true,
            false,
            false,
            false,
            false,
            false
        ],
        "brand_id": "63b6bccbbc400713acba8fbe",
        "experience_type_id": "63b6c24fa14b7a7762f053f3",
        "is_disable": false,
        "is_deleted": false,
        "created_by": "6360e17547fbf84e159a3777",
        "updated_by": "6360e17547fbf84e159a3777",
        "deleted_by": null,
        "createdAt": "2023-01-05T12:27:59.741Z",
        "updatedAt": "2023-01-06T04:25:41.547Z",
        "__v": 0
    }
</code>```

desired result should be =>

```<code> {
    "_id": "63b6c24fa14b7a7762f053f5",
    "question": [
        {
            "type": "single",
            "optional": false,
            "options": null,
            "is_disable": false,
            "is_deleted": true,
            "draggable": false,
            "choice": null,
            "updated_by": "6360e17547fbf84e159a3777",
            "deleted_by": null,
            "_id": "63b6c3789f67afe5a4c6140d",
            "category_option": [
                {
                    "name": {
                        "en": "bb",
                        "ar": "الخبرة الشاملة"
                    },
                    "optional": false,
                    "editable": false,
                    "sequence": 0,
                    "draggable": true,
                    "is_deleted": true,
                    "updated_by": "6360e17547fbf84e159a3777",
                    "deleted_by": null,
                    "_id": "63b6ce9674af1e81317ef2ff"
                }
            ],
            "name": {
                "en": "Please rate the following items c",
                "ar": "يرجى تقييم العناصر التالية"
            },
            "sequence": 0
        }
    ]
}
</code>```

Body:
I have data:

{
        "_id": "63b6c24fa14b7a7762f053f5",
        "question": [
            {
                "type": "single",
                "optional": false,
                "options": null,
                "is_disable": false,
                "is_deleted": true,
                "draggable": false,
                "choice": null,
                "updated_by": "6360e17547fbf84e159a3777",
                "deleted_by": null,
                "_id": "63b6c3789f67afe5a4c6140d",
                "category_option": [
                    {
                        "name": {
                            "en": "bb",
                            "ar": "الخبرة الشاملة"
                        },
                        "optional": false,
                        "editable": false,
                        "sequence": 0,
                        "draggable": true,
                        "is_deleted": true,
                        "updated_by": "6360e17547fbf84e159a3777",
                        "deleted_by": null,
                        "_id": "63b6ce9674af1e81317ef2ff"
                    }
                ],
                "name": {
                    "en": "Please rate the following items c",
                    "ar": "يرجى تقييم العناصر التالية"
                },
                "sequence": 0
            }
        ]
    }

i want to apply sort here and want to filter data by is_deleted. if is_deleted:true then i want data for particular question and particular category_question but whenever i run $map query it is returning me Boolean value.

code i have written:

const getSurvey = await SurveyQuestions.aggregate([
      {
        $match: {
          brand_id: brand_id,
          experience_type_id: experience_type,
          is_deleted: FALSE,
        },
      },
      {
        $addFields: {
          question: {
            $map: {
              input: "$question",
              as: "q",
              in: {
                $eq: ["$$q.is_deleted", true],
              },
            },
          },
        },
      },
)]

i am getting result as belove,

{
        "_id": "63b6c24fa14b7a7762f053f5",
        "question": [
            true,
            false,
            false,
            false,
            false,
            false
        ],
        "brand_id": "63b6bccbbc400713acba8fbe",
        "experience_type_id": "63b6c24fa14b7a7762f053f3",
        "is_disable": false,
        "is_deleted": false,
        "created_by": "6360e17547fbf84e159a3777",
        "updated_by": "6360e17547fbf84e159a3777",
        "deleted_by": null,
        "createdAt": "2023-01-05T12:27:59.741Z",
        "updatedAt": "2023-01-06T04:25:41.547Z",
        "__v": 0
    }

desired result should be =>

 {
    "_id": "63b6c24fa14b7a7762f053f5",
    "question": [
        {
            "type": "single",
            "optional": false,
            "options": null,
            "is_disable": false,
            "is_deleted": true,
            "draggable": false,
            "choice": null,
            "updated_by": "6360e17547fbf84e159a3777",
            "deleted_by": null,
            "_id": "63b6c3789f67afe5a4c6140d",
            "category_option": [
                {
                    "name": {
                        "en": "bb",
                        "ar": "الخبرة الشاملة"
                    },
                    "optional": false,
                    "editable": false,
                    "sequence": 0,
                    "draggable": true,
                    "is_deleted": true,
                    "updated_by": "6360e17547fbf84e159a3777",
                    "deleted_by": null,
                    "_id": "63b6ce9674af1e81317ef2ff"
                }
            ],
            "name": {
                "en": "Please rate the following items c",
                "ar": "يرجى تقييم العناصر التالية"
            },
            "sequence": 0
        }
    ]
}


问:
InvalidArgumentError: Offline Reinforcement Learning
I have tried to apply offline reinforcement learning based on X, Y and Z acceleration axes to control machine thrust and torque. I applied 1DCNN for the model and also the gym environment. When
I run the code I got the InvalidArgumentError in DQNAgent.Could you please help me to figure it out?

```<code>import pandas as pd
from google.colab import files
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
import gym
import tensorflow as tf
import random
import matplotlib.pyplot as plt

# List of Excel file names
xlsx_file_names = ['TBM20.xlsx', 'TBM21.xlsx','TBM22.xlsx','TBM23.xlsx','TBM24.xlsx']

# List to store dataframes
df_list = []

for file_name in xlsx_file_names:
  # Allow user to upload Excel file to Colab
  uploaded = files.upload()

  # Read excel file into dataframe
  df = pd.read_excel(file_name)
  df_list.append(df)

# Load and preprocess the data
thrust = df["thrust"]  # thrust data
torque = df["torque"]  # torque data
acceleration = df[["X","Y","Z"]]  # acceleration data
thrust = thrust / thrust.max()
torque = torque / torque.max()
acceleration = acceleration / acceleration.max()
df = np.concatenate((thrust[:, np.newaxis], torque[:, np.newaxis], acceleration), axis=1)

# Define the environment
class TBMAccelerationEnv(gym.Env):
  def __init__(self):
    self.state_space = 6
    self.action_space = 2
    self.current_state = np.zeros(self.state_space)

  def reset(self):
  # Reset the state of the environment
    self.current_state = np.zeros(self.state_space)
    return self.current_state

  def step(self, action):
    # Update the state based on the current action and some random noise
    self.current_state = self.current_state + action + np.random.normal(0, 0.1, size=(6,))

    # Calculate the reward based on the state
    reward = 0
    if abs(self.current_state[2:]).max() > 1:  # penalize large acceleration
      reward = -1
    elif abs(self.current_state[2:]).max() < 0.5:  # reward small acceleration
      reward = 1

    return self.current_state, reward, False

# Create the environment
env = TBMAccelerationEnv()

# Define the agent
class DQNAgent:
  def __init__(self, env):
    self.env = env
    self.state_space = env.state_space
    self.action_space = env.action_space
    self.memory = []
    self.gamma = 0.95  # discount rate
    self.epsilon = 1.0  # exploration rate
    self.epsilon_min = 0.01
    self.epsilon_decay = 0.995
    self.learning_rate = 0.001
    self.model = self._build_model()
    self.target_model = self._build_model()  # target model used to stabilize training
    self.target_model.set_weights(self.model.get_weights())

  def _build_model(self):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(self.state_space, 1)))
    model.add(tf.keras.layers.MaxPooling1D(pool_size=2))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(64, activation='relu'))  # modified
    model.add(tf.keras.layers.Dense(self.action_space, activation='linear'))  # modified
    model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam())
    return model
    model.summary()

  def act(self, state):
    reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the input to (batch_size, time_steps, features)
    if np.random.rand() <= self.epsilon:
      return random.randrange(self.action_space)
    act_values = self.model.predict(reshaped_state)
    return np.argmax(act_values[0])

  def update(self, state, action, next_state, reward):
    reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the input to (batch_size, time_steps, features)
    reshaped_next_state = tf.keras.layers.Reshape((1,self.state_space))(next_state)  # reshape the input to (batch_size, time_steps, features)
    self.memory.append((reshaped_state, action, reshaped_next_state, reward))
    batch_size = 32
    if len(self.memory) > batch_size:
      batch = random.sample(self.memory, batch_size)
      for state, action, next_state, reward in batch:
        target = reward + self.gamma * np.amax(self.target_model.predict(next_state)[0])
        target_f = self.model.predict(state)
        target_f[0][action] = target
        self.model.fit(state, target_f, epochs=1, verbose=0)
        if self.epsilon > self.epsilon_min:
          self.epsilon *= self.epsilon_decay

# Create the agent
agent = DQNAgent(env)

# Train the agent
num_episodes = 1000
for episode in range(num_episodes):
  state = env.reset()
  done = False
  while not done:
    action = agent.act(state)
    next_state, reward, done = env.step(action)
    agent.update(state, action, next_state, reward)
    state = next_state
</code>```

Here is the error which I have received.

```<code>   >     InvalidArgumentError                      Traceback (most recent call last)
    >     <ipython-input-14-6d726fa8d030> in <module>
    >           8   done = False
    >           9   while not done:
    >     ---> 10     action = agent.act(state)
    >          11     next_state, reward, done = env.step(action)
    >          12     agent.update(state, action, next_state, reward)
    >
    >          2 frames
    >         <ipython-input-13-fef419475f26> in act(self, state)
    >          56
    >          57   def act(self, state):
    >      ---> 58     reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the
    > input to (batch_size, time_steps, features)
    >          59     if np.random.rand() <= self.epsilon:
    >          60       return random.randrange(self.action_space)
    >
    >     /usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py
    > in error_handler(*args, **kwargs)
    >          65     except Exception as e:  # pylint: disable=broad-except
    >          66       filtered_tb = _process_traceback_frames(e.__traceback__)
    >     ---> 67       raise e.with_traceback(filtered_tb) from None
    >          68     finally:
    >          69       del filtered_tb
    >
    >     /usr/local/lib/python3.8/dist-packages/tensorflow/python/eager/execute.py
    > in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
    >          52   try:
    >          53     ctx.ensure_initialized()
    >     ---> 54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
    >          55                                         inputs, attrs, num_outputs)
    >          56   except core._NotOkStatusException as e:
    >
    >     InvalidArgumentError: Exception encountered when calling layer "reshape_1" (type Reshape).
    >
    >     Input to reshape is a tensor with 6 values, but the requested shape has 36 [Op:Reshape]
    >
    >     Call arguments received by layer "reshape_1" (type Reshape):
    >       • inputs=tf.Tensor(shape=(6,), dtype=float32)
</code>```

Body:
I have tried to apply offline reinforcement learning based on X, Y and Z acceleration axes to control machine thrust and torque. I applied 1DCNN for the model and also the gym environment. When
I run the code I got the InvalidArgumentError in DQNAgent.Could you please help me to figure it out?

import pandas as pd
from google.colab import files
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
import gym
import tensorflow as tf
import random
import matplotlib.pyplot as plt

# List of Excel file names
xlsx_file_names = ['TBM20.xlsx', 'TBM21.xlsx','TBM22.xlsx','TBM23.xlsx','TBM24.xlsx']

# List to store dataframes
df_list = []

for file_name in xlsx_file_names:
  # Allow user to upload Excel file to Colab
  uploaded = files.upload()

  # Read excel file into dataframe
  df = pd.read_excel(file_name)
  df_list.append(df)

# Load and preprocess the data
thrust = df["thrust"]  # thrust data
torque = df["torque"]  # torque data
acceleration = df[["X","Y","Z"]]  # acceleration data
thrust = thrust / thrust.max()
torque = torque / torque.max()
acceleration = acceleration / acceleration.max()
df = np.concatenate((thrust[:, np.newaxis], torque[:, np.newaxis], acceleration), axis=1)

# Define the environment
class TBMAccelerationEnv(gym.Env):
  def __init__(self):
    self.state_space = 6
    self.action_space = 2
    self.current_state = np.zeros(self.state_space)

  def reset(self):
  # Reset the state of the environment
    self.current_state = np.zeros(self.state_space)
    return self.current_state

  def step(self, action):
    # Update the state based on the current action and some random noise
    self.current_state = self.current_state + action + np.random.normal(0, 0.1, size=(6,))

    # Calculate the reward based on the state
    reward = 0
    if abs(self.current_state[2:]).max() > 1:  # penalize large acceleration
      reward = -1
    elif abs(self.current_state[2:]).max() < 0.5:  # reward small acceleration
      reward = 1

    return self.current_state, reward, False

# Create the environment
env = TBMAccelerationEnv()

# Define the agent
class DQNAgent:
  def __init__(self, env):
    self.env = env
    self.state_space = env.state_space
    self.action_space = env.action_space
    self.memory = []
    self.gamma = 0.95  # discount rate
    self.epsilon = 1.0  # exploration rate
    self.epsilon_min = 0.01
    self.epsilon_decay = 0.995
    self.learning_rate = 0.001
    self.model = self._build_model()
    self.target_model = self._build_model()  # target model used to stabilize training
    self.target_model.set_weights(self.model.get_weights())

  def _build_model(self):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(self.state_space, 1)))
    model.add(tf.keras.layers.MaxPooling1D(pool_size=2))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(64, activation='relu'))  # modified
    model.add(tf.keras.layers.Dense(self.action_space, activation='linear'))  # modified
    model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam())
    return model
    model.summary()

  def act(self, state):
    reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the input to (batch_size, time_steps, features)
    if np.random.rand() <= self.epsilon:
      return random.randrange(self.action_space)
    act_values = self.model.predict(reshaped_state)
    return np.argmax(act_values[0])

  def update(self, state, action, next_state, reward):
    reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the input to (batch_size, time_steps, features)
    reshaped_next_state = tf.keras.layers.Reshape((1,self.state_space))(next_state)  # reshape the input to (batch_size, time_steps, features)
    self.memory.append((reshaped_state, action, reshaped_next_state, reward))
    batch_size = 32
    if len(self.memory) > batch_size:
      batch = random.sample(self.memory, batch_size)
      for state, action, next_state, reward in batch:
        target = reward + self.gamma * np.amax(self.target_model.predict(next_state)[0])
        target_f = self.model.predict(state)
        target_f[0][action] = target
        self.model.fit(state, target_f, epochs=1, verbose=0)
        if self.epsilon > self.epsilon_min:
          self.epsilon *= self.epsilon_decay

# Create the agent
agent = DQNAgent(env)

# Train the agent
num_episodes = 1000
for episode in range(num_episodes):
  state = env.reset()
  done = False
  while not done:
    action = agent.act(state)
    next_state, reward, done = env.step(action)
    agent.update(state, action, next_state, reward)
    state = next_state

Here is the error which I have received.

   >     InvalidArgumentError                      Traceback (most recent call last)
    >     <ipython-input-14-6d726fa8d030> in <module>
    >           8   done = False
    >           9   while not done:
    >     ---> 10     action = agent.act(state)
    >          11     next_state, reward, done = env.step(action)
    >          12     agent.update(state, action, next_state, reward)
    >
    >          2 frames
    >         <ipython-input-13-fef419475f26> in act(self, state)
    >          56
    >          57   def act(self, state):
    >      ---> 58     reshaped_state = tf.keras.layers.Reshape((1,self.state_space))(state)  # reshape the
    > input to (batch_size, time_steps, features)
    >          59     if np.random.rand() <= self.epsilon:
    >          60       return random.randrange(self.action_space)
    >
    >     /usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py
    > in error_handler(*args, **kwargs)
    >          65     except Exception as e:  # pylint: disable=broad-except
    >          66       filtered_tb = _process_traceback_frames(e.__traceback__)
    >     ---> 67       raise e.with_traceback(filtered_tb) from None
    >          68     finally:
    >          69       del filtered_tb
    >
    >     /usr/local/lib/python3.8/dist-packages/tensorflow/python/eager/execute.py
    > in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
    >          52   try:
    >          53     ctx.ensure_initialized()
    >     ---> 54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
    >          55                                         inputs, attrs, num_outputs)
    >          56   except core._NotOkStatusException as e:
    >
    >     InvalidArgumentError: Exception encountered when calling layer "reshape_1" (type Reshape).
    >
    >     Input to reshape is a tensor with 6 values, but the requested shape has 36 [Op:Reshape]
    >
    >     Call arguments received by layer "reshape_1" (type Reshape):
    >       • inputs=tf.Tensor(shape=(6,), dtype=float32)


问:
What does 'static Strings arr[]' means in java?
I am trying to convert 2019 into "two zero one nine" with the help of recursion in java.

```<code>enter code herestatic String digits[]={"zero","one","two","three","four","five","six","seven",
"eight","nine"};
public static void printDigits(int number) {
    if(number==0){
        return;
    }
    int lastDigit=number%10;
    printDigits(number/10);
    System.out.print(digits[lastDigit]+" ");
}

public static void main(String[] args) {
    printDigits(2019);
}
</code>```

}

Body:
I am trying to convert 2019 into "two zero one nine" with the help of recursion in java.

enter code herestatic String digits[]={"zero","one","two","three","four","five","six","seven",
"eight","nine"};
public static void printDigits(int number) {
    if(number==0){
        return;
    }
    int lastDigit=number%10;
    printDigits(number/10);
    System.out.print(digits[lastDigit]+" ");
}

public static void main(String[] args) {
    printDigits(2019);
}

}


问:
How to install llvm as c/c++ library?
I'm trying to compile a code snippet that uses llvm as c++ library but I'm getting errors such as the compiler could not find header files.

The compiler commands I used are:

```<code>clang++ file.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs`
</code>```

and

```<code>clang++ file.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs` -v -fno-exceptions
</code>```

I've also tried to specify the include directory:

```<code>clang++ parser.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs` -v -fno-exceptions -I$(llvm-config –includedir)
</code>```

and with specifying manually the path to the lib.
However, nothing was successful.
It seems that I should install llvm as library apart from it being installed as a tool - but I can't find any reasonable description on how to do it.

If I'm right and it should be somehow installed, I would appreciate your help for explaining how to do that. If it shouldn't and you can see any other issue that is preventing me from compiling the code, I would appreciate your help in that.
Thanks in advance!

Title: How to install llvm as c/c++ library?

Body:
I'm trying to compile a code snippet that uses llvm as c++ library but I'm getting errors such as the compiler could not find header files.

The compiler commands I used are:

clang++ file.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs`

and

clang++ file.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs` -v -fno-exceptions

I've also tried to specify the include directory:

clang++ parser.cpp -o reader `llvm-config --cxxflags --libs --ldflags --system-libs` -v -fno-exceptions -I$(llvm-config –includedir)

and with specifying manually the path to the lib.
However, nothing was successful.
It seems that I should install llvm as library apart from it being installed as a tool - but I can't find any reasonable description on how to do it.

If I'm right and it should be somehow installed, I would appreciate your help for explaining how to do that. If it shouldn't and you can see any other issue that is preventing me from compiling the code, I would appreciate your help in that.
Thanks in advance!


问:
Microsoft Partner Center usb driver cab file submission issues
In order to authenticate the usb driver that was used, I attempted to submit hardware to the Microsoft Partner Center.
However, the cause of the error is not indicated and only the phrase "Error" is displayed.

I made the cab file as the link below.

https://learn.microsoft.com/en-us/windows-hardware/drivers/dashboard/code-signing-attestation

```<code>.OPTION EXPLICIT
.Set CabinetFileCountThreshold=0
.Set FolderFileCountThreshold=0
.Set FolderSizeThreshold=0
.Set MaxCabinetSize=0
.Set MaxDiskFileCount=0
.Set MaxDiskSize=0
.Set CompressionType=MSZIP
.Set Cabinet=on
.Set Compress=on
.Set CabinetNameTemplate=USB_DRIVER_x64.cab
.Set DestinationDir=USB_DRIVER_x64
D:\USB\DRIVER_x64.inf
D:\USB\DRIVER_x64.sys
D:\USB\DRIVER_x64.pdb
D:\USB\DRIVER_x64.cat
</code>```

The .inf, .sys, .pdb, and .cat files were all included, and the .cat and .pdb files were excluded, but the results were the same.

Body:
In order to authenticate the usb driver that was used, I attempted to submit hardware to the Microsoft Partner Center.
However, the cause of the error is not indicated and only the phrase "Error" is displayed.

I made the cab file as the link below.

https://learn.microsoft.com/en-us/windows-hardware/drivers/dashboard/code-signing-attestation

.OPTION EXPLICIT
.Set CabinetFileCountThreshold=0
.Set FolderFileCountThreshold=0
.Set FolderSizeThreshold=0
.Set MaxCabinetSize=0
.Set MaxDiskFileCount=0
.Set MaxDiskSize=0
.Set CompressionType=MSZIP
.Set Cabinet=on
.Set Compress=on
.Set CabinetNameTemplate=USB_DRIVER_x64.cab
.Set DestinationDir=USB_DRIVER_x64
D:\USB\DRIVER_x64.inf
D:\USB\DRIVER_x64.sys
D:\USB\DRIVER_x64.pdb
D:\USB\DRIVER_x64.cat

The .inf, .sys, .pdb, and .cat files were all included, and the .cat and .pdb files were excluded, but the results were the same.


问:
Convert the below JSON content to CSV with header
I want to convert the below content from JSON to CSV with the keys as headers thru jq. Please help.

{
  "BackupJobs": [
    {
      "AccountId": "12345678",
      "BackupJobId": "asd8f6wehrnvas-cker2-dfne",
      "BackupVaultName": "aws/efs/automatic-backup-vault",
      "BackupVaultArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-vault:aws/efs/automatic-backup-vault",
      "RecoveryPointArn": "arn:aws:backup:ha-middleeast-1:12345678:recovery-point:asd8f6wehrnvas-cker2-dfne",
      "ResourceArn": "arn:aws:elasticfilesystem:ha-middleeast-1:12345678:file-system/fs-47jsg3y47",
      "CreationDate": "2023-12-31T10:30:00+05:30",
      "CompletionDate": "2023-01-09T11:56:40.074000+05:30",
      "State": "COMPLETED",
      "PercentDone": "100.0",
      "BackupSizeInBytes": 0,
      "IamRoleArn": "arn:aws:iam::12345678:role/aws-service-role/backup.amazonaws.com/backuprole",
      "CreatedBy": {
        "BackupPlanId": "aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-plan:aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanVersion": "asd8f6wehrnvas-cker2-dfne",
        "BackupRuleId": "asd8f6wehrnvas-cker2-dfne"
      },
      "StartBy": "2023-01-09T18:30:00+05:30",
      "ResourceType": "EFS",
      "IsParent": false
    },
    {
      "AccountId": "12345678",
      "BackupJobId": "asd8f6wehrnvas-cker2-dfne",
      "BackupVaultName": "aws/efs/automatic-backup-vault",
      "BackupVaultArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-vault:aws/efs/automatic-backup-vault",
      "RecoveryPointArn": "arn:aws:backup:ha-middleeast-1:12345678:recovery-point:asd8f6wehrnvas-cker2-dfne",
      "ResourceArn": "arn:aws:elasticfilesystem:ha-middleeast-1:12345678:file-system/fs-47jsg3y47",
      "CreationDate": "2023-12-31T10:30:00+05:30",
      "CompletionDate": "2023-01-09T11:56:40.074000+05:30",
      "State": "COMPLETED",
      "PercentDone": "100.0",
      "BackupSizeInBytes": 0,
      "IamRoleArn": "arn:aws:iam::12345678:role/aws-service-role/backup.amazonaws.com/backuprole",
      "CreatedBy": {
        "BackupPlanId": "aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-plan:aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanVersion": "asd8f6wehrnvas-cker2-dfne",
        "BackupRuleId": "asd8f6wehrnvas-cker2-dfne"
      },
      "StartBy": "2023-01-09T18:30:00+05:30",
      "ResourceType": "EFS",
      "IsParent": false
    }
  ]
}
```
<p>The below command works to convert JSON to CSV of the values. Cant figure out to put the keys as headers.</p>
```aws backup list-backup-jobs --output json |
jq -r '.BackupJobs | map([.AccountId,.BackupJobId,.BackupVaultName,.RecoveryPointArn,.ResourceArn,.CreationDate,.CompletionDate,.State,.PercentDone,.BackupSizeInBytes,.ResourceType]
                   | join(", "))
                   | join("\n")'
```

Keys are AccountId, BackupJobId, BackupVaultName......

Body:
I want to convert the below content from JSON to CSV with the keys as headers thru jq. Please help.

{
  "BackupJobs": [
    {
      "AccountId": "12345678",
      "BackupJobId": "asd8f6wehrnvas-cker2-dfne",
      "BackupVaultName": "aws/efs/automatic-backup-vault",
      "BackupVaultArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-vault:aws/efs/automatic-backup-vault",
      "RecoveryPointArn": "arn:aws:backup:ha-middleeast-1:12345678:recovery-point:asd8f6wehrnvas-cker2-dfne",
      "ResourceArn": "arn:aws:elasticfilesystem:ha-middleeast-1:12345678:file-system/fs-47jsg3y47",
      "CreationDate": "2023-12-31T10:30:00+05:30",
      "CompletionDate": "2023-01-09T11:56:40.074000+05:30",
      "State": "COMPLETED",
      "PercentDone": "100.0",
      "BackupSizeInBytes": 0,
      "IamRoleArn": "arn:aws:iam::12345678:role/aws-service-role/backup.amazonaws.com/backuprole",
      "CreatedBy": {
        "BackupPlanId": "aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-plan:aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanVersion": "asd8f6wehrnvas-cker2-dfne",
        "BackupRuleId": "asd8f6wehrnvas-cker2-dfne"
      },
      "StartBy": "2023-01-09T18:30:00+05:30",
      "ResourceType": "EFS",
      "IsParent": false
    },
    {
      "AccountId": "12345678",
      "BackupJobId": "asd8f6wehrnvas-cker2-dfne",
      "BackupVaultName": "aws/efs/automatic-backup-vault",
      "BackupVaultArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-vault:aws/efs/automatic-backup-vault",
      "RecoveryPointArn": "arn:aws:backup:ha-middleeast-1:12345678:recovery-point:asd8f6wehrnvas-cker2-dfne",
      "ResourceArn": "arn:aws:elasticfilesystem:ha-middleeast-1:12345678:file-system/fs-47jsg3y47",
      "CreationDate": "2023-12-31T10:30:00+05:30",
      "CompletionDate": "2023-01-09T11:56:40.074000+05:30",
      "State": "COMPLETED",
      "PercentDone": "100.0",
      "BackupSizeInBytes": 0,
      "IamRoleArn": "arn:aws:iam::12345678:role/aws-service-role/backup.amazonaws.com/backuprole",
      "CreatedBy": {
        "BackupPlanId": "aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanArn": "arn:aws:backup:ha-middleeast-1:12345678:backup-plan:aws/efs/asd8f6wehrnvas-cker2-dfne",
        "BackupPlanVersion": "asd8f6wehrnvas-cker2-dfne",
        "BackupRuleId": "asd8f6wehrnvas-cker2-dfne"
      },
      "StartBy": "2023-01-09T18:30:00+05:30",
      "ResourceType": "EFS",
      "IsParent": false
    }
  ]
}

The below command works to convert JSON to CSV of the values. Cant figure out to put the keys as headers.

aws backup list-backup-jobs --output json |
jq -r '.BackupJobs | map([.AccountId,.BackupJobId,.BackupVaultName,.RecoveryPointArn,.ResourceArn,.CreationDate,.CompletionDate,.State,.PercentDone,.BackupSizeInBytes,.ResourceType]
                   | join(", "))
                   | join("\n")'

Keys are AccountId, BackupJobId, BackupVaultName......


问:
Average only items less than SlidesPerView in Swiper js
I'm using Swiper js on more than one page, I want to center the items because some pages have less number of items, but I don't want to interfere with items whose number of items is equal to or greater than SlidesPerView.

I added "justify-content-center" to the swiper-wrapper class, but this time the slider that meets the SlidesPerView is broken.


问:
WooCommerce PHP API: Bulk save products
I wanted to know if it is possible to save multiple products in bulk using the WooCommerce PHP API. I currently have 1000 products that I have to regularly reimport from a CSV file, and when I save them one by one through the Product class, it takes >10 minutes. I searched through the Docs but didn't find anything.

Title: WooCommerce PHP API: Bulk save products


问:
How to kubernetes scheduler log file?
As you know during od scheduling in kubernetes many steps are done and also many messages are printed for example with: klog.Infof(""). I would like to check all printed messages and the events happend in scheduler. How I can check kubernetes scheduler log file? kubectl get events or kubectl describe pod  are not useful for this purpose.

I checked the answer from here, but journalctl -u apiserver -f  did not show kuberenets scheduler logs.

Title: How to kubernetes scheduler log file?


问:
Where are ETW providers stored?

Where are ETW providers stored? Do they run as processes on Windows?

What does the ProviderId parameter in EventRegister() refer to? Does it refer to an existing ETW provider on the system, or it can be some arbitrary value?

Title: Where are ETW providers stored?


问:
pictures are not shown in django production site
I have a django website in production. Everything works fine except pictures are not shown. The pictures are not stored in the database but located in a different location on the server.
When I inspect the site than the url is shown correctly

This is in my template

```<code>{% if img_url != "" %}
    <img scr="{{ img_url|safe }}" width="500" height="300">
    <br>
{% else %}
{% endif %}
</code>```

This is in my view how I generate the url. The pictures are located in each program and link_picture is just the name and ending of that picture e.g. picture1.png

```<code>url = os.path.join(settings.MEDIA_ROOT,project.get_program_display(),project.link_picture)
    if os.path.exists(url):
        img_url = url
    else:
        img_url = ""
</code>```

This is in my settings

```<code>STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join('/mnt/data/import', 'media')
</code>```

This is in my apache2 config file

```<code>Alias /static /home/user1/FDB/static
    <Directory /home/user1/FDB/static>
            Require all granted
    </Directory>

    Alias /media /mnt/data/import/media
    <Directory /mnt/data/import/media>
            Require all granted
    </Directory>

    <Directory /home/user1/FDB/fdb>
            <Files wsgi.py>
                    Require all granted
            </Files>
    </Directory>

    WSGIScriptAlias / /home/user1/FDB/fdb/wsgi.py
    WSGIDaemonProcess django_app python-path=/home/user1/FDB python-home=/home/user1/FDB/venv
    WSGIProcessGroup django_app
</code>```

Any help is appreciated.

Body:
I have a django website in production. Everything works fine except pictures are not shown. The pictures are not stored in the database but located in a different location on the server.
When I inspect the site than the url is shown correctly

This is in my template

{% if img_url != "" %}

{% else %}
{% endif %}

This is in my view how I generate the url. The pictures are located in each program and link_picture is just the name and ending of that picture e.g. picture1.png

url = os.path.join(settings.MEDIA_ROOT,project.get_program_display(),project.link_picture)
    if os.path.exists(url):
        img_url = url
    else:
        img_url = ""

This is in my settings

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join('/mnt/data/import', 'media')

This is in my apache2 config file

Alias /static /home/user1/FDB/static
    <Directory /home/user1/FDB/static>
            Require all granted
    </Directory>

    Alias /media /mnt/data/import/media
    <Directory /mnt/data/import/media>
            Require all granted
    </Directory>

    <Directory /home/user1/FDB/fdb>
            <Files wsgi.py>
                    Require all granted
            </Files>
    </Directory>

    WSGIScriptAlias / /home/user1/FDB/fdb/wsgi.py
    WSGIDaemonProcess django_app python-path=/home/user1/FDB python-home=/home/user1/FDB/venv
    WSGIProcessGroup django_app

Any help is appreciated.


问:
Spotify API revoke bearer token without refresh
I have this particular code that I use to retrieve Artist detail using Spotify API,

```<code>       function getspotify(artist) {
        fetch(
          "https://api.spotify.com/v1/search" +
            "?q=" +
            artist +
            "&type=artist&limit=10&offset=0",
          {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization:
                "Bearer " +
                "XXXX",
            },
          }
        ).then((response) => {
          response.json().then((data) => {
            var myjson = JSON.stringify(data, null, 2);
            console.log(myjson);
            Object.keys(data["artists"]).forEach(function (key) {
              ddg = data["artists"].items;
              console.log(ddg);});});});}
</code>```

The problem is, after one hour the bearer token expires and I have to manually revoke the token from spotify's console, Is there a way to keep the bearer token active forever ?

Body:
I have this particular code that I use to retrieve Artist detail using Spotify API,

       function getspotify(artist) {
        fetch(
          "https://api.spotify.com/v1/search" +
            "?q=" +
            artist +
            "&type=artist&limit=10&offset=0",
          {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization:
                "Bearer " +
                "XXXX",
            },
          }
        ).then((response) => {
          response.json().then((data) => {
            var myjson = JSON.stringify(data, null, 2);
            console.log(myjson);
            Object.keys(data["artists"]).forEach(function (key) {
              ddg = data["artists"].items;
              console.log(ddg);});});});}

The problem is, after one hour the bearer token expires and I have to manually revoke the token from spotify's console, Is there a way to keep the bearer token active forever ?


问:
nebula-spark-connector getting connection timeout in NebulaGraph
Some details:

NebulaGraph version is 3.2.0

spark-connector version is 3.0.0

Deployment way: Docker

Aliyun's own test machine built with docker
When I use spark-writer to connect to nebula connection failed connect time out

```<code>def getNebulaconnectionConfig(): NebulaConnectionConfig={ // connection config without ssl

val config=

NebulaConnectionConfig .builder()

.withMetaAddress( metaAddress ="112.

.125:9559") .withGraphAddress(graphAddress="112.

.125:9669") .withConenctionRetry( connectionRetry=2)

.build()
</code>```

It gives the error as follows

```<code>com.facebook.thrift.transport.TTransportException Create breakpoint:java.net.SocketTineoutException:connect tined out at com.facebook.thrift.transport.TSocket.open(TSocket.1ava:206)
at com.vesoft.nebula.client.neta.Hetaclient.getclient(Hetaclient.java:148) at com.vesoft.nebula.client.neta.Metaclient.doConnect(Hetactient,java:127) at com.vesoft.nebula.client.meta.Metaclient.connect(Metaclient.java:116)
at com.vesoft.nebula.connector.nebula.MetaProvider.<init>(MetaProvider.scala:53) at com.vesoft.nebula.connector,writer.Nebulaliriter.<init>(Nebutawriter.scala:22)
at com.vesoft.nebula.connector.writer.NebulaVertexiiriter.<init>(NebulaVentexWriter.scala:18)
at com.vesoft.nebula.connector.writer.NebulaVertexWriterFactory.createDatalriter(NebulaSourcenriter.scala:28) at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTaskS.run(iiriteToDataSourceV2Exec.scala:113)
at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2ExecSSanonfunSdoExecute$2.apply(WriteToDataSource at org.apache,spark.sql.execution.datasources.v2.WriteToDataSourceV2ExecSSanonfunSdoExecute$2.apply(WriteToDataSource at org.apache.spark.scheduler.ResultTask.runTask(ResultTask,scala:90)
at org.apache.spark.scheduler.Task.run(Task,scala:123)
at org.apache,spark.executor.ExecutorSTaskRunnerSSanonfunS10.apply(Executor.scala:408) at org.apache.spark.util.UtilsS.tryWithSafeFinally(Utils,scala:1360)
at org.apache.spark.executor.ExecutorSTaskRunner.run(Executor,scala:414) <3 internal lines> Caused by: java.net.SocketTineoutException Createbreakpoint: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketInpl.socketConnect(OualStackPLainSocketImpl.java:81)
</code>```

Want to know why this error occurs.

Body:
Some details:

NebulaGraph version is 3.2.0

spark-connector version is 3.0.0

Deployment way: Docker

Aliyun's own test machine built with docker
When I use spark-writer to connect to nebula connection failed connect time out

def getNebulaconnectionConfig(): NebulaConnectionConfig={ // connection config without ssl

val config=

NebulaConnectionConfig .builder()

.withMetaAddress( metaAddress ="112.

.125:9559") .withGraphAddress(graphAddress="112.

.125:9669") .withConenctionRetry( connectionRetry=2)

.build()

It gives the error as follows

com.facebook.thrift.transport.TTransportException Create breakpoint:java.net.SocketTineoutException:connect tined out at com.facebook.thrift.transport.TSocket.open(TSocket.1ava:206)
at com.vesoft.nebula.client.neta.Hetaclient.getclient(Hetaclient.java:148) at com.vesoft.nebula.client.neta.Metaclient.doConnect(Hetactient,java:127) at com.vesoft.nebula.client.meta.Metaclient.connect(Metaclient.java:116)
at com.vesoft.nebula.connector.nebula.MetaProvider.<init>(MetaProvider.scala:53) at com.vesoft.nebula.connector,writer.Nebulaliriter.<init>(Nebutawriter.scala:22)
at com.vesoft.nebula.connector.writer.NebulaVertexiiriter.<init>(NebulaVentexWriter.scala:18)
at com.vesoft.nebula.connector.writer.NebulaVertexWriterFactory.createDatalriter(NebulaSourcenriter.scala:28) at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTaskS.run(iiriteToDataSourceV2Exec.scala:113)
at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2ExecSSanonfunSdoExecute$2.apply(WriteToDataSource at org.apache,spark.sql.execution.datasources.v2.WriteToDataSourceV2ExecSSanonfunSdoExecute$2.apply(WriteToDataSource at org.apache.spark.scheduler.ResultTask.runTask(ResultTask,scala:90)
at org.apache.spark.scheduler.Task.run(Task,scala:123)
at org.apache,spark.executor.ExecutorSTaskRunnerSSanonfunS10.apply(Executor.scala:408) at org.apache.spark.util.UtilsS.tryWithSafeFinally(Utils,scala:1360)
at org.apache.spark.executor.ExecutorSTaskRunner.run(Executor,scala:414) <3 internal lines> Caused by: java.net.SocketTineoutException Createbreakpoint: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketInpl.socketConnect(OualStackPLainSocketImpl.java:81)

Want to know why this error occurs.


问:
Trying to get user's location via web browser when user did not erased tab, browser is operating on the background and device GPS is on
Trying to get the user's location via a web browser when the user did not erase the tab, the browser operates in the background, and the device GPS is On (running in the background).

I have configured getCurrentPosition and WatchPosition on our site. And everything works perfectly fine when the user is in the browser tab (our site), but when the device is locked (and the user did not erase the tab, the browser is operating in the background, and the device's GPS is On), I am blind. I can't get the user's location. How to do that using Here Map?


问:
Function addDoc() called with invalid data. Unsupported field value: undefined, when an object is passed. React Js
I want to send an "object" in firestore.

```<code>const handleSubmit = () => {
  console.log(typeof(basketArray))
  addDoc(orderCollectionRef, {
    name: newName,
    email: newEmail,
    phone: newPhone,
    home: newHome,
    pinCode: newPinCode,
    city: newCity,
    state: newState,
    numberOfBooks: (basket.length),
    order: basket,
  }).then(makePayment)
}
</code>```

The basket is an object.

I tried using
Object.value(basket)
Object.entries(basket)
Object.key(basket)
none of these worked.

Body:
I want to send an "object" in firestore.

const handleSubmit = () => {
  console.log(typeof(basketArray))
  addDoc(orderCollectionRef, {
    name: newName,
    email: newEmail,
    phone: newPhone,
    home: newHome,
    pinCode: newPinCode,
    city: newCity,
    state: newState,
    numberOfBooks: (basket.length),
    order: basket,
  }).then(makePayment)
}

The basket is an object.

I tried using
Object.value(basket)
Object.entries(basket)
Object.key(basket)
none of these worked.


问:
Why does CallContext.LogicalGetData not return my object?
I want to access the IOwinContext through a provider I can inject into my controllers/services. To achieve that I am using a middleware that sets the context into the CallContext as:

```<code>public static IAppBuilder UseOwinContextInitializer(this IAppBuilder app)
{
    return app.Use(async (context, next) =>
    {
        CallContext.LogicalSetData("IOwinContext", context);
        await next();
    });
}
</code>```

And my provider:

```<code>public class CallContextOwinContextProvider : IOwinContextProvider
{
    public IOwinContext CurrentContext => (IOwinContext) CallContext.LogicalGetData("IOwinContext");
}
</code>```

This always worked fine until I updated my Katana Nugets to v4.x now (everything Owin related).
I don't see why this update impacted the functionality of the CallContext, but no matter what I set in my middleware (even when using a simple hardcoded string) I am not able to recuperate it later.

Does anyone know why this no longer works or if there is a better way to access the IOwinContext elsewhere?

Version 2
Using a snippet I found here does not work either.

```<code>public static IAppBuilder UseOwinContextInitializer(this IAppBuilder app)
{
    return app.Use(async (context, next) =>
    {
        CallContextOwinContextProvider.OwinContext.Value = context;
        await next();
    });
}

public class CallContextOwinContextProvider : IOwinContextProvider
{
    public static AsyncLocal<IOwinContext> OwinContext = new AsyncLocal<IOwinContext>();
    public IOwinContext CurrentContext => OwinContext.Value;
}
</code>```

Body:
I want to access the IOwinContext through a provider I can inject into my controllers/services. To achieve that I am using a middleware that sets the context into the CallContext as:

public static IAppBuilder UseOwinContextInitializer(this IAppBuilder app)
{
    return app.Use(async (context, next) =>
    {
        CallContext.LogicalSetData("IOwinContext", context);
        await next();
    });
}

And my provider:

public class CallContextOwinContextProvider : IOwinContextProvider
{
    public IOwinContext CurrentContext => (IOwinContext) CallContext.LogicalGetData("IOwinContext");
}

This always worked fine until I updated my Katana Nugets to v4.x now (everything Owin related).
I don't see why this update impacted the functionality of the CallContext, but no matter what I set in my middleware (even when using a simple hardcoded string) I am not able to recuperate it later.

Does anyone know why this no longer works or if there is a better way to access the IOwinContext elsewhere?

Version 2
Using a snippet I found here does not work either.

public static IAppBuilder UseOwinContextInitializer(this IAppBuilder app)
{
    return app.Use(async (context, next) =>
    {
        CallContextOwinContextProvider.OwinContext.Value = context;
        await next();
    });
}

public class CallContextOwinContextProvider : IOwinContextProvider
{
    public static AsyncLocal<IOwinContext> OwinContext = new AsyncLocal<IOwinContext>();
    public IOwinContext CurrentContext => OwinContext.Value;
}


问:
Question about the multi-objective reinforcement learning with Pareto set
I am studying and researching reinforcement learning.

Recently, I have been interested in multi-objective reinforcement learning.

An approach using the Pareto set of most MORL papers was presented. Does Pareto set mean here data set? Also, it is thought that using the Pareto set in an environment where the action space is huge will be inefficient by comparing the non-Pareto optimal point and the Pareto optimal point.

I would appreciate it if you could explain the relationship between multi-objective reinforcement learning and the Pareto set, and whether the Pareto set is necessary.


问:
Why can't I dismiss kivy popup with function
Why can't I dismiss kivy popup in function. But if try do directly it's working

press() function is working, and print data, but not closing a popup.

```<code> def random_range():
            """open random range function"""
            rangelist = list(range(80))
            random.shuffle(rangelist)
            filllist = [17, 40, 56, 63]
            for i in rangelist:
                if i in filllist:
                    continue
                def press(obj):
                    """button press function"""
                    user_answer = str(obj.text)[0]
                    print(right_answerc)
                    print(user_answer)
                    self.popup.dismiss
                    return
</code>```
```<code>                main_boxlayout = BoxLayout(orientation='vertical')
                num, header, body, right_answerc = question(i)
                self.popup = Popup(title ='Test popup',
                                   content = main_boxlayout, auto_dismiss = False)
                main_boxlayout.add_widget(Label(text = str(num))) #question number
                main_boxlayout.add_widget(Label(text = str(header))) #question header
                main_boxlayout.add_widget(Label(text = str(right_answerc))) #right answer
                right_answer = (Label(text = str(right_answerc)))
                main_boxlayout.add_widget(right_answer)
                self.main_label = (Label(text = "Your input"))
                main_boxlayout.add_widget(self.main_label)
                button1 = (Button(text = str(body[0])))
                button1.bind(on_press = press)
                button2 = (Button(text = str(body[1])))
                button2.bind(on_press = press)
                button3 = (Button(text = str(body[2])))
                button3.bind(on_press = press)
                button4 = (Button(text = str(body[3])))
                button4.bind(on_press = press)
                button5 = (Button(text = str(body[4])))
                button5.bind(on_press = press)
                button6 = (Button(text = "Next question" ))
</code>```

but this button is working

```<code>                button6.bind(on_release = self.popup.dismiss)
                main_boxlayout.add_widget(button1)
                main_boxlayout.add_widget(button2)
                main_boxlayout.add_widget(button3)
                main_boxlayout.add_widget(button4)
                main_boxlayout.add_widget(button5)
                main_boxlayout.add_widget(button6)
                self.popup.open()

        random_range()
</code>```

All other options, without success

Body:
Why can't I dismiss kivy popup in function. But if try do directly it's working

press() function is working, and print data, but not closing a popup.

 def random_range():
            """open random range function"""
            rangelist = list(range(80))
            random.shuffle(rangelist)
            filllist = [17, 40, 56, 63]
            for i in rangelist:
                if i in filllist:
                    continue
                def press(obj):
                    """button press function"""
                    user_answer = str(obj.text)[0]
                    print(right_answerc)
                    print(user_answer)
                    self.popup.dismiss
                    return

                main_boxlayout = BoxLayout(orientation='vertical')
                num, header, body, right_answerc = question(i)
                self.popup = Popup(title ='Test popup',
                                   content = main_boxlayout, auto_dismiss = False)
                main_boxlayout.add_widget(Label(text = str(num))) #question number
                main_boxlayout.add_widget(Label(text = str(header))) #question header
                main_boxlayout.add_widget(Label(text = str(right_answerc))) #right answer
                right_answer = (Label(text = str(right_answerc)))
                main_boxlayout.add_widget(right_answer)
                self.main_label = (Label(text = "Your input"))
                main_boxlayout.add_widget(self.main_label)
                button1 = (Button(text = str(body[0])))
                button1.bind(on_press = press)
                button2 = (Button(text = str(body[1])))
                button2.bind(on_press = press)
                button3 = (Button(text = str(body[2])))
                button3.bind(on_press = press)
                button4 = (Button(text = str(body[3])))
                button4.bind(on_press = press)
                button5 = (Button(text = str(body[4])))
                button5.bind(on_press = press)
                button6 = (Button(text = "Next question" ))

but this button is working

                button6.bind(on_release = self.popup.dismiss)
                main_boxlayout.add_widget(button1)
                main_boxlayout.add_widget(button2)
                main_boxlayout.add_widget(button3)
                main_boxlayout.add_widget(button4)
                main_boxlayout.add_widget(button5)
                main_boxlayout.add_widget(button6)
                self.popup.open()

        random_range()

All other options, without success


问:
Enterprise Integrator 6.5 Clustering/Loadbalancing
Upon implementing WSO2 EI Clustering and LoadBalancing with Apache on 2 nodes, the routing and functioning of EI management console goes well when only one node is up.
When the 2 nodes are up , the management console behaves unexpectedly (displays home page with missing parts, logout when clicking on any link like list of users,…)
the EI logging displays the following:

WARN - AuthenticationHandler Illegal access attempt at [2023-01-04 18:09:18,0700] from IP address null while trying to authenticate access to service RegistryAdminService
[2023-01-04 18:09:18,708] [EI-Core] ERROR - RegistryAdminServiceClient Error occurred while checking registry mode

log in to the management console and navigate inside


问:
Node fluent-ffmpeg screenshots on Windows
The fluent-ffmpeg package has a function that will create screenshots at even intervals in a video for a given count. The problem with this is that it often spawns a ENAMETOOLONG error on Windows.

To get around this, I copied the relevant parts of the source code that I needed and instead of running it all as one long command, split it up into n many commands (where n is the amount of screenshots).

This seems to work at first. It (sometimes) gets the first screenshot, but then it throws the same ENAMETOOLONG error. How can I get around this?

Here is what I have attmpted:

```<code>const count = 50 // just an example
const dest = path.join(os.tmpdir(), `screenshots_${Date.now()}`)

const interval = 100 / (1 + count)
let timemarks = Array(count)
    .fill(0).map((_, i) => (interval * (i + 1)) + '%')
    .map(mark => {
        if (('' + mark).match(/^([\d.]+)%$/)) {
            // @ts-ignore
            return videoDuration * parseFloat(mark) / 100
        } else {
            return mark
        }
    })
    .map(mark => {
        if (typeof mark === 'number') {
            return mark
        }

        if (mark.indexOf(':') === -1 && mark.indexOf('.') >= 0) {
            return Number(mark)
        }

        const parts = mark.split(':')
        let secs = Number(parts.pop())
        if (parts.length) {
            secs += Number(parts.pop()) * 60
        }

        if (parts.length) {
            secs += Number(parts.pop()) * 3600
        }

        return secs
    })
    .sort((a, b) => a - b)

// my first attempt:
for (const mark of timemarks) {
    this.video
        .screenshot({
            count: 1,
            folder: dest,
            timemarks: [mark],
        })
}

// second attempt:
let i = 0
for (const mark of timemarks) {
    const filename = `frame_${i.toString().padStart(count.toString().length, '0')}.jpg`
    this.video
        .setStartTime(mark)
        .output(path.join(dest, filename))
        .frames(1)
        .run()
    i++
}
</code>```

For context, this.video is just ffmpeg(videoFilePath).

My first attempt, as I previously stated, just throws the same error and doesn't really get anywhere. Sometimes I get the first screenshot, most times I do not.
The second attempt doesn't even do anything. It seems to take it's time doing something, but I don't actually get any screenshots. If they saved anywhere, I don't know where.

Is anyone able to help me with this?

Body:
The fluent-ffmpeg package has a function that will create screenshots at even intervals in a video for a given count. The problem with this is that it often spawns a ENAMETOOLONG error on Windows.

To get around this, I copied the relevant parts of the source code that I needed and instead of running it all as one long command, split it up into n many commands (where n is the amount of screenshots).

This seems to work at first. It (sometimes) gets the first screenshot, but then it throws the same ENAMETOOLONG error. How can I get around this?

Here is what I have attmpted:

const count = 50 // just an example
const dest = path.join(os.tmpdir(), `screenshots_${Date.now()}`)

const interval = 100 / (1 + count)
let timemarks = Array(count)
    .fill(0).map((_, i) => (interval * (i + 1)) + '%')
    .map(mark => {
        if (('' + mark).match(/^([\d.]+)%$/)) {
            // @ts-ignore
            return videoDuration * parseFloat(mark) / 100
        } else {
            return mark
        }
    })
    .map(mark => {
        if (typeof mark === 'number') {
            return mark
        }

        if (mark.indexOf(':') === -1 && mark.indexOf('.') >= 0) {
            return Number(mark)
        }

        const parts = mark.split(':')
        let secs = Number(parts.pop())
        if (parts.length) {
            secs += Number(parts.pop()) * 60
        }

        if (parts.length) {
            secs += Number(parts.pop()) * 3600
        }

        return secs
    })
    .sort((a, b) => a - b)

// my first attempt:
for (const mark of timemarks) {
    this.video
        .screenshot({
            count: 1,
            folder: dest,
            timemarks: [mark],
        })
}

// second attempt:
let i = 0
for (const mark of timemarks) {
    const filename = `frame_${i.toString().padStart(count.toString().length, '0')}.jpg`
    this.video
        .setStartTime(mark)
        .output(path.join(dest, filename))
        .frames(1)
        .run()
    i++
}

For context, this.video is just ffmpeg(videoFilePath).

My first attempt, as I previously stated, just throws the same error and doesn't really get anywhere. Sometimes I get the first screenshot, most times I do not.
The second attempt doesn't even do anything. It seems to take it's time doing something, but I don't actually get any screenshots. If they saved anywhere, I don't know where.

Is anyone able to help me with this?


问:
Render or Load the Lottie file animation then the whole page should be visible
Render or Load the Lottie file animation then the whole page should be visible because right now when the page loads the lottie file loads with a bit dilay, which makes the lottie file section to collaps which spoils the loading experience, so i want the lottie file to render completly first then make the page visible

here is a similar setup on codepen link

`   let homeBannerLottie = bodymovin.loadAnimation({
container: document.querySelector('.h_banner_lottie'),
render: 'svg',
loop: 0,
autoplay: false,
path: './assets/lottie/banner-lottie.json'
});

```<code>    //! visibility home
    let body = document.body;
    let home = document.querySelector('.h_banner');
    let homeLottie = document.querySelector('.h_banner_lottie');

    homeLottie.style.visibility = 'visible';

    setTimeout(() => {
        body.style.visibility = 'visible';
        home.style.visibility = 'visible';
        homeBannerLottie.play();
    }, 500);`
</code>```

Body:
Render or Load the Lottie file animation then the whole page should be visible because right now when the page loads the lottie file loads with a bit dilay, which makes the lottie file section to collaps which spoils the loading experience, so i want the lottie file to render completly first then make the page visible

here is a similar setup on codepen link

`   let homeBannerLottie = bodymovin.loadAnimation({
container: document.querySelector('.h_banner_lottie'),
render: 'svg',
loop: 0,
autoplay: false,
path: './assets/lottie/banner-lottie.json'
});

    //! visibility home
    let body = document.body;
    let home = document.querySelector('.h_banner');
    let homeLottie = document.querySelector('.h_banner_lottie');

    homeLottie.style.visibility = 'visible';

    setTimeout(() => {
        body.style.visibility = 'visible';
        home.style.visibility = 'visible';
        homeBannerLottie.play();
    }, 500);`


问:
Flutter with VS Code- Bad CMake executable: "". Check to make sure it is installed or the value of the "cmake.cmakePath"
I have been using Android Studio to code in Flutter and Dart but decided to switch to VS code because it's lighter. I noticed that When I'm writing and I press Cmd + S; it pops up the error

```<code>Bad CMake executable: "". Check to make sure it is installed or the value of the "cmake.cmakePath" setting contains the correct path
</code>```

I have uninstalled and installed the Cmake extension but the error still persisted.

Body:
I have been using Android Studio to code in Flutter and Dart but decided to switch to VS code because it's lighter. I noticed that When I'm writing and I press Cmd + S; it pops up the error

Bad CMake executable: "". Check to make sure it is installed or the value of the "cmake.cmakePath" setting contains the correct path

I have uninstalled and installed the Cmake extension but the error still persisted.