问:
Mpdf takes too much time to generate PDF
I'm using mPDF in Yii2 php framwork to generate the pdf as report.
getting the result as expected but it is taking too much time to generate the pdf-report (around 5-10 sec).
Pdf

This is the code for mPdf setup

```<code>        ini_set('memory_limit', '6144M');
        set_time_limit(10000);
        $path = \Yii::getAlias("@vendor/MPDF/mpdf.php");
        require_once($path);
        $mpdf = new \mPDF('en-GB-x', '', '', '', 5, 5, 5, 5, 6, 3);
        $mpdf->addPage('P');
        $mpdf->packTableData = true;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->list_indent_first_level = 0;
        $mpdf->showWatermarkText = true;
        $mpdf->watermarkTextAlpha = 0.3;
        $mpdf->simpleTables = true;
        $file_name = '';
</code>```

And this is the main code to generate PDF

```<code>$table = "<table  width='100%'>";
$table .= "<thead>";
$table .= "<tr>";
$table .= "<td colspan='1' style='width: 20%;' align='left'></td>";
$table .= "<td colspan='5' style='width: 60%;' align='center'>";
$table .= "<h3 style='margin-top:20px; font-size: 26px;'>" . $ofc_detail['company_name'] . "</h3>";
$table .= "</td>";
$table .= "<td colspan='1' style='width: 40%; font-size: 12px;' align='center'>";
$table .= "<div><img src='" . $photo . "' width='31' height='50' /><br /></div>";
$table .= "</td>";
$table .= "</tr>";
$table .= "<tr >";
$table .= "<th colspan='7'><center>QUOTE</center></th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th colspan='7' align='left'>Date :" . $quotation_date . "</th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th colspan='7' align='left'>Quotation ID :" . $quotation_id . "</th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th colspan='7' align='left'>Created By :" . $created_by . "</th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th height='40' colspan='7' align='left'></th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th colspan='7' align='left'>To</th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'>Customer Name</th>";
$table .= "<td colspan='6'>" . $cust_name . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'>Mobile </th>";
$table .= "<td colspan='6'>" . $mobile . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'>Company Name</th>";
$table .= "<td colspan='6'>" . $organization . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'>GST No.</th>";
$table .= "<td colspan='6'>" . $gst_no . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'>Address</th>";
$table .= "<td colspan='6'>" . $addr_str . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th align='left'></th>";
$table .= "<td colspan='6'>" . $addr_delivery . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th height='60' colspan='7' align='left'></th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th colspan='7'><center>Sub: - " . $subject . "</center></th>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='7'>Dear Sir,</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='7'>As discussed I am sending you the quotation</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<th height='20' colspan='7' align='left'></th>";
$table .= "</tr>";
$table .= "</thead>";
$table .= "</table>";
$table .= "<table border='1' width='100%'>";
$table .= "<tr>";
$table .= "<th>S.No.</th>";
$table .= "<th>Item Name</th>";
$table .= "<th>MRP</th>";
$table .= "<th>Selling Price</th>";
$table .= "<th>Quantity</th>";
$table .= "<th>Discount</th>";
$table .= "<th>Amount</th>";
$table .= "</tr>";
$table .= "<tbody>";
$i = 1;
$tot = 0;
foreach ($query as $k => $v) {
    $tot = $tot + $v['amt'];
    if ($v['discount'] == '') {
        $discount = '0';
    } else {
        $discount = $v['discount'];
    }
    $table .= "<tr>"
        . "<td align='center'>" . $i++ . "</td>"
        . "<td align='left'>" . $v['name'] . "</td>"
        . "<td align='center'>" . $v['MRP'] . "</td>"
        . "<td align='center'>" . $v['selling_price'] . "</td>"
        . "<td align='center'>" . $v['qty'] . "</td>"
        . "<td align='center'>" . $discount . "%</td>"
        . "<td align='right'>" . $v['amt'] . "</td>"
        . "</tr>";
}
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>TOTAL</td>";
$table .= "<td colspan='1' align='right'>" . $tt_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>DISCOUNT</td>";
$table .= "<td colspan='1' align='right'>" . $dis_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>SUB TOTAL</td>";
$table .= "<td colspan='1' align='right'>" . $sub_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>CGST</td>";
$table .= "<td colspan='1' align='right'>" . $cgst_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>SGST</td>";
$table .= "<td colspan='1' align='right'>" . $sgst_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>IGST</td>";
$table .= "<td colspan='1' align='right'>" . $igst_amt . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td colspan='1'></td>";
$table .= "<td colspan='5' align='right'>CESS</td>";
$table .= "<td colspan='1' align='right'>" . $cess_amt . "</td>";
$table .= "</tr>";

if(!empty($queryToGetOtherItems)){

    foreach ($queryToGetOtherItems as $data) {
        if ($data['discount_percent'] == '') {
            $discount = '0';
        } else {
            $discount = $data['discount_percent'];
        }
        $table .= "<tr>"
        . "<td colspan='1'></td>"
        . "<td colspan='5' align='right'>" . $data['name'] . "</td>"
        . "<td colspan='1' align='right'>" . $data['total_amount'] . "</td>"
        . "</tr>";
    }
    }

    $table .= "<tr>";
    $table .= "<td colspan='1'></td>";
    $table .= "<td colspan='5' align='right'>GRAND TOTAL</td>";
    $table .= "<td colspan='1' align='right'>" . $tot_amt . "</td>";
    $table .= "</tr>";
    $table .= "</tbody>";
    $table .= "</table>";
    $table .= "<table width='100%'>";
    $table .= "</tbody>";
    $table .= "<tr>";
    $table .= "<th height='60' colspan='7' align='left'></th>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td colspan='7' align='left'><strong>TERMS & CONDITIONS :</strong><br>" . $description . "</td>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td align='left' colspan='7'><strong>With Regards</strong><br><br><strong>Name :</strong> " . $ofc_detail['company_name'] . "</td>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td align='left'  colspan='7'><strong>Mobile No</strong> :" . $ofc_detail['ofc_mob_one'] . "</td>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<th height='60' colspan='7' align='left'></th>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td colspan='7'><center>Address : " . $ofc_detail['address'] . "</center></td>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td colspan='7'><center>GST No : " . $ofc_detail['gst_number'] . "</center></td>";
    $table .= "</tr>";
    $table .= "<tr>";
    $table .= "<td colspan='7'><center>E-Mail ID : " . $ofc_detail['ofc_email_one'] . "</center></td>";
    $table .= "</tr>";
    $table .= "</tbody>";
    $table .= "</table>";
}
$file_name = "Quotation_" . $quotation_id . "_" . date('Y_m_d_his') . ".pdf";
$mpdf->WriteHTML($table);
$files = $_SERVER['DOCUMENT_ROOT'] . '/path/' . $file_name;
$content = $mpdf->Output($files, 'F');
</code>```

To resolve the issue I've checked for the following this

Optimized the main query and was able to get response in just 0.26 to 0.30sec
but still not able to generate in less seconds.

Body:
I'm using mPDF in Yii2 php framwork to generate the pdf as report.
getting the result as expected but it is taking too much time to generate the pdf-report (around 5-10 sec).
Pdf

This is the code for mPdf setup

        ini_set('memory_limit', '6144M');
        set_time_limit(10000);
        $path = \Yii::getAlias("@vendor/MPDF/mpdf.php");
        require_once($path);
        $mpdf = new \mPDF('en-GB-x', '', '', '', 5, 5, 5, 5, 6, 3);
        $mpdf->addPage('P');
        $mpdf->packTableData = true;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->list_indent_first_level = 0;
        $mpdf->showWatermarkText = true;
        $mpdf->watermarkTextAlpha = 0.3;
        $mpdf->simpleTables = true;
        $file_name = '';

And this is the main code to generate PDF

$table = "
";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "";
$table .= "
" . $ofc_detail['company_name'] . "
";
$table .= "	";
$table .= "";
$table .= "

";
$table .= "	";
$table .= "
";
$table .= "
";
$table .= "QUOTE	";
$table .= "
";
$table .= "
";
$table .= "Date :" . $quotation_date . "	";
$table .= "
";
$table .= "
";
$table .= "Quotation ID :" . $quotation_id . "	";
$table .= "
";
$table .= "
";
$table .= "Created By :" . $created_by . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "
";
$table .= "
";
$table .= "To	";
$table .= "
";
$table .= "
";
$table .= "Customer Name	";
$table .= "" . $cust_name . "	";
$table .= "
";
$table .= "
";
$table .= "Mobile 	";
$table .= "" . $mobile . "	";
$table .= "
";
$table .= "
";
$table .= "Company Name	";
$table .= "" . $organization . "	";
$table .= "
";
$table .= "
";
$table .= "GST No.	";
$table .= "" . $gst_no . "	";
$table .= "
";
$table .= "
";
$table .= "Address	";
$table .= "" . $addr_str . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "" . $addr_delivery . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "
";
$table .= "
";
$table .= "Sub: - " . $subject . "	";
$table .= "
";
$table .= "
";
$table .= "Dear Sir,	";
$table .= "
";
$table .= "
";
$table .= "As discussed I am sending you the quotation	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "
";
$table .= "
";
$table .= "
";
$table .= "
";
$table .= "
";
$table .= "S.No.	";
$table .= "Item Name	";
$table .= "MRP	";
$table .= "Selling Price	";
$table .= "Quantity	";
$table .= "Discount	";
$table .= "Amount	";
$table .= "
";
$table .= "
";
$i = 1;
$tot = 0;
foreach ($query as $k => $v) {
    $tot = $tot + $v['amt'];
    if ($v['discount'] == '') {
        $discount = '0';
    } else {
        $discount = $v['discount'];
    }
    $table .= "
"
        . "" . $i++ . "	"
        . "" . $v['name'] . "	"
        . "" . $v['MRP'] . "	"
        . "" . $v['selling_price'] . "	"
        . "" . $v['qty'] . "	"
        . "" . $discount . "%	"
        . "" . $v['amt'] . "	"
        . "
";
}
$table .= "
";
$table .= "	";
$table .= "TOTAL	";
$table .= "" . $tt_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "DISCOUNT	";
$table .= "" . $dis_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "SUB TOTAL	";
$table .= "" . $sub_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "CGST	";
$table .= "" . $cgst_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "SGST	";
$table .= "" . $sgst_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "IGST	";
$table .= "" . $igst_amt . "	";
$table .= "
";
$table .= "
";
$table .= "	";
$table .= "CESS	";
$table .= "" . $cess_amt . "	";
$table .= "
";

if(!empty($queryToGetOtherItems)){

    foreach ($queryToGetOtherItems as $data) {
        if ($data['discount_percent'] == '') {
            $discount = '0';
        } else {
            $discount = $data['discount_percent'];
        }
        $table .= "
"
        . "	"
        . "" . $data['name'] . "	"
        . "" . $data['total_amount'] . "	"
        . "
";
    }
    }

    $table .= "
";
    $table .= "	";
    $table .= "GRAND TOTAL	";
    $table .= "" . $tot_amt . "	";
    $table .= "
";
    $table .= "
";
    $table .= "
";
    $table .= "
";
    $table .= "
";
    $table .= "
";
    $table .= "	";
    $table .= "
";
    $table .= "
";
    $table .= "TERMS & CONDITIONS :
" . $description . "	";
    $table .= "
";
    $table .= "
";
    $table .= "With Regards

Name : " . $ofc_detail['company_name'] . "	";
    $table .= "
";
    $table .= "
";
    $table .= "Mobile No :" . $ofc_detail['ofc_mob_one'] . "	";
    $table .= "
";
    $table .= "
";
    $table .= "	";
    $table .= "
";
    $table .= "
";
    $table .= "Address : " . $ofc_detail['address'] . "	";
    $table .= "
";
    $table .= "
";
    $table .= "GST No : " . $ofc_detail['gst_number'] . "	";
    $table .= "
";
    $table .= "
";
    $table .= "E-Mail ID : " . $ofc_detail['ofc_email_one'] . "	";
    $table .= "
";
    $table .= "
";
    $table .= "
";
}
$file_name = "Quotation_" . $quotation_id . "_" . date('Y_m_d_his') . ".pdf";
$mpdf->WriteHTML($table);
$files = $_SERVER['DOCUMENT_ROOT'] . '/path/' . $file_name;
$content = $mpdf->Output($files, 'F');

To resolve the issue I've checked for the following this

Optimized the main query and was able to get response in just 0.26 to 0.30sec
but still not able to generate in less seconds.


来源: stackexchange

问:
Discord.py - '_MissingSentinel' Error when initially joining voice channel
When i make my bot initially join a voice channel with await channel.connect() it produces an error 95% of the time saying the following:

```<code>[ERROR]:discord.state:Exception occurred during Voice Protocol voice server update handler
Traceback (most recent call last):
File "/.local/lib/python3.9/site-packages/discord/state.py", line 157, in logging_coroutine
await coroutine
File "/.local/lib/python3.9/site-packages/discord/voice_client.py", line 337, in on_voice_server_update
await self.ws.close(4000)
AttributeError: '_MissingSentinel' object has no attribute 'close'
</code>```

I have had this error for a while and it doesnt seem to affect the bots ability to join voice channels or play audio, i still worry it will cause problems in the future, does anyone know what this is coming from?

```<code>    async def run_queue(self, guild_id: int):
        self.queue_running.append(guild_id)
        guild = client.get_guild(guild_id)
        ch = guild.get_channel(self.queue[str(guild_id)][0]["channel_id"])
        await ch.connect()
        voice = guild.voice_client

        while str(guild_id) in self.queue:
            if self.print_queue:
                print(self.queue)
            if voice.channel.id != self.queue[str(guild_id)][0]["channel_id"]:
                ch = guild.get_channel(self.queue[str(guild_id)][0]["channel_id"])
                await guild.change_voice_state(channel=ch)

            try:
                voice.play(discord.FFmpegPCMAudio(source=f"Bot/Soundfiles/{str(voice.guild.id)}/{self.queue[str(voice.guild.id)][0]['user_id']}.mp3"))
            except Exception as e:
                print(f"error playing: {e}")
                pass

            while voice.is_playing():
                await asyncio.sleep(0.2)
            else:
                self.remove_queue(str(guild.id))
                if not(str(guild_id) in self.queue):
                    await guild.change_voice_state(channel=None)
                    await voice.disconnect()

        self.queue_running.remove(guild.id)
</code>```

This is the code block that it occurs in, i have narrowed it down to the await ch.connect() line where the error happens although it still executes and works properly

ContentLicense: CC BY-SA 4.0

Body:
When i make my bot initially join a voice channel with await channel.connect() it produces an error 95% of the time saying the following:

[ERROR]:discord.state:Exception occurred during Voice Protocol voice server update handler
Traceback (most recent call last):
File "/.local/lib/python3.9/site-packages/discord/state.py", line 157, in logging_coroutine
await coroutine
File "/.local/lib/python3.9/site-packages/discord/voice_client.py", line 337, in on_voice_server_update
await self.ws.close(4000)
AttributeError: '_MissingSentinel' object has no attribute 'close'

I have had this error for a while and it doesnt seem to affect the bots ability to join voice channels or play audio, i still worry it will cause problems in the future, does anyone know what this is coming from?

    async def run_queue(self, guild_id: int):
        self.queue_running.append(guild_id)
        guild = client.get_guild(guild_id)
        ch = guild.get_channel(self.queue[str(guild_id)][0]["channel_id"])
        await ch.connect()
        voice = guild.voice_client

        while str(guild_id) in self.queue:
            if self.print_queue:
                print(self.queue)
            if voice.channel.id != self.queue[str(guild_id)][0]["channel_id"]:
                ch = guild.get_channel(self.queue[str(guild_id)][0]["channel_id"])
                await guild.change_voice_state(channel=ch)

            try:
                voice.play(discord.FFmpegPCMAudio(source=f"Bot/Soundfiles/{str(voice.guild.id)}/{self.queue[str(voice.guild.id)][0]['user_id']}.mp3"))
            except Exception as e:
                print(f"error playing: {e}")
                pass

            while voice.is_playing():
                await asyncio.sleep(0.2)
            else:
                self.remove_queue(str(guild.id))
                if not(str(guild_id) in self.queue):
                    await guild.change_voice_state(channel=None)
                    await voice.disconnect()

        self.queue_running.remove(guild.id)

This is the code block that it occurs in, i have narrowed it down to the await ch.connect() line where the error happens although it still executes and works properly


问:
Non-resolvable parent POM-Could not transfer artifact
I am new Java developer.I tried to load the build after generating from spring intializer.Receiving the following error while trying to import maven project.

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>dev.example.restapi</groupId>
    <artifactId>dev.restapi.proj</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>dev.restapi.proj</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I tried Maven update , mvn clean install problem is not yet solved.

I tried mvn -U build as suggested

Error received is
[ERROR]     Non-resolvable parent POM for dev.example.restapi:dev.restapi.proj:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:3.0.1 from/to central (https://repo.maven.apache.org/maven2): transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/3.0.1/spring-boot-starter-parent-3.0.1.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connection reset by peer ->

Body:
I am new Java developer.I tried to load the build after generating from spring intializer.Receiving the following error while trying to import maven project.

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>dev.example.restapi</groupId>
    <artifactId>dev.restapi.proj</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>dev.restapi.proj</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I tried Maven update , mvn clean install problem is not yet solved.

I tried mvn -U build as suggested

Error received is
[ERROR]     Non-resolvable parent POM for dev.example.restapi:dev.restapi.proj:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:3.0.1 from/to central (https://repo.maven.apache.org/maven2): transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/3.0.1/spring-boot-starter-parent-3.0.1.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connection reset by peer ->


问:
Is there a way to only style the selected option?
Usually when you create a <select> option field and use color to change the color.
This applies only to when the dropdown is clicked upon and is in an active state.

Is it actually possible to change the color of the option that is selected? So if you look at the code, only make the option Apple red that is selected (when another fruit is selected, make that red). However, the colors of the text need to black in the dropdown.

select option {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option>Apple</option>
  <option>Banana</option>
  <option>Peach</option>
  <option>Strawberry</option>
  <option>Pineapple</option>
</select></code>```

Since this component is a re-used one, I can not edit the HTML structure of it.

I tried to give the options a color, but this resulted in changed all of the option in the active dropdown and not the item selected.

I also looked up other topics and answers in here but every provided code also changes the color in the active dropdown state or they modify the HTML.

Body:
Usually when you create a <select> option field and use color to change the color.
This applies only to when the dropdown is clicked upon and is in an active state.

Is it actually possible to change the color of the option that is selected? So if you look at the code, only make the option Apple red that is selected (when another fruit is selected, make that red). However, the colors of the text need to black in the dropdown.

select option {
  color: red;
}

<select>
  <option>Apple</option>
  <option>Banana</option>
  <option>Peach</option>
  <option>Strawberry</option>
  <option>Pineapple</option>
</select>

Since this component is a re-used one, I can not edit the HTML structure of it.

I tried to give the options a color, but this resulted in changed all of the option in the active dropdown and not the item selected.

I also looked up other topics and answers in here but every provided code also changes the color in the active dropdown state or they modify the HTML.


问:
How to deal with the error serializing dates when they're returned from getServerSideProps?
Whenever I try to return a date object from getServerSideProps, I get an error:

```<code>Error: Error serializing `.post.createdAt` returned from `getServerSideProps` in "/community/[postSlug]".
</code>```

I don't want to manually loop through all the posts on every request and delete (or stringify) the date field.

Is there some automatic way to fix this issue all throughout my next.js project?

Body:
Whenever I try to return a date object from getServerSideProps, I get an error:

Error: Error serializing `.post.createdAt` returned from `getServerSideProps` in "/community/[postSlug]".

I don't want to manually loop through all the posts on every request and delete (or stringify) the date field.

Is there some automatic way to fix this issue all throughout my next.js project?


问:
flutter - how to use barcode scanner in flutter
I am building a POS system for desktop in flutter. I have used this package -> package to get product suggestions and barcode suggestions. It works fine when I search product by manuallay typing. and when I type manually barcode it also works fine. but when I scan the barcode using the barcode scanner it does not add the product in the list.

How can I detect the event in that form field or add product into list using barcode scanner ?

CODE

```<code> Expanded(
                                      child: TypeAheadField(
                                        textFieldConfiguration:
                                            TextFieldConfiguration(
                                                decoration: const InputDecoration(
                                                    label:
                                                        Text("Search Product"),
                                                    prefixIcon: Icon(
                                                        Icons.shopping_bag),
                                                    border:
                                                        OutlineInputBorder()),
                                                controller: _productController),
                                        suggestionsCallback: (pattern) async {
                                          return await POSServices
                                              .getProudctByNameOrBarcode(
                                                  pattern);
                                        },
                                        minCharsForSuggestions: 1,
                                        itemBuilder: (context, suggestion) {
                                          suggestion as Map;
                                          return ListTile(
                                            leading: const Icon(
                                              Icons.shopping_bag_outlined,
                                              color: Colors.blue,
                                            ),
                                            title: Text(
                                                suggestion['english_name']),
                                            subtitle: Text(
                                                "Rs. ${suggestion['sale_price']}"),
                                          );
                                        },
                                        onSuggestionSelected: (suggestion) {
                                          productData = suggestion as Map;

                              _productController.text =suggestion['english_name'].toString();

       posBuilderController.getProductDetailsWithMultiplePrices(
                                                    suggestion['product_id'].toString()).then((data) {
//code
});
                                        },

                                      ),
                                    ),
</code>```

Body:
I am building a POS system for desktop in flutter. I have used this package -> package to get product suggestions and barcode suggestions. It works fine when I search product by manuallay typing. and when I type manually barcode it also works fine. but when I scan the barcode using the barcode scanner it does not add the product in the list.

How can I detect the event in that form field or add product into list using barcode scanner ?

CODE

 Expanded(
                                      child: TypeAheadField(
                                        textFieldConfiguration:
                                            TextFieldConfiguration(
                                                decoration: const InputDecoration(
                                                    label:
                                                        Text("Search Product"),
                                                    prefixIcon: Icon(
                                                        Icons.shopping_bag),
                                                    border:
                                                        OutlineInputBorder()),
                                                controller: _productController),
                                        suggestionsCallback: (pattern) async {
                                          return await POSServices
                                              .getProudctByNameOrBarcode(
                                                  pattern);
                                        },
                                        minCharsForSuggestions: 1,
                                        itemBuilder: (context, suggestion) {
                                          suggestion as Map;
                                          return ListTile(
                                            leading: const Icon(
                                              Icons.shopping_bag_outlined,
                                              color: Colors.blue,
                                            ),
                                            title: Text(
                                                suggestion['english_name']),
                                            subtitle: Text(
                                                "Rs. ${suggestion['sale_price']}"),
                                          );
                                        },
                                        onSuggestionSelected: (suggestion) {
                                          productData = suggestion as Map;

                              _productController.text =suggestion['english_name'].toString();

       posBuilderController.getProductDetailsWithMultiplePrices(
                                                    suggestion['product_id'].toString()).then((data) {
//code
});
                                        },

                                      ),
                                    ),


问:
exec: "git": executable file not found in $PATH when running golangcli-lint
I'm using golangcli-lint for my projects. But, when I run it using golangcli-lint run, it throws this error

ERRO Running error: context loading failed: failed to load packages: failed to load with go/packages: err: exit status 1: stderr: go: github.com/personal/private-repo@v1.5.4-staging.0.20221037132524-fa474c90e736: git init --bare in /home/personal/snap/golangci-lint/104/go/pkg/mod/cache/vcs/0478a3848f1237177112e0218abaefe19791c78a4f537df39ac0804ae69a3a05: exec: "git": executable file not found in $PATH
go: github.com/personal/private-repo@v1.5.4-staging.0.20221037132524-fa474c90e736: git init --bare in /home/koinworks/snap/golangci-lint/104/go/pkg/mod/cache/vcs/0478a3848f1237177112e0218abaefe19791c78a4f537df39ac0804ae69a3a05: exec: "git": executable file not found in $PATH
```

What happens here? I googled it, but they told me to install git because it's not installed. But I've been using this laptop for coding and using git & github for years with countless commits without any problem.

I use Ubuntu 20.04.

Body:
I'm using golangcli-lint for my projects. But, when I run it using golangcli-lint run, it throws this error

ERRO Running error: context loading failed: failed to load packages: failed to load with go/packages: err: exit status 1: stderr: go: github.com/personal/private-repo@v1.5.4-staging.0.20221037132524-fa474c90e736: git init --bare in /home/personal/snap/golangci-lint/104/go/pkg/mod/cache/vcs/0478a3848f1237177112e0218abaefe19791c78a4f537df39ac0804ae69a3a05: exec: "git": executable file not found in $PATH
go: github.com/personal/private-repo@v1.5.4-staging.0.20221037132524-fa474c90e736: git init --bare in /home/koinworks/snap/golangci-lint/104/go/pkg/mod/cache/vcs/0478a3848f1237177112e0218abaefe19791c78a4f537df39ac0804ae69a3a05: exec: "git": executable file not found in $PATH

What happens here? I googled it, but they told me to install git because it's not installed. But I've been using this laptop for coding and using git & github for years with countless commits without any problem.

I use Ubuntu 20.04.


问:
Turn some columns of dataframe to a sheet and display it in itables
I want to turn some columns of my dataframe to a sheet and display it using itables. is it possible to achieve such thing? are there any other module that I can use for it since itables only accept dataframe in the param as far as I know.

Thanks.

enter image description here

this dataframe displayed in itables where "C" column is a sheet.


问:
Connect to MongoDB Atlas while i am behind college proxy
I have a MERN application in my system that used to work perfectly, now i am behind my college proxy , so I changed node proxy using

```<code>npm config set proxy http://username:password@host:port
npm config set https-proxy http://username:password@host:port
</code>```

And in mongo atlas i have allowed all IP addresses to connect.

```<code>0.0.0.0/0  (includes your current IP address)
</code>```

still while running the apllication i am getting this error from mongoDB side.

```<code>const serverSelectionError = new ServerSelectionError();
                               ^
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
</code>```

I also tried to connect using mongosh and MongoDB compass any of these didn't connect to the atlas.

someone help me, please.

Body:
I have a MERN application in my system that used to work perfectly, now i am behind my college proxy , so I changed node proxy using

npm config set proxy http://username:password@host:port
npm config set https-proxy http://username:password@host:port

And in mongo atlas i have allowed all IP addresses to connect.

0.0.0.0/0  (includes your current IP address)

still while running the apllication i am getting this error from mongoDB side.

const serverSelectionError = new ServerSelectionError();
                               ^
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/

I also tried to connect using mongosh and MongoDB compass any of these didn't connect to the atlas.

someone help me, please.


问:
Accidently ran `sudo chown root@root -R /.` instead of `sudo chown root@root -R ./`
I wanted to change tho permission of a file structure and accidently ran

sudo chown root@root -R /.

instead of

sudo chown root@root -R ./

is there anyway i can undo that?
I don't have a backup of my system. If there is nothing a can do I'll just install a different os since all the relevant data is backed up.


问:
Is there a way to use `pytest-snapshot` with unsortable list?
I want to implement a test that looks like this :

def test_some_function(snapshot):

        my_unsortable_list = my_function()

        assert my_unsortable_list == snapshot
```
<ul>
<li>However the <code>my_unsortable_list</code> variable is of type <code>List[Dict]</code> and there is no easy way to sort it.</li>
<li>Also, the values inside <code>my_unsortable_list</code> are always the same but the order is random.</li>
<li>Therefore the assertion <code>assert my_unsortable_list == snapshot</code> fails if we run this test.</li>
</ul>
<p>I was wondering if there is a way to get rid of snapshot order and do something like this :</p>
<pre class="lang-py prettyprint-override"><code>assert len(my_unsortable_list) == len(snapshot) # Compare number of elements in lists
assert all([x in my_unsortable_list for x in snapshot]) # Assert all elements are in both lists
</code>```

The code above fails, is there a way to use advanced features of pytest-snapshot so that works ?

Body:
I want to implement a test that looks like this :

def test_some_function(snapshot):

        my_unsortable_list = my_function()

        assert my_unsortable_list == snapshot

However the my_unsortable_list variable is of type List[Dict] and there is no easy way to sort it.

Also, the values inside my_unsortable_list are always the same but the order is random.

Therefore the assertion assert my_unsortable_list == snapshot fails if we run this test.

I was wondering if there is a way to get rid of snapshot order and do something like this :

assert len(my_unsortable_list) == len(snapshot) # Compare number of elements in lists
assert all([x in my_unsortable_list for x in snapshot]) # Assert all elements are in both lists

The code above fails, is there a way to use advanced features of pytest-snapshot so that works ?


问:
Event that gets called when webview is about to load a new page
In my webView app, I want to show my loading spinner when the page is about to load a new page. My problem is finding an event that gets run when the webview is about to load a new page. I tried onPageStarted but for me there's a 1 second delay from when its starts to load a new page and when the event gets fired. Also, I know I've done this in the past (~2 years ago) but I don't have that code anymore.. so are there any other alternatives?

If you have any questions feel free to ask :D


问:
PAT Token creation via terraform - API version string must be in format
I'm able to create PAT Token via Terraform with very simple way:

```<code>resource "restapi_object" "pat_token_ado_creation" {
  path = "/_apis/tokens/pats/pats?api-version=7.0-preview.1"
  data = jsonencode({
    displayName        = "PAT_${var.organisation}"
    scope = "vso.project_write"
    validTo = timeadd(timestamp(), "1h")
    allOrgs = false
  })
  id_attribute = "patToken/displayName"
  update_method = "PUT"
}
</code>```

This works just fine BUT when I'm trying to destroy this token, I'm getting following error:

```<code>Error: unexpected response code '500': {"$id":"1","innerException":null,"message":"Invalid api version string: \"7.0-preview.1/PAT_CWF\". Api version string must be in the format: {Major}.{Minor}[-preview[.{ResourceVersion}]].","typeName":"Microsoft.VisualStudio.Services.WebApi.VssInvalidApiResourceVersionException, Microsoft.VisualStudio.Services.WebApi","typeKey":"VssInvalidApiResourceVersionException","errorCode":0,"eventId":3000}
</code>```

Body:
I'm able to create PAT Token via Terraform with very simple way:

resource "restapi_object" "pat_token_ado_creation" {
  path = "/_apis/tokens/pats/pats?api-version=7.0-preview.1"
  data = jsonencode({
    displayName        = "PAT_${var.organisation}"
    scope = "vso.project_write"
    validTo = timeadd(timestamp(), "1h")
    allOrgs = false
  })
  id_attribute = "patToken/displayName"
  update_method = "PUT"
}

This works just fine BUT when I'm trying to destroy this token, I'm getting following error:

Error: unexpected response code '500': {"$id":"1","innerException":null,"message":"Invalid api version string: \"7.0-preview.1/PAT_CWF\". Api version string must be in the format: {Major}.{Minor}[-preview[.{ResourceVersion}]].","typeName":"Microsoft.VisualStudio.Services.WebApi.VssInvalidApiResourceVersionException, Microsoft.VisualStudio.Services.WebApi","typeKey":"VssInvalidApiResourceVersionException","errorCode":0,"eventId":3000}


问:
stimulusjs get all values as array
I just need get all values how to get it ?

```<code>export default class extends Controller {

    static values = {
        test: 123,
        path: String,
        createUrl: String,
        mappedClasses: Array,
        columnDefs: Array,
        defaultSort: Object
    };

    connect() {

        console.log('config',{
            testOneValue: this.testValue,
            testPathValue: this.pathValue,
            values1: this.constructor.values,
            values2: Object.values(this.constructor.values),
        });
</code>```

this give my

```<code>Object { testOneValue: 123, testPathValue: "/app/educalendarevent/list?urltarget=crud_63c1225deae26&_list_mode=json", values1: {…}, values2: (6) […] }

testOneValue: 123

testPathValue: "/app/educalendarevent/list?urltarget=crud_63c1225deae26&_list_mode=json"

values1: Object { test: 123, path: String(), createUrl: String(), … }

columnDefs: function Array()

createUrl: function String()

defaultSort: function Object()

mappedClasses: function Array()

path: function String()

test: 123

<prototype>: Object { … }

values2: Array(6) [ 123, String(), String(), … ]
</code>```

Title: stimulusjs get all values as array

Body:
I just need get all values how to get it ?

export default class extends Controller {

    static values = {
        test: 123,
        path: String,
        createUrl: String,
        mappedClasses: Array,
        columnDefs: Array,
        defaultSort: Object
    };

    connect() {

        console.log('config',{
            testOneValue: this.testValue,
            testPathValue: this.pathValue,
            values1: this.constructor.values,
            values2: Object.values(this.constructor.values),
        });

this give my

Object { testOneValue: 123, testPathValue: "/app/educalendarevent/list?urltarget=crud_63c1225deae26&_list_mode=json", values1: {…}, values2: (6) […] }

testOneValue: 123

testPathValue: "/app/educalendarevent/list?urltarget=crud_63c1225deae26&_list_mode=json"

values1: Object { test: 123, path: String(), createUrl: String(), … }

columnDefs: function Array()

createUrl: function String()

defaultSort: function Object()

mappedClasses: function Array()

path: function String()

test: 123

<prototype>: Object { … }

values2: Array(6) [ 123, String(), String(), … ]


问:
its trait bounds were not satisfied label: method `serialize` not found for this struct
I'm trying to save AccountInfo in a struct that #[derive(BorshSerialize, BorshDeserialize, Clone, Debug)] to send SOL to this account. AccountInfo is a struct in library that don't impl serialize method. This account is randomly chosen from a map in contract so I cannot pass it into data to make instructions. This is the code:</p>
```<code>#[derive(BorshSerialize, BorshDeserialize, Clone, Debug)]
pub struct State<'a> {
    pub owner: AccountInfo<'a>,
}
</code>```

Body:
I'm trying to save AccountInfo in a struct that #[derive(BorshSerialize, BorshDeserialize, Clone, Debug)] to send SOL to this account. AccountInfo is a struct in library that don't impl serialize method. This account is randomly chosen from a map in contract so I cannot pass it into data to make instructions. This is the code:

#[derive(BorshSerialize, BorshDeserialize, Clone, Debug)]
pub struct State<'a> {
    pub owner: AccountInfo<'a>,
}


问:
Run Task Scheduler task in user interactive mode even windows is lock
Is there any way to trigger some task from task scheduler as interactive task. Like if I am logged in and have a task that runs only if user is logged in than my 2nd application from code I send interactive commands like enter but it doesn't work if my windows is locked and task scheduler runs a application than it will not able to get user interactive command from my 2nd application .

I tried to create task in scheduler using Users group and run task weather user logged in or not but nothing works when windows get locked.


问:
Generate ABP Authorization Access Token from Service Application(API service) for Mobile Application without password/password grant
I want Access token for social login users with out password and password grant in ABP framework version 4.3 and .Net core 6.

```<code>IEnumerable<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>() {
                new KeyValuePair<string, string>("Client_Id",_configuration["AuthServer:ClientId"]),
                new KeyValuePair<string, string>("UserName", userName),
                new KeyValuePair<string, string>("Password", password),
                new KeyValuePair<string, string>("grant_type", "password")
                };

ResponseTokenDTO response = new ResponseTokenDTO();
            using (var httpClient = new HttpClient())
            {
                var identityUrl = _configuration["AuthServer:Authority"];
                var url = identityUrl + "/connect/token";
                using (var conn = new FormUrlEncodedContent(postData))
                {
                    conn.Headers.Clear();
                    conn.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    HttpResponseMessage response1 = await httpClient.PostAsync(url, conn);
                    var userDetails = await _appUserRepository.FindAsync(r => r.UserName == userName);
                    if (response1.IsSuccessStatusCode)
                    {
                        result = await response1.Content.ReadAsStringAsync();
                    }
                }
            }
</code>```

How to Get token with out password for google or apple login users because mobile team sharing email address for those users. with out token user not able to access APIs.

```<code>var tokenValue = "";
try
{
    var claims = new Claim[] {
    new (JwtRegisteredClaimNames.Sub, identityUser.Id.ToString()),
    new (JwtRegisteredClaimNames.Email, identityUser.Email)
};

    var signingCredentials = new SigningCredentials(
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)),
        SecurityAlgorithms.HmacSha256);

    var Token = new JwtSecurityToken(
        _jwtOptions.Issuer,
        _jwtOptions.Audience,
        claims,
        null,
        DateTime.UtcNow.AddDays(1),
        signingCredentials
        );

    tokenValue = new JwtSecurityTokenHandler().WriteToken(Token);
}
</code>```

I tried above code but that token is not accepting ABP.

Body:
I want Access token for social login users with out password and password grant in ABP framework version 4.3 and .Net core 6.

IEnumerable<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>() {
                new KeyValuePair<string, string>("Client_Id",_configuration["AuthServer:ClientId"]),
                new KeyValuePair<string, string>("UserName", userName),
                new KeyValuePair<string, string>("Password", password),
                new KeyValuePair<string, string>("grant_type", "password")
                };

ResponseTokenDTO response = new ResponseTokenDTO();
            using (var httpClient = new HttpClient())
            {
                var identityUrl = _configuration["AuthServer:Authority"];
                var url = identityUrl + "/connect/token";
                using (var conn = new FormUrlEncodedContent(postData))
                {
                    conn.Headers.Clear();
                    conn.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    HttpResponseMessage response1 = await httpClient.PostAsync(url, conn);
                    var userDetails = await _appUserRepository.FindAsync(r => r.UserName == userName);
                    if (response1.IsSuccessStatusCode)
                    {
                        result = await response1.Content.ReadAsStringAsync();
                    }
                }
            }

How to Get token with out password for google or apple login users because mobile team sharing email address for those users. with out token user not able to access APIs.

var tokenValue = "";
try
{
    var claims = new Claim[] {
    new (JwtRegisteredClaimNames.Sub, identityUser.Id.ToString()),
    new (JwtRegisteredClaimNames.Email, identityUser.Email)
};

    var signingCredentials = new SigningCredentials(
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)),
        SecurityAlgorithms.HmacSha256);

    var Token = new JwtSecurityToken(
        _jwtOptions.Issuer,
        _jwtOptions.Audience,
        claims,
        null,
        DateTime.UtcNow.AddDays(1),
        signingCredentials
        );

    tokenValue = new JwtSecurityTokenHandler().WriteToken(Token);
}

I tried above code but that token is not accepting ABP.


问:
How to efficiently query points within a radius on the GPU in PyTorch?

import torch
import time
from time import perf_counter
torch.manual_seed(0)
```
<p>Given a collection of points (here in 2D):</p>
<pre class="lang-py prettyprint-override"><code>n = 25000
threshold = 0.001
device = 'cuda'

x = torch.rand(n, 2, device=device)
</code>```

Can you show a faster way to calculate the number of collisions within a radius threshold than the naive solution:

t1 = perf_counter()
d2 = torch.sum((x[:, None, :] - x[None, :, :])**2, dim=2)
collisions = int((torch.sum(d2 < threshold**2) - n)/2)
torch.cuda.synchronize()
t2 = perf_counter()
print(collisions, t2 - t1)
>>> 909 0.0498829899588599
```
<p>?</p>
<p>It can be done faster on the CPU, e.g. like</p>
<pre class="lang-py prettyprint-override"><code>from scipy.spatial import KDTree
x = x.cpu().numpy()
t1 = perf_counter()
tree = KDTree(x)
collisions = tree.query_pairs(threshold)
t2 = perf_counter()
print(len(collisions), t2 - t1)
>>> 909 0.009740175097249448
</code>```

But can it be sped up on the GPU in PyTorch?

Body:
import torch
import time
from time import perf_counter
torch.manual_seed(0)

Given a collection of points (here in 2D):

n = 25000
threshold = 0.001
device = 'cuda'

x = torch.rand(n, 2, device=device)

Can you show a faster way to calculate the number of collisions within a radius threshold than the naive solution:

t1 = perf_counter()
d2 = torch.sum((x[:, None, :] - x[None, :, :])**2, dim=2)
collisions = int((torch.sum(d2 < threshold**2) - n)/2)
torch.cuda.synchronize()
t2 = perf_counter()
print(collisions, t2 - t1)
>>> 909 0.0498829899588599

?

It can be done faster on the CPU, e.g. like

from scipy.spatial import KDTree
x = x.cpu().numpy()
t1 = perf_counter()
tree = KDTree(x)
collisions = tree.query_pairs(threshold)
t2 = perf_counter()
print(len(collisions), t2 - t1)
>>> 909 0.009740175097249448

But can it be sped up on the GPU in PyTorch?


问:
Import to next.config.js
I want to import file to next.config.js.

```<code>    import * as  all from "./links/redirects.js";
    /** @type {import('next').NextConfig} */
    module.exports = {
      reactStrictMode: false,
      trailingSlash: true,
}
</code>```

(I added only part of module.exports content)

but I got error
Cannot use import statement outside a module

so I added In file package.json I added "type": "module" and I got error:
Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
ReferenceError: module is not defined

Title: Import to next.config.js

Body:
I want to import file to next.config.js.

    import * as  all from "./links/redirects.js";
    /** @type {import('next').NextConfig} */
    module.exports = {
      reactStrictMode: false,
      trailingSlash: true,
}

(I added only part of module.exports content)

but I got error
Cannot use import statement outside a module

so I added In file package.json I added "type": "module" and I got error:
Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
ReferenceError: module is not defined


问:
How to get the page_type property from google analytics API
I am trying to fetch the following data from GA using API

I am not able to find which dimension to use to fetch the page_type.

```<code>analytics.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': view_id,
                "pageSize": ga_page_size,
                "samplingLevel": "LARGE",
                'dateRanges': [
                    {'startDate': start_date, 'endDate': end_date}
                ],
                'metrics': [
                    {'expression': 'ga:bounces', 'alias': 'bounces'},
                    {'expression': 'ga:sessions', 'alias': 'sessions'},
                    {'expression': 'ga:transactions', 'alias': 'transactions'},
                    {'expression': 'ga:transactionRevenue', 'alias': 'transactionRevenue'},
                    {'expression': 'ga:transactionsPerSession', 'alias': 'transactionsPerSession'},
                    {'expression': 'ga:revenuePerTransaction', 'alias': 'revenuePerTransaction'}
                ],
                "dimensions": [
                    {"name": "ga:landingPagePath"}
                ],
            }]
    }
).execute(num_retries=3)
</code>```

Requesting help on this.

Body:
I am trying to fetch the following data from GA using API

I am not able to find which dimension to use to fetch the page_type.

analytics.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': view_id,
                "pageSize": ga_page_size,
                "samplingLevel": "LARGE",
                'dateRanges': [
                    {'startDate': start_date, 'endDate': end_date}
                ],
                'metrics': [
                    {'expression': 'ga:bounces', 'alias': 'bounces'},
                    {'expression': 'ga:sessions', 'alias': 'sessions'},
                    {'expression': 'ga:transactions', 'alias': 'transactions'},
                    {'expression': 'ga:transactionRevenue', 'alias': 'transactionRevenue'},
                    {'expression': 'ga:transactionsPerSession', 'alias': 'transactionsPerSession'},
                    {'expression': 'ga:revenuePerTransaction', 'alias': 'revenuePerTransaction'}
                ],
                "dimensions": [
                    {"name": "ga:landingPagePath"}
                ],
            }]
    }
).execute(num_retries=3)

Requesting help on this.


问:
ways to migrate MongoDB from Atals to Digital Ocean
I want to migrate a huge database of MongoDB from Atlas to Digital Ocean MongoDB, Is there any service or scrips that can help me to achieve this without data loss or problem?

Currently I can take the backup, which is of 300GB and Restore it manually.


问:
Lambda Layer for GDAL
I am trying to use the GDAL as a lambda layer in my AWS environment. But I am getting this error response:

```<code>"errorMessage": "Unable to import module 'lambda_function': cannot import name '_gdal' from 'osgeo' (/opt/python/osgeo/__init__.py)",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
}
</code>```

I believe I did not install that GDAL successfully. I just used the "pip install [GDAL Wheel file] -t . " command to install using the wheel file and imported the generated file to my lambda layer.

I did that because I'm having a problem running the command "pip install gdal" it says "Running setup.py install for GDAL did not run successfully."

Now, my question is, is there any way I can import gdal as layer in my AWS environment using python?

Title: Lambda Layer for GDAL

Body:
I am trying to use the GDAL as a lambda layer in my AWS environment. But I am getting this error response:

"errorMessage": "Unable to import module 'lambda_function': cannot import name '_gdal' from 'osgeo' (/opt/python/osgeo/__init__.py)",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
}

I believe I did not install that GDAL successfully. I just used the "pip install [GDAL Wheel file] -t . " command to install using the wheel file and imported the generated file to my lambda layer.

I did that because I'm having a problem running the command "pip install gdal" it says "Running setup.py install for GDAL did not run successfully."

Now, my question is, is there any way I can import gdal as layer in my AWS environment using python?


问:
How to filter nested list with JPA Specification directly in the query?
I have the following classes:

```<code>@Entity
@Table
public class ScheduleCourierEntity extends BaseEntity {

    @OneToMany(mappedBy = "courier", cascade = ALL, fetch = LAZY, orphanRemoval = true)
    private List<ScheduleDayAvailabilityEntity> weekAvailability = new ArrayList<>();

}
</code>```
```<code> @Entity
 @Table
 public class ScheduleDayAvailabilityEntity extends BaseEntity {

     @Enumerated(STRING)
     private DayOfWeek weekDay;

     @ManyToOne(fetch = LAZY)
     private ScheduleCourierEntity courier;

 }
</code>```

A ScheduleCourierEntity can have availabilities for every week day (7 elements). I am using JPA Specification to retrieve the courier that has the availability for a specific DayOfWeek, let's say FRIDAY. I want to make the query return ScheduleCourierEntity the list containing only one element, the ScheduleDayAvailabilityEntity of FRIDAY, so that:

Memory won't be loaded with unnecessary data

I won't have to filter out FRIDAY out of the other days

Is there any possible way to achieve that?
Thanks in advance

This is the Specification method:

```<code> @Override
 public Predicate toPredicate(@NonNull Root<ScheduleCourierEntity> root, @NonNull CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
     this.root = root;
     this.criteriaBuilder = criteriaBuilder;
     Join<Object, Object> weekAvailabilityJoin = root.join(WEEK_AVAILABILITY);
     Path<Object> path = weekAvailabilityJoin.get(WEEK_DAY);
     predicates.add(criteriaBuilder.equal(path, searchRequest.getDate().getDayOfWeek()));
     query.distinct(true);
     return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
}
</code>```

I only managed to retrieve a courier that has the required day, but it always comes with a list of 7 elements.

Body:
I have the following classes:

@Entity
@Table
public class ScheduleCourierEntity extends BaseEntity {

    @OneToMany(mappedBy = "courier", cascade = ALL, fetch = LAZY, orphanRemoval = true)
    private List<ScheduleDayAvailabilityEntity> weekAvailability = new ArrayList<>();

}

 @Entity
 @Table
 public class ScheduleDayAvailabilityEntity extends BaseEntity {

     @Enumerated(STRING)
     private DayOfWeek weekDay;

     @ManyToOne(fetch = LAZY)
     private ScheduleCourierEntity courier;

 }

A ScheduleCourierEntity can have availabilities for every week day (7 elements). I am using JPA Specification to retrieve the courier that has the availability for a specific DayOfWeek, let's say FRIDAY. I want to make the query return ScheduleCourierEntity the list containing only one element, the ScheduleDayAvailabilityEntity of FRIDAY, so that:

Memory won't be loaded with unnecessary data

I won't have to filter out FRIDAY out of the other days

Is there any possible way to achieve that?
Thanks in advance

This is the Specification method:

 @Override
 public Predicate toPredicate(@NonNull Root<ScheduleCourierEntity> root, @NonNull CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
     this.root = root;
     this.criteriaBuilder = criteriaBuilder;
     Join<Object, Object> weekAvailabilityJoin = root.join(WEEK_AVAILABILITY);
     Path<Object> path = weekAvailabilityJoin.get(WEEK_DAY);
     predicates.add(criteriaBuilder.equal(path, searchRequest.getDate().getDayOfWeek()));
     query.distinct(true);
     return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
}

I only managed to retrieve a courier that has the required day, but it always comes with a list of 7 elements.


问:
How can I fix my WordPress Image Error with WP Bakery?
I am only able to upload single images per time using the WP Page Builder, I have to save the page and then upload another image, whenever I try uploading another image, the screen greys out until I save the page before I'm able to upload another image

I should be able to just upload pictures as much as I want before saving the page


问:
When using parallel producer-consumer pattern, how let consumer know if producer caught exception?
In the code below producer is started in separate thread, and adding some items to ConcurrentQueue<T> queue . Consumer consists of while(true) loop and is trying to dequeue items from queue all the time.
When producer is finished  - it is raising producerFinished event flag, so that Consumer can detect that and exit infinite loop.
The problem occurs when Producer catches exception - it can't raise producerFinished event flag, and Consumer is stuck forever.
Can you recommend some solution on how Consumer can detect if Producer caught exception?

```<code>public override async Task SendMultiSkuSpmRequests(SpmRequestMultiSku hostRequest,
    IServerStreamWriter<SpmResponse> responseStream, ServerCallContext context)
{
    ConcurrentQueue<SpmResponse> queue = new ConcurrentQueue<SpmResponse>();
    ManualResetEvent producerFinished = new ManualResetEvent(false);

    Task.Factory.StartNew(() => EnqueueSpmResponsesForMultiSku(hostRequest, queue, producerFinished));

    logger.Debug($"Starting to monitor Spm response queue, and will send them one by one via stream back to test Host.");
    while (true)
    {
        SpmResponse response;
        while (queue.Any())
        {
            queue.TryDequeue(out response);
            logger.Debug($"Sending Spm response back to client.");
            await responseStream.WriteAsync(response);
        }

        if (producerFinished.WaitOne(50))
        {
            logger.Debug($"Producer is finished and queue is empty - will exit the while(true) loop");
            break;
        }
    }
}
</code>```

Body:
In the code below producer is started in separate thread, and adding some items to ConcurrentQueue<T> queue . Consumer consists of while(true) loop and is trying to dequeue items from queue all the time.
When producer is finished  - it is raising producerFinished event flag, so that Consumer can detect that and exit infinite loop.
The problem occurs when Producer catches exception - it can't raise producerFinished event flag, and Consumer is stuck forever.
Can you recommend some solution on how Consumer can detect if Producer caught exception?

public override async Task SendMultiSkuSpmRequests(SpmRequestMultiSku hostRequest,
    IServerStreamWriter<SpmResponse> responseStream, ServerCallContext context)
{
    ConcurrentQueue<SpmResponse> queue = new ConcurrentQueue<SpmResponse>();
    ManualResetEvent producerFinished = new ManualResetEvent(false);

    Task.Factory.StartNew(() => EnqueueSpmResponsesForMultiSku(hostRequest, queue, producerFinished));

    logger.Debug($"Starting to monitor Spm response queue, and will send them one by one via stream back to test Host.");
    while (true)
    {
        SpmResponse response;
        while (queue.Any())
        {
            queue.TryDequeue(out response);
            logger.Debug($"Sending Spm response back to client.");
            await responseStream.WriteAsync(response);
        }

        if (producerFinished.WaitOne(50))
        {
            logger.Debug($"Producer is finished and queue is empty - will exit the while(true) loop");
            break;
        }
    }
}


问:
I'm getting "the object of type 'MeshRenderer' has been destroyed but you are still trying to acces it" after destroying and instantiating a prefab
So i have a plumber/pipe game which looks like this:
Pipe/Plumber game.

When the level is not finished within the time or limited moves the user gets a try again button which restarts the game by destroying the current prefab with all the pipes and instantiates a new prefab of the same level.

Every pipe holds a pipe class, which is also responsible for changing the material of the pipe itself, here are a few examples of what it looks like:
When level is not finished,
When level is finished.

But when the prefab gets destroyed and instatiated to start again, the materials cant be changed like that anymore because i get a error that says: "MissingReferenceException: the object of type 'MeshRenderer' has been destroyed but you are still trying to acces it. Your script should either check if it is null or you should not destroy the object."

In the "Start()" of the script I cache the MeshRenderer of the pipe like this:

private MeshRenderer _renderer;

private void Start()
{
    _renderer = GetComponent<MeshRenderer>();
}
```
<p>There a also 4 functions for changing the material of the pipe that make use of this cached component:</p>
<pre class="lang-cs prettyprint-override"><code>//Changes the material of the pipe to the watered pipe
public void ChangeColor()
{
    _renderer.material = _wateredPipe;
}

//Changes the material of the pipe to the original material
public void RevertToOriginalMaterial()
{
    _renderer.material = _originalMaterial;
}

//Changes the material of the pipe to the red material
public void MakePipeRed()
{
    _renderer.material.color = Color.red;
}

//Changes the material of the pipe to the green material
public void MakePipeGreen()
{
    _renderer.material.color = Color.green;
}
</code>```

This is what the script that destroys and instantiates the object looks like, the function ResetPipeGrid() gets called if the button is clicked:

[SerializeField] private GameObject pipeGridPrefab;
private GameObject _currentPipeGrid;

private void Start()
{
    _currentPipeGrid = GameObject.FindGameObjectWithTag("PipeGrid");
}

public void ResetPipeGrid()
{
    DestroyGrid();
    InstantiateGrid();
}

private void InstantiateGrid()
{
    _currentPipeGrid = Instantiate(pipeGridPrefab);
}

private void DestroyGrid()
{
    Destroy(_currentPipeGrid);
}
```

After i instantiate the prefab, it throws this exception and it points to these functions/the cached component.

I broke my brains on this problem the past few days but i do know for sure it has something to do with the cached component, i tried to cache the materials but this wasn't the problem.

Body:
So i have a plumber/pipe game which looks like this:
Pipe/Plumber game.

When the level is not finished within the time or limited moves the user gets a try again button which restarts the game by destroying the current prefab with all the pipes and instantiates a new prefab of the same level.

Every pipe holds a pipe class, which is also responsible for changing the material of the pipe itself, here are a few examples of what it looks like:
When level is not finished,
When level is finished.

But when the prefab gets destroyed and instatiated to start again, the materials cant be changed like that anymore because i get a error that says: "MissingReferenceException: the object of type 'MeshRenderer' has been destroyed but you are still trying to acces it. Your script should either check if it is null or you should not destroy the object."

In the "Start()" of the script I cache the MeshRenderer of the pipe like this:

private MeshRenderer _renderer;

private void Start()
{
    _renderer = GetComponent<MeshRenderer>();
}

There a also 4 functions for changing the material of the pipe that make use of this cached component:

//Changes the material of the pipe to the watered pipe
public void ChangeColor()
{
    _renderer.material = _wateredPipe;
}

//Changes the material of the pipe to the original material
public void RevertToOriginalMaterial()
{
    _renderer.material = _originalMaterial;
}

//Changes the material of the pipe to the red material
public void MakePipeRed()
{
    _renderer.material.color = Color.red;
}

//Changes the material of the pipe to the green material
public void MakePipeGreen()
{
    _renderer.material.color = Color.green;
}

This is what the script that destroys and instantiates the object looks like, the function ResetPipeGrid() gets called if the button is clicked:

[SerializeField] private GameObject pipeGridPrefab;
private GameObject _currentPipeGrid;

private void Start()
{
    _currentPipeGrid = GameObject.FindGameObjectWithTag("PipeGrid");
}

public void ResetPipeGrid()
{
    DestroyGrid();
    InstantiateGrid();
}

private void InstantiateGrid()
{
    _currentPipeGrid = Instantiate(pipeGridPrefab);
}

private void DestroyGrid()
{
    Destroy(_currentPipeGrid);
}

After i instantiate the prefab, it throws this exception and it points to these functions/the cached component.

I broke my brains on this problem the past few days but i do know for sure it has something to do with the cached component, i tried to cache the materials but this wasn't the problem.


问:
how to get the li element on button dropdown clicked?

    <button type="button" class="button-m button-default dropdown-toggle http-button copyInput" data-toggle="dropdown" style="border-right:none !important;">
      Http://

    </button>

        Http://

        Https://

```

What javascript code or directive to be used?

Body:
    <button type="button" class="button-m button-default dropdown-toggle http-button copyInput" data-toggle="dropdown" style="border-right:none !important;">
      Http://

    </button>

        Http://

        Https://

What javascript code or directive to be used?


问:
How to clear cookie with signed=true
I want to ask about how to clear cookie with signed=true.
For the following two optons, the first case cleared the cookie : res.clearCookie('test, OPTION2), but the second case didn't clear the cookie: res.clearCookie('test, OPTION1).
Only difference is signed=true and signed=false.

How to clear the cookie with signed=true?

```<code>const OPTION1 = {
  secure: true,
  signed: true,
  maxAge: 1000 * 60 * 10,
  sameSite: 'Strict',
}

const OPTION2 = {
  secure: true,
  signed: false,
  maxAge: 1000 * 60 * 10,
  sameSite: 'Strict',
}
</code>```

To get a solution about my asking

Title: How to clear cookie with signed=true

Body:
I want to ask about how to clear cookie with signed=true.
For the following two optons, the first case cleared the cookie : res.clearCookie('test, OPTION2), but the second case didn't clear the cookie: res.clearCookie('test, OPTION1).
Only difference is signed=true and signed=false.

How to clear the cookie with signed=true?

const OPTION1 = {
  secure: true,
  signed: true,
  maxAge: 1000 * 60 * 10,
  sameSite: 'Strict',
}

const OPTION2 = {
  secure: true,
  signed: false,
  maxAge: 1000 * 60 * 10,
  sameSite: 'Strict',
}

To get a solution about my asking


问:
How many images are generated when Image augmentation is used (either for individual image or for all image)
How can I determine how many images will be created after image augmentation via tensorflow ImageDataGenerator.
What will be that number for an individual image and likewise all images.

I have total 17 image (16 image for train and 1 image for test)

    import tensorflow as tf
    from tensorflow.keras.preprocessing.image import ImageDataGenerator

    aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1,
                         height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
                         horizontal_flip=True, fill_mode="nearest")

    history_model = model.fit_generator(
    aug.flow(X_train , y_train, batch_size = 32),  epochs=10, verbose=0)
```


问:
Potential harm of discontinuing support for Facebook Web Games platform with active mobile apps
I have an app which uses the FB SDK, currently it supports 3 platforms, iOS, Android and Facebook Web Games (Canvas).
Canvas platform is no longer supported and I would like to remove it from the dashboard.

What potential harm, if any, could come from discontinuing support for the Facebook Web Games platform when the Android and iOS versions of the app are still active and utilizing the Facebook SDK? Could this affect the functionality of the mobile SDK in any way? AppRequests, Invites?

Lack of clear documentation on potential impact of discontinuing support for Facebook Web Games on mobile platforms for the same app Dashboard warnings


问:
C# HttpClient Host In Header not work with response 301/302
After using other DNS clients to resolve the IP and manually set the HOST in HEADER, it works fine, but when the server responds with 301/302 to other websites, the HOST in HEADER does not automatically change to the new HOST</p>
```<code>public static HttpClient HttpClient { get; } =
    new(new HttpClientHandler() {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
        AllowAutoRedirect = true,
        MaxAutomaticRedirections = 6,
        CheckCertificateRevocationList = false,
        ServerCertificateCustomValidationCallback = (_, _, _, _) => true  });
        HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
        HttpClient.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        HttpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");
        HttpClient.Timeout = TimeSpan.FromMilliseconds(App.Config.HttpClientWait ? App.Config.HttpClientAsyncTimeout : App.Config.HttpClientTimeout);

var url = this.DomainTask.Domain!.Trim().StartsWith("http://") || this.DomainTask.Domain.Trim().StartsWith("https://") ? this.DomainTask.Domain : $"{(this.UseHttps ? "https" : "http")}://{this.DomainTask.Domain}/";
var uri = new Uri(url);
var protocol = url.StartsWith("https://") ? "https" : "http";
var ipUrl = $"{protocol}://{this.DomainTask.Result!.Ip}:{uri.Port}/";
var msg = new HttpRequestMessage(HttpMethod.Get, IPAddress.TryParse(this.DomainTask.Result!.Ip, out _) ? ipUrl : url);
msg.Headers.Host = this.DomainTask.Domain;
if (App.Config.Debug) App.Logger.Debug($"{this.DomainTask.Domain} - ipUrl: {msg.RequestUri}");

var result = HttpClient!.SendAsync(msg).ContinueWith(x => {......});
</code>```

Body:
After using other DNS clients to resolve the IP and manually set the HOST in HEADER, it works fine, but when the server responds with 301/302 to other websites, the HOST in HEADER does not automatically change to the new HOST

public static HttpClient HttpClient { get; } =
    new(new HttpClientHandler() {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
        AllowAutoRedirect = true,
        MaxAutomaticRedirections = 6,
        CheckCertificateRevocationList = false,
        ServerCertificateCustomValidationCallback = (_, _, _, _) => true  });
        HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
        HttpClient.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        HttpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");
        HttpClient.Timeout = TimeSpan.FromMilliseconds(App.Config.HttpClientWait ? App.Config.HttpClientAsyncTimeout : App.Config.HttpClientTimeout);

var url = this.DomainTask.Domain!.Trim().StartsWith("http://") || this.DomainTask.Domain.Trim().StartsWith("https://") ? this.DomainTask.Domain : $"{(this.UseHttps ? "https" : "http")}://{this.DomainTask.Domain}/";
var uri = new Uri(url);
var protocol = url.StartsWith("https://") ? "https" : "http";
var ipUrl = $"{protocol}://{this.DomainTask.Result!.Ip}:{uri.Port}/";
var msg = new HttpRequestMessage(HttpMethod.Get, IPAddress.TryParse(this.DomainTask.Result!.Ip, out _) ? ipUrl : url);
msg.Headers.Host = this.DomainTask.Domain;
if (App.Config.Debug) App.Logger.Debug($"{this.DomainTask.Domain} - ipUrl: {msg.RequestUri}");

var result = HttpClient!.SendAsync(msg).ContinueWith(x => {......});


问:
Does unseen cells from tilemap affect performance in Godot
Let's say I have a single Tilemap 6400 x 6400, I fill whole layer0 with some cell then I draw objects on top, and then even some more objects on top.

When rendering godot goes through it layer by layer? And objects on layer0 affect the performance while drawing for nothing? Even if they can't be seen?

Should I be careful about objects that can be seen and delete them on the TileMap to achieve the best performance?


问:
Getting url after download dialog with iMacro
I'm grabbing a web page has a form inside, and after submitting the form (click on the button) download file dialog, is opened and the file will be downloaded.
In this case, I need only the final download link (I can see this link after starting the download in the downloads tab of chrome). this link doesn't exist on the page and I can't use something like the EXTRACT method.

FCI:

```<code>iMacros for CR v10.1.1, 'Free', CR108, Linux Manjaro.
</code>```

Update 1:

I just created a sample demo, In this demo I need copy the file link, actually this link "https://speed.hetzner.de/100MB.bin".
You can see the demo here: https://custom-oakq.frb.io/

Update 2:
FCI added to post.

Body:
I'm grabbing a web page has a form inside, and after submitting the form (click on the button) download file dialog, is opened and the file will be downloaded.
In this case, I need only the final download link (I can see this link after starting the download in the downloads tab of chrome). this link doesn't exist on the page and I can't use something like the EXTRACT method.

FCI:

iMacros for CR v10.1.1, 'Free', CR108, Linux Manjaro.

Update 1:

I just created a sample demo, In this demo I need copy the file link, actually this link "https://speed.hetzner.de/100MB.bin".
You can see the demo here: https://custom-oakq.frb.io/

Update 2:
FCI added to post.


问:
java org.json not supporting special characters like \uf4f8 ,\uf389\uf60d \u2026 emojis)
I have java string like below and I am trying to convert to JSONArray using org.json library.

```<code> String content = "[{  \"message\":\"This year\\u2019s #SexiestManAlive goes to @chrisevans \\uf389\\uf60d \\u2026they did this one for us \\uf979\\n(\\uf4f8: @mschwartzphoto x @people )\"}]"
JSONArray jsonArray = new JSONArray(content);
</code>```

When I am converting this to JSONArray some extends emojis are not converting  (\uf4f8 ,\uf389\uf60d \u2026". )

it looks like this after converting this msg to jsonarray

"This year’s #SexiestManAlive goes to @chrisevans  …they did this one for us 凉\n(: @mschwartzphoto x @people )"

How can we handle this  ? please need help on this.

For Reference:: actually text message in API looks like this
This year’s #SexiestManAlive goes to @chrisevans  …they did this one for us
(: @mschwartzphoto x @people )

Body:
I have java string like below and I am trying to convert to JSONArray using org.json library.

 String content = "[{  \"message\":\"This year\\u2019s #SexiestManAlive goes to @chrisevans \\uf389\\uf60d \\u2026they did this one for us \\uf979\\n(\\uf4f8: @mschwartzphoto x @people )\"}]"
JSONArray jsonArray = new JSONArray(content);

When I am converting this to JSONArray some extends emojis are not converting  (\uf4f8 ,\uf389\uf60d \u2026". )

it looks like this after converting this msg to jsonarray

"This year’s #SexiestManAlive goes to @chrisevans  …they did this one for us 凉\n(: @mschwartzphoto x @people )"

How can we handle this  ? please need help on this.

For Reference:: actually text message in API looks like this
This year’s #SexiestManAlive goes to @chrisevans  …they did this one for us
(: @mschwartzphoto x @people )


问:
Bumping inner libraries version in nx monorepo
We are currently moving some of our inner libraries into a nx monorepo.
Those libraries are publishable.
What can we use to bump our libraries versions?</p>


问:
npm package for compare xml file in angular ? i have xml file i should compare xml file and show the what updates of existing xml file
```<code>     ` existing file:
     <?xml version="1.0" encoding="ISO-8859-1"?>
     <note>
     <to>Tove</to>
     <from>Jani</from>
     <heading>Reminder</heading>
     <body>Don't forget me this weekend!</body>
     </note>

 updated file :

     <?xml version="1.0"?  encoding="ISO-8859-1"?>
     <catalog>
     <book id="bk101">
     <author>Gambardella, Matthew</author>
     <title>XML Developer's Guide</title>
     </book>
     </catalog>

   getXml() {
   var result = XMLValidator.validate(xmlString, {
     allowBooleanAttributes: true,
     });
       console.log('result', result);
     }
</code>```

how to write method for xml file  i need solution to write method for it in angular ts file how do i write and which npm package for xml file validation i dont aware
`

Body:
     ` existing file:
     <?xml version="1.0" encoding="ISO-8859-1"?>
     <note>
     <to>Tove</to>
     <from>Jani</from>
     <heading>Reminder</heading>
     Don't forget me this weekend!
     </note>

 updated file :

     <?xml version="1.0"?  encoding="ISO-8859-1"?>
     <catalog>
     <book id="bk101">
     <author>Gambardella, Matthew</author>
     <title>XML Developer's Guide</title>
     </book>
     </catalog>

   getXml() {
   var result = XMLValidator.validate(xmlString, {
     allowBooleanAttributes: true,
     });
       console.log('result', result);
     }

how to write method for xml file  i need solution to write method for it in angular ts file how do i write and which npm package for xml file validation i dont aware
`


问:
Optain information in time-real using third part resources
This post is for optain information, i have this architecture:

Server software own----> API ----> Server provider

Actually i'm obtain information from server provider use an API, this information is obtained from  our own software server, but this happen each hour because we use a cron job.

I wanna know if exist some technology where i can obtain the information more quickly where i don't need use a cron i mean, where for example: When heppen a change in Server provider i can know automatic this situation and i can get information.

I wanna know if "sockets web" is the tech that i need learn or if exist other way.

Repeat i don't want that yours say me how i can do it i want know what tech exist (using the architecture explained) that i can use.

Thank u a lot for the help.


问:
From several lines a hierarchy into one line
I have a table with data hierarchy

```<code>CREATE TABLE my_table(
    object_id varchar,
    parent_id varchar
);

INSERT INTO my_table(object_id , parent_id)
VALUES
('1', '0'),
('2', '0'),
('3', '1'),
('4', '1'),
('5', '1'),
('6', '3'),
('7', '2'),
('8', '2');
</code>```

object_id
parent_id

1
0

2
0

3
1

4
1

5
1

6
3

7
2

8
2

I need to tranformation to

object_id
parent_id

{1,3,4,5,6},{2,7,8}
0

I think there is no way to do without an intermediate table

So far, I have only found this request, but I don’t know which way to dig further

```<code>SELECT parent_id, array_to_string(array_agg(distinct(object_id)), ' , ', '') AS object_id
FROM my_table
GROUP BY parent_id;
</code>```

Thx

Body:
I have a table with data hierarchy

CREATE TABLE my_table(
    object_id varchar,
    parent_id varchar
);

INSERT INTO my_table(object_id , parent_id)
VALUES
('1', '0'),
('2', '0'),
('3', '1'),
('4', '1'),
('5', '1'),
('6', '3'),
('7', '2'),
('8', '2');

object_id
parent_id

1
0

2
0

3
1

4
1

5
1

6
3

7
2

8
2

I need to tranformation to

object_id
parent_id

{1,3,4,5,6},{2,7,8}
0

I think there is no way to do without an intermediate table

So far, I have only found this request, but I don’t know which way to dig further

SELECT parent_id, array_to_string(array_agg(distinct(object_id)), ' , ', '') AS object_id
FROM my_table
GROUP BY parent_id;

Thx


问:
Javascript detect Ajax call from iFrame
There is a service I'm using which allows me to add Javascript to their pages in a sandboxed iFrame. However, obviously, browsers are not allowing us to read data from the parent document.

So I was wondering if it's possible to listen to a specific Ajax call from inside that iFrame (the Ajax call will be made from the parent document)? Can we somehow see what XMLHTTP requests are being sent?

Ideally with vanilla Javascript.

Title: Javascript detect Ajax call from iFrame


问:
In Webpack file main.js is empty
I have started learning webpack and now i faced problem . Problem is that npm
downloads in dist/folder file main.js empty

asset main.js 0 bytes [emitted] [minimized] (name: main)
./src/index.js 1 bytes [built] [code generated]
webpack 5.75.0 compiled successfully in 100 ms

And i have no idea to solve this problem . And thanks for answers in advance

Title: In Webpack file main.js is empty


问:
Flutter upload image
Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown

```<code>Future<dynamic> getPhotoUrl(int profileID) async {
    print("get Photo url $profileID");
    var client = http.Client();
    var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
    Map<String, String> headers = {
      'APIVersion': '1',
      "Authorization": token,
    };

    var response = await client.get(url, headers: headers);
    if (200 == response.statusCode) {
      return response.body;
    } else {

    }
    print("avatar url: $currentPhotoUrl");
  }
</code>```

tried this and it doesn't work

```<code>Future<void> getPhotoUrl(int profileID) async {
    print("get photo url $profileID");
    var client = http.Client();

    Map<String, String> headers = {
      "Authorization": token
    };
    final http.Response response = await client.get(
        Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
        headers: headers);

    if (response.statusCode == 200) {
      Map responseBody = jsonDecode(response.body);
      var data = responseBody["data"];
      if (data.length < 1) {}
      else {
        currentPhotoUrl.value = data[0]["content"][0]["medium"];
      }
    } else {
      throw WebSocketException("server error: ${response.statusCode}");
    }

    print("photos url: $currentPhotoUrl");
  }
</code>```

Title: Flutter upload image

Body:
Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown

Future<dynamic> getPhotoUrl(int profileID) async {
    print("get Photo url $profileID");
    var client = http.Client();
    var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
    Map<String, String> headers = {
      'APIVersion': '1',
      "Authorization": token,
    };

    var response = await client.get(url, headers: headers);
    if (200 == response.statusCode) {
      return response.body;
    } else {

    }
    print("avatar url: $currentPhotoUrl");
  }

tried this and it doesn't work

Future<void> getPhotoUrl(int profileID) async {
    print("get photo url $profileID");
    var client = http.Client();

    Map<String, String> headers = {
      "Authorization": token
    };
    final http.Response response = await client.get(
        Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
        headers: headers);

    if (response.statusCode == 200) {
      Map responseBody = jsonDecode(response.body);
      var data = responseBody["data"];
      if (data.length < 1) {}
      else {
        currentPhotoUrl.value = data[0]["content"][0]["medium"];
      }
    } else {
      throw WebSocketException("server error: ${response.statusCode}");
    }

    print("photos url: $currentPhotoUrl");
  }


问:
FCM notifications not being displayed by devices
I have a PHP application, through which users can send out alerts (to read a message) to clients who have an app installed. It seems to work pretty well, but I have a consistent small percentage of recipients who say they never get any alerts on their phones. The problem doesn't seem to be restricted to any particular model of phone, and the few users I've spoken to have had the relevant notification permissions allowed.

My code:

First I loop through the recipients identified by the web application and create a notification packet per recipient device:

```<code>        $packets = [];
        foreach($messages_to_send as $msg)
        {
            $message_id = intval($msg['message_id']);
            $device_token = $msg['device_token'];

            if(!isset($packets[$device_token]))
                $packets[$device_token] = [];

            if(!isset($packets[$device_token][$message_id])) {
                $packets[$device_token][$message_id] = [
                    'notification' => [
                        'title' => 'A new message has been received!',
                        'body' => 'Open notifications',
                        'sound' => 'default',
                        'badge' => '1'
                    ],
                    'priority' => 'high',
                    'data' => [
                        'type' => 'sms',
                        'msg_id' => $message_id,
                    ]
                ];
            }
        }
</code>```

Then I loop through those packets and send a cURL request to FCM per message, per device:

```<code>        $headers = [];
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key='. $server_key;

        foreach($packets as $device_token => $messages)
        {
            foreach($messages as $msg_id => $messages_to_send)
            {
                $msg_json = json_encode($messages_to_send);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $fcm_url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_json);
                curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                //Send the request
                $curl_response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                $curl_error = null;
                if( ($httpCode != 200) || (curl_errno($ch)) )
                    $curl_error = ($httpCode != 200) ? 'Firebase response not received (200)' : 'Firebase cURL error: ' . curl_strerror(curl_errno($ch));

                curl_close($ch);
                $curl_response = json_decode($curl_response, true);

                $status = null;
                $sent_ok = 0;
                if($curl_error !== null)
                    $status = $curl_error;
                else
                {
                    if($curl_response['success'] != 1)
                        $status = 'FCM failure';
                    else
                    {
                        if(!isset($curl_response['results'][0]['message_id']))
                            $status = 'Device token no longer recognised by FCM';
                        else
                        {
                            $sent_ok = 1;
                            $status = $curl_response['results'][0]['message_id'];
                        }
                    }
                }

                // Register the sending status per recipient
            }
        }
</code>```

I would love to get this issue closed off. Is there anything wrong with the way I am sending out these notifications? If not, what (other than express permissions) would cause a device to not display an alert?

Body:
I have a PHP application, through which users can send out alerts (to read a message) to clients who have an app installed. It seems to work pretty well, but I have a consistent small percentage of recipients who say they never get any alerts on their phones. The problem doesn't seem to be restricted to any particular model of phone, and the few users I've spoken to have had the relevant notification permissions allowed.

My code:

First I loop through the recipients identified by the web application and create a notification packet per recipient device:

        $packets = [];
        foreach($messages_to_send as $msg)
        {
            $message_id = intval($msg['message_id']);
            $device_token = $msg['device_token'];

            if(!isset($packets[$device_token]))
                $packets[$device_token] = [];

            if(!isset($packets[$device_token][$message_id])) {
                $packets[$device_token][$message_id] = [
                    'notification' => [
                        'title' => 'A new message has been received!',
                        'body' => 'Open notifications',
                        'sound' => 'default',
                        'badge' => '1'
                    ],
                    'priority' => 'high',
                    'data' => [
                        'type' => 'sms',
                        'msg_id' => $message_id,
                    ]
                ];
            }
        }

Then I loop through those packets and send a cURL request to FCM per message, per device:

        $headers = [];
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key='. $server_key;

        foreach($packets as $device_token => $messages)
        {
            foreach($messages as $msg_id => $messages_to_send)
            {
                $msg_json = json_encode($messages_to_send);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $fcm_url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_json);
                curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                //Send the request
                $curl_response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                $curl_error = null;
                if( ($httpCode != 200) || (curl_errno($ch)) )
                    $curl_error = ($httpCode != 200) ? 'Firebase response not received (200)' : 'Firebase cURL error: ' . curl_strerror(curl_errno($ch));

                curl_close($ch);
                $curl_response = json_decode($curl_response, true);

                $status = null;
                $sent_ok = 0;
                if($curl_error !== null)
                    $status = $curl_error;
                else
                {
                    if($curl_response['success'] != 1)
                        $status = 'FCM failure';
                    else
                    {
                        if(!isset($curl_response['results'][0]['message_id']))
                            $status = 'Device token no longer recognised by FCM';
                        else
                        {
                            $sent_ok = 1;
                            $status = $curl_response['results'][0]['message_id'];
                        }
                    }
                }

                // Register the sending status per recipient
            }
        }

I would love to get this issue closed off. Is there anything wrong with the way I am sending out these notifications? If not, what (other than express permissions) would cause a device to not display an alert?