来源: stackexchange

问:
How to know if my app is using internal or external microphone and/or speakes
Is there a way for me to be reactively notified if the user has switched to an external microphone and/or is using external speakers? I know I can register a BroadcastReciever that detects if the user has plugged in his headset but what about Bluetooth-connected devices?

To clarify: I have two views. One needs to display whether the user is using an External or Internal microphone and the other one needs to display if the user is using external or internal speakers. What is the best way to achieve such a task?

ContentLicense: CC BY-SA 4.0


问:
Subtitles in MUI data grid column
I'm a designer and I'm designing a dashboard that will be coded using MUI library for React. I have a question regarding Data grid. Would it be possible to put subtitles under the main title of the columns? Or would it have to be done in a way that we create an additional row below and place the subtitles there? Thanks

I was googling this problem but haven't found a solution

Title: Subtitles in MUI data grid column


问:
Bitmap dispose does not work and throws an Argument Exception
```<code>        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                bmp = (Bitmap)eventArgs.Frame.Clone();
                cameraDisplay.Image = bmp;

            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream();
            }

            //GC.Collect();
        }
</code>```

I'm trying to show a camera stream in a picturebox.
This method is the "NewFrame" of AForge Video.
The problem is when I try to use a "bitmap.dispose()" or a "using(Bitmap bmp = (Bitmap)eventArgs.Frame.Clone()){}" both when used throw an Argument Exception.

```<code>        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                //bmp = (Bitmap)eventArgs.Frame.Clone();

                using (Bitmap bmp = (Bitmap)eventArgs.Frame.Clone())
                {
                    cameraDisplay.Image = bmp;
                }
            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream();
            }

            //GC.Collect();
        }
</code>```

This was my attempt, but as I said, it throws the Exception.
I also tried to set the Bitmap variable as global, but it didn't work...

Body:
        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                bmp = (Bitmap)eventArgs.Frame.Clone();
                cameraDisplay.Image = bmp;

            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream();
            }

            //GC.Collect();
        }

I'm trying to show a camera stream in a picturebox.
This method is the "NewFrame" of AForge Video.
The problem is when I try to use a "bitmap.dispose()" or a "using(Bitmap bmp = (Bitmap)eventArgs.Frame.Clone()){}" both when used throw an Argument Exception.

        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                //bmp = (Bitmap)eventArgs.Frame.Clone();

                using (Bitmap bmp = (Bitmap)eventArgs.Frame.Clone())
                {
                    cameraDisplay.Image = bmp;
                }
            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream();
            }

            //GC.Collect();
        }

This was my attempt, but as I said, it throws the Exception.
I also tried to set the Bitmap variable as global, but it didn't work...


问:
Python3 Unicode Character Space
So I'm trying to find a way for python3 to tell me how much space a character takes up
I have found a method that works for some characters, it looks like this

```<code>from wcwidth import wcswidth
length = wcswidth('ひ')
</code>```

But this doesn't work with some characters, ones like this
﷽
is there any way to fix this?

Title: Python3 Unicode Character Space

Body:
So I'm trying to find a way for python3 to tell me how much space a character takes up
I have found a method that works for some characters, it looks like this

from wcwidth import wcswidth
length = wcswidth('ひ')

But this doesn't work with some characters, ones like this
﷽
is there any way to fix this?


问:
Python pandas, how to remove extra white space between columns
DataFrame.to_string() uses one extra white space between columns for sign alignment.
How to remove it?

INFORMATION

I have a fixed field file: adb.dat , which fixed length for each row is 93.
adb.dat

```<code>20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;
</code>```

But when I use DataFrame.to_string(), and write this string to a new file,
the length of each row is 94.

First try

According to pandas-dev git, issue#571 said this is a justify problem, so I followed their discussion and tried, but I cannot get my expected result.
https://github.com/pandas-dev/pandas/issues/571

Here is my code

```<code>    df= pd.read_fwf(py_file_fullnm,
    skiprows=1,
    skipfooter=1,
    header=None,
    names=['content1','content2'],
    colspecs=[(0,16),(16,93)],
    delimiter="\0",
    skipinitialspace =True,
    dtype='string')

    data=df.to_string(index=False,header=None,justify='right')
    print(data)
    with open('testing.dat','w') as editor:
        editor.write("20230731;  ")
        editor.write("\n"+data)
        editor.write("\n00000007;   ")
</code>```

Second try

According to Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts

We can use

```<code>df.iloc[0].fillna('').str.strip().str.cat(sep=' ')
</code>```

to remove the space between each column, it works, but the length become shorter than first try, field length is 61.

Here is my code

```<code>    df= pd.read_fwf(py_file_fullnm,
    skiprows=1,
    skipfooter=1,
    header=None,
    names=['content1','content2'],
    colspecs=[(0,16),(16,93)],
    delimiter="\0",
    skipinitialspace =True,
    dtype='string')

    with open('testing.dat','w') as editor:
        editor.write("20230731;  ")
        for i in range (0,5):
            data=df.iloc[i].fillna('').str.strip().str.cat(sep='')
            editor.write("\n"+data)
        editor.write("\n00000005;   ")
</code>```

Any method I can use to remove this extra space between each columns, and keep the same field length? Thank you.

First try Result

```<code>20230731;
7914785201501236 AAA    TEST TEST                     94481873
7914785201502341 AAA    TEST TEST                     94481873
7914785201503455 AAA    TEST TEST                     94481873
6736705201501232 AAA    TEST TEST                     94481873
6736705201502347 AAA    TEST TEST                     94481873
00000005;
</code>```

Second try Result

```<code>20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;
</code>```

My expected result

```<code>20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;
</code>```

Body:
DataFrame.to_string() uses one extra white space between columns for sign alignment.
How to remove it?

INFORMATION

I have a fixed field file: adb.dat , which fixed length for each row is 93.
adb.dat

20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;

But when I use DataFrame.to_string(), and write this string to a new file,
the length of each row is 94.

First try

According to pandas-dev git, issue#571 said this is a justify problem, so I followed their discussion and tried, but I cannot get my expected result.
https://github.com/pandas-dev/pandas/issues/571

Here is my code

    df= pd.read_fwf(py_file_fullnm,
    skiprows=1,
    skipfooter=1,
    header=None,
    names=['content1','content2'],
    colspecs=[(0,16),(16,93)],
    delimiter="\0",
    skipinitialspace =True,
    dtype='string')

    data=df.to_string(index=False,header=None,justify='right')
    print(data)
    with open('testing.dat','w') as editor:
        editor.write("20230731;  ")
        editor.write("\n"+data)
        editor.write("\n00000007;   ")

Second try

According to Remove the automatic two spaces between columns that Pandas DataFrame.to_string inserts

We can use

df.iloc[0].fillna('').str.strip().str.cat(sep=' ')

to remove the space between each column, it works, but the length become shorter than first try, field length is 61.

Here is my code

    df= pd.read_fwf(py_file_fullnm,
    skiprows=1,
    skipfooter=1,
    header=None,
    names=['content1','content2'],
    colspecs=[(0,16),(16,93)],
    delimiter="\0",
    skipinitialspace =True,
    dtype='string')

    with open('testing.dat','w') as editor:
        editor.write("20230731;  ")
        for i in range (0,5):
            data=df.iloc[i].fillna('').str.strip().str.cat(sep='')
            editor.write("\n"+data)
        editor.write("\n00000005;   ")

Any method I can use to remove this extra space between each columns, and keep the same field length? Thank you.

First try Result

20230731;
7914785201501236 AAA    TEST TEST                     94481873
7914785201502341 AAA    TEST TEST                     94481873
7914785201503455 AAA    TEST TEST                     94481873
6736705201501232 AAA    TEST TEST                     94481873
6736705201502347 AAA    TEST TEST                     94481873
00000005;

Second try Result

20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;

My expected result

20230731;
7914785201501236AAA    TEST TEST                     94481873
7914785201502341AAA    TEST TEST                     94481873
7914785201503455AAA    TEST TEST                     94481873
6736705201501232AAA    TEST TEST                     94481873
6736705201502347AAA    TEST TEST                     94481873
00000005;


问:
Vscode Can't find Qt library in linux

I Just want to code Qt qmake project in vscode and UI in main qt editor, But Vs code not finding qt library, tried hard but not find any solution or good installation source.

```<code>[main.cpp 2022-12-05 15:28:59.408]
,,In file included from main.cpp:1:
mainwindow.h:4:10: fatal error: QMainWindow: No such file or directory
    4 | #include <QMainWindow>
      |          ^~~~~~~~~~~~~
compilation terminated.
</code>```

Tried including path but didn't work.

bash: /usr/local/Qt-6.4.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin:/opt/Qt:/opt/Qt/Tools/QtCreator/bin:/opt/Qt/Tools/QtDesignStudio/bin:/opt/Qt/Tools: No such file or directory

I watch some solution in stack overflow, but didn't work for me

Title: Vscode Can't find Qt library in linux

Body:
I Just want to code Qt qmake project in vscode and UI in main qt editor, But Vs code not finding qt library, tried hard but not find any solution or good installation source.

[main.cpp 2022-12-05 15:28:59.408]
,,In file included from main.cpp:1:
mainwindow.h:4:10: fatal error: QMainWindow: No such file or directory
    4 | #include <QMainWindow>
      |          ^~~~~~~~~~~~~
compilation terminated.

Tried including path but didn't work.

bash: /usr/local/Qt-6.4.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin:/opt/Qt:/opt/Qt/Tools/QtCreator/bin:/opt/Qt/Tools/QtDesignStudio/bin:/opt/Qt/Tools: No such file or directory

I watch some solution in stack overflow, but didn't work for me


问:
Yahoo Finance API wrong opening value at the time the markets open
I have written a Python code using yahoo finance api to identify all stocks with gap up and for my strategy I need this list as soon as possible after the market opening, e.g. at 9.31 a.m.. But now I found out that this list changes constantly. That means at 9.31 the list contains e.g. [a,b,c], at 9.35 it contains [b,c,d] and only after about 20 minutes the list remains stable at e.g. [c,e]. At first I thought it was a bug in my code. But then I looked manually (without api and even without Python) on the normal yahoo finance homepage (summary table for stocks) and found that also there the opening values changed between 9.30 and 10.00 at least for certain stocks. How is this possible?

I think there are two oportunities:

There is no official opening value (I should say that I do not know much about the stock market). This means that the brokers on the stock exchange first process information after market opening and only after some time the official market opening value is announced. Yahoo and other apis estimate the opening value until then and this estimate can be wrong. In this case, is there a way to estimate the opening value more accurate?

Yahoo provides wrong values for the opening (at least in their free version). In this case, is there an alternative (preferably free) to find out the actual market opening value as soon as possible?


问:
server side rendering not generating with Nextjs
I am new to nextjs, in my application uses ContextProvider along with App.js like below

and layout also wrapped around the main Component but serverside rendering (HTML is not generating on the view source) like below

my observations are that I removed all the wrappers then SSR is happening can someone suggest how to handle correctly


问:
pip install -e . behind proxy
I'm developing a Python-application on my private computer (Win11) supposed to be run on my work-computer (Win10) behind proxy. The application is working fine on my private computer, but I get stuck on "No matching distribution found for setuptools" for my work-computer. I am quite new in Python-world so I hope someone can help me find where I stumble and how to proceed. Apologies for incorrect terminology due to limited knowledge about this.

I am using Anaconda and virtual environment for both computers. My folder structure is according to this

```<code>myapp/
    pyproject.toml
    requirements.txt
    setup.cfg
    setup.py
    src/
        myapp/
            __init__.py
            app.py
            scripts.py
    tests/
</code>```

setup.py contain:

```<code>from setuptools import setup

if __name__ == "__main__":
    setup()
</code>```

setup.cfg contain (in addition to [metadata])

```<code>[options]
zip_safe = False
include_package_data = True
package_dir=
    =src
packages=find:
install_requires =
    matplotlib
    numpy
    pandas
    PyQt5
    scikit_image
    scipy

[options.package_data]
* = *.txt, *.md

[options.packages.find]
where=src

[options.entry_points]
console_scripts =
    myapp = myapp.myapp:main
</code>```

On my private computer I can, after activating a virtual environment, do:

 pip install -e .

and then run my program by

 python -m myapp.myapp

On my work-computer I succeed installing single packages using

 pip install --proxy=http://<myproxy> pandas

When I try
pip install --proxy=http://<myproxy> -e .

it fails by

```<code>ERROR: Could not find a version that satisfies the requirement setuptools (from version: none)
ERROR: No matching distribution found for setuptools
</code>```

I've also tried with python -m before pip. Same error.

The installed setuptools had a higher version number than on my private computer so I installed the same version in the virtual environment on my work-computer. Same error again.

I've tried to take away all the external requirements from setup.cfg and then pip install -e .. Same error.

I've also tested setting up the virtual environment and using pip install -e . on another private computer running Windows 10. It works as it should.

Why do I get the error on setuptools on my work-computer when setuptools is installed and in a version that do work on my private computer? It seems that it fails running setup.py because of this. Any ideas or knowledge on how to proceed?

Title: pip install -e . behind proxy

Body:
I'm developing a Python-application on my private computer (Win11) supposed to be run on my work-computer (Win10) behind proxy. The application is working fine on my private computer, but I get stuck on "No matching distribution found for setuptools" for my work-computer. I am quite new in Python-world so I hope someone can help me find where I stumble and how to proceed. Apologies for incorrect terminology due to limited knowledge about this.

I am using Anaconda and virtual environment for both computers. My folder structure is according to this

myapp/
    pyproject.toml
    requirements.txt
    setup.cfg
    setup.py
    src/
        myapp/
            __init__.py
            app.py
            scripts.py
    tests/

setup.py contain:

from setuptools import setup

if __name__ == "__main__":
    setup()

setup.cfg contain (in addition to [metadata])

[options]
zip_safe = False
include_package_data = True
package_dir=
    =src
packages=find:
install_requires =
    matplotlib
    numpy
    pandas
    PyQt5
    scikit_image
    scipy

[options.package_data]
* = *.txt, *.md

[options.packages.find]
where=src

[options.entry_points]
console_scripts =
    myapp = myapp.myapp:main

On my private computer I can, after activating a virtual environment, do:

 pip install -e .

and then run my program by

 python -m myapp.myapp

On my work-computer I succeed installing single packages using

 pip install --proxy=http://<myproxy> pandas

When I try
pip install --proxy=http://<myproxy> -e .

it fails by

ERROR: Could not find a version that satisfies the requirement setuptools (from version: none)
ERROR: No matching distribution found for setuptools

I've also tried with python -m before pip. Same error.

The installed setuptools had a higher version number than on my private computer so I installed the same version in the virtual environment on my work-computer. Same error again.

I've tried to take away all the external requirements from setup.cfg and then pip install -e .. Same error.

I've also tested setting up the virtual environment and using pip install -e . on another private computer running Windows 10. It works as it should.

Why do I get the error on setuptools on my work-computer when setuptools is installed and in a version that do work on my private computer? It seems that it fails running setup.py because of this. Any ideas or knowledge on how to proceed?


问:
How to make calculations on two columns after groupby
now I have a dataframe, initial dataframe,now I want to group by IDs, and do linear regression between df['market'] with df['Return'], and the regression values should be 250 rolling window, which means for the nth regression, I need to take 250 previous values to do the regression. After that, I need to save the regression parameter to a new column in the dataframe. How can I achieve that? Thank you!

I defined a new function and tried to use df.groupby.apply(),

df.set_index('Date').groupby(['ID'])[['market','Return']].rolling(90, min_periods=0).apply(reg)

but it complains "No numeric types to aggregate".

```<code>def reg(x,y):
    temp = scipy.stats.linregress(x,y)[0]
    return temp
</code>```

I also tried
df.groupby('ID')['market','Return'].rolling(90, min_periods=0).apply(lambda x: scipy.stats.linregress(x['market'],x['Return'])[0])

But it complains KeyError: 'market'

Body:
now I have a dataframe, initial dataframe,now I want to group by IDs, and do linear regression between df['market'] with df['Return'], and the regression values should be 250 rolling window, which means for the nth regression, I need to take 250 previous values to do the regression. After that, I need to save the regression parameter to a new column in the dataframe. How can I achieve that? Thank you!

I defined a new function and tried to use df.groupby.apply(),

df.set_index('Date').groupby(['ID'])[['market','Return']].rolling(90, min_periods=0).apply(reg)

but it complains "No numeric types to aggregate".

def reg(x,y):
    temp = scipy.stats.linregress(x,y)[0]
    return temp

I also tried
df.groupby('ID')['market','Return'].rolling(90, min_periods=0).apply(lambda x: scipy.stats.linregress(x['market'],x['Return'])[0])

But it complains KeyError: 'market'


问:
If student work as Monitor and Member in same date then count it as MonitorId else MembersId. I am using 2 different query with Union. Any Other way?
```<code>Table A (Activities)
A.id
A.name
A.address
A.date
B.id

Table B (Monitor)
B.id
B.name
B.uniqueSymbol

Table C (Students)
c.id
c.name
c.uniqueSymbol

Table AC
A.id
C.id

In activities (Table A), one student can be a Monitor (Table B) and multiple students (Table C) can be members. Monitor has uniqueSymbol that is stored in both Table B and Table C (only if participates as member also). There can be multiple activities in same date, so a student can work as a Monitor in one Activities and work as a members in other activities in same date. If he works as Monitor then he gets $10 bonus and if works as member then only $5 but student can't get bonus for Monitor and Members for same date. He/she only gets bonus for Monitor if he/she works as both Monitor and Members.

Now I want to calculate how much bonus all the Monitors and Members get by grouping the Monitor and Members ids.

</code>```

(select B.id as MonitorId, B.name as MonitorName,

count(distinct A.date) as totalDays, '10' as Rate, (count(distinct A.date) * 10 ) as bonus, 'Monitor' as Type from A,
B where A.id=i.B.id and A.date>='2021-06-05' AND A.date<='2021-07-25'

Group by B.id order by totalDays desc) UNION  (select  C.id as MemberId, C.name as MemberName,
count(distinct A.date) as totalDays, '5' as Rate,  (count(distinct A.date) * 5 ) as bonus, 'Members' as Type  from A, C, AC  where
A.id=AC.id AND ac.id= C.id AND A.date>='2021-06-05' AND A.date<='2021-07-25' group by

C.id ORDER BY totalDays desc);

```<code>

</code>```

If anybody can help me in this either with making Query or suggestion.

Body:
Table A (Activities)
A.id
A.name
A.address
A.date
B.id

Table B (Monitor)
B.id
B.name
B.uniqueSymbol

Table C (Students)
c.id
c.name
c.uniqueSymbol

Table AC
A.id
C.id

In activities (Table A), one student can be a Monitor (Table B) and multiple students (Table C) can be members. Monitor has uniqueSymbol that is stored in both Table B and Table C (only if participates as member also). There can be multiple activities in same date, so a student can work as a Monitor in one Activities and work as a members in other activities in same date. If he works as Monitor then he gets $10 bonus and if works as member then only $5 but student can't get bonus for Monitor and Members for same date. He/she only gets bonus for Monitor if he/she works as both Monitor and Members.

Now I want to calculate how much bonus all the Monitors and Members get by grouping the Monitor and Members ids.

(select B.id as MonitorId, B.name as MonitorName,

count(distinct A.date) as totalDays, '10' as Rate, (count(distinct A.date) * 10 ) as bonus, 'Monitor' as Type from A,
B where A.id=i.B.id and A.date>='2021-06-05' AND A.date<='2021-07-25'

Group by B.id order by totalDays desc) UNION  (select  C.id as MemberId, C.name as MemberName,
count(distinct A.date) as totalDays, '5' as Rate,  (count(distinct A.date) * 5 ) as bonus, 'Members' as Type  from A, C, AC  where
A.id=AC.id AND ac.id= C.id AND A.date>='2021-06-05' AND A.date<='2021-07-25' group by

C.id ORDER BY totalDays desc);

If anybody can help me in this either with making Query or suggestion.


问:
Python Flask request.get_json() returns None but request is json
flask.request.get_json(cache=False) returns None;

So I looked at the documentation:
https://tedboy.github.io/flask/generated/generated/flask.Request.get_json.html

It explains that it will return None if the Mime-Type is not application/json.

However the Content-Type header is set correctly and the weird thing is, it had worked before I had removed a folder which had not really anything to do with the code, but rather with the data from my backend.

It would work if I set force=True, but I'd hate to rewrite all the backend code.

Looking at the source code, I searched for the function deciding wether a request is JSON or not:

```<code>    @property
    def is_json(self):
        """Indicates if this request is JSON or not.  By default a request
        is considered to include JSON data if the mimetype is
        :mimetype:`application/json` or :mimetype:`application/*+json`.

        .. versionadded:: 0.11
        """
        mt = self.mimetype
        if mt == 'application/json':
            return True
        if mt.startswith('application/') and mt.endswith('+json'):
            return True
        return False
</code>```

I don't know where Request.mimetype would be defined in the end, though.

All I can say is that the even the browser could recognize my data as JSON.
See here.

```<code>        if not (force or self.is_json):
            return None

</code>```

I'm sure it's hanging here...

Body:
flask.request.get_json(cache=False) returns None;

So I looked at the documentation:
https://tedboy.github.io/flask/generated/generated/flask.Request.get_json.html

It explains that it will return None if the Mime-Type is not application/json.

However the Content-Type header is set correctly and the weird thing is, it had worked before I had removed a folder which had not really anything to do with the code, but rather with the data from my backend.

It would work if I set force=True, but I'd hate to rewrite all the backend code.

Looking at the source code, I searched for the function deciding wether a request is JSON or not:

    @property
    def is_json(self):
        """Indicates if this request is JSON or not.  By default a request
        is considered to include JSON data if the mimetype is
        :mimetype:`application/json` or :mimetype:`application/*+json`.

        .. versionadded:: 0.11
        """
        mt = self.mimetype
        if mt == 'application/json':
            return True
        if mt.startswith('application/') and mt.endswith('+json'):
            return True
        return False

I don't know where Request.mimetype would be defined in the end, though.

All I can say is that the even the browser could recognize my data as JSON.
See here.

        if not (force or self.is_json):
            return None

I'm sure it's hanging here...


问:
How to create a function for desktop only?
I have an event listener that is currently being triggered on mousemove. However i want this to only be applied to desktop and not mobile.

And vice versa, for my own reference how would I apply it to mobile only if I wanted to?

Here is my function wrapped around an if statement that if the innerWidth is more than 1000, to trigger add the event listener on mousemove. however I still see it being applied to mobile.

```<code>    if (window.innerWidth > 1000) {
    document.addEventListener("mousemove", debounce(inactiveUser, 10000));
    }
</code>```

If it's helpful, I am triggering an action event being sent to a tool we use for analytics and campaigns called Evergage. The function is below, along with a console log that I added:

```<code>    const inactiveUser = () => {
        console.log("mouse move on desktop only");
        sendEvent({
            action: "Inactive Checkout",
        });
    };
</code>```

Body:
I have an event listener that is currently being triggered on mousemove. However i want this to only be applied to desktop and not mobile.

And vice versa, for my own reference how would I apply it to mobile only if I wanted to?

Here is my function wrapped around an if statement that if the innerWidth is more than 1000, to trigger add the event listener on mousemove. however I still see it being applied to mobile.

    if (window.innerWidth > 1000) {
    document.addEventListener("mousemove", debounce(inactiveUser, 10000));
    }

If it's helpful, I am triggering an action event being sent to a tool we use for analytics and campaigns called Evergage. The function is below, along with a console log that I added:

    const inactiveUser = () => {
        console.log("mouse move on desktop only");
        sendEvent({
            action: "Inactive Checkout",
        });
    };


问:
How to suppress SCSS linting for 1 line in VS Code?
I've written an SCSS mixin for creating a series of @container rules:

```<code>@mixin form-grid-double-size-breakpoint($itemSize, $gapSize) {
  $breakPoint: $gapSize + $itemSize * 2;

  @container customcontainername (min-width: #{$breakPoint}) {
    // Styles specific for this container width
  }
}
</code>```

The problem is with the interpolation hash-and-curlies that insert the computed breakpoint width. These are necessary to get the @container rule to work. It is valid SCSS code that compiles well and runs as expected. However, in VisualStudio Code, it is regarded as invalid code:

```<code>"code": "css-lcurlyexpected",
"message": "{ expected",

"code": "css-ruleorselectorexpected",
"message": "at-rule or selector expected",
</code>```

So I would like to get rid of this misleading error message in VS Code, but can't find a description of what linter is responsible for this and how to disable/suppress this faulty error message.

I have tried all sorts of SCSS alternatives, like (string.)unquote, putting the hash-and-curlies within the variable declaration, etc. But then the @container query becomes invalid.

Any help will be highly appreciated,

Michel

Body:
I've written an SCSS mixin for creating a series of @container rules:

@mixin form-grid-double-size-breakpoint($itemSize, $gapSize) {
  $breakPoint: $gapSize + $itemSize * 2;

  @container customcontainername (min-width: #{$breakPoint}) {
    // Styles specific for this container width
  }
}

The problem is with the interpolation hash-and-curlies that insert the computed breakpoint width. These are necessary to get the @container rule to work. It is valid SCSS code that compiles well and runs as expected. However, in VisualStudio Code, it is regarded as invalid code:

"code": "css-lcurlyexpected",
"message": "{ expected",

"code": "css-ruleorselectorexpected",
"message": "at-rule or selector expected",

So I would like to get rid of this misleading error message in VS Code, but can't find a description of what linter is responsible for this and how to disable/suppress this faulty error message.

I have tried all sorts of SCSS alternatives, like (string.)unquote, putting the hash-and-curlies within the variable declaration, etc. But then the @container query becomes invalid.

Any help will be highly appreciated,

Michel


问:
How to scan all the ports and kill all the assigned processes with them - python 3.7.9
The idea is to get all the ports closed. So Firstly I taskkill the process and then close the port.

To get the ports and PID I tried, "netstat -ano -a", but whenever I try to get the info from the command it's messy, i tried to use, "re.search(':\d\d\d\d\d', output)", to get the ports, doesn't work.

how can i get the ports with the PID of the program assigned?


问:
Facebook Auth in Nestjs, backend side, get access token and work with it
Is it OK? I'ven't found any appropriate library for gettins email and username from token</p>
```<code>async facebookSignUp(accessToken): Promise<TokenDto> {
    const { data } = await firstValueFrom(
        this.httpService.get<User>(`https://graph.facebook.com/me?fields=id,name,email&access_token=${accessToken}`).pipe(
            catchError((error: AxiosError) => {
                this.logger.error(error.response.data);
                throw 'An error happened!';
            }),
        ),
    );
</code>```

Body:
Is it OK? I'ven't found any appropriate library for gettins email and username from token

async facebookSignUp(accessToken): Promise<TokenDto> {
    const { data } = await firstValueFrom(
        this.httpService.get<User>(`https://graph.facebook.com/me?fields=id,name,email&access_token=${accessToken}`).pipe(
            catchError((error: AxiosError) => {
                this.logger.error(error.response.data);
                throw 'An error happened!';
            }),
        ),
    );


问:
How to count total number of records in firebase realtime database?
I'm trying to display total number of users registered in my Firebase realtime database and I want to display them. I tried using the one in the firebase docs but it doesn't work on me. I saw some tutorials but they are the previous SDK version.</p>


问:
LinkedIn Cruise Control authenticaton in AWS Prometheus
We are going to integrate LinkedIn Cruise-Control(CC) in our Kafka stack.
The flow looks:
Kafka(AWS MSK brokers) ->(sends metrics) -> AWS Prometheus ->(consume metrics) -> Cruise Control.

But when CC tries to fetch metrics from AWS Prometheus, it fails with an error:

ERROR Error when attempting to query Prometheus metrics java.io.IOException: Received non-success response code on Prometheus API HTTP call, response code = 403, response body = {"message":"Missing Authentication Token"}

Does anyone configured cruise-control to fetch metrics from AWS Prometheus? How we can specify user's credentials to let CC to authenticate itself?


问:
How EC2 / EKS pod authenticates with token generating services
My basic knowledge, we create roles, attach policies to roles like s3 access, and attach that role to ec2 or EKS pod using the federated identity / OIDC.

But I am not understanding, when the ec2 machine or pod gets a token from AWS, how AWS authenticates that API call?


问:
Django server hangs sometimes
I am new to Django and I run into strange problem that the server hangs sometimes.

The server uses APScheduler to do periodic tasks and send data to frontend via WebSocket. So, after the server freezes, I pressed CRTL+C to perform keyboard Interrupt. The server became normal again.

I run the server in debug mode locally on my machine. But this problem only happens once or twice for the past two weeks. The rest of time it runs normally.

The first time it happened when I tried to login.

Application instance \<Task pending name='Task-1119' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox25f4bObad70 method=POST uri=/admin/login/ clientproto=HTTP/1.1\> took too long to shut down and was killed
```
<p>The second time it happened when I tried to visit <code>taskManager</code> page.</p>
<pre class="lang-none prettyprint-override"><code>Application instance \<Task pending name='Task-153' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox19fbb5140550 method=POST uri=/taskManager clientproto=HTTP/1.1\> took too long to shut down and was killed
</code>```

Python: 3.10.7

Django: 3.2

Channel: 3.0.5 And I am using InMemoryChannelLayer

I am not sure if it jammed when trying to response GET or POST, or the server jammed first so it cannot process any request.

I tried to google this problem. It seems that other developers may have the similar problem because of WebSocket. I added some msg to be printed before any WebSocketConsumer function called. But I did not see any related ones in the cmd.

I am really confusing now. Since I cannot replicate the problem. Can anyone give me some suggestions about how to debug this problem?

Title: Django server hangs sometimes

Body:
I am new to Django and I run into strange problem that the server hangs sometimes.

The server uses APScheduler to do periodic tasks and send data to frontend via WebSocket. So, after the server freezes, I pressed CRTL+C to perform keyboard Interrupt. The server became normal again.

I run the server in debug mode locally on my machine. But this problem only happens once or twice for the past two weeks. The rest of time it runs normally.

The first time it happened when I tried to login.

Application instance \<Task pending name='Task-1119' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox25f4bObad70 method=POST uri=/admin/login/ clientproto=HTTP/1.1\> took too long to shut down and was killed

The second time it happened when I tried to visit taskManager page.

Application instance \<Task pending name='Task-153' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox19fbb5140550 method=POST uri=/taskManager clientproto=HTTP/1.1\> took too long to shut down and was killed

Python: 3.10.7

Django: 3.2

Channel: 3.0.5 And I am using InMemoryChannelLayer

I am not sure if it jammed when trying to response GET or POST, or the server jammed first so it cannot process any request.

I tried to google this problem. It seems that other developers may have the similar problem because of WebSocket. I added some msg to be printed before any WebSocketConsumer function called. But I did not see any related ones in the cmd.

I am really confusing now. Since I cannot replicate the problem. Can anyone give me some suggestions about how to debug this problem?


问:
Bootstrap 5.2 Carousel wo'nt show the third image
I'm trying to have a 3 page carousel that displays my products image and callouts but somehow it's only showing only 2 images it wont go to the third one.

In the {% render 'meliades' %} part I'm only including the image and callout from different page everything is the same except call out position and images.

.BornHS__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Close {
  display: none;
}

.BornHS__Wrapper .Content__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Modal__Content {
  background: #2b2b2bcc;
  border-radius: 4px;
  box-shadow: 0 0 24px rgba(0, 0, 0, 0.22);
  color: #2b2b2b;
  opacity: 0;
  position: absolute;
  transition: all 0.3s ease-in-out;
  visibility: hidden;
  z-index: 4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper {
  padding: 10px;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
  font-size: 16px;
  text-transform: uppercase;
  color: #f4f4f4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper p {
  font-size: 14px;
  margin: 0;
  padding: 0;
}

.BornHS__Wrapper .BornHS__Input {
  height: 0;
  opacity: 0;
  overflow: hidden;
  position: fixed;
  text-indent: -9999px;
  width: 0;
  z-index: -1;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label {
  background: #f4f4f480;
  border-radius: 50%;
  cursor: pointer;
  height: 20px !important;
  position: absolute;
  transition: all 300ms ease;
  width: 20px !important;
  z-index: 2;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before,
.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  background: #2b2b2b;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  height: 40%;
  width: 2px;
}

.BornHS__Wrapper .BornHS__Input~.BornHS__Overlay {
  display: none;
  height: 100%;
  left: 0;
  position: absolute;
  width: 100%;
  top: 0;
  z-index: 3;
}

.BornHS__Wrapper .BornHS__Input:checked+.BornHS__Label {
  transform: rotate(45deg);
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Modal__Content {
  opacity: 1;
  visibility: visible;
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Overlay {
  display: block;
}

.BornHS__Wrapper.BornHS__Blur figure {
  -webkit-filter: blur(2px);
  -moz-filter: blur(2px);
  -o-filter: blur(2px);
  -ms-filter: blur(2px);
  filter: blur(2px);
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input {
  display: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input+.BornHS__Label {
  opacity: 0.5;
  pointer-events: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked {
  display: inline-block;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked+.BornHS__Label {
  opacity: 1;
  pointer-events: auto;
}

.BornHS__Modal {
  bottom: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  z-index: 1;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close {
  background: #2b2b2b;
  border-radius: 50%;
  cursor: pointer;
  display: block;
  height: 20px;
  right: -5px;
  position: absolute;
  top: -5px;
  transition: all 300ms ease;
  transform: rotate(45deg);
  width: 20px;
  z-index: 5;
  display: none;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before,
.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  background: #fff;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  height: 40%;
  width: 2px;
}

/* START - 428 - START */

@media (max-width: 428px) {
  .BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
    font-size: 12px;
    text-transform: uppercase;
  }
  .callOutProductTitle {
    font-size: 20px !important;
  }
  .callOutProductSKU {
    font-size: 14px !important;
  }
  .callOutProductPage {
    font-size: 12px !important;
    color: #9b8642 !important;
  }
  #meliades-circle-1 {
    left: 67%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 48%;
  }
  #meliades-circle-4 {
    left: 47.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 93%;
    top: 21.5%;
  }
  #meliades-content-1 {
    left: 7%;
    top: 26%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 6%;
    top: 37%;
  }
  #meliades-content-4 {
    left: 13%;
    top: 68%;
  }
  #meliades-content-5 {
    left: 57%;
    top: 55%;
  }
  #meliades-content-6 {
    left: 47.5%;
    top: 11%;
  }
}

/* END - 428 - END */

/* START - 768 - START */

@media (min-width: 768px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 29%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 48%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 49%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 18%;
    top: 30%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 11.5%;
    top: 43%;
  }
  #meliades-content-4 {
    left: 22.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 53%;
  }
  #meliades-content-6 {
    left: 64.5%;
    top: 16%;
  }
}

/* END - 768 - END */

/* START - 1024 - START */

@media (min-width: 1024px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 57%;
    top: 48%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 31.5%;
    top: 32%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 17%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 63%;
  }
  #meliades-content-5 {
    left: 58%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72%;
    top: 18%;
  }
}

/* END - 1024 - END */

/* START - 1280 - START */

@media (min-width: 1280px) {
  #meliades-circle-1 {
    left: 58%;
    top: 39%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 45.5%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.8%;
    top: 44%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 29.5%;
    top: 40%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 14%;
  }
}

/* END - 1280 - END */

/* START - 1366 - START */

@media (min-width: 1366px) {
  #meliades-circle-1 {
    left: 58.1%;
    top: 38%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.3%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.6%;
    top: 43%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 30.2%;
    top: 41%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.7%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 15%;
  }
}

/* END - 1366 - END */

/* START - 1440 - START */

@media (min-width: 1440px) {
  .imageSize {
    width: 50%;
  }
  #meliades-circle-1 {
    left: 60%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55.5%;
    top: 45%;
  }
  #meliades-circle-6 {
    left: 72.5%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 60.5%;
    top: 41%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 30.5%;
    top: 42%;
  }
  #meliades-content-4 {
    left: 49.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 49%;
  }
  #meliades-content-6 {
    left: 73.2%;
    top: 15%;
  }
}

/* END - 1440 - END */

/* START - 1920 - START */

@media (min-width: 1920px) {
  #meliades-circle-1 {
    left: 57%;
    top: 40.5%;
  }
  #meliades-circle-2 {
    left: 76%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 50%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 57.5%;
    top: 44%;
  }
  #meliades-content-2 {
    right: -20%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 33%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 50%;
  }
  #meliades-content-6 {
    left: 73.5%;
    top: 17%;
  }
}

/* END - 1920 - END */

/* START - 2560 - START */

@media (min-width: 2560px) {
  #meliades-circle-1 {
    left: 60.5%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 47%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 60.8%;
    top: 40%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 34.8%;
    top: 45%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 62.5%;
  }
  #meliades-content-5 {
    left: 55.4%;
    top: 49.5%;
  }
  #meliades-content-6 {
    left: 73.4%;
    top: 19%;
  }
}

/* END - 2560 - END */

@-webkit-keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

@keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

.sonar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #000000;
  border: 1px solid #2b2b2b;
  -webkit-animation: sonar 1300ms ease-out infinite;
  animation: sonar 1300ms ease-out infinite;
}

.callOutProductTitle {
  font-size: 30px;
}

.callOutProductSKU {
  font-size: 18px;
}

.callOutProductPage {
  font-size: 14px;
  color: #9b8642 !important;
}

.callOutProductPage:hover {
  color: #9b8642 !important;
  text-decoration: underline;
}

.callOutDiv {
  padding-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div id="carouselExampleInterval" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      {% render 'meliades' %}
    </div>
    <div class="carousel-item">
      {% render 'white-matera' %}
    </div>
    <div class="carousel-item">
      {% render 'mezuzah' %}
    </div>
  </div>

  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>

  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script></code>```

Body:
I'm trying to have a 3 page carousel that displays my products image and callouts but somehow it's only showing only 2 images it wont go to the third one.

In the {% render 'meliades' %} part I'm only including the image and callout from different page everything is the same except call out position and images.

.BornHS__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Close {
  display: none;
}

.BornHS__Wrapper .Content__Wrapper {
  position: relative;
}

.BornHS__Wrapper .BornHS__Modal__Content {
  background: #2b2b2bcc;
  border-radius: 4px;
  box-shadow: 0 0 24px rgba(0, 0, 0, 0.22);
  color: #2b2b2b;
  opacity: 0;
  position: absolute;
  transition: all 0.3s ease-in-out;
  visibility: hidden;
  z-index: 4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper {
  padding: 10px;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
  font-size: 16px;
  text-transform: uppercase;
  color: #f4f4f4;
}

.BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper p {
  font-size: 14px;
  margin: 0;
  padding: 0;
}

.BornHS__Wrapper .BornHS__Input {
  height: 0;
  opacity: 0;
  overflow: hidden;
  position: fixed;
  text-indent: -9999px;
  width: 0;
  z-index: -1;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label {
  background: #f4f4f480;
  border-radius: 50%;
  cursor: pointer;
  height: 20px !important;
  position: absolute;
  transition: all 300ms ease;
  width: 20px !important;
  z-index: 2;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before,
.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  background: #2b2b2b;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Input+.BornHS__Label:after {
  height: 40%;
  width: 2px;
}

.BornHS__Wrapper .BornHS__Input~.BornHS__Overlay {
  display: none;
  height: 100%;
  left: 0;
  position: absolute;
  width: 100%;
  top: 0;
  z-index: 3;
}

.BornHS__Wrapper .BornHS__Input:checked+.BornHS__Label {
  transform: rotate(45deg);
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Modal__Content {
  opacity: 1;
  visibility: visible;
}

.BornHS__Wrapper .BornHS__Input:checked~.BornHS__Overlay {
  display: block;
}

.BornHS__Wrapper.BornHS__Blur figure {
  -webkit-filter: blur(2px);
  -moz-filter: blur(2px);
  -o-filter: blur(2px);
  -ms-filter: blur(2px);
  filter: blur(2px);
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input {
  display: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input+.BornHS__Label {
  opacity: 0.5;
  pointer-events: none;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked {
  display: inline-block;
}

.BornHS__Wrapper.BornHS__Blur .BornHS__Input:checked+.BornHS__Label {
  opacity: 1;
  pointer-events: auto;
}

.BornHS__Modal {
  bottom: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  z-index: 1;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close {
  background: #2b2b2b;
  border-radius: 50%;
  cursor: pointer;
  display: block;
  height: 20px;
  right: -5px;
  position: absolute;
  top: -5px;
  transition: all 300ms ease;
  transform: rotate(45deg);
  width: 20px;
  z-index: 5;
  display: none;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before,
.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  background: #fff;
  content: "";
  cursor: pointer;
  display: block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:before {
  height: 2px;
  width: 40%;
}

.BornHS__Wrapper .BornHS__Modal__Content .BornHS__Close:after {
  height: 40%;
  width: 2px;
}

/* START - 428 - START */

@media (max-width: 428px) {
  .BornHS__Wrapper .BornHS__Modal__Content .Content__Wrapper .BornHS__Title {
    font-size: 12px;
    text-transform: uppercase;
  }
  .callOutProductTitle {
    font-size: 20px !important;
  }
  .callOutProductSKU {
    font-size: 14px !important;
  }
  .callOutProductPage {
    font-size: 12px !important;
    color: #9b8642 !important;
  }
  #meliades-circle-1 {
    left: 67%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 48%;
  }
  #meliades-circle-4 {
    left: 47.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 93%;
    top: 21.5%;
  }
  #meliades-content-1 {
    left: 7%;
    top: 26%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 6%;
    top: 37%;
  }
  #meliades-content-4 {
    left: 13%;
    top: 68%;
  }
  #meliades-content-5 {
    left: 57%;
    top: 55%;
  }
  #meliades-content-6 {
    left: 47.5%;
    top: 11%;
  }
}

/* END - 428 - END */

/* START - 768 - START */

@media (min-width: 768px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 29%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 48%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 49%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 18%;
    top: 30%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 11.5%;
    top: 43%;
  }
  #meliades-content-4 {
    left: 22.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 53%;
  }
  #meliades-content-6 {
    left: 64.5%;
    top: 16%;
  }
}

/* END - 768 - END */

/* START - 1024 - START */

@media (min-width: 1024px) {
  #meliades-circle-1 {
    left: 71%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 30%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 57%;
    top: 48%;
  }
  #meliades-circle-6 {
    left: 95%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 31.5%;
    top: 32%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 17%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 63%;
  }
  #meliades-content-5 {
    left: 58%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72%;
    top: 18%;
  }
}

/* END - 1024 - END */

/* START - 1280 - START */

@media (min-width: 1280px) {
  #meliades-circle-1 {
    left: 58%;
    top: 39%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 45.5%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.8%;
    top: 44%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 29.5%;
    top: 40%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 14%;
  }
}

/* END - 1280 - END */

/* START - 1366 - START */

@media (min-width: 1366px) {
  #meliades-circle-1 {
    left: 58.1%;
    top: 38%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.3%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46%;
  }
  #meliades-circle-6 {
    left: 72%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 58.6%;
    top: 43%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 30.2%;
    top: 41%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 65%;
  }
  #meliades-content-5 {
    left: 55.7%;
    top: 51%;
  }
  #meliades-content-6 {
    left: 72.7%;
    top: 15%;
  }
}

/* END - 1366 - END */

/* START - 1440 - START */

@media (min-width: 1440px) {
  .imageSize {
    width: 50%;
  }
  #meliades-circle-1 {
    left: 60%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.2%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55.5%;
    top: 45%;
  }
  #meliades-circle-6 {
    left: 72.5%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 60.5%;
    top: 41%;
  }
  #meliades-content-2 {
    left: 82%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 30.5%;
    top: 42%;
  }
  #meliades-content-4 {
    left: 49.5%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 56%;
    top: 49%;
  }
  #meliades-content-6 {
    left: 73.2%;
    top: 15%;
  }
}

/* END - 1440 - END */

/* START - 1920 - START */

@media (min-width: 1920px) {
  #meliades-circle-1 {
    left: 57%;
    top: 40.5%;
  }
  #meliades-circle-2 {
    left: 76%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 50%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 46.5%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 22.5%;
  }
  #meliades-content-1 {
    left: 57.5%;
    top: 44%;
  }
  #meliades-content-2 {
    right: -20%;
    top: 45%;
  }
  #meliades-content-3 {
    left: 33%;
    top: 44%;
  }
  #meliades-content-4 {
    left: 50%;
    top: 64%;
  }
  #meliades-content-5 {
    left: 55.5%;
    top: 50%;
  }
  #meliades-content-6 {
    left: 73.5%;
    top: 17%;
  }
}

/* END - 1920 - END */

/* START - 2560 - START */

@media (min-width: 2560px) {
  #meliades-circle-1 {
    left: 60.5%;
    top: 37%;
  }
  #meliades-circle-2 {
    left: 80%;
    top: 40%;
    display: none;
  }
  #meliades-circle-3 {
    left: 40%;
    top: 49%;
  }
  #meliades-circle-4 {
    left: 49.5%;
    top: 60%;
  }
  #meliades-circle-5 {
    left: 55%;
    top: 47%;
  }
  #meliades-circle-6 {
    left: 73%;
    top: 23%;
  }
  #meliades-content-1 {
    left: 60.8%;
    top: 40%;
  }
  #meliades-content-2 {
    left: 20%;
    top: 47%;
  }
  #meliades-content-3 {
    left: 34.8%;
    top: 45%;
  }
  #meliades-content-4 {
    left: 49.8%;
    top: 62.5%;
  }
  #meliades-content-5 {
    left: 55.4%;
    top: 49.5%;
  }
  #meliades-content-6 {
    left: 73.4%;
    top: 19%;
  }
}

/* END - 2560 - END */

@-webkit-keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

@keyframes sonar {
  from {
    box-shadow: 0 0 0 0 #f4f4f4, 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
  to {
    box-shadow: 0 0 0 10px rgba(255, 147, 223, 0), 0 0 4px 2px rgba(0, 0, 0, 0.4);
  }
}

.sonar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #000000;
  border: 1px solid #2b2b2b;
  -webkit-animation: sonar 1300ms ease-out infinite;
  animation: sonar 1300ms ease-out infinite;
}

.callOutProductTitle {
  font-size: 30px;
}

.callOutProductSKU {
  font-size: 18px;
}

.callOutProductPage {
  font-size: 14px;
  color: #9b8642 !important;
}

.callOutProductPage:hover {
  color: #9b8642 !important;
  text-decoration: underline;
}

.callOutDiv {
  padding-top: 20px;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

      {% render 'meliades' %}

      {% render 'white-matera' %}

      {% render 'mezuzah' %}

  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="prev">

    Previous
  </button>

  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="next">

    Next
  </button>


问:
Import a different module acording to a string given in props
My question is pretty simple : I have some ugly repetitive React imports and rendering code, and couldn't find a way to make it clean so I am hoping someone already encountered this problem and might know a better solution...

Here is the component I'm trying to make more dynamic :

```<code>import { InfoIcon } from '../assets/InfoIcon'

import { DemandsIcon } from '../assets/DemandsIcon'
import { HomeIcon } from '../assets/HomeIcon'
import { MyWorkIcon } from '../assets/MyWorkIcon'
import { PortfoliosIcon } from '../assets/PortfoliosIcon'
import { ProjectsIcon } from '../assets/ProjectsIcon'

export const ModuleIcon = ({ iconName }) => {
  switch (iconName) {
    case 'home':
      return <HomeIcon />
    case 'myWork':
      return <MyWorkIcon />
    case 'projects':
      return <ProjectsIcon />
    case 'portfolios':
      return <PortfoliosIcon />
    case 'demands':
      return <DemandsIcon />
    default:
      return <InfoIcon />
  }
}

</code>```

Here, all the components I am importing are just a component that return an svg

If you need more info, I am available :)

I didn't find any other solution as I just don't understand how to import according to a string given in props

Body:
My question is pretty simple : I have some ugly repetitive React imports and rendering code, and couldn't find a way to make it clean so I am hoping someone already encountered this problem and might know a better solution...

Here is the component I'm trying to make more dynamic :

import { InfoIcon } from '../assets/InfoIcon'

import { DemandsIcon } from '../assets/DemandsIcon'
import { HomeIcon } from '../assets/HomeIcon'
import { MyWorkIcon } from '../assets/MyWorkIcon'
import { PortfoliosIcon } from '../assets/PortfoliosIcon'
import { ProjectsIcon } from '../assets/ProjectsIcon'

export const ModuleIcon = ({ iconName }) => {
  switch (iconName) {
    case 'home':
      return <HomeIcon />
    case 'myWork':
      return <MyWorkIcon />
    case 'projects':
      return <ProjectsIcon />
    case 'portfolios':
      return <PortfoliosIcon />
    case 'demands':
      return <DemandsIcon />
    default:
      return <InfoIcon />
  }
}

Here, all the components I am importing are just a component that return an svg

If you need more info, I am available :)

I didn't find any other solution as I just don't understand how to import according to a string given in props


问:
Is it possible to automatically cast by method signature
Is there a way to do something like this:

public class Controler{

    public String doSomething(int i){
        Service s = new Service();
        A a = s.doIt(i);
        return this.doSmthingWithA(a);
    }

    private static String doSmthingWithA(A a) {
        return "a";
    }

    private static String doSmthingWithA(B b) {
        return "b";
    }

    private static String doSmthingWithA(C c) {
        return "c";
    }
}

class A {
}

class B extends A {
}

class C extends A {
}

class Service{
    public A doIt(int i){
        if(i == 1){
            return new B();
        }
        return new C();
    }
}
```
<p>And the unit test</p>
<pre class="lang-java prettyprint-override"><code>@Test
public void t(){
    Controler c = new Controler();
    Assert.assertEquals("b",c.doSomething(1));
    Assert.assertEquals("c",c.doSomething(2));
}
</code>```

Now, I always got c.doSomething(1) equals to "a" or I want to find a way without explicit cast. This example is very simple, but in my case I use it to simplify a catch expression in my app with more than 15 different checked exceptions.

Body:
Is there a way to do something like this:

public class Controler{

    public String doSomething(int i){
        Service s = new Service();
        A a = s.doIt(i);
        return this.doSmthingWithA(a);
    }

    private static String doSmthingWithA(A a) {
        return "a";
    }

    private static String doSmthingWithA(B b) {
        return "b";
    }

    private static String doSmthingWithA(C c) {
        return "c";
    }
}

class A {
}

class B extends A {
}

class C extends A {
}

class Service{
    public A doIt(int i){
        if(i == 1){
            return new B();
        }
        return new C();
    }
}

And the unit test

@Test
public void t(){
    Controler c = new Controler();
    Assert.assertEquals("b",c.doSomething(1));
    Assert.assertEquals("c",c.doSomething(2));
}

Now, I always got c.doSomething(1) equals to "a" or I want to find a way without explicit cast. This example is very simple, but in my case I use it to simplify a catch expression in my app with more than 15 different checked exceptions.


问:
Issue fetching primary keys of table in embedded data source H2
I am writing a unit test to test the data source behaviour.

I have written test like below

```<code>@ExtendWith(MockitoExtension.class)
public class HTests {

    private H helper;
    private DataSource dataSource;

    @BeforeEach
    void setUp() {
        dataSource = new EmbeddedDatabaseBuilder()
                .setName("testDB;MODE=PostgreSQL")
                .setType(EmbeddedDatabaseType.H2) //.H2
                .addScript("schema.sql")
                .build();
        helper = new H(dataSource);
    }

    @Test
    void getPkKeys() throws SQLException {
        String primaryKey = helper.pkKeys("links");
        Assertions.assertEquals("ID", primaryKey);
    }
</code>```

The primary key function is written like below inside class H

```<code>@Component
@AllArgsConstructor
@Slf4j
public class H {

    private final DataSource dataSource;

    public String pkKeys(String table) {
        try(Connection connection = dataSource.getConnection()) {
            DatabaseMetaData db = connection.getMetaData();
            try(ResultSet tableColumns = connection.getMetaData().getPrimaryKeys(null, "public", table)) {
                while (tableColumns.next()) {
                    log.info("Found {}", tableColumns.getString(COLUMN_NAME));
                    return tableColumns.getString(COLUMN_NAME);
                }
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }

        throw new IllegalStateException("primary key is required");
    }
}
</code>```

My schema.sql looks like below

CREATE TABLE EMPLOYEE
(
    ID int NOT NULL,
    FIRST_NAME varchar(255),
    LAST_NAME varchar(255),
    ADDRESS varchar(255),
    PRIMARY KEY (ID)
);

INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');

DROP TABLE IF EXISTS links;

CREATE TABLE links (
    id SERIAL PRIMARY KEY,
    url VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    description VARCHAR (255),
        last_update DATE
);

INSERT INTO links (url, name)
VALUES('https://www.postgresqltutorial.com','PostgreSQL Tutorial');
```
<p>Issue is <code>primaryKey</code> function never returns primary keys of above tables.</p>
<p>Error logged is</p>
<pre class="lang-none prettyprint-override"><code>15:46:19.866 [main] DEBUG org.springframework.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [schema.sql] in 11 ms.
15:46:19.867 [main] DEBUG org.springframework.jdbc.datasource.SimpleDriverDataSource - Creating new JDBC Driver Connection to [jdbc:h2:mem:testDB;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]

java.lang.IllegalStateException: primary key is required

    at abc.bcd.sql.H.pkKeys(H.java:40)
</code>```

I have verified via debugger that these tables are created fine and are available in database metadata of connection instance.

Body:
I am writing a unit test to test the data source behaviour.

I have written test like below

@ExtendWith(MockitoExtension.class)
public class HTests {

    private H helper;
    private DataSource dataSource;

    @BeforeEach
    void setUp() {
        dataSource = new EmbeddedDatabaseBuilder()
                .setName("testDB;MODE=PostgreSQL")
                .setType(EmbeddedDatabaseType.H2) //.H2
                .addScript("schema.sql")
                .build();
        helper = new H(dataSource);
    }

    @Test
    void getPkKeys() throws SQLException {
        String primaryKey = helper.pkKeys("links");
        Assertions.assertEquals("ID", primaryKey);
    }

The primary key function is written like below inside class H

@Component
@AllArgsConstructor
@Slf4j
public class H {

    private final DataSource dataSource;

    public String pkKeys(String table) {
        try(Connection connection = dataSource.getConnection()) {
            DatabaseMetaData db = connection.getMetaData();
            try(ResultSet tableColumns = connection.getMetaData().getPrimaryKeys(null, "public", table)) {
                while (tableColumns.next()) {
                    log.info("Found {}", tableColumns.getString(COLUMN_NAME));
                    return tableColumns.getString(COLUMN_NAME);
                }
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }

        throw new IllegalStateException("primary key is required");
    }
}

My schema.sql looks like below

CREATE TABLE EMPLOYEE
(
    ID int NOT NULL,
    FIRST_NAME varchar(255),
    LAST_NAME varchar(255),
    ADDRESS varchar(255),
    PRIMARY KEY (ID)
);

INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');

DROP TABLE IF EXISTS links;

CREATE TABLE links (
    id SERIAL PRIMARY KEY,
    url VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    description VARCHAR (255),
        last_update DATE
);

INSERT INTO links (url, name)
VALUES('https://www.postgresqltutorial.com','PostgreSQL Tutorial');

Issue is primaryKey function never returns primary keys of above tables.

Error logged is

15:46:19.866 [main] DEBUG org.springframework.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [schema.sql] in 11 ms.
15:46:19.867 [main] DEBUG org.springframework.jdbc.datasource.SimpleDriverDataSource - Creating new JDBC Driver Connection to [jdbc:h2:mem:testDB;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]

java.lang.IllegalStateException: primary key is required

    at abc.bcd.sql.H.pkKeys(H.java:40)

I have verified via debugger that these tables are created fine and are available in database metadata of connection instance.


问:
Ionic angular cordova upload audio File to server
I'm trying to upload an audio file, created with MediaObject, to the server using Ionic, Angular, Cordova. I'm using the Native File plugin and httpClient from @angular/common/http.

I can't get the file on the server side with PHP $_FILES('audio'). I can't detect what I'm doing wrong. Maybe I need to get the file with file.getFile() ? but I can't get it to work.

I already try "multipart/form-data", "file", "false", "undefined" as "Content-Type" but cannot get the file on server side.

Here is my code, I have all the necessary includes and there are no errors in the console.

```<code>audio: MediaObject;
audioFile: FileEntry;
fileName: string;

startAudio() {

    this.fileName = "audio" + Date.now() + ".mp3";
    this.audio = this.media.create(this.fileName);
    this.audio.startRecord();

}

async finishAudio(){
    this.audio.stopRecord();

    const formAudio = new FormData();

    //this.audioFile = this.file.getFile(this.file.externalDataDirectory.replace(/file:\/\//g, ''), this.fileName, { create: false });

    const buffer = await this.file.readAsArrayBuffer(this.file.externalDataDirectory, this.fileName);
    const fileBlob = new Blob([buffer], {type:'audio/mp3'});
    console.log(buffer);
    formAudio.append("audio", fileBlob, this.fileName);
    this.responseAudioForm = this.audioFormService.postFile(formArchivo);
            this.responseAudioForm.subscribe(data =>{
                this.responseDataAudioForm = data ;
                let title = data.title;
                let message = data.message;
    });
}

/* AudioFormService */

postFile(formData:FormData): Observable<any>{
        //console.log(fields);
        const httpOptions = {
            headers: new HttpHeaders({
                "Content-Type": "application/x-www-form-urlencoded",
            })
        }

        this.presentLoading();
        return this.httpClient.post(this.apiUpdateURL, formData, httpOptions)
            .pipe(
                map(results => {
                    console.log("RAW:",results);
                    this.dismissLoading();
                    this.showToast();
                    return results;
                }),
                catchError(err => {
                    console.log("Handling error:", err);
                    this.showAlert(err.statusText,err.name,err.message);
                    return throwError(err);
                }),
                catchError(err => {
                    console.log("caught rethrown:", err);
                    return of([]);
                })
            );
}
</code>```

Solution. in case it can help someone

```<code>audio: MediaObject;
audioFile: FileEntry;

responseAyudaForm: Observable<any>;
responseDataAyudaForm: any = [];

// Start audio recording
async startAudio() {

    var path: string = "";
    if(this.platform.is("ios")){

      path = this.file.tempDirectory;
      this.fileName = new Date().getTime() + ".mp3";
      this.audioFile = await this.file.createFile(path, this.fileName, true);
      this.audio = this.media.create(this.file.tempDirectory.replace(/^file:\/\//, '') + this.fileName);

    } else {

      path = this.file.externalDataDirectory;
      this.fileName = new Date().getTime() + ".mp3";
      this.audioFile = await this.file.createFile(path, this.fileName, true);
      this.audio = this.media.create(this.audioFile.nativeURL);

    }

    this.audio.startRecord();
    console.log("Record Start");
}

// Stop audio recording and upload file to server
async finishAudio() {

    this.audio.stopRecord();
    console.log("Stop Recording");

    // Upload the new recording
    await new Promise(resolve => setTimeout(resolve, 200));

    console.log("Start Blob convertion");
    const blob = await this.getBlobFromFileEntry(this.audioFile);
    console.log("Finish Blob convertion");

    const formFile = new FormData();

    formFile.append("audio", blob, this.fileName);

    this.responseAyudaForm = this.ayudaService.postFile(formFile);
    this.responseAyudaForm.subscribe(data =>{
        this.responseDataAyudaForm = data ;
        let title = data.title;
        let message = data.message;
    });

}

getBlobFromFileEntry(fileEntry: FileEntry): Promise<Blob> {

    return new Promise((resolve, reject) => {

      fileEntry.file((file) => {

        const reader = new FileReader();
        reader.onloadend = function(e) {

          try {

            const { result: buffer } = e.target
            const blob = new Blob( [new Uint8Array(buffer as any)], { type: 'audio/mp3' } /* or file.type */

            );
            console.log(blob);
            resolve(blob);

          } catch (error) { reject(error); }

        };

        reader.onabort = (ev) => reject(ev);
        reader.onerror = (ev) => reject(ev);
        reader.readAsArrayBuffer(file);

      }, reject)
    });
}

/**
/ AyudaService.postFile()
**/
postFile(formData:FormData): Observable<any>{

    /*const httpOptions = {
        headers: new HttpHeaders({
            "Content-Type": 'file',
        })
    }*/

    this.presentLoading();
    return this.httpClient.post(this.apiAudioURL, formData) /* I removed the httpOptions parameter and it worked */
        .pipe(
            map(results => {
                console.log("RAW:",results);
                this.dismissLoading();
                this.showToast();
                return results;
            }),
            catchError(err => {
                console.log("Handling error:", err);
                this.showAlert(err.statusText,err.name,err.message);
                return throwError(err);
            }),
            catchError(err => {
                console.log("Caught Rethrown:", err);
                return of([]);
            })
        );
}
</code>```

Body:
I'm trying to upload an audio file, created with MediaObject, to the server using Ionic, Angular, Cordova. I'm using the Native File plugin and httpClient from @angular/common/http.

I can't get the file on the server side with PHP $_FILES('audio'). I can't detect what I'm doing wrong. Maybe I need to get the file with file.getFile() ? but I can't get it to work.

I already try "multipart/form-data", "file", "false", "undefined" as "Content-Type" but cannot get the file on server side.

Here is my code, I have all the necessary includes and there are no errors in the console.

audio: MediaObject;
audioFile: FileEntry;
fileName: string;

startAudio() {

    this.fileName = "audio" + Date.now() + ".mp3";
    this.audio = this.media.create(this.fileName);
    this.audio.startRecord();

}

async finishAudio(){
    this.audio.stopRecord();

    const formAudio = new FormData();

    //this.audioFile = this.file.getFile(this.file.externalDataDirectory.replace(/file:\/\//g, ''), this.fileName, { create: false });

    const buffer = await this.file.readAsArrayBuffer(this.file.externalDataDirectory, this.fileName);
    const fileBlob = new Blob([buffer], {type:'audio/mp3'});
    console.log(buffer);
    formAudio.append("audio", fileBlob, this.fileName);
    this.responseAudioForm = this.audioFormService.postFile(formArchivo);
            this.responseAudioForm.subscribe(data =>{
                this.responseDataAudioForm = data ;
                let title = data.title;
                let message = data.message;
    });
}

/* AudioFormService */

postFile(formData:FormData): Observable<any>{
        //console.log(fields);
        const httpOptions = {
            headers: new HttpHeaders({
                "Content-Type": "application/x-www-form-urlencoded",
            })
        }

        this.presentLoading();
        return this.httpClient.post(this.apiUpdateURL, formData, httpOptions)
            .pipe(
                map(results => {
                    console.log("RAW:",results);
                    this.dismissLoading();
                    this.showToast();
                    return results;
                }),
                catchError(err => {
                    console.log("Handling error:", err);
                    this.showAlert(err.statusText,err.name,err.message);
                    return throwError(err);
                }),
                catchError(err => {
                    console.log("caught rethrown:", err);
                    return of([]);
                })
            );
}

Solution. in case it can help someone

audio: MediaObject;
audioFile: FileEntry;

responseAyudaForm: Observable<any>;
responseDataAyudaForm: any = [];

// Start audio recording
async startAudio() {

    var path: string = "";
    if(this.platform.is("ios")){

      path = this.file.tempDirectory;
      this.fileName = new Date().getTime() + ".mp3";
      this.audioFile = await this.file.createFile(path, this.fileName, true);
      this.audio = this.media.create(this.file.tempDirectory.replace(/^file:\/\//, '') + this.fileName);

    } else {

      path = this.file.externalDataDirectory;
      this.fileName = new Date().getTime() + ".mp3";
      this.audioFile = await this.file.createFile(path, this.fileName, true);
      this.audio = this.media.create(this.audioFile.nativeURL);

    }

    this.audio.startRecord();
    console.log("Record Start");
}

// Stop audio recording and upload file to server
async finishAudio() {

    this.audio.stopRecord();
    console.log("Stop Recording");

    // Upload the new recording
    await new Promise(resolve => setTimeout(resolve, 200));

    console.log("Start Blob convertion");
    const blob = await this.getBlobFromFileEntry(this.audioFile);
    console.log("Finish Blob convertion");

    const formFile = new FormData();

    formFile.append("audio", blob, this.fileName);

    this.responseAyudaForm = this.ayudaService.postFile(formFile);
    this.responseAyudaForm.subscribe(data =>{
        this.responseDataAyudaForm = data ;
        let title = data.title;
        let message = data.message;
    });

}

getBlobFromFileEntry(fileEntry: FileEntry): Promise<Blob> {

    return new Promise((resolve, reject) => {

      fileEntry.file((file) => {

        const reader = new FileReader();
        reader.onloadend = function(e) {

          try {

            const { result: buffer } = e.target
            const blob = new Blob( [new Uint8Array(buffer as any)], { type: 'audio/mp3' } /* or file.type */

            );
            console.log(blob);
            resolve(blob);

          } catch (error) { reject(error); }

        };

        reader.onabort = (ev) => reject(ev);
        reader.onerror = (ev) => reject(ev);
        reader.readAsArrayBuffer(file);

      }, reject)
    });
}

/**
/ AyudaService.postFile()
**/
postFile(formData:FormData): Observable<any>{

    /*const httpOptions = {
        headers: new HttpHeaders({
            "Content-Type": 'file',
        })
    }*/

    this.presentLoading();
    return this.httpClient.post(this.apiAudioURL, formData) /* I removed the httpOptions parameter and it worked */
        .pipe(
            map(results => {
                console.log("RAW:",results);
                this.dismissLoading();
                this.showToast();
                return results;
            }),
            catchError(err => {
                console.log("Handling error:", err);
                this.showAlert(err.statusText,err.name,err.message);
                return throwError(err);
            }),
            catchError(err => {
                console.log("Caught Rethrown:", err);
                return of([]);
            })
        );
}


问:
Issue to knit to PDF document - Error with available.packages
I am very new to R and have been trying to knit my R script to a PDF document. There seems to be an issue with loading tinytex. The error message I got is the following:

Error in contrib.url(repos, type):
trying to use CRAN without setting a mirror
Calls:  ... update.packages -> available.packages -> contrib.url
Execution halted

My script is the following:
install.packages("tinytex", repos="http://cran.us.r-project.org")
library(readxl)
library(tidyverse)
library(ggplot2)
library(knitr)
library(stringr)
library(dplyr)
library(tinytex)

I thought that install.packages("tinytex", repos="http://cran.us.r-project.org") would fix the error with using CRAN without a mirror.
What does "update.packages -> available.packages -> contrib.url" message mean?

How can I fix this error message, please? Thank you.


问:
Problems starting SonarQube - macOS Ventura
I recently started learning SonarQube, but I had troubles trying to start it. Can anyone help?

```<code>Running SonarQube...
Removed stale pid file: ./SonarQube.pid
2022.12.05 12:50:16 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2022.12.05 12:50:16 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:49417]
2022.12.05 12:50:17 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
Exception in thread "main" java.lang.UnsupportedOperationException: The Security Manager is deprecated and will be removed in a future release
    at java.base/java.lang.System.setSecurityManager(System.java:416)
    at org.elasticsearch.bootstrap.Security.setSecurityManager(Security.java:99)
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:70)
2022.12.05 12:50:17 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [ElasticSearch]: 1
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped

</code>```

The command I used to start it: /opt/sonarqube/bin/macosx-universal-64/sonar.sh console

I tried to start SonarQube, but it simply did not work. I installed openJDK11

Body:
I recently started learning SonarQube, but I had troubles trying to start it. Can anyone help?

Running SonarQube...
Removed stale pid file: ./SonarQube.pid
2022.12.05 12:50:16 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2022.12.05 12:50:16 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:49417]
2022.12.05 12:50:17 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
Exception in thread "main" java.lang.UnsupportedOperationException: The Security Manager is deprecated and will be removed in a future release
    at java.base/java.lang.System.setSecurityManager(System.java:416)
    at org.elasticsearch.bootstrap.Security.setSecurityManager(Security.java:99)
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:70)
2022.12.05 12:50:17 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [ElasticSearch]: 1
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped
2022.12.05 12:50:17 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped

The command I used to start it: /opt/sonarqube/bin/macosx-universal-64/sonar.sh console

I tried to start SonarQube, but it simply did not work. I installed openJDK11


问:
Problem with splitting columns with semicolon Power Query
I've been generating the same CSV file every month for a year now and splitting the values by the semicolon successfully every time. However, the columns this time don't split for some reason.

Some of the values split, but the majority don't.
What am I doing wrong?

Thank you very much!

I searched but didn't find anyone talking about this problem, and thought of posting here.