问:
dll not adding to References for a web-site project in VS2022
for a website project(NOT web application project), all dll's which exist in the bin folder are a part of the property-pages-references folder, in VS2019. thus compile successfully.
when tried to open the same project in VS2022, one of the main dll's, though present in the bin folder, does not show up in property-pages-references folder.
thus the project does not compile.
when tried to add the dll in property-pages-references folder, it does not add, but a .refresh file for the same gets added to the bin folder.</p>


来源: stackexchange

问:
Take live snapshot using python and gstreamer
I am using python and gstreamer v4l2src to launch the following pipeline in the code below that displays what's seen on the connected webcam. I'm using pyqt5 to control the video parameters like brightness, contrast, focus ect. When I get the correct look, I'll like to be able to take a snapshot of it, but I'm not sure on how to do so.

```<code>class VideoWidget(qtw.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setAttribute(qtc.Qt.WA_NativeWindow)
        self.windowId = self.winId()
        # need to sync window ids with underlying OS
        qtw.qApp.sync()
        self.pipeline = None

    def prepare(self):

        pipeline = """
         v4l2src device=/dev/video0 ! image/jpeg, width=1920, height=1080, framerate=30/1, format=MJPG ! nvv4l2decoder mjpeg=1 ! nvvidconv ! rotate angle=-0.3491 ! videocrop top=100 bottom=200 right=500 left=600 ! glimagesink
        """

        self.pipeline = Gst.parse_launch(pipeline)
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.enable_sync_message_emission()
        bus.connect('sync-message::element', self.on_sync_message)

    def on_sync_message(self, bus, msg):
        message_name = msg.get_structure().get_name()
        if message_name == 'prepare-window-handle':
            win_id = self.windowId
            assert win_id
            imagesink = msg.src
            imagesink.set_window_handle(win_id)

    def start_webcam(self):
        self.pipeline.set_state(Gst.State.PLAYING)

    def stop_webcam(self):
        self.pipeline.set_state(Gst.State.PAUSED)

    def snap_shot(self, filename):
        pass
</code>```

So far, I've used the following but it's not ideally what I want, and the resolution is not that good. How can I use gstreamer to do so.

```<code>    def snap_shot(self, filename):

        snap_shot = qtg.QScreen.grabWindow(qtw.QApplication.primaryScreen(),
            self.winId())

        filename, ext = os.path.splitext(filename)
        snap_shot.save(filename, ext[1:])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using python and gstreamer v4l2src to launch the following pipeline in the code below that displays what's seen on the connected webcam. I'm using pyqt5 to control the video parameters like brightness, contrast, focus ect. When I get the correct look, I'll like to be able to take a snapshot of it, but I'm not sure on how to do so.

class VideoWidget(qtw.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setAttribute(qtc.Qt.WA_NativeWindow)
        self.windowId = self.winId()
        # need to sync window ids with underlying OS
        qtw.qApp.sync()
        self.pipeline = None

    def prepare(self):

        pipeline = """
         v4l2src device=/dev/video0 ! image/jpeg, width=1920, height=1080, framerate=30/1, format=MJPG ! nvv4l2decoder mjpeg=1 ! nvvidconv ! rotate angle=-0.3491 ! videocrop top=100 bottom=200 right=500 left=600 ! glimagesink
        """

        self.pipeline = Gst.parse_launch(pipeline)
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.enable_sync_message_emission()
        bus.connect('sync-message::element', self.on_sync_message)

    def on_sync_message(self, bus, msg):
        message_name = msg.get_structure().get_name()
        if message_name == 'prepare-window-handle':
            win_id = self.windowId
            assert win_id
            imagesink = msg.src
            imagesink.set_window_handle(win_id)

    def start_webcam(self):
        self.pipeline.set_state(Gst.State.PLAYING)

    def stop_webcam(self):
        self.pipeline.set_state(Gst.State.PAUSED)

    def snap_shot(self, filename):
        pass

So far, I've used the following but it's not ideally what I want, and the resolution is not that good. How can I use gstreamer to do so.

    def snap_shot(self, filename):

        snap_shot = qtg.QScreen.grabWindow(qtw.QApplication.primaryScreen(),
            self.winId())

        filename, ext = os.path.splitext(filename)
        snap_shot.save(filename, ext[1:])


问:
Use AWS KMS for encrypt/decrypt secrets in spring-cloud-config server
How to make use of KMS for encrypting and decrypting secrets in the spring cloud config server?</p>


问:
How to use Shell Function for Excel VBA on MAC
Please, could someone help me with this question. This code that sends messages of information that is in excel, through WhastApp, works correctly in windows, but I need to adapt it so that it works in an Excel of a MAC computer.

I think I understand that the problem is in the execution of the SHELL function that initializes the application, but I don't know what adaptation I should do to make it operative in MAC.

Thank you in advance for your valuable help.

```<code>Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Const SW_NORMAL = 1  'para optimizar la aplicación
Sub envioCartera()
Application.ScreenUpdating = True ' Inabilitar la pantalla
'Application.EnableEvents = False
'ActiveSheet.DisplayPageBreaks = False

Dim Rango As Range
Dim x
Dim Mensaje, saludo, cuerpo, cierre, archivo As String
Dim i, fila, id1, id2, id3, y, k, t1, t2 As Integer
archivo = ThisWorkbook.Name

Call SendKeys("{NUMLOCK}", True)
'loExcel = CreateObject("Excel.Application")
'ReturnValue = Shell("C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE")
Workbooks(archivo).Activate
fila = Hoja1.Cells(Rows.Count, 2).End(xlUp).Row
If fila >= 3 Then

    Hoja3.Range("c11") = Now

    saludo = Hoja3.Range("b4").Text
    cuerpo = " " & Hoja3.Range("c4").Text
    cierre = Hoja3.Range("d4").Text
    id1 = Hoja3.Range("B6").Value
    id2 = Hoja3.Range("C6").Value

    For i = 3 To fila
     'For Each Rango In Hoja1.Range("Cartera[Cliente]") 'Nombre de la tabla y columna
        Mensaje = VBA.Replace("whatsapp://send?phone=" & Hoja1.Cells(i, 5).Text & Hoja1.Cells(i, 4).Value & "&text=" & saludo & Chr(13) & Chr(13) & "%20" & Hoja1.Cells(i, id1) & Chr(13) & "%20" & cuerpo & " " & FormatCurrency(Hoja1.Cells(i, id2), 0) & " " & cierre, " ", "%20")

        Application.Wait Now + TimeValue("00:00:03")

        x = ShellExecute(hwnd, "Open", Mensaje, &O0, &O0, SW_NORMAL)  'Para obtener el mensaje

        Application.Wait Now + TimeValue("00:00:06")

            Call SendKeys("{NUMLOCK}", True)
            Call SendKeys("~", True)  'El caracter ~ es para presionar enter y enviar el mensaje
            Call SendKeys("{NUMLOCK}", True)

        Next i

'AppActivate "Excel", 1
Workbooks(ThisWorkbook.Name).Activate   'Volver la ventana
Hoja1.Select
Call SendKeys("{NUMLOCK}", True)
Hoja3.Range("c12") = Now
MsgBox ("Mensaje con Exito"), vbInformation
Application.ScreenUpdating = True ' Habilitar la pantalla lo que hace
Application.EnableEvents = True

Else
MsgBox "No hay contactos", vbCritical, "excelparatodos.com"
End If

End Sub
</code>```
```<code></code>```

type here

```<code></code>```

Body:
Please, could someone help me with this question. This code that sends messages of information that is in excel, through WhastApp, works correctly in windows, but I need to adapt it so that it works in an Excel of a MAC computer.

I think I understand that the problem is in the execution of the SHELL function that initializes the application, but I don't know what adaptation I should do to make it operative in MAC.

Thank you in advance for your valuable help.

Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Const SW_NORMAL = 1  'para optimizar la aplicación
Sub envioCartera()
Application.ScreenUpdating = True ' Inabilitar la pantalla
'Application.EnableEvents = False
'ActiveSheet.DisplayPageBreaks = False

Dim Rango As Range
Dim x
Dim Mensaje, saludo, cuerpo, cierre, archivo As String
Dim i, fila, id1, id2, id3, y, k, t1, t2 As Integer
archivo = ThisWorkbook.Name

Call SendKeys("{NUMLOCK}", True)
'loExcel = CreateObject("Excel.Application")
'ReturnValue = Shell("C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE")
Workbooks(archivo).Activate
fila = Hoja1.Cells(Rows.Count, 2).End(xlUp).Row
If fila >= 3 Then

    Hoja3.Range("c11") = Now

    saludo = Hoja3.Range("b4").Text
    cuerpo = " " & Hoja3.Range("c4").Text
    cierre = Hoja3.Range("d4").Text
    id1 = Hoja3.Range("B6").Value
    id2 = Hoja3.Range("C6").Value

    For i = 3 To fila
     'For Each Rango In Hoja1.Range("Cartera[Cliente]") 'Nombre de la tabla y columna
        Mensaje = VBA.Replace("whatsapp://send?phone=" & Hoja1.Cells(i, 5).Text & Hoja1.Cells(i, 4).Value & "&text=" & saludo & Chr(13) & Chr(13) & "%20" & Hoja1.Cells(i, id1) & Chr(13) & "%20" & cuerpo & " " & FormatCurrency(Hoja1.Cells(i, id2), 0) & " " & cierre, " ", "%20")

        Application.Wait Now + TimeValue("00:00:03")

        x = ShellExecute(hwnd, "Open", Mensaje, &O0, &O0, SW_NORMAL)  'Para obtener el mensaje

        Application.Wait Now + TimeValue("00:00:06")

            Call SendKeys("{NUMLOCK}", True)
            Call SendKeys("~", True)  'El caracter ~ es para presionar enter y enviar el mensaje
            Call SendKeys("{NUMLOCK}", True)

        Next i

'AppActivate "Excel", 1
Workbooks(ThisWorkbook.Name).Activate   'Volver la ventana
Hoja1.Select
Call SendKeys("{NUMLOCK}", True)
Hoja3.Range("c12") = Now
MsgBox ("Mensaje con Exito"), vbInformation
Application.ScreenUpdating = True ' Habilitar la pantalla lo que hace
Application.EnableEvents = True

Else
MsgBox "No hay contactos", vbCritical, "excelparatodos.com"
End If

End Sub

type here


问:
Cannot open or write to database file
I have a problem, and I hope someone can point me in the right direction.

I'm a retired .Net developer. I have a simple recipe database program on my computer that I wrote for me and my wife to store our recipes. It's a very bare bones program; you can create, edit and delete recipe categories, and create, edit and delete recipes in any category. Very basic; it doesn't even have search or print functionality. It was written in Visual Basic using Visual Studio 19. Its data is stored in a Microsoft Access database.

Today, I was tinkering with the program. I don't know what I did, but now when I run the program, when it tries to access the database, I get the error message "cannot open or write to the file....you need permission to view and write its data." No other process is accessing the database, and the file permissions haven't changed since the last time the program ran successfully. I can access the database using Microsoft Access, but I can't access it with my program.

If anyone can give me any ideas how to fix this issue, I'd be very grateful. Thanks.

Title: Cannot open or write to database file


问:
Intellij 2022.3.1 won't load the AspectJ plugin
I'm building a Minecraft plugin that passes the functions to a Lua interpreter, and after exploring all other options for doing hooks without manually writing everything (i.e. using a built in function from Spigot that lets me easily intercept every event handler; I am not able to use arguments with this, making it worthless for my case) I've discovered my best option is AspectJ.

I installed the latest version of IntelliJ, then installed the relevant plugin and followed the instruction to "add a library containing aspectjrt.jar to my project" (I added org.aspectj:aspectjrt:1.9.19 through build.gradle, and added 'include 'aspectjrt:1.9.19'' to my settings.gradle). It also says to add a facet, but I can't do that due to the error "Requires plugin 'com.intellij.aop' to be installed." I can't find any reference to a dedicated AOP plugin for IntelliJ, in fact I'm told the AspectJ plugin is supposed to add support for it. There seems to be no other reference to this error online.

What am I doing wrong?


问:
How to concatenate datasets for tflite model maker?
Assume I have datasets loaded from different directories

```<code>from tflite_model_maker import object_detector

DIR_IMAGES_TRAIN1="/data_dir1"
DIR_IMAGES_TRAIN2="/data_dir2"
DIR_ANNOT_TRAIN1="/annot_dir1"
DIR_ANNOT_TRAIN2="/annot_dir2"
LABEL_MAP = ["custom_object"]

train_data = object_detector.DataLoader.from_pascal_voc(DIR_IMAGES_TRAIN1, DIR_ANNOT_TRAIN1, LABEL_MAP)
train_data2 = object_detector.DataLoader.from_pascal_voc(DIR_IMAGES_TRAIN2, DIR_ANNOT_TRAIN2, LABEL_MAP)

</code>```

How to concatenate them into one?

The DataLoader doesn't seem to come with a function like 'concatenate'.

Body:
Assume I have datasets loaded from different directories

from tflite_model_maker import object_detector

DIR_IMAGES_TRAIN1="/data_dir1"
DIR_IMAGES_TRAIN2="/data_dir2"
DIR_ANNOT_TRAIN1="/annot_dir1"
DIR_ANNOT_TRAIN2="/annot_dir2"
LABEL_MAP = ["custom_object"]

train_data = object_detector.DataLoader.from_pascal_voc(DIR_IMAGES_TRAIN1, DIR_ANNOT_TRAIN1, LABEL_MAP)
train_data2 = object_detector.DataLoader.from_pascal_voc(DIR_IMAGES_TRAIN2, DIR_ANNOT_TRAIN2, LABEL_MAP)

How to concatenate them into one?

The DataLoader doesn't seem to come with a function like 'concatenate'.


问:
After connecting to a Google account (with the help of firebase), routing to another component does not work for me (I am dealing with Angular)
After logging in to a Google account (by using firebase) automatic routing to another component does not work for me and I remain in the same component that I was in before logging in.

I wrote routes in app-routing.module.ts then I wrote a function in auth.service.ts.
The content of the function: when I log in to a Google account, I am automatically transferred to the component. But I stay in the same component that is defined as the home page.

app-routing.module.ts

The function (auth.service.ts)


问:
discord.js v14 play slash command
I'm trying to make a "play" slash command for my discord bot using discord.js v14.

right now this is what I have

```<code>//Imports the "../utils/BaseSlashCommand" file
const BaseSlashCommand = require('../../../utils/BaseSlashCommand');
//Imports the "SlashCommandBuilder" package
const { SlashCommandBuilder, ApplicationCommandType, ApplicationCommand, VoiceChannel, PermissionFlagsBits } = require('discord.js');
const { MessageEmbedm } = require('discord.js');
const { QueryType, Player } = require('discord-player');

//Extends the "BaseSlashCommand" Class from the "../utils/BaseSlashCommand" file
module.exports = class PlaySlashCommand extends BaseSlashCommand {
    constructor() {
        //Calls the 'super' constructor to initialize(inherit) the parent class and its methods pass its arguments to it
        super('play')
    }

    async run(client, interaction) {

        //const player = new Player(client);
        const player = new Player(client, { audioPlayer: 'node-opus', source: 'youtube' });

        // player.on("error", (error) => {
        //     console.error(error);
        // });

        // player.on("open", () => {
        //     console.log('---------------------------------PLAYER IS OPEN---------------------------------------');
        // });

        const voiceChannel = interaction.member.voice.channel;
        if (!voiceChannel) return interaction.reply({ content: 'You must be in a voice channel to use this command.', ephemeral: true });
        if (!interaction.guild.members.me.permissions.has(PermissionFlagsBits.Connect || PermissionFlagsBits.Speak));

        const queue = await player.createQueue(interaction.guild)
        if (!queue.connection) await queue.connect(voiceChannel);

        //let embed = new MessageEmbed();

        let url = interaction.options.getString('song')
        const result = await player.search(url,{
            requestedBy: interaction.user,
            searchEngine: QueryType.YOUTUBE_SEARCH
        })

        //console.log(result.tracks[0]);

        if (result.tracks.length === 0) return interaction.reply({ content: 'No results found', ephemeral: true })

        try {

            const song = result.tracks[0];
            queue.addTrack(song);
            if (!queue.playing) await queue.play();

        } catch (error) {
            console.error(error);
        }

        // embed
        // .setDescription(`**[${song.title}](${song.url}) has been added to the Queue`)
        // .setThumbnail(song.thumbnail)
        // .setFooter({ text: `Duration: ${song.duration}`});

        // await interaction.editReply({
        //     embeds: [embed]
        // });

    };

            //Creates a method called "getSlashCommandJSON" which returns an instance of SlashCommandBuilder for this command
            getSlashCommandJSON() {
                //return new SlashCommandBuilder()
                return new SlashCommandBuilder()
                //sets the name of the command to the name of the instance which comes from the name of the commands class
                .setName(this.name)
                .setDescription('Play command')
                .addStringOption(option =>
                    option
                    .setName('song')
                    .setDescription('The URL to the song you want to play')
                    .setRequired(true))
                .toJSON();
            };
};
</code>```

when I run the code I get this error

```<code>Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:164:15)
    at writeGeneric (node:internal/stream_base_commons:155:3)
    at Socket._writeGeneric (node:net:795:11)
    at Socket._write (node:net:807:8)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at PassThrough.ondata (node:internal/streams/readable:754:22)
    at PassThrough.emit (node:events:390:28)
    at PassThrough.Readable.read (node:internal/streams/readable:527:10) {
  errno: -4047,
  code: 'EPIPE',
  syscall: 'write'
}
(node:43884) Warning: [DiscordPlayerWarning] Unhandled "error" event! Events "error", "connectionError" must have event listeners!
</code>```

after researching I've found that this error is most likely being caused by the player either not being opened or by it being closed before the song is added to the queue or played. How can I fix this?

also here is a list of all the npm packages I'm using if it helps

├── @discordjs/builders@1.4.0

├── @discordjs/opus@0.8.0

├── @discordjs/rest@1.4.0

├── @discordjs/voice@0.14.0

├── discord-player@5.3.2

├── discord.js@14.7.1

├── dotenv@16.0.3

├── ffmpeg-static@5.1.0

├── nodemon@2.0.20

└── ytdl-core@4.11.2

I've tried adding code to check whether the player was open or not using different methods I found online

```<code>if (player.open) {
  console.log(`Player is open`);
} else {
  console.log(`Player is closed`);
}
</code>```
```<code> player.on("error", (error) => {
             console.error(error);
         });

         player.on("open", () => {
             console.log('---------------------------------PLAYER IS OPEN---------------------------------------');
         });
</code>```

as well as using code example directly from the discord-player official documentation

Title: discord.js v14 play slash command

Body:
I'm trying to make a "play" slash command for my discord bot using discord.js v14.

right now this is what I have

//Imports the "../utils/BaseSlashCommand" file
const BaseSlashCommand = require('../../../utils/BaseSlashCommand');
//Imports the "SlashCommandBuilder" package
const { SlashCommandBuilder, ApplicationCommandType, ApplicationCommand, VoiceChannel, PermissionFlagsBits } = require('discord.js');
const { MessageEmbedm } = require('discord.js');
const { QueryType, Player } = require('discord-player');

//Extends the "BaseSlashCommand" Class from the "../utils/BaseSlashCommand" file
module.exports = class PlaySlashCommand extends BaseSlashCommand {
    constructor() {
        //Calls the 'super' constructor to initialize(inherit) the parent class and its methods pass its arguments to it
        super('play')
    }

    async run(client, interaction) {

        //const player = new Player(client);
        const player = new Player(client, { audioPlayer: 'node-opus', source: 'youtube' });

        // player.on("error", (error) => {
        //     console.error(error);
        // });

        // player.on("open", () => {
        //     console.log('---------------------------------PLAYER IS OPEN---------------------------------------');
        // });

        const voiceChannel = interaction.member.voice.channel;
        if (!voiceChannel) return interaction.reply({ content: 'You must be in a voice channel to use this command.', ephemeral: true });
        if (!interaction.guild.members.me.permissions.has(PermissionFlagsBits.Connect || PermissionFlagsBits.Speak));

        const queue = await player.createQueue(interaction.guild)
        if (!queue.connection) await queue.connect(voiceChannel);

        //let embed = new MessageEmbed();

        let url = interaction.options.getString('song')
        const result = await player.search(url,{
            requestedBy: interaction.user,
            searchEngine: QueryType.YOUTUBE_SEARCH
        })

        //console.log(result.tracks[0]);

        if (result.tracks.length === 0) return interaction.reply({ content: 'No results found', ephemeral: true })

        try {

            const song = result.tracks[0];
            queue.addTrack(song);
            if (!queue.playing) await queue.play();

        } catch (error) {
            console.error(error);
        }

        // embed
        // .setDescription(`**[${song.title}](${song.url}) has been added to the Queue`)
        // .setThumbnail(song.thumbnail)
        // .setFooter({ text: `Duration: ${song.duration}`});

        // await interaction.editReply({
        //     embeds: [embed]
        // });

    };

            //Creates a method called "getSlashCommandJSON" which returns an instance of SlashCommandBuilder for this command
            getSlashCommandJSON() {
                //return new SlashCommandBuilder()
                return new SlashCommandBuilder()
                //sets the name of the command to the name of the instance which comes from the name of the commands class
                .setName(this.name)
                .setDescription('Play command')
                .addStringOption(option =>
                    option
                    .setName('song')
                    .setDescription('The URL to the song you want to play')
                    .setRequired(true))
                .toJSON();
            };
};

when I run the code I get this error

Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:164:15)
    at writeGeneric (node:internal/stream_base_commons:155:3)
    at Socket._writeGeneric (node:net:795:11)
    at Socket._write (node:net:807:8)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at PassThrough.ondata (node:internal/streams/readable:754:22)
    at PassThrough.emit (node:events:390:28)
    at PassThrough.Readable.read (node:internal/streams/readable:527:10) {
  errno: -4047,
  code: 'EPIPE',
  syscall: 'write'
}
(node:43884) Warning: [DiscordPlayerWarning] Unhandled "error" event! Events "error", "connectionError" must have event listeners!

after researching I've found that this error is most likely being caused by the player either not being opened or by it being closed before the song is added to the queue or played. How can I fix this?

also here is a list of all the npm packages I'm using if it helps

├── @discordjs/builders@1.4.0

├── @discordjs/opus@0.8.0

├── @discordjs/rest@1.4.0

├── @discordjs/voice@0.14.0

├── discord-player@5.3.2

├── discord.js@14.7.1

├── dotenv@16.0.3

├── ffmpeg-static@5.1.0

├── nodemon@2.0.20

└── ytdl-core@4.11.2

I've tried adding code to check whether the player was open or not using different methods I found online

if (player.open) {
  console.log(`Player is open`);
} else {
  console.log(`Player is closed`);
}

 player.on("error", (error) => {
             console.error(error);
         });

         player.on("open", () => {
             console.log('---------------------------------PLAYER IS OPEN---------------------------------------');
         });

as well as using code example directly from the discord-player official documentation


问:
How to pass double variable from service into controller
I will provide here a better back story so you can understand a problem.

I have a user, user can have a wallet, now when I list on page all wallets from user, he can click on button to create a new transaction for any wallet. Also, on that page I have field that show me a total net worth of user, that is actually sum of all wallets balance. And that works fine. Now , user can create a transaction without any problem, but problem is updating a net worth on page, so obviously when user add transaction and for example if his net worth is 500 but user created a transaction for 100, his net worth should be updated to 400.

This is thymeleaf how I show total net worth for user;

```<code><div class="header" th:each="wallets : ${wallets}">
<h1>Net Worth</h1>
<h1 th:text="${wallets.totalBalance}"></h1>
</div>
</code>```

Nothing special, and this is method and controller:

```<code>@Override
public Wallet netWorth(Long userId) {
    Wallet wallet = new Wallet();
    List<Wallet> wallets = walletRepository.findDistinctIdByUserId(userId);
    double worth = 0;
    for (int i = 0; i < wallets.size(); i++)
        worth += wallets.get(i).getInitialBalance();
    wallet.setTotalBalance(worth);
    return wallet;
}
</code>```

So basically I go thought all user wallets in for loop and sum each balance and then set that result on field.

This is controller and model that I use on thymeleaf to show wallets that logged user have and also his net worth as I explained before.

```<code> @GetMapping("/userWallet/balance/{user_id}")
 public String getUserWallet(@PathVariable(value = "user_id") Long user_id, Model model) {
    model.addAttribute("wallet", walletService.findDistinctIdByUserId(user_id));
    model.addAttribute("wallets", walletService.netWorth(user_id));
    return "user_profile";
}
</code>```

Now is main problem:

I have a service that works fine:

```<code>@Override
public double netWorthAfterOutcomeTransaction(Long userId, double amount) {
    List<Wallet> wallets = walletRepository.findDistinctIdByUserId(userId);
    Wallet wallet = new Wallet();
    double worth = 0;
    double worthAfterOutcome = 0;
    for (int i = 0; i < wallets.size(); i++)
        worth += wallets.get(i).getInitialBalance();
    worthAfterOutcome = worth - amount;
    wallet.setTotalBalance(worthAfterOutcome);
    logger.info("Amount entered is:  " + amount);
    logger.info("Balance after outcome is : " + wallet.getTotalBalance());

    return worthAfterOutcome;
}
</code>```

On loggers that I added new balance after transaction is good, for example if user balance is 4000 and I on form set amount 300 logger will provide next info:

```<code>Amount entered is:  300.0
Balance after outcome is : 3700.0
</code>```

So total balance for all wallets or net worth is updated fine, I have a trouble just to show that new result in thymyleaf. I tried like this:

```<code>    model.addAttribute("wallets", transactionService.netWorthAfterOutcomeTransaction(user_id,);
</code>```

But I have problem to pass double amount in that model

Body:
I will provide here a better back story so you can understand a problem.

I have a user, user can have a wallet, now when I list on page all wallets from user, he can click on button to create a new transaction for any wallet. Also, on that page I have field that show me a total net worth of user, that is actually sum of all wallets balance. And that works fine. Now , user can create a transaction without any problem, but problem is updating a net worth on page, so obviously when user add transaction and for example if his net worth is 500 but user created a transaction for 100, his net worth should be updated to 400.

This is thymeleaf how I show total net worth for user;

Net Worth

Nothing special, and this is method and controller:

@Override
public Wallet netWorth(Long userId) {
    Wallet wallet = new Wallet();
    List<Wallet> wallets = walletRepository.findDistinctIdByUserId(userId);
    double worth = 0;
    for (int i = 0; i < wallets.size(); i++)
        worth += wallets.get(i).getInitialBalance();
    wallet.setTotalBalance(worth);
    return wallet;
}

So basically I go thought all user wallets in for loop and sum each balance and then set that result on field.

This is controller and model that I use on thymeleaf to show wallets that logged user have and also his net worth as I explained before.

 @GetMapping("/userWallet/balance/{user_id}")
 public String getUserWallet(@PathVariable(value = "user_id") Long user_id, Model model) {
    model.addAttribute("wallet", walletService.findDistinctIdByUserId(user_id));
    model.addAttribute("wallets", walletService.netWorth(user_id));
    return "user_profile";
}

Now is main problem:

I have a service that works fine:

@Override
public double netWorthAfterOutcomeTransaction(Long userId, double amount) {
    List<Wallet> wallets = walletRepository.findDistinctIdByUserId(userId);
    Wallet wallet = new Wallet();
    double worth = 0;
    double worthAfterOutcome = 0;
    for (int i = 0; i < wallets.size(); i++)
        worth += wallets.get(i).getInitialBalance();
    worthAfterOutcome = worth - amount;
    wallet.setTotalBalance(worthAfterOutcome);
    logger.info("Amount entered is:  " + amount);
    logger.info("Balance after outcome is : " + wallet.getTotalBalance());

    return worthAfterOutcome;
}

On loggers that I added new balance after transaction is good, for example if user balance is 4000 and I on form set amount 300 logger will provide next info:

Amount entered is:  300.0
Balance after outcome is : 3700.0

So total balance for all wallets or net worth is updated fine, I have a trouble just to show that new result in thymyleaf. I tried like this:

    model.addAttribute("wallets", transactionService.netWorthAfterOutcomeTransaction(user_id,);

But I have problem to pass double amount in that model


问:
Aws amplify user group react-native
I'm using @aws-amplify (https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/) to create users and authenticate.

Now I've created 2 user groups (admin and user) in Aws Cognito.

I would like to add a certain user to a specific user group when signing up.

How do i achieve this?

Title: Aws amplify user group react-native


问:
cleanest way to trigger a function in child component from parent component in react native
I followed a react native tutorial that builds a todo list(and stores todo items with useState) and I wanted to add delete-todo item functionality. I put a delete button(using Icon react native elements) on the navbar(in App(App.js) component's return):

```<code><NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen
            name="home"
            component={HomeScreen}
            options={({ navigation }) => ({
              headerRight: () => (
                <View>
                  <Icon
                    ...
                    onPress={() => HomeScreen.deleteSelected()}
                  />
                </View>
              ),
            })}
          />
          ...
        </Stack.Navigator>
</NavigationContainer>
</code>```

However, this doesn't work since deleteSelected is a local function defined in HomeScreen(HomeScreen.js) component:

```<code>export default function HomeScreen({ navigation }) {
  ...
  const [items, setItems] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);

  const deleteSelected = () => {...}
</code>```

I defined deleteSelected inside the HomeScreen component since the required states(items and selectedItems) are defined there.

After some research, I found I can implement such a trigger using forwardRef and useImperativeHandle as shown in https://stackoverflow.com/a/65389631/20883133 . I am wondering if there is a cleaner(more versatile) way to implement a function trigger from the parent component to a function in the child component in react native.

I was told some state manager dependencies can help, like Zustand or Recoil. I read recoil docs in detail but couldn't figure out how it can help with such a problem.

Body:
I followed a react native tutorial that builds a todo list(and stores todo items with useState) and I wanted to add delete-todo item functionality. I put a delete button(using Icon react native elements) on the navbar(in App(App.js) component's return):

<NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen
            name="home"
            component={HomeScreen}
            options={({ navigation }) => ({
              headerRight: () => (
                <View>
                  <Icon
                    ...
                    onPress={() => HomeScreen.deleteSelected()}
                  />
                </View>
              ),
            })}
          />
          ...
        </Stack.Navigator>
</NavigationContainer>

However, this doesn't work since deleteSelected is a local function defined in HomeScreen(HomeScreen.js) component:

export default function HomeScreen({ navigation }) {
  ...
  const [items, setItems] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);

  const deleteSelected = () => {...}

I defined deleteSelected inside the HomeScreen component since the required states(items and selectedItems) are defined there.

After some research, I found I can implement such a trigger using forwardRef and useImperativeHandle as shown in https://stackoverflow.com/a/65389631/20883133 . I am wondering if there is a cleaner(more versatile) way to implement a function trigger from the parent component to a function in the child component in react native.

I was told some state manager dependencies can help, like Zustand or Recoil. I read recoil docs in detail but couldn't figure out how it can help with such a problem.


问:
How to add a whole year in Excel cells using python. (Ex. Cell A1 = 01/01/2022 , Cell A2 = 01/02/2022 and so on)
```<code>import openpyxl
from openpyxl import Workbook, load_workbook
workbook = openpyxl.load_workbook(r"C:\Users\Public\Documents\2022Data.xlsx")
worksheet = workbook['Sheet1']
worksheet.cell(row=2, column=1).value = '01/01/2022'
workbook.save(r"C:\Users\Public\Documents\2022Data.xlsx")
</code>```

This code just helps me with the first cell A2 but I would like to fill all the cells in Column A to coplete the full 2022 year.

Body:
import openpyxl
from openpyxl import Workbook, load_workbook
workbook = openpyxl.load_workbook(r"C:\Users\Public\Documents\2022Data.xlsx")
worksheet = workbook['Sheet1']
worksheet.cell(row=2, column=1).value = '01/01/2022'
workbook.save(r"C:\Users\Public\Documents\2022Data.xlsx")

This code just helps me with the first cell A2 but I would like to fill all the cells in Column A to coplete the full 2022 year.


问:
What job does vscode file watcher do?
I met error "Visual Studio Code is unable to watch for file changes in this large workspace" when I  work on a remote server. The solution to this problem is here: https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc

As I do not have permission to edit /etc/sysctl.conf to increase the limit, I have to exclude some directories from file watcher. I wonder what job does vscode file watcher do, and what happens if certain files are not tracked by the file watcher? So far I think file watcher is not so important so it should be safe to exclude files from file watcher?

Title: What job does vscode file watcher do?


问:
Spring Boot Order of Initialization for reading from Database
I am currently using hibernate repositories and I need roles in my database, as one of my service layers uses the roles at startup.

```<code>@SpringBootApplication
public class FedditBackendApplication {

   public static void main(String[] args) {
      SpringApplication.run(FedditBackendApplication.class, args);
   }
   @Bean
   CommandLineRunner init (RoleRepository roleRepo) {
      return args -> {
         for(ERole role: ERole.values()) {
            if (!roleRepo.existsByName(role)){
               roleRepo.save(new Role(role));
            }
         }
      };
   }
   @Bean
   public ModelMapper modelMapper() {
      return new ModelMapper();
   }
}
</code>```

To initialize my roles into my database, I let spring do my schema creation, however I need to put these rows into the database directly afterwards.

Is There a better way to do this?  The issue I'm running into is that one of my Service components gets from the roleRepository in the constructor and it's not finding anything when I use this initialization method.

```<code>@Service
@Transactional
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;
    private final RoleRepository roleRepository;
    private final PasswordEncoder encoder;
    private final JwtUtils jwtUtils;
    private final Set<Role> userRoles;
    public UserServiceImpl(UserRepository userRepository, AuthenticationManager authenticationManager, RoleRepository roleRepository, PasswordEncoder encoder, JwtUtils jwtUtils,Set<Role> userRoles){
        this.userRepository = userRepository;
        this.authenticationManager = authenticationManager;
        this.roleRepository = roleRepository;
        this.encoder = encoder;
        this.jwtUtils = jwtUtils;
        this.userRoles = new HashSet<>();

        Optional<Role> userRole = this.roleRepository.findByName(ERole.ROLE_USER);
        // throws error on next line because userRole is not present in the DB
        this.userRoles.add(userRole.get());
    }
}
</code>```

I've tried changing the order of the bean initialization with no success.

It seems that the CommandLineRunner bean initializes after the service layers.

```<code>@Bean
CommandLineRunner init (RoleRepository roleRepo) {
  return args -> {
     for(ERole role: ERole.values()) {
        if (!roleRepo.existsByName(role)){
           roleRepo.save(new Role(role));
        }
     }
  };
}
</code>```

I'd like to initialize these rows after the schema is created, though I'm not really sure how.

https://github.com/vw0389/feddit-backend/tree/comments is the repo and branch if relevant

Body:
I am currently using hibernate repositories and I need roles in my database, as one of my service layers uses the roles at startup.

@SpringBootApplication
public class FedditBackendApplication {

   public static void main(String[] args) {
      SpringApplication.run(FedditBackendApplication.class, args);
   }
   @Bean
   CommandLineRunner init (RoleRepository roleRepo) {
      return args -> {
         for(ERole role: ERole.values()) {
            if (!roleRepo.existsByName(role)){
               roleRepo.save(new Role(role));
            }
         }
      };
   }
   @Bean
   public ModelMapper modelMapper() {
      return new ModelMapper();
   }
}

To initialize my roles into my database, I let spring do my schema creation, however I need to put these rows into the database directly afterwards.

Is There a better way to do this?  The issue I'm running into is that one of my Service components gets from the roleRepository in the constructor and it's not finding anything when I use this initialization method.

@Service
@Transactional
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;
    private final RoleRepository roleRepository;
    private final PasswordEncoder encoder;
    private final JwtUtils jwtUtils;
    private final Set<Role> userRoles;
    public UserServiceImpl(UserRepository userRepository, AuthenticationManager authenticationManager, RoleRepository roleRepository, PasswordEncoder encoder, JwtUtils jwtUtils,Set<Role> userRoles){
        this.userRepository = userRepository;
        this.authenticationManager = authenticationManager;
        this.roleRepository = roleRepository;
        this.encoder = encoder;
        this.jwtUtils = jwtUtils;
        this.userRoles = new HashSet<>();

        Optional<Role> userRole = this.roleRepository.findByName(ERole.ROLE_USER);
        // throws error on next line because userRole is not present in the DB
        this.userRoles.add(userRole.get());
    }
}

I've tried changing the order of the bean initialization with no success.

It seems that the CommandLineRunner bean initializes after the service layers.

@Bean
CommandLineRunner init (RoleRepository roleRepo) {
  return args -> {
     for(ERole role: ERole.values()) {
        if (!roleRepo.existsByName(role)){
           roleRepo.save(new Role(role));
        }
     }
  };
}

I'd like to initialize these rows after the schema is created, though I'm not really sure how.

https://github.com/vw0389/feddit-backend/tree/comments is the repo and branch if relevant


问:
vb.net | How to play youtube video or DropBox video in Forms?
I am trying to play a video from my dropbox or from youtube in VB.NET.
Tried it with the media player and with the web browser, but both are much too old.

And doesn't work properly. Do you have any tips?

AxMediaPlayer, WebBrowser doesnt work. It is way to old!


问:
Why when I send the data through a normal JSON text (Thunder Client) it works, but if I use forms (Thunder Client) It doesn't?
I've tried it with Postman too and it does the same thing. I was following a tutorial and ran into this problem, which the creator didn't have. I copied and pasted (After error) his same working folder and the same thing:

It works with JSON:

But it doesn't using Forms:

I used to think I will never use one of this pages, but now I'm introducing myself to programming, I know I will use it thousands of times. I have like 4 hours straight looking to solve this problem. Please!

This is my schema:

```<code>import mongoose from "mongoose";

const postSchema = new mongoose.Schema({
    title: {
        type: "String",
        required: true,
        trim: true,
    },
    description: {
        type: "String",
        required: true,
        trim: true,
    },
    image: {
        url: "String",
        public_id: "String",
    }
})

export default mongoose.model('Post', postSchema)
</code>```

And this is my createPost:

```<code>const createPost = async (req, res) => {
    try {
        const { title, description } = req.body;

        const newPost = new Post({ title, description })

        await newPost.save()

        return res.json(newPost)
    } catch (error) {
        res.status(500).json({error: error.message})
    }
}

</code>```

Body:
I've tried it with Postman too and it does the same thing. I was following a tutorial and ran into this problem, which the creator didn't have. I copied and pasted (After error) his same working folder and the same thing:

It works with JSON:

But it doesn't using Forms:

I used to think I will never use one of this pages, but now I'm introducing myself to programming, I know I will use it thousands of times. I have like 4 hours straight looking to solve this problem. Please!

This is my schema:

import mongoose from "mongoose";

const postSchema = new mongoose.Schema({
    title: {
        type: "String",
        required: true,
        trim: true,
    },
    description: {
        type: "String",
        required: true,
        trim: true,
    },
    image: {
        url: "String",
        public_id: "String",
    }
})

export default mongoose.model('Post', postSchema)

And this is my createPost:

const createPost = async (req, res) => {
    try {
        const { title, description } = req.body;

        const newPost = new Post({ title, description })

        await newPost.save()

        return res.json(newPost)
    } catch (error) {
        res.status(500).json({error: error.message})
    }
}


问:
How to update the results of a function into a dictionary in python?
I want to multiply each element of a dictionary by items from a given list and store the result in another dictionary, with the first dictionary's keys serving as the keys in the second dictionary. The result, however, contains an error in that the product of the last item in the dictionary overwrites the product results of the previous product. View the code below for a better understanding:

```<code>def mult(num, x):
  return num * x

num = {'one':1, 'two':2, 'three':3}
x = [11, 12, 13, 14, 15, 16, 17]
r = dict()
resu = dict()

for k, n in num.items():
  for i in x:
    prod = mult(n, i)
    r[i] = prod
  resu[k] = r

resu
</code>```

The following is the output I'm getting:

```<code>{'one': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51},
 'two': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51},
 'three': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51}}
</code>```

The expected result should be like:

```<code>{'one': {11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17},
  'two': {11: 22, 12: 24, 13: 26, 14: 28, 15: 30, 16: 32, 17: 34},
  'three': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51}}
</code>```

Is there anyone who can assist me with this? Thank you in advance.

Body:
I want to multiply each element of a dictionary by items from a given list and store the result in another dictionary, with the first dictionary's keys serving as the keys in the second dictionary. The result, however, contains an error in that the product of the last item in the dictionary overwrites the product results of the previous product. View the code below for a better understanding:

def mult(num, x):
  return num * x

num = {'one':1, 'two':2, 'three':3}
x = [11, 12, 13, 14, 15, 16, 17]
r = dict()
resu = dict()

for k, n in num.items():
  for i in x:
    prod = mult(n, i)
    r[i] = prod
  resu[k] = r

resu

The following is the output I'm getting:

{'one': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51},
 'two': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51},
 'three': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51}}

The expected result should be like:

{'one': {11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17},
  'two': {11: 22, 12: 24, 13: 26, 14: 28, 15: 30, 16: 32, 17: 34},
  'three': {11: 33, 12: 36, 13: 39, 14: 42, 15: 45, 16: 48, 17: 51}}

Is there anyone who can assist me with this? Thank you in advance.


问:
How do you re-render multiple React components inside of one parent React component in one go?
I want to be able to shuffle these tickets when I click a project option in the drop down. I didn't figure it would work but I tried writing three separate useState functions for each ticket type array. I know the shuffleTickets method is being called correctly, just not doing what I want. Are you able to pass in multiple parameters for a useState function?</p>
```<code>import React from "react";
import { useState } from "react";
import styles from "./Tickets.module.css";
import TicketTable from "./TicketTable";
import Modal from "./Modal";

const Tickets = () => {
  const notStartedTickets = [
    { id: 1, assignee: "trevor strnad", time: "1h" },
    { id: 9, assignee: "trevor strnad", time: "1h" },
    { id: 10, assignee: "n8 feet under ", time: "1h" },
  ];
  const inProgressTickets = [
    { id: 11, assignee: "n8 feet under ", time: "1h" },
    { id: 12, assignee: "ryan knight", time: "1h" },
    { id: 15, assignee: "trevor strnad", time: "1h" },
  ];
  const completedTickets = [
    { id: 16, assignee: "n8 feet under ", time: "1h" },
    { id: 17, assignee: "ryan knight", time: "1h" },
    { id: 18, assignee: "trevor strnad", time: "1h" },
  ];

  const [shuffledNewTickets, setShuffledNewTickets] = useState(notStartedTickets);
  const [shuffledStartedTickets, setShuffledStartedTickets] = useState(inProgressTickets);
  const [shuffledDoneTickets, setShuffledDoneTickets] = useState(completedTickets);

  const shuffleTickets = () => {

    setShuffledNewTickets(notStartedTickets.sort((a, b) => Math.random() - 0.5));
    setShuffledStartedTickets(inProgressTickets.sort((a, b) => Math.random() - 0.5));
    setShuffledDoneTickets(completedTickets.sort((a, b) => Math.random() - 0.5));

  }

  return (
    <>
      <div className={styles.create}>
        <select className={styles.projects}>
          <option value="project 1" onClick={shuffleTickets}>Project 1</option>
          <option value="project 2" onClick={shuffleTickets}>Project 2</option>
          <option value="project 3" onClick={shuffleTickets}>Project 3</option>
          <option value="project 4" onClick={shuffleTickets}>Project 4</option>
        </select>
        <button onClick={toggleNewTicketModal} className={styles.button}>
          create ticket
        </button>
      </div>
      <div className={styles.tickets}>
        {editTicketModal ?
          <Modal onToggleModal={toggleEditTicketModal} onCreateTicket={createTicket} title={'edit ticket'}/>
        : createTicketModal ?
        <Modal onToggleModal={toggleNewTicketModal} onCreateTicket={createTicket} title={'new ticket'} />
        : null
        }
        {/* {modal && (
          <Modal onToggleModal={toggleModal} onCreateTicket={createTicket} title={title}/>
        )} */}
        <TicketTable
          color={"red"}
          header={"not started"}
          tickets={shuffledNewTickets}
          onToggleModal={toggleEditTicketModal}
        />
        <TicketTable
          color={"blue"}
          header={"in progress"}
          tickets={shuffledStartedTickets}
          onToggleModal={toggleEditTicketModal}
        />
        <TicketTable
          color={"green"}
          header={"completed"}
          tickets={shuffledDoneTickets}
          onToggleModal={toggleEditTicketModal}
        />
      </div>
    </>
  );
};

export default Tickets;
</code>```

Body:
I want to be able to shuffle these tickets when I click a project option in the drop down. I didn't figure it would work but I tried writing three separate useState functions for each ticket type array. I know the shuffleTickets method is being called correctly, just not doing what I want. Are you able to pass in multiple parameters for a useState function?

import React from "react";
import { useState } from "react";
import styles from "./Tickets.module.css";
import TicketTable from "./TicketTable";
import Modal from "./Modal";

const Tickets = () => {
  const notStartedTickets = [
    { id: 1, assignee: "trevor strnad", time: "1h" },
    { id: 9, assignee: "trevor strnad", time: "1h" },
    { id: 10, assignee: "n8 feet under ", time: "1h" },
  ];
  const inProgressTickets = [
    { id: 11, assignee: "n8 feet under ", time: "1h" },
    { id: 12, assignee: "ryan knight", time: "1h" },
    { id: 15, assignee: "trevor strnad", time: "1h" },
  ];
  const completedTickets = [
    { id: 16, assignee: "n8 feet under ", time: "1h" },
    { id: 17, assignee: "ryan knight", time: "1h" },
    { id: 18, assignee: "trevor strnad", time: "1h" },
  ];

  const [shuffledNewTickets, setShuffledNewTickets] = useState(notStartedTickets);
  const [shuffledStartedTickets, setShuffledStartedTickets] = useState(inProgressTickets);
  const [shuffledDoneTickets, setShuffledDoneTickets] = useState(completedTickets);

  const shuffleTickets = () => {

    setShuffledNewTickets(notStartedTickets.sort((a, b) => Math.random() - 0.5));
    setShuffledStartedTickets(inProgressTickets.sort((a, b) => Math.random() - 0.5));
    setShuffledDoneTickets(completedTickets.sort((a, b) => Math.random() - 0.5));

  }

  return (
    <>

        <select className={styles.projects}>
          <option value="project 1" onClick={shuffleTickets}>Project 1</option>
          <option value="project 2" onClick={shuffleTickets}>Project 2</option>
          <option value="project 3" onClick={shuffleTickets}>Project 3</option>
          <option value="project 4" onClick={shuffleTickets}>Project 4</option>
        </select>
        <button onClick={toggleNewTicketModal} className={styles.button}>
          create ticket
        </button>

        {editTicketModal ?
          <Modal onToggleModal={toggleEditTicketModal} onCreateTicket={createTicket} title={'edit ticket'}/>
        : createTicketModal ?
        <Modal onToggleModal={toggleNewTicketModal} onCreateTicket={createTicket} title={'new ticket'} />
        : null
        }
        {/* {modal && (
          <Modal onToggleModal={toggleModal} onCreateTicket={createTicket} title={title}/>
        )} */}
        <TicketTable
          color={"red"}
          header={"not started"}
          tickets={shuffledNewTickets}
          onToggleModal={toggleEditTicketModal}
        />
        <TicketTable
          color={"blue"}
          header={"in progress"}
          tickets={shuffledStartedTickets}
          onToggleModal={toggleEditTicketModal}
        />
        <TicketTable
          color={"green"}
          header={"completed"}
          tickets={shuffledDoneTickets}
          onToggleModal={toggleEditTicketModal}
        />

    </>
  );
};

export default Tickets;


问:
How to log parameters instead of placeholders using sqlx with Postgres?
I'm using sqlx for the first time today.

I'm having really hard time understanding my SQL errors because I cannot copy & paste logged queries in my IDE because the parameters are not converted from placeholders.

It prints:

```<code>SELECT * from players where team_id = $1 AND id = $2
</code>```

but I would like the below instead:

```<code>SELECT * from players where team_id = 'ABC' AND id = '123'
</code>```

How to do this?

Body:
I'm using sqlx for the first time today.

I'm having really hard time understanding my SQL errors because I cannot copy & paste logged queries in my IDE because the parameters are not converted from placeholders.

It prints:

SELECT * from players where team_id = $1 AND id = $2

but I would like the below instead:

SELECT * from players where team_id = 'ABC' AND id = '123'

How to do this?


问:
How to export script and execute it with next/script
Salutations!

I am working on a Tailwind-css-Next.js-Typescript project trying to implement a theme toggler. It works fine except for the on-load flicker.

In the past I implemented a solution similar to https://github.com/vercel/next.js/discussions/12533 but now that only next/script is accepted, when using Typescript you can't export a script without export which paradoxically returns an Uncaught SyntaxError: Unexpected token 'export' error.
Also scripts like this won't execute anyway if you add them in the Head instead of inside the body. Which in turn is a problem because tailwind wants the script in the head.

This is my current script (note that I must use export{} and create a module otherwise the Typescript linter doesn't let me save the file):

```<code>var theme = localStorage.getItem("dark-theme") || "light";
if (theme === "dark") {
  document.documentElement.classList.add("dark");
}
export {};
</code>```

And I try to use it like so:

```<code>import "./globals.css";
import Script from "next/script";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      {/*
        <head /> will contain the components returned by the nearest parent
        head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
      */}
      <head />
      <body>
        <Script
          type="module"
          strategy="beforeInteractive"
          src="themeScript.tsx"
        />
        {children}
      </body>
    </html>
  );
}
</code>```

But this causes a Uncaught SyntaxError: Unexpected token 'export' (at themeScript.tsx:1:1)

I have also tried adding the following both in the Head and in the body. It doesn't return an error but doesn't produce a result.

```<code><Script id="find-dark-mode">{localStorage.getItem("dark-theme") === true ? document.documentElement.classList.add('dark') : document.documentElement.classList.remove('dark')}</Script>
</code>```

This question is similar to Next 13 & Tailwind Darkmode Flickering but I am asking about next 13 scripts in general.

I appreciate your time in advance.

Body:
Salutations!

I am working on a Tailwind-css-Next.js-Typescript project trying to implement a theme toggler. It works fine except for the on-load flicker.

In the past I implemented a solution similar to https://github.com/vercel/next.js/discussions/12533 but now that only next/script is accepted, when using Typescript you can't export a script without export which paradoxically returns an Uncaught SyntaxError: Unexpected token 'export' error.
Also scripts like this won't execute anyway if you add them in the Head instead of inside the body. Which in turn is a problem because tailwind wants the script in the head.

This is my current script (note that I must use export{} and create a module otherwise the Typescript linter doesn't let me save the file):

var theme = localStorage.getItem("dark-theme") || "light";
if (theme === "dark") {
  document.documentElement.classList.add("dark");
}
export {};

And I try to use it like so:

import "./globals.css";
import Script from "next/script";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (

      {/*
         will contain the components returned by the nearest parent
        head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
      */}

This question is similar to Next 13 & Tailwind Darkmode Flickering but I am asking about next 13 scripts in general.

I appreciate your time in advance.


问:
Crash runnng in android apps created kivymd and colab buildozer
I have done successfully to convert a very simple python scripts into android apps using colab buildozer.
I uses only kivymd.app
However when I added kivymd.uix.pickers, it crashes when I run the app in my android phone.
Please tell me what was wrong and simple solution.
I have editted the buildozer.spec line 40 to: requirements = python3,kivy,kivymd
Below are the py and kv file.</p>
```<code>#main.py
from kivymd.app import MDApp
from kivymd.uix.pickers import MDDatePicker

class MainApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "DeepPurple"
    def show_date_picker(self):
        date_dialog = MDDatePicker()
        date_dialog.open()
if __name__ == '__main__':
    app = MainApp()
    app.run()

</code>```
```<code>MDFloatLayout:
    MDLabel:
        text: "My Tasks"
        pos_hint: {'x': .5,'y': .45}
    MDRectangleFlatButton:
        text: 'Date Picker'
        pos_hint: {'x': .5, 'y':.5}
        on_release: app.show_date_picker()

</code>```

Body:
I have done successfully to convert a very simple python scripts into android apps using colab buildozer.
I uses only kivymd.app
However when I added kivymd.uix.pickers, it crashes when I run the app in my android phone.
Please tell me what was wrong and simple solution.
I have editted the buildozer.spec line 40 to: requirements = python3,kivy,kivymd
Below are the py and kv file.

#main.py
from kivymd.app import MDApp
from kivymd.uix.pickers import MDDatePicker

class MainApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "DeepPurple"
    def show_date_picker(self):
        date_dialog = MDDatePicker()
        date_dialog.open()
if __name__ == '__main__':
    app = MainApp()
    app.run()

MDFloatLayout:
    MDLabel:
        text: "My Tasks"
        pos_hint: {'x': .5,'y': .45}
    MDRectangleFlatButton:
        text: 'Date Picker'
        pos_hint: {'x': .5, 'y':.5}
        on_release: app.show_date_picker()


问:
POSTGRES jsonb document GIN Indexes are created on what all objects?
I am using Postgres DB 13.5. From pgdocs -

The technical difference between a jsonb_ops and a jsonb_path_ops GIN
index is that the former creates independent index items for each key
and value in the data, while the latter creates index items only for
each value in the data. Basically, each jsonb_path_ops index item
is a hash of the value and the key(s) leading to it; for example to
index {"foo": {"bar": "baz"}}

Understanding the above in detail is important for me coz my jdata (document) is big with many keys and nested objects. Consider  my json data that is stored as jsonb in a column named  jdata looks like below -

```<code>{
  "supplier": {
    "id": "3c67b6eb-3b0d-492d-8736-66df107b83b3",
    "customer": {
      "type": "pro",
      "name": "John George",
      "address": [
        {
          "add-id": "098ad4df-2a90-4fda-8f92-dbe8d7196732",
          "addressActive": true,
          "street": "abc street",
          "zip": 94044,
          "staying-since": "long long",
          "accessibility": {
            "traffic": "heavy/congested",
            "bestwaytoreach": {
              "weekdays": {
                "bart/metro/calltrain": true,
                "price": {
                  "off-peak-hours": "affordable",
                  "peak-hours": "high"
                },
                "journey-time": "super-fast"
              }
            },
            "weekends": {
              "byroad": {
                "ok": true,
                "distance": "long",
                "has-tolls": {
                  "true": true,
                  "toll-price": "relatively-high"
                },
                "journey-speed": "fast"
              }
            }
          }
        },
        {
          "add-id": "ddd1d2a0-9050-4bcf-a3ad-2e608d65e468",
          "addressActive": true,
          "street": "xyz street",
          "zip": 10001,
          "staying-since": "moved recently",
          "accessibility": {
            "traffic": "heavy/congested",
            "bestwaytoreach": {
              "weekdays": {
                "subway": true,
                "price": {
                  "off-peak-hours": "affordable",
                  "peak-hours": "high"
                },
                "journey-speed": "super-fast"
              }
            },
            "weekends": {
              "byroad": {
                "ok": true,
                "distance": "moderate",
                "tolls": {
                  "has-tolls": true,
                  "toll-price": "relatively-high"
                },
                "journey-time": "super-fast"
              }
            }
          }
        }
      ],
      "firstName": "John",
      "lastName": "CRAWFORD",
      "emailAddresses": {
        "personal": [
          "johnreplies@jg.com",
          "ursjohn@jg.com",
          "1234@jg.com"
        ],
        "official": [
          {
            "repies-in": "1 day",
            "email": "jg@jg.com"
          },
          {
            "check's regularly": true,
            "repies-in": "1 Hour",
            "email": "jg-watching@jg.com"
          }
        ]
      },
      "cities": [
        "NYC",
        "LA",
        "SF",
        "DC"
      ],
      "splCustFlag": null,
      "isPerson": true,
      "isEntity": false,
      "allowEmailSolicit": "Y",
      "allowPhoneSolicit": "Y",
      "taxPayer": true,
      "suffix": null,
      "title": null,
      "birthDate": "05/10/1993",
      "loyaltyPrograms": null,
      "phoneNumbers-summary": [
        1234567890,
        1234567899,
        1234567898,
        1234567897
      ],
      "phoneNumbers": [
        {
          "description": null,
          "extension": null,
          "number": 1234567890,
          "countryCode": null,
          "type": "Business"
        },
        {
          "description": null,
          "extension": null,
          "number": 1234567899,
          "countryCode": null,
          "type": "Home"
        }
      ],
      "data-privacy": {
        "required": true,
        "laws": [
          "CCPA",
          "GDPR"
        ]
      }
    }
  }
}
</code>```

Now if I create GIN  jsonb_ops index for jdata column - I want to clarify what all keys and values will be part of index.
For example - "staying-since" is a key nested at below path and it's part of "address" array too. But it's still a key, thought nested deep in the document. So will it be part of the index.

```<code>{
  "supplier": {
    "customer": {
      "address": [
        {
          "staying-since": "long long" ...
</code>```

And similarly "long long" is a value of a deeply nested key. Will it also be indexed.

And if GIN jsonb_path_ops index is created for jdata column --
Will a hash of "long long" value along with the path that leads to it will also be indexed.

```<code>hash(
      "supplier": {
        "customer": {
          "address":[{"staying-since": "long long"}]
          }
         }
     )
</code>```

will the above also gets index.

I am aware about the operators that are supported by the GIN index types and am aware about the usage of these operators -

jsonb_ops       ? ?& ?| @> @? @@

jsonb_path_ops      @> @? @@

Body:
I am using Postgres DB 13.5. From pgdocs -

The technical difference between a jsonb_ops and a jsonb_path_ops GIN
index is that the former creates independent index items for each key
and value in the data, while the latter creates index items only for
each value in the data. Basically, each jsonb_path_ops index item
is a hash of the value and the key(s) leading to it; for example to
index {"foo": {"bar": "baz"}}

Understanding the above in detail is important for me coz my jdata (document) is big with many keys and nested objects. Consider  my json data that is stored as jsonb in a column named  jdata looks like below -

{
  "supplier": {
    "id": "3c67b6eb-3b0d-492d-8736-66df107b83b3",
    "customer": {
      "type": "pro",
      "name": "John George",
      "address": [
        {
          "add-id": "098ad4df-2a90-4fda-8f92-dbe8d7196732",
          "addressActive": true,
          "street": "abc street",
          "zip": 94044,
          "staying-since": "long long",
          "accessibility": {
            "traffic": "heavy/congested",
            "bestwaytoreach": {
              "weekdays": {
                "bart/metro/calltrain": true,
                "price": {
                  "off-peak-hours": "affordable",
                  "peak-hours": "high"
                },
                "journey-time": "super-fast"
              }
            },
            "weekends": {
              "byroad": {
                "ok": true,
                "distance": "long",
                "has-tolls": {
                  "true": true,
                  "toll-price": "relatively-high"
                },
                "journey-speed": "fast"
              }
            }
          }
        },
        {
          "add-id": "ddd1d2a0-9050-4bcf-a3ad-2e608d65e468",
          "addressActive": true,
          "street": "xyz street",
          "zip": 10001,
          "staying-since": "moved recently",
          "accessibility": {
            "traffic": "heavy/congested",
            "bestwaytoreach": {
              "weekdays": {
                "subway": true,
                "price": {
                  "off-peak-hours": "affordable",
                  "peak-hours": "high"
                },
                "journey-speed": "super-fast"
              }
            },
            "weekends": {
              "byroad": {
                "ok": true,
                "distance": "moderate",
                "tolls": {
                  "has-tolls": true,
                  "toll-price": "relatively-high"
                },
                "journey-time": "super-fast"
              }
            }
          }
        }
      ],
      "firstName": "John",
      "lastName": "CRAWFORD",
      "emailAddresses": {
        "personal": [
          "johnreplies@jg.com",
          "ursjohn@jg.com",
          "1234@jg.com"
        ],
        "official": [
          {
            "repies-in": "1 day",
            "email": "jg@jg.com"
          },
          {
            "check's regularly": true,
            "repies-in": "1 Hour",
            "email": "jg-watching@jg.com"
          }
        ]
      },
      "cities": [
        "NYC",
        "LA",
        "SF",
        "DC"
      ],
      "splCustFlag": null,
      "isPerson": true,
      "isEntity": false,
      "allowEmailSolicit": "Y",
      "allowPhoneSolicit": "Y",
      "taxPayer": true,
      "suffix": null,
      "title": null,
      "birthDate": "05/10/1993",
      "loyaltyPrograms": null,
      "phoneNumbers-summary": [
        1234567890,
        1234567899,
        1234567898,
        1234567897
      ],
      "phoneNumbers": [
        {
          "description": null,
          "extension": null,
          "number": 1234567890,
          "countryCode": null,
          "type": "Business"
        },
        {
          "description": null,
          "extension": null,
          "number": 1234567899,
          "countryCode": null,
          "type": "Home"
        }
      ],
      "data-privacy": {
        "required": true,
        "laws": [
          "CCPA",
          "GDPR"
        ]
      }
    }
  }
}

Now if I create GIN  jsonb_ops index for jdata column - I want to clarify what all keys and values will be part of index.
For example - "staying-since" is a key nested at below path and it's part of "address" array too. But it's still a key, thought nested deep in the document. So will it be part of the index.

{
  "supplier": {
    "customer": {
      "address": [
        {
          "staying-since": "long long" ...

And similarly "long long" is a value of a deeply nested key. Will it also be indexed.

And if GIN jsonb_path_ops index is created for jdata column --
Will a hash of "long long" value along with the path that leads to it will also be indexed.

hash(
      "supplier": {
        "customer": {
          "address":[{"staying-since": "long long"}]
          }
         }
     )

will the above also gets index.

I am aware about the operators that are supported by the GIN index types and am aware about the usage of these operators -

jsonb_ops       ? ?& ?| @> @? @@

jsonb_path_ops      @> @? @@


问:
Can a custom header in react-navigation receive the scrollview ref in a createStackNavigator without creating a context and custom wrappers?
I am trying to see if I can emulate the iOS header in a cross platform without using native-navigator

However, I can't seem to find a way of doing the following using the standard custom Header API

detecting that the entire screen content is in a ScrollView or Hoc'ed scroll view (which is done by headerLargeTitle

passing up the scroll view ref which allows the header animation to determine where it is in the sequence to scroll.

What I've done before was to have a context that is used by the Header and tracks the scrollviewref by having a HoC that pushes up the value into the context.  Though that works it looks pretty clunky.

I am thinking that for me to implement this cleanly I need to be able to get the ScrollView ref and animate the height of the view as needed.

What I am thinking is it needs a custom navigator altogether to get this to work and the existing createStackNavigator will not be able to handle this case too well.


问:
Update bitmap on button click
I am drawing a box with certain measurements and updating the angle at which it is viewed which I set as a double 'offset'. I am trying to get the view to change as I click a button to increase its offset. How would I update the bitmap to reflect the button click.

"

```<code>    public void Form1_Load(object sender, EventArgs e)
    {
        myBitmap = new Bitmap(this.ClientRectangle.Width,
            this.ClientRectangle.Height);

        graphicsObj = Graphics.FromImage(myBitmap);
        Pen linePen = new Pen(Color.Red, 3);
        graphicsObj.Drawline(linePen, 50, 50, 100, 50);

    public void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics graphicsObj = e.Graphics;
        graphicsObj.DrawImage(myBitmap, 0, 0, myBitmap.Width, myBitmap.Height);
     }

    public void button1_Click(object sender, EventArgs e)
    {
        offsetButton = offsetButton + .10;
        **call or update bitmap**
    }
</code>```

"

Title: Update bitmap on button click

Body:
I am drawing a box with certain measurements and updating the angle at which it is viewed which I set as a double 'offset'. I am trying to get the view to change as I click a button to increase its offset. How would I update the bitmap to reflect the button click.

"

    public void Form1_Load(object sender, EventArgs e)
    {
        myBitmap = new Bitmap(this.ClientRectangle.Width,
            this.ClientRectangle.Height);

        graphicsObj = Graphics.FromImage(myBitmap);
        Pen linePen = new Pen(Color.Red, 3);
        graphicsObj.Drawline(linePen, 50, 50, 100, 50);

    public void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics graphicsObj = e.Graphics;
        graphicsObj.DrawImage(myBitmap, 0, 0, myBitmap.Width, myBitmap.Height);
     }

    public void button1_Click(object sender, EventArgs e)
    {
        offsetButton = offsetButton + .10;
        **call or update bitmap**
    }

"


问:
Image Super Sampling tool using the Tensorflow library to upscale image in browser
I am unable to generate a super-sampled image and would like some advice.

The HTML, CSS, and JS are below for your review. As you can see, the goal is to enable a webpage visitor to upload a low-resolution image and generate and auto-download an enhanced image. This is meant to be done in the browser without using a database. The image will be stored in the browser, and the user should have a seamless experience.

HTML

```<code>     <!-- HTML form that allows the user to select and upload an image file -->

     <form>
       <label for="image">Select an image:</label>
       <input type="file" id="image" name="image" accept="image/jpeg, image/png">
       <button class="upload-button" onclick="processImage()">Super Sample</button>
     </form>

     <!-- Canvas element to display the enhanced image -->
     <canvas id="canvas"></canvas>
</code>```

CSS

```<code>     /* Global styles */
     body {
       font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-         serif;
       margin: 0;
       background-color: #f3f3f3;
     }

     /* Styles for the form and canvas elements */
     form {
       display: flex;
       flex-direction: column;
       align-items: center;
       margin: 50px;
     }

     label {
       color: #333;
       font-size: 16px;
     }

     input[type="file"] {
       margin: 10px;
     }

     button {
       margin: 10px;
       padding: 10px;
       background-color: #333;
       color: #fff;
       border: none;
       border-radius: 4px;
       cursor: pointer;
     }

     canvas {
       border: 1px solid #333;
       margin: 10px;
       display: block;
     }

     /* Center the canvas element */
     form, canvas {
       text-align: center;
     }

</code>```

JS

```<code>     // Load the TensorFlow.js library
     import * as tf from '@tensorflow/tfjs';

     // Load the MobileNet model
     const model = await tf.loadLayersModel('https://storage.googleapis.com/tfjs-     models/tfjs/mobilenet_v1_1.0_224/model.json');

     // JavaScript function to process the image and update the download link
     async function processImage() {
       // Get the selected file from the input element
       var file = document.getElementById("image").files[0];

       // Check if the file is an image
       if (!file.type.match("image.*")) {
         alert("Please select an image file");
         return;
       }

       // Create an image element to display the selected image
       var image = new Image();
       image.src = URL.createObjectURL(file);

       // Set the canvas dimensions to the dimensions of the image
       var canvas = document.getElementById("canvas");
       canvas.width = image.width;
       canvas.height = image.height;

       // Draw the image on the canvas
       var ctx = canvas.getContext("2d");
       ctx.drawImage(image, 0, 0, image.width, image.height);

       // Convert the canvas to a tensor
       var tensor = tf.browser.fromPixels(canvas);

       // Resize the tensor to the size expected by the MobileNet model
       var resized

</code>```

Body:
I am unable to generate a super-sampled image and would like some advice.

The HTML, CSS, and JS are below for your review. As you can see, the goal is to enable a webpage visitor to upload a low-resolution image and generate and auto-download an enhanced image. This is meant to be done in the browser without using a database. The image will be stored in the browser, and the user should have a seamless experience.

HTML

     <form>
       Select an image:
       <input type="file" id="image" name="image" accept="image/jpeg, image/png">
       <button class="upload-button" onclick="processImage()">Super Sample</button>
     </form>

     <canvas id="canvas"></canvas>

CSS

     /* Global styles */
     body {
       font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-         serif;
       margin: 0;
       background-color: #f3f3f3;
     }

     /* Styles for the form and canvas elements */
     form {
       display: flex;
       flex-direction: column;
       align-items: center;
       margin: 50px;
     }

     label {
       color: #333;
       font-size: 16px;
     }

     input[type="file"] {
       margin: 10px;
     }

     button {
       margin: 10px;
       padding: 10px;
       background-color: #333;
       color: #fff;
       border: none;
       border-radius: 4px;
       cursor: pointer;
     }

     canvas {
       border: 1px solid #333;
       margin: 10px;
       display: block;
     }

     /* Center the canvas element */
     form, canvas {
       text-align: center;
     }

JS

     // Load the TensorFlow.js library
     import * as tf from '@tensorflow/tfjs';

     // Load the MobileNet model
     const model = await tf.loadLayersModel('https://storage.googleapis.com/tfjs-     models/tfjs/mobilenet_v1_1.0_224/model.json');

     // JavaScript function to process the image and update the download link
     async function processImage() {
       // Get the selected file from the input element
       var file = document.getElementById("image").files[0];

       // Check if the file is an image
       if (!file.type.match("image.*")) {
         alert("Please select an image file");
         return;
       }

       // Create an image element to display the selected image
       var image = new Image();
       image.src = URL.createObjectURL(file);

       // Set the canvas dimensions to the dimensions of the image
       var canvas = document.getElementById("canvas");
       canvas.width = image.width;
       canvas.height = image.height;

       // Draw the image on the canvas
       var ctx = canvas.getContext("2d");
       ctx.drawImage(image, 0, 0, image.width, image.height);

       // Convert the canvas to a tensor
       var tensor = tf.browser.fromPixels(canvas);

       // Resize the tensor to the size expected by the MobileNet model
       var resized


问:
how to parse the data written in the ring buffer by perf_event_open() under sample mode?
I am new to perf_event_open(), and I have several questions;
So I am trying to collect addresses of pages that triggers MEM_LOAD_RETIRED.L3_MISS and MEM_INST_RETIRED.ALL_STORES for mysqld under sampled mode.

Under sample mode, I am using mmap to read from a ring buffer, I know that

The first page should be perf_event_mmap_page, followed by 2^n pages as the ring buffer.

My question is, in the data section[the blue section], is the mmap values arranged in a way like

a) perf_event_header followed by data, followed by data, followed by perf_event_header, followed by data

b) perf_event_header followed by data, followed by data, followed by data

I am assuming the mmap values are arranged by a), and I find that I constantly collect address 0x0 when setting

```<code>attr.type = PERF_TYPE_HARDWARE;
attr.config = PERF_COUNT_HW_INSTRUCTIONS;
</code>```

P.S. I have read through this post, Using perf_event_open() to get sample address ,however the addr=0, and I am very sure that I am testing on a physical machine.

and collect nothing at all when using the following configurations:

```<code>type = PERF_TYPE_HARDWARE
config = PERF_COUNT_HW_CACHE_MISSES | PERF_COUNT_HW_CACHE_REFERENCES
</code>```
```<code>type = PERF_TYPE_HW_CACHE
config = PERF_COUNT_HW_CACHE_LL | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16)
</code>```

And also, what are the differences between the above two configurations? they seem both to be collecting hardware caches.

I also find that I can collect info when

monitoring current process[pid = 0],

and some processes[for example pid = 1],

but not for the others, for example, mysqld

Many thanks in advance! Help of any kind is welcomed!

Body:
I am new to perf_event_open(), and I have several questions;
So I am trying to collect addresses of pages that triggers MEM_LOAD_RETIRED.L3_MISS and MEM_INST_RETIRED.ALL_STORES for mysqld under sampled mode.

Under sample mode, I am using mmap to read from a ring buffer, I know that

The first page should be perf_event_mmap_page, followed by 2^n pages as the ring buffer.

My question is, in the data section[the blue section], is the mmap values arranged in a way like

a) perf_event_header followed by data, followed by data, followed by perf_event_header, followed by data

b) perf_event_header followed by data, followed by data, followed by data

I am assuming the mmap values are arranged by a), and I find that I constantly collect address 0x0 when setting

attr.type = PERF_TYPE_HARDWARE;
attr.config = PERF_COUNT_HW_INSTRUCTIONS;

P.S. I have read through this post, Using perf_event_open() to get sample address ,however the addr=0, and I am very sure that I am testing on a physical machine.

and collect nothing at all when using the following configurations:

type = PERF_TYPE_HARDWARE
config = PERF_COUNT_HW_CACHE_MISSES | PERF_COUNT_HW_CACHE_REFERENCES

type = PERF_TYPE_HW_CACHE
config = PERF_COUNT_HW_CACHE_LL | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16)

And also, what are the differences between the above two configurations? they seem both to be collecting hardware caches.

I also find that I can collect info when

monitoring current process[pid = 0],

and some processes[for example pid = 1],

but not for the others, for example, mysqld

Many thanks in advance! Help of any kind is welcomed!


问:
React Native, expo go app is very buggy and takes long to render
I am using React Native and DynamoDB to create an app and testing on Expo Go. My app is essentially trying to render a bunch of elements (with around 15 attributes -- lat, lon, etc.) that I fetch from the database on google maps api. I have approximately 200 elements that I am storing in redux that I want to display, but it is being very buggy and slow. I will be scaling the app to many more elements, so this is a huge performance issue. Any advice on how to go about this?

I tried reducing the number of elements, and then it was working fine, but that doesn't address the issue. Is it possible that Expo Go is for very lightweight apps? But even then, 200 elements is not a lot.


问:
How to get SLURM_ARRAY_TASK_ID when submitting job on command line
I want to be able to select a file or dir based on the TASK_ID.

Ideally like this

```<code>sbatch -o %a.log --array=1-10 script.sh data/%a
</code>```

But %a is only meant to be used for log files, and can't be passed to the script at runtime.

In the docs $SLURM_ARRAY_TASK_ID is brought up. But that requires modifying the script because only then will that variable be set (not when I submit the job with sbatch)!

Is there really no nice way to do this?

Body:
I want to be able to select a file or dir based on the TASK_ID.

Ideally like this

sbatch -o %a.log --array=1-10 script.sh data/%a

But %a is only meant to be used for log files, and can't be passed to the script at runtime.

In the docs $SLURM_ARRAY_TASK_ID is brought up. But that requires modifying the script because only then will that variable be set (not when I submit the job with sbatch)!

Is there really no nice way to do this?


问:
Sequelize CLI ,Docker ,ConnectionRefusedError [SequelizeConnectionRefusedError]
I am trying to implement the sequelize cli with docker but it's not working as it suppose to work and i have no idea where i am going wrong.
ConnectionRefusedError [SequelizeConnectionRefusedError] but in the config file i have added all
kind of details properly and assigned the docker variable value in front for them as well so that it can run.

Dockerfile

```<code>FROM node:19
WORKDIR /app
COPY package.json /app
ARG NODE_ENV
RUN if [ "$NODE_ENV" = "development" ]; \
        then npm install; \
        else npm install --only=production; \
        fi

COPY . .
ENV PORT 5000
EXPOSE $PORT
CMD ["node","index.js"]
</code>```

docker-compose.yml

```<code>version: "3.7"
services:
  node-app:
    build: .
    ports:
      - "3000:5000"
    environment:
      - PORT=5000
      - POSTGRES_PASSWORD=test123
      - NODE_ENV=development
  database:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=${DB_USER:-postgres}
      - POSTGRES_PASSWORD=${DB_PASSWORD:-test123}
      - POSTGRES_DB=${DB_NAME:-docker_development}
    volumes:
      - postgres-db:/var/lib/postgresql/data

volumes:
  postgres-db:

</code>```

docker.compose.dev.yml

```<code>version: "3.7"
services:
  node-app:
    build:
      context: .
      args:
       NODE_ENV: development
    volumes:
      - ./:/app
      - /app/node_modules
    environment:
      - NODE_ENV=development
    command: npm run dev
</code>```

this is the screenshot which i am getting when i doterminal output of my file

```<code>docker logs docker logs docker_practice_node-app_1
</code>```

docker_practice_node-app_1(container name)

just for the reference this is my folder structure
folder structure

Body:
I am trying to implement the sequelize cli with docker but it's not working as it suppose to work and i have no idea where i am going wrong.
ConnectionRefusedError [SequelizeConnectionRefusedError] but in the config file i have added all
kind of details properly and assigned the docker variable value in front for them as well so that it can run.

Dockerfile

FROM node:19
WORKDIR /app
COPY package.json /app
ARG NODE_ENV
RUN if [ "$NODE_ENV" = "development" ]; \
        then npm install; \
        else npm install --only=production; \
        fi

COPY . .
ENV PORT 5000
EXPOSE $PORT
CMD ["node","index.js"]

docker-compose.yml

version: "3.7"
services:
  node-app:
    build: .
    ports:
      - "3000:5000"
    environment:
      - PORT=5000
      - POSTGRES_PASSWORD=test123
      - NODE_ENV=development
  database:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=${DB_USER:-postgres}
      - POSTGRES_PASSWORD=${DB_PASSWORD:-test123}
      - POSTGRES_DB=${DB_NAME:-docker_development}
    volumes:
      - postgres-db:/var/lib/postgresql/data

volumes:
  postgres-db:

docker.compose.dev.yml

version: "3.7"
services:
  node-app:
    build:
      context: .
      args:
       NODE_ENV: development
    volumes:
      - ./:/app
      - /app/node_modules
    environment:
      - NODE_ENV=development
    command: npm run dev

this is the screenshot which i am getting when i doterminal output of my file

docker logs docker logs docker_practice_node-app_1

docker_practice_node-app_1(container name)

just for the reference this is my folder structure
folder structure


问:
In the flink program, how to customize the multi-parallel Source to read the HBase partition table
In the flink program, how to customize the multi-parallel Source to read the HBase partition table.

```<code>For example, there are 9 partitions, 3 degrees of parallelism, and one degree of parallelism reads the data of 3 partitions, and it is guaranteed to be accurate once
</code>```
```<code>How to realize the correspondence between parallelism and partition after implementing ParallelSourceFunction
</code>```

How to ensure the accuracy of the data here

Body:
In the flink program, how to customize the multi-parallel Source to read the HBase partition table.

For example, there are 9 partitions, 3 degrees of parallelism, and one degree of parallelism reads the data of 3 partitions, and it is guaranteed to be accurate once

How to realize the correspondence between parallelism and partition after implementing ParallelSourceFunction

How to ensure the accuracy of the data here


问:
Angular client, Express/Node.js server calling Stripe - CORS issue with Options request
I have an Angular App client, that calls an Express Server, hosted on Google Cloud, that calls the Stripe CheckoutSession API.

I am getting the following error:

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my1scoop-1d694.ue.r.appspot.com/api/stripe/createCheckoutSession. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.
</code>```

Angular app's Service, which calls the Express API

startCheckoutSession = (
source: string,
productId: string
): Observable => {
const headers = new HttpHeaders().set('Authorization', this.jwtAuth);

```<code>return this.http.post<CheckoutSession>(
  environment.api.baseUrl + '/api/stripe/createCheckoutSession',
  {
    source,
    productId,
    callbackUrl: this.buildCallbackUrl(),
  },
  { headers }
);
</code>```

};

Express App

import * as cors from 'cors';

const app: Application = express();

app.use(cors.default());

... eventually, it will call Stripe's REST API.  But, it is not getting that far due to the CORS issue.

Thanks for any input.

Body:
I have an Angular App client, that calls an Express Server, hosted on Google Cloud, that calls the Stripe CheckoutSession API.

I am getting the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my1scoop-1d694.ue.r.appspot.com/api/stripe/createCheckoutSession. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.

Angular app's Service, which calls the Express API

startCheckoutSession = (
source: string,
productId: string
): Observable => {
const headers = new HttpHeaders().set('Authorization', this.jwtAuth);

return this.http.post<CheckoutSession>(
  environment.api.baseUrl + '/api/stripe/createCheckoutSession',
  {
    source,
    productId,
    callbackUrl: this.buildCallbackUrl(),
  },
  { headers }
);

};

Express App

import * as cors from 'cors';

const app: Application = express();

app.use(cors.default());

... eventually, it will call Stripe's REST API.  But, it is not getting that far due to the CORS issue.

Thanks for any input.


问:
gsapi_init_with_args' is made -100 with long and Asian language in filename
I'm using this function to "compress" PDF files. If the filename has Asian language (Japanese and Vietnamese) and the number of characters in filename is longer 15, the error "'gsapi_init_with_args' is made -100" will appear.

Example:

Input Filename: "こんにちは、私の名前は.pdf" or "Xin chào, tôi tên là. Xin chào, tôi tên là.pdf"

Output Filename: "こんにち.p" or "Xin cháo, tôi tơn lá". They're without extension in filename, zero size and incorrect filename.

Expected Filename: "こんにちは、私の名前は.pdf" or "Xin chào, tôi tên là. Xin chào, tôi tên là.pdf" with smaller size.

If the filename has Asian language (Japanese and Vietnamese) and the number of characters in filename is shorter 15, it's OK to use.

My environment:

Windows 11 English US 64-bit (Locale in Settings is Japanese)

Ghostscript version: 9.55.0 32-bit

Ghostscript.NET v1.2.3 (latest)
Please help me fix this. Thank you in advance.

```<code>try
            {
                string strFilePath = PDFFile.FullName;
                string strFileNameOnly = Path.GetFileNameWithoutExtension(PDFFile.Name);

                GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion();
                string strFullnameOutput = Path.Combine(strOutput, strFileNameOnly) + ".pdf";
List<string> switches = new List<string>
                {
                    "-empty",
                    "-dQUIET",
                    "-dSAFER",
                    "-dBATCH",
                    "-dNOPAUSE",
                    "-dNOPROMPT",
                    "-sDEVICE=pdfwrite",
                    "-dCompatibilityLevel=2.0",
                    "-dPDFSETTINGS =/default",
                    "-sOutputFile=" + strFullnameOutput,
                    //"-dPrinted=false",
                    "-c",
                    "-f",
                    strFilePath,
                };

                using (GhostscriptProcessor gsProc = new GhostscriptProcessor())
                {
                    try
                    {
                        gsProc.StartProcessing(switches.ToArray(), null);
                        isDone = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        isDone = false;
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isDone = false;
            }
</code>```

I've tried to change another computer but same result.

Body:
I'm using this function to "compress" PDF files. If the filename has Asian language (Japanese and Vietnamese) and the number of characters in filename is longer 15, the error "'gsapi_init_with_args' is made -100" will appear.

Example:

Input Filename: "こんにちは、私の名前は.pdf" or "Xin chào, tôi tên là. Xin chào, tôi tên là.pdf"

Output Filename: "こんにち.p" or "Xin cháo, tôi tơn lá". They're without extension in filename, zero size and incorrect filename.

Expected Filename: "こんにちは、私の名前は.pdf" or "Xin chào, tôi tên là. Xin chào, tôi tên là.pdf" with smaller size.

If the filename has Asian language (Japanese and Vietnamese) and the number of characters in filename is shorter 15, it's OK to use.

My environment:

Windows 11 English US 64-bit (Locale in Settings is Japanese)

Ghostscript version: 9.55.0 32-bit

Ghostscript.NET v1.2.3 (latest)
Please help me fix this. Thank you in advance.

try
            {
                string strFilePath = PDFFile.FullName;
                string strFileNameOnly = Path.GetFileNameWithoutExtension(PDFFile.Name);

                GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion();
                string strFullnameOutput = Path.Combine(strOutput, strFileNameOnly) + ".pdf";
List<string> switches = new List<string>
                {
                    "-empty",
                    "-dQUIET",
                    "-dSAFER",
                    "-dBATCH",
                    "-dNOPAUSE",
                    "-dNOPROMPT",
                    "-sDEVICE=pdfwrite",
                    "-dCompatibilityLevel=2.0",
                    "-dPDFSETTINGS =/default",
                    "-sOutputFile=" + strFullnameOutput,
                    //"-dPrinted=false",
                    "-c",
                    "-f",
                    strFilePath,
                };

                using (GhostscriptProcessor gsProc = new GhostscriptProcessor())
                {
                    try
                    {
                        gsProc.StartProcessing(switches.ToArray(), null);
                        isDone = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        isDone = false;
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isDone = false;
            }

I've tried to change another computer but same result.


问:
How do I check if all Dagger dependencies for a component are scoped?
I’m converting a large service to use Dagger, and I have a component with a lot of dependencies in the generated graph, and I want to ensure everything is scoped.

Initially, I tried to look at all the modules of the component to ensure that all their @Provides were annotated with a scope. However, one can have a class that uses @Inject, not have any @Provides methods in the modules, and that be unscoped if not specified on the class.

Right now, in order to check if I missed anything, I go into the generated code and look to see if anything is missing a double-checked locked provider. However, this isn’t very efficient and feels error-prone, as there are cases (such as a component dependency) where we don’t need a provider, since we reference the dependent component directly.

Is there a simple way to check for unscoped bindings for a component? I’d like to make sure that for the component, only one instance of every object in its graph is created in its lifetime.