问:
How to prevent double page loading in React/NextJS + Framer Motion
I'm trying to animate an image gallery with framer-motion.

I'm using AnimatePresence to detect the value change and animate accordingly.

When I click any links on the same page, for example to a related product, the page renders twice.

Without AnimatePresence it works fine. What am I doing wrong here?

This version, without motion works fine, and causes no errors ( but obvs doesn't animate.. )

```<code>   // useSate - Change Image
   const [currentImage, setCurrentImage] = useState(0);

   const galleryImages = [
      image_one.url,
      image_two.url,
      image_three.url,
      image_four.url,
   ]

   // Click Handler
   <div onClick={ () => { setCurrentImage( 1 ) } }></div>

   // Gallery Image Container
   <div style={{ backgroundImage: "url(" + galleryImages[currentImage] + ")" }}></div>
</code>```

This version causes the links on the page to trigger a 'double reload', but the gallery works..

```<code>   <AnimatePresence>
      <motion.div
         initial={{ opacity: 0, scale: 1.05 }}
         animate={{ opacity: 1, scale: 1 }}
         transition={{
            duration: .4,
            ease: "easeInOut"
         }}
         style={{ backgroundImage: "url(" + galleryImages[currentImage] + ")" }}
         key={ currentImage }
      >
      </motion.div>
   </AnimatePresence>
</code>```

I've also tried using mode="exit" (/exitBeforeEnter), and useEffect.

Body:
I'm trying to animate an image gallery with framer-motion.

I'm using AnimatePresence to detect the value change and animate accordingly.

When I click any links on the same page, for example to a related product, the page renders twice.

Without AnimatePresence it works fine. What am I doing wrong here?

This version, without motion works fine, and causes no errors ( but obvs doesn't animate.. )

   // useSate - Change Image
   const [currentImage, setCurrentImage] = useState(0);

   const galleryImages = [
      image_one.url,
      image_two.url,
      image_three.url,
      image_four.url,
   ]

   // Click Handler

 { setCurrentImage( 1 ) } }>

   // Gallery Image Container

This version causes the links on the page to trigger a 'double reload', but the gallery works..

   <AnimatePresence>
      <motion.div
         initial={{ opacity: 0, scale: 1.05 }}
         animate={{ opacity: 1, scale: 1 }}
         transition={{
            duration: .4,
            ease: "easeInOut"
         }}
         style={{ backgroundImage: "url(" + galleryImages[currentImage] + ")" }}
         key={ currentImage }
      >
      </motion.div>
   </AnimatePresence>

I've also tried using mode="exit" (/exitBeforeEnter), and useEffect.


来源: stackexchange

问:
jQuery can't find elements after re-rendering but elements appear in the devtools inspector
I'm using bootsrap-select, and because it has bug with the refresh method I have to destroy and re-render the selects:

```<code>$("#some_select").selectpicker('destroy');
$("#some_select").selectpicker('render');
</code>```

After it I have a selector of jQuery to elements inside the bootsrap-select drop-down:

```<code>$(`.selectpicker:not(.${selector1}) a.dropdown-item${selector2}`).
</code>```

The selector doesn't find matches anymore. If I place that line above the destroy part it does find.

Also it seem to work after destroying if I remove the last part of the selector:

```<code>a.dropdown-item${selector2}`
</code>```

And it finds the correct elements. The part that's removed was added by ajax to load the dropdown items. Not sure if the AJAX could cause issues here together with the re-rendering method of bootsrap-select, but still the elements are seen in devtools.

If I console.log the selector matches before the destroy and then I click one of the matches then I get "Node cannot be found in the current page"

So it means the underlying Dom was destroyed. However I use the selector after the destroy part so it means the elements were re created by the time I use the selector (and can be seen in the devtools)

What can cause that and how can I make the selector find matches again?

ContentLicense: CC BY-SA 4.0

Body:
I'm using bootsrap-select, and because it has bug with the refresh method I have to destroy and re-render the selects:

$("#some_select").selectpicker('destroy');
$("#some_select").selectpicker('render');

After it I have a selector of jQuery to elements inside the bootsrap-select drop-down:

$(`.selectpicker:not(.${selector1}) a.dropdown-item${selector2}`).

The selector doesn't find matches anymore. If I place that line above the destroy part it does find.

Also it seem to work after destroying if I remove the last part of the selector:

a.dropdown-item${selector2}`

And it finds the correct elements. The part that's removed was added by ajax to load the dropdown items. Not sure if the AJAX could cause issues here together with the re-rendering method of bootsrap-select, but still the elements are seen in devtools.

If I console.log the selector matches before the destroy and then I click one of the matches then I get "Node cannot be found in the current page"

So it means the underlying Dom was destroyed. However I use the selector after the destroy part so it means the elements were re created by the time I use the selector (and can be seen in the devtools)

What can cause that and how can I make the selector find matches again?


问:
How to reveal relations between number of words and target with self-attention based models?
Transformers can handle variable length input, but what if the number of words might correlate with the target? Let's say we want to perform a sentiment analysis for some reviews where the longer reviews are more probable to be bad. How can the model harness this knowledge? Of course a simple solution could be to add this count as a feature after the self-attention layer. However, this hand-crafted-like approach wouldn't reveal more complex relations, for example if there is a high number of word X, it correlates with target 1, except if there is also high number of word Y, in which case the target tends to be 0.

How could this information be included using deep learning? Paper recommendations in the topic are also well appreciated.


问:
How to keep boolean 'true' even after a loop in 2D arrays in java
i was doing my individual assignment and i encounter logic error.
My assignment was to make bus booking system. i got everything right except, if i want to buy another ticket, the booked seat will disappear. The boolean value keep returning to 'false' after the loop is done. this is fraction of my code:

```<code>import java.util.Scanner;

public class IndividualAssignment {

    public static void main(String[] args) throws ParseException, IOException {
        int row, col, seatNumber;
        boolean seatingChart[][] = new boolean[10][3];
        String yesno;
        Scanner input = new Scanner(System.in);

        while (true) {
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    seatingChart[i][j] = false;
                }
            }

            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }
            // Prompt the user to enter a seat number
            System.out.print("Enter a seat number: ");
            seatNumber = input.nextInt();

            // Calculate the row and column of the seat based on the seat number
            row = (seatNumber - 1) / 3;
            col = (seatNumber - 1) % 3;

            // Check if the seat is available
            if (!seatingChart[row][col]) {
                // If the seat is available, mark it as taken (true)
                seatingChart[row][col] = true;
                System.out.println("Seat " + seatNumber + "(row " + (row + 1) + ", column " + (col + 1) + ") has been reserved.");
            } else {
                // If the seat is not available, print an error message
                System.out.println("Sorry, that seat is already taken.");
            }
            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }

            System.out.println("Do you want to continue? (y/n)");
            yesno = input.next();

            if (yesno.equalsIgnoreCase("n")) {
                break;
            } else if (!yesno.equalsIgnoreCase("y")) {
                System.out.println("Invalid input. Please enter y or n.");
            }
        }
    }
}
</code>```

The result:

```<code>1  2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Enter a seat number: 1
Seat 1(row 1, column 1) has been reserved.

X 2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Do you want to continue? (y/n)
y

1  2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Enter a seat number: 2
Seat 2(row 1, column 2) has been reserved.

1  X 3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30
Do you want to continue? (y/n)
</code>```

I was expecting the selected seat to keep being 'true' even after I choose "y". I hope anyone can solve my problem.

Thank you.

Body:
i was doing my individual assignment and i encounter logic error.
My assignment was to make bus booking system. i got everything right except, if i want to buy another ticket, the booked seat will disappear. The boolean value keep returning to 'false' after the loop is done. this is fraction of my code:

import java.util.Scanner;

public class IndividualAssignment {

    public static void main(String[] args) throws ParseException, IOException {
        int row, col, seatNumber;
        boolean seatingChart[][] = new boolean[10][3];
        String yesno;
        Scanner input = new Scanner(System.in);

        while (true) {
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    seatingChart[i][j] = false;
                }
            }

            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }
            // Prompt the user to enter a seat number
            System.out.print("Enter a seat number: ");
            seatNumber = input.nextInt();

            // Calculate the row and column of the seat based on the seat number
            row = (seatNumber - 1) / 3;
            col = (seatNumber - 1) % 3;

            // Check if the seat is available
            if (!seatingChart[row][col]) {
                // If the seat is available, mark it as taken (true)
                seatingChart[row][col] = true;
                System.out.println("Seat " + seatNumber + "(row " + (row + 1) + ", column " + (col + 1) + ") has been reserved.");
            } else {
                // If the seat is not available, print an error message
                System.out.println("Sorry, that seat is already taken.");
            }
            // Print the seating chart
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    if (seatingChart[i][j]) {
                        System.out.print("X ");
                    } else {
                        System.out.print((i * 3 + j + 1) + "  ");
                    }
                }
                System.out.println();
            }

            System.out.println("Do you want to continue? (y/n)");
            yesno = input.next();

            if (yesno.equalsIgnoreCase("n")) {
                break;
            } else if (!yesno.equalsIgnoreCase("y")) {
                System.out.println("Invalid input. Please enter y or n.");
            }
        }
    }
}

The result:

1  2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Enter a seat number: 1
Seat 1(row 1, column 1) has been reserved.

X 2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Do you want to continue? (y/n)
y

1  2  3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30

Enter a seat number: 2
Seat 2(row 1, column 2) has been reserved.

1  X 3
4  5  6
7  8  9
10  11  12
13  14  15
16  17  18
19  20  21
22  23  24
25  26  27
28  29  30
Do you want to continue? (y/n)

I was expecting the selected seat to keep being 'true' even after I choose "y". I hope anyone can solve my problem.

Thank you.


问:
.net 6 Blazor WebAssembly Deployed to Azure 400 Error when trying to send email via SendGrid
I have a basic Blazor WebAssembly project that is using SendGrid to send form data via email. Locally it works fine. I have deployed to Azure App Service and setup API Management as well.

Locally I set an EnvironmentVariable to hold my SendGrid Api key.

This is the EmailService code.

```<code>public async Task<ServiceResponse<Contact>> SendEmail(Contact info)
        {
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
            var toEmail = _config.GetSection("SendGrid:EmailTo").Value;
            var toName = _config.GetSection("SendGrid:EmailName").Value;
            var _subject = _config.GetSection("SendGrid:EmailSubject").Value;

            var client = new SendGridClient(apiKey);
            var from = new EmailAddress($"{info.Email}", $"{info.Name}");
            var subject = _subject;
            var to = new EmailAddress(toEmail, toName);
            var plainTextContent = info.Message;
            var htmlContent = info.Message;
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);

            if (response.IsSuccessStatusCode)
            {
                return new ServiceResponse<Contact>
                {
                    Data = info,
                    Success = true,
                    Message = "Message has been sent."
                };
            }
            else
            {
                return new ServiceResponse<Contact> { Success = false };

            }

        }
</code>```

In Azure App Service I created an Application setting named "SENDGRID_API_KEY" and it holds the SendGrid API key. I also tried modifying the request before it is sent and added the Authorization header there as well.
When the form submits, it returns a 400 (Bad Request) error.

I do not have a secure certificate on this site yet.

Any ideas? Please let me know if you need more info.

Body:
I have a basic Blazor WebAssembly project that is using SendGrid to send form data via email. Locally it works fine. I have deployed to Azure App Service and setup API Management as well.

Locally I set an EnvironmentVariable to hold my SendGrid Api key.

This is the EmailService code.

public async Task<ServiceResponse<Contact>> SendEmail(Contact info)
        {
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
            var toEmail = _config.GetSection("SendGrid:EmailTo").Value;
            var toName = _config.GetSection("SendGrid:EmailName").Value;
            var _subject = _config.GetSection("SendGrid:EmailSubject").Value;

            var client = new SendGridClient(apiKey);
            var from = new EmailAddress($"{info.Email}", $"{info.Name}");
            var subject = _subject;
            var to = new EmailAddress(toEmail, toName);
            var plainTextContent = info.Message;
            var htmlContent = info.Message;
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);

            if (response.IsSuccessStatusCode)
            {
                return new ServiceResponse<Contact>
                {
                    Data = info,
                    Success = true,
                    Message = "Message has been sent."
                };
            }
            else
            {
                return new ServiceResponse<Contact> { Success = false };

            }

        }

In Azure App Service I created an Application setting named "SENDGRID_API_KEY" and it holds the SendGrid API key. I also tried modifying the request before it is sent and added the Authorization header there as well.
When the form submits, it returns a 400 (Bad Request) error.

I do not have a secure certificate on this site yet.

Any ideas? Please let me know if you need more info.


问:
How to debug the form component in ant-design4?
I want to debug the form component, I rebuilt the rc-filed-form (added the sourcemap file) and started it inside the project, but chrome doesn't seem to use my generated sourcemap for code restoration. I'd like to ask why this is, or is my debugger method wrong? I hope you can help me!

I checked webpack's resource service and didn't find the relevant map resource, is this the cause of the problem?


问:
EROFS: read-only file system, open 'Files/car.png'
Hello I Am Geting An Issue EROFS: read-only file system, open 'Files/car.png'.

First I want to Ask Do Heroku and Cyclic Allow To Store Binary Data like Images,Videos on their Server If Yes

Why Do I am Getting The Above Issue


问:
Select from list without duplicates
I have a table "Content" like this (other fields omitted)

```<code>id, name, value
1, test, abc
2, test, xyz
3, test2, abc
4, test2, xyz
</code>```

I'm trying to retrieve the rows from "Content" using an input list like this (list of name_value):

[test_abc, test2_xyz]

I work in Java and I can do some processing on the list before running the query.

Here is what I tried:

First, I split the input list into two lists, first one has all the names and second one has all the values.

Then, I run my query, which looks like this:

```<code>SELECT c from content c WHERE c.name IN :names AND c.value IN :values
</code>```

I set the parameters to the two lists I created beforehand.

This doesn't work because it will return all the rows and not something unique.

Actual result:

(1, test, abc)
(2, test, xyz)
(3, test, abc)
(4, test2, xyz)
```
<p>Expected result is</p>
<pre class="lang-none prettyprint-override"><code>(1, test, abc)
(4, test2, xyz)
</code>```

My query is not good and I'm not sure how I can fix it.

Title: Select from list without duplicates

Body:
I have a table "Content" like this (other fields omitted)

id, name, value
1, test, abc
2, test, xyz
3, test2, abc
4, test2, xyz

I'm trying to retrieve the rows from "Content" using an input list like this (list of name_value):

[test_abc, test2_xyz]

I work in Java and I can do some processing on the list before running the query.

Here is what I tried:

First, I split the input list into two lists, first one has all the names and second one has all the values.

Then, I run my query, which looks like this:

SELECT c from content c WHERE c.name IN :names AND c.value IN :values

I set the parameters to the two lists I created beforehand.

This doesn't work because it will return all the rows and not something unique.

Actual result:

(1, test, abc)
(2, test, xyz)
(3, test, abc)
(4, test2, xyz)

Expected result is

(1, test, abc)
(4, test2, xyz)

My query is not good and I'm not sure how I can fix it.


问:
Qt QTreeWidget looping over top level items slows down after sorting
I've got a Qt related question (for c++) regarding the QTreeWidget and hope someone can help.

I am working with the QTreeWidget and have run into a performance issue that I can't seem to solve. I basically have made a simple extension of it that allows me to easily filter the tree (hide items depending on filters). Running through all top level items and hiding/showing them depending on the filter is very easy, however it slows down whenever the tree is allowed to be sorted (e.g. by calling setSortingEnabled(true) on the QTreeWidget). Does anyone know a way around this or a better way to do this?

The way I filter the the items is as follows:

```<code>setUpdatesEnabled(false);

for(int i = 0; i < topLevelItemCount(); ++i)
{
   // Retrieve item
   const auto pItem = topLevelItem( i );

   bool hide = false;

   for(filter : mFilters){
        // Stop if a filter already hides the item
        if(hide) break;

        // Check filter
        hide = filter.checkFilter(pItem);
   }

   pItem->setHidden(false);
}

setUpdatesEnabled(true);
</code>```

This function itself is very fast, it can run in one or two seconds for a test with 1 million items. However once setSortingEnabled(true) is called to also allow sorting it slows down significantly. I've checked with debugging and it's not the sorting that slows things down, the function above will now take ages to complete. It will now take a few minute at least compared to the mere seconds it took previously (when sorting is not allowed).

To me it appears that if sorting is enabled even once then the call

```<code>const auto pItem = topLevelItem( i );
</code>```

or

```<code>pItem->setHidden(hide)
</code>```

slows down significantly.

Can anyone shed some light on this issue or suggest a faster/better way to apply filters and/or loop through all top level items in the QTreeWidget?

I've looked online for faster ways to loop through the top level items, but most suggest topLevelItem(int i). I've not seen any thread regarding slowdown after sorting is enabled.

I've tried a few things, namely

Using QTreeWidgetIterators rather than topLevelItem(int i)

Calling setUpdatesEnabled(false) and setUpdatesEnabled(true) before and after the filter check respectively

Calling setSortingEnabled(false) and setSortingEnabled(true) before and after the filter check respectively

Retrieving all items in a QList findItems when searching for a wildcard string and looping over the returned QList

Looping over the QList<QTreeWidgetItem*> with pointers to items used when the tree was populated via addTopLevelItems(list)

None of these have had any impact on the performance unfortunately. If sorting has ever been enabled, then looping over items slows down significantly.

Body:
I've got a Qt related question (for c++) regarding the QTreeWidget and hope someone can help.

I am working with the QTreeWidget and have run into a performance issue that I can't seem to solve. I basically have made a simple extension of it that allows me to easily filter the tree (hide items depending on filters). Running through all top level items and hiding/showing them depending on the filter is very easy, however it slows down whenever the tree is allowed to be sorted (e.g. by calling setSortingEnabled(true) on the QTreeWidget). Does anyone know a way around this or a better way to do this?

The way I filter the the items is as follows:

setUpdatesEnabled(false);

for(int i = 0; i < topLevelItemCount(); ++i)
{
   // Retrieve item
   const auto pItem = topLevelItem( i );

   bool hide = false;

   for(filter : mFilters){
        // Stop if a filter already hides the item
        if(hide) break;

        // Check filter
        hide = filter.checkFilter(pItem);
   }

   pItem->setHidden(false);
}

setUpdatesEnabled(true);

This function itself is very fast, it can run in one or two seconds for a test with 1 million items. However once setSortingEnabled(true) is called to also allow sorting it slows down significantly. I've checked with debugging and it's not the sorting that slows things down, the function above will now take ages to complete. It will now take a few minute at least compared to the mere seconds it took previously (when sorting is not allowed).

To me it appears that if sorting is enabled even once then the call

const auto pItem = topLevelItem( i );

or

pItem->setHidden(hide)

slows down significantly.

Can anyone shed some light on this issue or suggest a faster/better way to apply filters and/or loop through all top level items in the QTreeWidget?

I've looked online for faster ways to loop through the top level items, but most suggest topLevelItem(int i). I've not seen any thread regarding slowdown after sorting is enabled.

I've tried a few things, namely

Using QTreeWidgetIterators rather than topLevelItem(int i)

Calling setUpdatesEnabled(false) and setUpdatesEnabled(true) before and after the filter check respectively

Calling setSortingEnabled(false) and setSortingEnabled(true) before and after the filter check respectively

Retrieving all items in a QList findItems when searching for a wildcard string and looping over the returned QList

Looping over the QList<QTreeWidgetItem*> with pointers to items used when the tree was populated via addTopLevelItems(list)

None of these have had any impact on the performance unfortunately. If sorting has ever been enabled, then looping over items slows down significantly.


问:
Am i required to do a fftshift or iffshift after cross correlation?
I am doing cross correlation for 2 vectors, v1, v2, following the fft method.

I am not allowed to use a lib so i had to do it old style and my knowledge on this is pretty limitted.
The process is this:

FFT on v1

FFT on v2

cross = v1*conjugated(v2)

result = IFFT(cross)

My question is, do i need to do a shift for the result vector. If yes would it be a FFTSHIFT or an IFFTSHIFT?


问:
How do I add a number onto all the values of a map?
This is my first language, so I don't understand Kotlin syntax all that well, and I don't know many of the function names.

Tried adding 1 to the values of the map, didn't work.


问:
React testing library - testing setState inside Promise then caused An update to TestComponent inside a test was not wrapped in act
I'm trying to test a custom hook which setting a state in a Promise then/catch block.

This is my custom hook:

```<code>import {useState} from 'react';
import {useBackendApi} from './backend-api';

export function useMyCustomHook(): {status?: Status; loadData: () => void} {
    const [status, setStatus] = useState<Status>();
    const backendApi = useBackendApi();

    const loadData = (): void => {
        backendApi.makeApiCall().then(() => {
            setStatus(Status.SUCCESS);
        }).catch(() => {
            setStatus(Status.ERROR);
        });
    };

    return {status, loadData};
}

export enum Status {
    SUCCESS = 1,
    ERROR = 2,
}
</code>```

And these are my tests:

```<code>import {act, renderHook, waitFor} from '@testing-library/react';
import * as BackendApiHooks from './backend-api';
import {Status, useMyCustomHook} from './my-custom-hook';

describe('useMyCustomHook', () => {
    afterEach(() => {
        jest.clearAllMocks();
    });

    it('should set the status to SUCCESS when makeApiCall resolved', async () => {
        jest.spyOn(BackendApiHooks, 'useBackendApi').mockReturnValue({
            makeApiCall: jest.fn().mockReturnValue(Promise.resolve()),
        });
        const {result} = renderHook(() => useMyCustomHook());

        await act(() => {
            result.current.loadData();
        });

        await waitFor(() => expect(result.current.status).toBe(Status.SUCCESS));
    });

    it('should set the status to ERROR when makeApiCall rejected', async () => {
        jest.spyOn(BackendApiHooks, 'useBackendApi').mockReturnValue({
            makeApiCall: jest.fn().mockReturnValue(Promise.reject()),
        });
        const {result} = renderHook(() => useMyCustomHook());

        await act(() => {
            result.current.loadData();
        });

        await waitFor(() => expect(result.current.status).toBe(Status.ERROR));
    });
});
</code>```

My tests are passed but on the first test there is an error printed to the console:

```<code>Warning: An update to TestComponent inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at TestComponent (/****/node_modules/@testing-library/react/dist/pure.js:281:5)

   8 |     const loadData = (): void => {
   9 |         backendApi.makeApiCall().then(() => {
> 10 |             setStatus(Status.SUCCESS);
     |             ^
  11 |         }).catch(() => {
  12 |             setStatus(Status.ERROR);
  13 |         });

  at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
  at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
  at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
  at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
  at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
  at src/modules/table/components/my-custom-hook.ts:10:13
</code>```

It happens although I wrapped the result.current.loadData() in act.

Important note: It happens only on the first test (with the resolve mock) but not on the second test (with the reject mock)

Couldn't find any relevant solution in other questions. What am I missing?

Body:
I'm trying to test a custom hook which setting a state in a Promise then/catch block.

This is my custom hook:

import {useState} from 'react';
import {useBackendApi} from './backend-api';

export function useMyCustomHook(): {status?: Status; loadData: () => void} {
    const [status, setStatus] = useState<Status>();
    const backendApi = useBackendApi();

    const loadData = (): void => {
        backendApi.makeApiCall().then(() => {
            setStatus(Status.SUCCESS);
        }).catch(() => {
            setStatus(Status.ERROR);
        });
    };

    return {status, loadData};
}

export enum Status {
    SUCCESS = 1,
    ERROR = 2,
}

And these are my tests:

import {act, renderHook, waitFor} from '@testing-library/react';
import * as BackendApiHooks from './backend-api';
import {Status, useMyCustomHook} from './my-custom-hook';

describe('useMyCustomHook', () => {
    afterEach(() => {
        jest.clearAllMocks();
    });

    it('should set the status to SUCCESS when makeApiCall resolved', async () => {
        jest.spyOn(BackendApiHooks, 'useBackendApi').mockReturnValue({
            makeApiCall: jest.fn().mockReturnValue(Promise.resolve()),
        });
        const {result} = renderHook(() => useMyCustomHook());

        await act(() => {
            result.current.loadData();
        });

        await waitFor(() => expect(result.current.status).toBe(Status.SUCCESS));
    });

    it('should set the status to ERROR when makeApiCall rejected', async () => {
        jest.spyOn(BackendApiHooks, 'useBackendApi').mockReturnValue({
            makeApiCall: jest.fn().mockReturnValue(Promise.reject()),
        });
        const {result} = renderHook(() => useMyCustomHook());

        await act(() => {
            result.current.loadData();
        });

        await waitFor(() => expect(result.current.status).toBe(Status.ERROR));
    });
});

My tests are passed but on the first test there is an error printed to the console:

Warning: An update to TestComponent inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at TestComponent (/****/node_modules/@testing-library/react/dist/pure.js:281:5)

   8 |     const loadData = (): void => {
   9 |         backendApi.makeApiCall().then(() => {
> 10 |             setStatus(Status.SUCCESS);
     |             ^
  11 |         }).catch(() => {
  12 |             setStatus(Status.ERROR);
  13 |         });

  at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
  at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
  at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
  at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
  at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
  at src/modules/table/components/my-custom-hook.ts:10:13

It happens although I wrapped the result.current.loadData() in act.

Important note: It happens only on the first test (with the resolve mock) but not on the second test (with the reject mock)

Couldn't find any relevant solution in other questions. What am I missing?


问:
Back up Log file with different extension
I am using below config file for log generation

```<code><configuration>
    <configSections>
        <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
    </configSections>

    <log4net>
        <appender name="TestLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="${ALLUSERSPROFILE}////Logs//Test.log" />
            <appendToFile value="true"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
            </layout>
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="5MB" />
        </appender>

        <root>
            <level value="ALL"/>
            <appender-ref ref="TestLogFileAppender"/>
        </root>

        <logger additivity="false" name="TestLogger">
            <appender-ref ref="TestLogFileAppender"/>
        </logger>

    </log4net>
</configuration>
</code>```

My expectation is to get the log file in below format
Current Log file name Test.log.
When it reaches to 5MB, expecting back up file name as below

Test_1.bak
:
"
:
:
Test_10.bak

Body:
I am using below config file for log generation

<configuration>
    <configSections>

    </configSections>

    <log4net>
        <appender name="TestLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="${ALLUSERSPROFILE}////Logs//Test.log" />
            <appendToFile value="true"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
            </layout>
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="5MB" />
        </appender>

        <root>
            <level value="ALL"/>
            <appender-ref ref="TestLogFileAppender"/>
        </root>

        <logger additivity="false" name="TestLogger">
            <appender-ref ref="TestLogFileAppender"/>
        </logger>

    </log4net>
</configuration>

My expectation is to get the log file in below format
Current Log file name Test.log.
When it reaches to 5MB, expecting back up file name as below

Test_1.bak
:
"
:
:
Test_10.bak


问:
C# Windows Forrm "MouseWheel" does not appear in zoomControl1
I want to use the code below, but the "MouseWheel" event is not working.</p>
```<code>private void zoomControl1_MouseWheel(object sender, MouseEventArgs e)
    {

       if (Control.ModifierKeys == Keys.Control && e.Delta > 0)
       {
          zoomControl1.Zoom += 0.1f;
       }
       else if (Control.ModifierKeys == Keys.Control && e.Delta < 0)
       {
          zoomControl1.Zoom -= 0.1f;
       }
    }
</code>```

Body:
I want to use the code below, but the "MouseWheel" event is not working.

private void zoomControl1_MouseWheel(object sender, MouseEventArgs e)
    {

       if (Control.ModifierKeys == Keys.Control && e.Delta > 0)
       {
          zoomControl1.Zoom += 0.1f;
       }
       else if (Control.ModifierKeys == Keys.Control && e.Delta < 0)
       {
          zoomControl1.Zoom -= 0.1f;
       }
    }


问:
Developer mode required for installing
I have an iOS app that is distributed via diawi.com. This has worked fine before, but now the iPad requires developer mode to install. I think I have found the solution here here. But I have not found any reason why this is happening now. Is it something new Apple is doing? Is it any way for me to not having to enable developer mode when installing in the future?</p>

Title: Developer mode required for installing


问:
iframe print() contentWindow force actual size
I have pdf file in iframe, I have button to open Printing tool. Automatic add "Fit to printable area"

iframe.contentWindow.print();

Can I force "actual size"?


问:
Getting date and time which user can not change
I am currently developing an app that used for write some document and send them to a database. Issue is app need to get date and time automatically when form created and users can modify system date & time.
First, I search for solution on the internet, then one of the solutions is using a service that return time and later on count that time, so time can not be modified by user. This solution will not for this app because users can be in a place that do not have cell reception or internet access, so app need to work without internet access as long as sending data to remote database via internet.(date of form must be the time when form created)

Second idea is about network-provided time and time zone. If user want to change, he or she must disable those setting then modify time. I think when user want to write a form, app will check whether it is on or off. If it is of app will show an alert dialog which force them to activate those settings.

So I tested, I turned off wifi and cellular, turned off those setting, modified time and waited for a couple minutes. Then I turned on those setting and system showed correct time.

Also, after system corrected its date and time without network connection when I activated network-provided time and time zone setting, It made me think maybe app can get date from a place that user can not modify, yet I could not find information about this.

So I am looking for reliable method, and open for new ideas. If there was not I will implement second method.

Thank all of you who spared their time and read this.

And Second solustion will look like  this:

```<code>private boolean isTimeZoneAutomatic(Context c) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 0) == 1;
    } else {
        return android.provider.Settings.System.getInt(c.getContentResolver(), Settings.System.AUTO_TIME_ZONE, 0) == 1;
    }
}
</code>```

Do you have any suggestion?

Body:
I am currently developing an app that used for write some document and send them to a database. Issue is app need to get date and time automatically when form created and users can modify system date & time.
First, I search for solution on the internet, then one of the solutions is using a service that return time and later on count that time, so time can not be modified by user. This solution will not for this app because users can be in a place that do not have cell reception or internet access, so app need to work without internet access as long as sending data to remote database via internet.(date of form must be the time when form created)

Second idea is about network-provided time and time zone. If user want to change, he or she must disable those setting then modify time. I think when user want to write a form, app will check whether it is on or off. If it is of app will show an alert dialog which force them to activate those settings.

So I tested, I turned off wifi and cellular, turned off those setting, modified time and waited for a couple minutes. Then I turned on those setting and system showed correct time.

Also, after system corrected its date and time without network connection when I activated network-provided time and time zone setting, It made me think maybe app can get date from a place that user can not modify, yet I could not find information about this.

So I am looking for reliable method, and open for new ideas. If there was not I will implement second method.

Thank all of you who spared their time and read this.

And Second solustion will look like  this:

private boolean isTimeZoneAutomatic(Context c) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 0) == 1;
    } else {
        return android.provider.Settings.System.getInt(c.getContentResolver(), Settings.System.AUTO_TIME_ZONE, 0) == 1;
    }
}

Do you have any suggestion?


问:
Authorization error when trying to upload github repository
I created a repository on my github as usual to upload an application, as I always do. But after pasting all the necessary commands charged by github, after I give git push -u origin main

the error is returned to me

```<code>git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I already uploaded several applications on github and this never happened. How to solve?

Body:
I created a repository on my github as usual to upload an application, as I always do. But after pasting all the necessary commands charged by github, after I give git push -u origin main

the error is returned to me

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I already uploaded several applications on github and this never happened. How to solve?


问:
fetch data from one table and insert into another using php
I want to insert all my fetch data into another table using PHP, but I can't figure out how to do it.

I already fetched the selected data as you can see in image using check box

and I can fetch it. I don't know if fetch is the right word

Here is the code that I use:

```<code><?php
require '../config/connect.php';
require '../config/config.php';

if(isset($_POST['save_multicheckbox']))
{
  foreach ($_POST['id'] as $id):
    $query=mysqli_query($conn,"SELECT * FROM `liveselling` WHERE id='$id'");
    //$srow=mysqli_num_rows($query);
    $row=mysqli_num_rows($query);

    if($row > 0)
    {
      while($result = mysqli_fetch_array($query)){
      {
        $customer = $result["customer"];
        $code = $result["code"];
        $supplier = $result["supplier"];
        $product = $result["product"];
        $qty = $result["qty"];
        $price = $result["price"];
?>
        <tr>
          <td><?php echo $customer ?> </td>
          <td><?php echo $code ?> </td>
          <td><?php echo $supplier ?> </td>
          <td><?php echo $product ?> </td>
          <td><?php echo $qty ?> </td>
          <td><?php echo $price ?> </td>
        </tr>
<?php
      }
    }
  }
  endforeach;
}
else
{
    echo'
    <tr>
        <td colspan = "4"><center>Record Not Found</center></td>
    </tr>';
}
?>
</code>```

Now how can I insert all the fetch data into new table in SQL?

Body:
I want to insert all my fetch data into another table using PHP, but I can't figure out how to do it.

I already fetched the selected data as you can see in image using check box

and I can fetch it. I don't know if fetch is the right word

Here is the code that I use:

<?php
require '../config/connect.php';
require '../config/config.php';

if(isset($_POST['save_multicheckbox']))
{
  foreach ($_POST['id'] as $id):
    $query=mysqli_query($conn,"SELECT * FROM `liveselling` WHERE id='$id'");
    //$srow=mysqli_num_rows($query);
    $row=mysqli_num_rows($query);

    if($row > 0)
    {
      while($result = mysqli_fetch_array($query)){
      {
        $customer = $result["customer"];
        $code = $result["code"];
        $supplier = $result["supplier"];
        $product = $result["product"];
        $qty = $result["qty"];
        $price = $result["price"];
?>

          <?php echo $customer ?>
          <?php echo $code ?>
          <?php echo $supplier ?>
          <?php echo $product ?>
          <?php echo $qty ?>
          <?php echo $price ?>

<?php
      }
    }
  }
  endforeach;
}
else
{
    echo'

        Record Not Found

';
}
?>

Now how can I insert all the fetch data into new table in SQL?


问:
How can a native Android App support multiple SSO providers and allow users to login with different accounts without requiring manual logout in Chrome
I am trying to implement an SSO login in a native Android app and want to follow the best practices outlined in RFC 8252 (OAuth 2.0 for Native Apps). This requires using Custom Tabs rather than  WebViews:

B.2.  Android Implementation Details

Apps can initiate an authorization request in the browser, without the user leaving the app, through the Android Custom Tab feature, which implements the in-app browser tab pattern.  The user's default browser can be used to handle requests when no browser supports Custom Tabs.

The login process is working correctly, but once a user logs in with a specific account in a Chrome Custom Tab, it is not possible to log in with a different account without manually logging out in Chrome.

On iOS, this issue can be addressed using an ASWebAuthenticationSession with the prefersEphemeralWebBrowserSession parameter set to true, but this solution is not available on Android.

Chrome does offer experimental support for Incognito Custom Tabs, but this requires user opt-in and displays a privacy warning when the deep link to the app is fired.

I am looking for a solution that allows a native Android app to support multiple SSO providers and allows users to log in with different accounts without requiring manual logout in Chrome.


问:
MUI Radio Button - Expected spacing argument Error
In my MUI Radio Component on the onChange event I get this weird error.

Below is my component. My feeling is that formik.setFieldValue is setting an object.

```<code><Grid item xs={6} sm={6}>
    <Box display="flex" justifyContent="right" alignItems="center">
        <RadioGroup
            row
            aria-labelledby="isAddressFiscal"
            defaultValue={true}
            name="isAddressFiscal"
            onChange={(e, value) => formik.setFieldValue("isAddressFiscal", !formik.values.isAddressFiscal)}
            value={formik.values.isAddressFiscal}
        >
            <FormControlLabel value={true} control={<Radio />} label="Si" />
            <FormControlLabel value={false} control={<Radio />} label="No" />
        </RadioGroup>
    </Box>
</Grid>
</code>```

Body:
In my MUI Radio Component on the onChange event I get this weird error.

Below is my component. My feeling is that formik.setFieldValue is setting an object.

<Grid item xs={6} sm={6}>
    <Box display="flex" justifyContent="right" alignItems="center">
        <RadioGroup
            row
            aria-labelledby="isAddressFiscal"
            defaultValue={true}
            name="isAddressFiscal"
            onChange={(e, value) => formik.setFieldValue("isAddressFiscal", !formik.values.isAddressFiscal)}
            value={formik.values.isAddressFiscal}
        >
            <FormControlLabel value={true} control={<Radio />} label="Si" />
            <FormControlLabel value={false} control={<Radio />} label="No" />
        </RadioGroup>
    </Box>
</Grid>


问:
Tomcat Error - The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
i am running Tomcat by using the below command on an AWS EC2 instance

docker run -d -p 80:8080 tomcat:jre8

verified with docker ps -a and container seems to be running fine, see below

50d8d7c12bce   tomcat:jre8   "catalina.sh run"   20 minutes ago   Up 20 minutes               0.0.0.0:80->8080/tcp, :::80->8080/tcp   sad_banach

I shall get the default tomcat page but when i access the public ip at port 80, i get the following error -

HTTP Status 404 – Not Found
Type Status Report

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/10.0.23

Tried to access the tomcat locally and got the following

curl http://localhost:8080
curl: (7) Failed to connect to localhost port 8080 after 0 ms: Connection refused

I have checked the security group etc and they all look good.

All the help is highly appreciated.


问:
Auth0 dynamic white label login page with custom domain with dynamic signIn options
My current task is to create a dynamic login page for different clients and different users through our internal subscription system. And white label it by client

The requirements are:

White label based on the domain

Different login options based on the company or user subscription. Meaning as user Foo in company A you might log in with a password/email and google SSO. And as user Bar in company B might have only a password/email login.

Current implementation

On FE app we are using a library @auth0/auth0-react with loginWithRedirect

On BE, which is dedicated to communication with FE via websocket. We use library auth0, to validate the user with accessToken for establishing the connection. Meaning the domain and clientId must be matching for both of them

My question is: What is the simplest way how to create a white labeled loginWithRedirect with dynamic login options (e.g.: with or without SSO) for company/user. Without creating a new tenant and new db connection for each case? Also, it is quite tricky to connect the FE and BE credentials (domain and clientId) dynamically based on the client’s request.


问:
Filter a JavaScript array containing an array
I am trying to filter a table based on the user's input (search). This search string sends a teamId to the getFilteredPlayers function and I would like to return a list of players that are linked to that teamId. See an example of a player in the players array below;

See getFilteredPlayers function below, it is not returning anything currently. Please recommend some changes please

```<code>let getFilteredPlayers = (players, search) => {
            if (search && search.length > 0) {
                return players.filter((x) => {
                    return search.any((y) => x.playersTeams == y);
                });
            }
            return players;
        };
</code>```

Body:
I am trying to filter a table based on the user's input (search). This search string sends a teamId to the getFilteredPlayers function and I would like to return a list of players that are linked to that teamId. See an example of a player in the players array below;

See getFilteredPlayers function below, it is not returning anything currently. Please recommend some changes please

let getFilteredPlayers = (players, search) => {
            if (search && search.length > 0) {
                return players.filter((x) => {
                    return search.any((y) => x.playersTeams == y);
                });
            }
            return players;
        };


问:
{C++} Why does using the default copy constructor, DMA class pointers along with memory-deallocating destructor inhibit the program functionality?
Although I think I have a fairly decent idea of why these three elements together are not desirable to have in a program, I would feel more confident with a curated answer to my question. Why does having a default copy constructor, a class that has dynamically allocated memory (stored in member pointers) and a destructor that deallocates the dynamic memory results in a program with a very inhibited functionality which is more error prone?

```<code>#include <iostream>
#include <string>
#include <random>
using namespace std;
class dynamicArray {
int* arr;
public:
dynamicArray() {    arr = new int[4]; }
~dynamicArray() {   delete[] arr;   arr = NULL; }
    int* getObjptr(dynamicArray X) {    return X.arr;}
    void setrandom() {  srand(time(0)); for (int i = 0; i < 4; i++)arr[i] = rand() % 5; }
    void display() {    for (int i = 0; i < 4; i++) cout << arr[i] << " ";   cout << endl;}
};
int main() {
    dynamicArray object;
    object.setrandom();
    dynamicArray object2;
    object2.setrandom();
    object.display();
    object2.display();
    object.getObjptr(object2);
    object.display();
    object2.display();
    return 0;
}

</code>```

The simple example program demonstrates my point. The program essentially throws an exception whenever you pass a class object to a function.

Body:
Although I think I have a fairly decent idea of why these three elements together are not desirable to have in a program, I would feel more confident with a curated answer to my question. Why does having a default copy constructor, a class that has dynamically allocated memory (stored in member pointers) and a destructor that deallocates the dynamic memory results in a program with a very inhibited functionality which is more error prone?

#include <iostream>
#include <string>
#include <random>
using namespace std;
class dynamicArray {
int* arr;
public:
dynamicArray() {    arr = new int[4]; }
~dynamicArray() {   delete[] arr;   arr = NULL; }
    int* getObjptr(dynamicArray X) {    return X.arr;}
    void setrandom() {  srand(time(0)); for (int i = 0; i < 4; i++)arr[i] = rand() % 5; }
    void display() {    for (int i = 0; i < 4; i++) cout << arr[i] << " ";   cout << endl;}
};
int main() {
    dynamicArray object;
    object.setrandom();
    dynamicArray object2;
    object2.setrandom();
    object.display();
    object2.display();
    object.getObjptr(object2);
    object.display();
    object2.display();
    return 0;
}

The simple example program demonstrates my point. The program essentially throws an exception whenever you pass a class object to a function.


问:
Unable to connect to Postgres from PySpark on kubernetes
I am trying to connect to Postgres from PySpark. Both Postgres and PySpark are running on Kubernetes. Here is the error log -

```<code>Traceback (most recent call last):
  File "/./spark-process.py", line 149, in <module>
    main()
  File "/./spark-process.py", line 75, in main
    df.writeStream.foreachBatch(foreach_batch_function).start().awaitTermination()
  File "/spark/python/lib/pyspark.zip/pyspark/sql/streaming.py", line 101, in awaitTermination
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 117, in deco
pyspark.sql.utils.StreamingQueryException22/12/21 13:42:41 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20221221134121-0029/6 is now RUNNING
: An exception was raised by the Python Proxy. Return Message: Traceback (most recent call last):
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 2442, in _call_proxy
    return_value = getattr(self.pool[obj_id], method)(*params)
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 196, in call
    raise e
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 193, in call
    self.func(DataFrame(jdf, self.sql_ctx), batch_id)
  File "/./spark-process.py", line 45, in foreach_batch_function
    .option("driver", "org.postgresql.Driver")\
  File "/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 1107, in save
    self._jwrite.save()
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 111, in deco
    return f(*a, **kw)
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o60.save.
: org.postgresql.util.PSQLException: The authentication type 10 is not supported. Check that you have configured the pg_hba.conf file to include the client's IP address or subnet, and that it is using an authentication scheme supported by the driver.
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:642)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:223)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:67)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:212)
    at org.postgresql.Driver.makeConnection(Driver.java:407)
    at org.postgresql.Driver.connect(Driver.java:275)
    at org.apache.spark.sql.execution.datasources.jdbc.connection.BasicConnectionProvider.getConnection(BasicConnectionProvider.scala:49)
    at org.apache.spark.sql.execution.datasources.jdbc.connection.ConnectionProvider$.create(ConnectionProvider.scala:63)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$.$anonfun$createConnectionFactory$1(JdbcUtils.scala:62)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:48)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)
</code>```

I used the bitnami/postgres helm chart to install Postgres and bitnami/spark helm chart to install the spark cluster.

I am submitting my spark app using this command -

```<code>kubectl run spark-base -it --rm --labels="app=spark-client"  --image-pull-policy Never --restart Never   --image sparklayer:latest -- bash ./spark/bin/spark-submit --master spark://spark-cluster-master-svc:7077  --executor-memory 512MB   --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1,org.postgresql:postgresql:9.4.1209  ./spark-process.py
</code>```
```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import *

def foreach_batch_function(df, epoch_id):
    df.write.mode("append").format("jdbc").option("url", "jdbc:postgresql://postgres-postgresql.meetupstream.svc.cluster.local:5432/postgres")\
      .option("dbtable","postgres").option("user","postgres")\
      .option("password", "PV386AmWM0")\
      .option("driver", "org.postgresql.Driver")\
      .save()

def main():

    spark = SparkSession \
        .builder \
        .appName("SparkProcess") \
        .config("spark.dynamicAllocation.enabled", "false") \
        .config("spark.streaming.backpressure.enabled", "true") \
        .config("spark.streaming.kafka.maxRatePerPartition", 100) \
        .getOrCreate()

    df = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "kafka-local.meetupstream.svc.cluster.local:9092").option("subscribe", "meetup-rsvps-topic").option("startingOffsets", "earliest").load()

    df.writeStream.foreachBatch(foreach_batch_function).start().awaitTermination()

if __name__ == '__main__':
    main()
</code>```

Here is some info I got about Postgres after installing it from the helm chart.

```<code>PostgreSQL can be accessed via port 5432 on the following DNS names from within your cluster:

    postgres-postgresql.meetupstream.svc.cluster.local - Read/Write connection
</code>```

Note that I'm able to access the postgre database using this command -

```<code>kubectl run postgres-postgresql-client --rm --tty -i --restart='Never' --namespace meetupstream --image docker.io/bitnami/postgresql:15.1.0-debian-11-r7 --env="PGPASSWORD=$POSTGRES_PASSWORD"       --command -- psql --host postgres-postgresql -U postgres -d postgres -p 5432
</code>```

But when I try to connect to Postgres database from spark it shows me error.

Body:
I am trying to connect to Postgres from PySpark. Both Postgres and PySpark are running on Kubernetes. Here is the error log -

Traceback (most recent call last):
  File "/./spark-process.py", line 149, in <module>
    main()
  File "/./spark-process.py", line 75, in main
    df.writeStream.foreachBatch(foreach_batch_function).start().awaitTermination()
  File "/spark/python/lib/pyspark.zip/pyspark/sql/streaming.py", line 101, in awaitTermination
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 117, in deco
pyspark.sql.utils.StreamingQueryException22/12/21 13:42:41 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20221221134121-0029/6 is now RUNNING
: An exception was raised by the Python Proxy. Return Message: Traceback (most recent call last):
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 2442, in _call_proxy
    return_value = getattr(self.pool[obj_id], method)(*params)
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 196, in call
    raise e
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 193, in call
    self.func(DataFrame(jdf, self.sql_ctx), batch_id)
  File "/./spark-process.py", line 45, in foreach_batch_function
    .option("driver", "org.postgresql.Driver")\
  File "/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 1107, in save
    self._jwrite.save()
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 111, in deco
    return f(*a, **kw)
  File "/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o60.save.
: org.postgresql.util.PSQLException: The authentication type 10 is not supported. Check that you have configured the pg_hba.conf file to include the client's IP address or subnet, and that it is using an authentication scheme supported by the driver.
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:642)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:223)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:67)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:212)
    at org.postgresql.Driver.makeConnection(Driver.java:407)
    at org.postgresql.Driver.connect(Driver.java:275)
    at org.apache.spark.sql.execution.datasources.jdbc.connection.BasicConnectionProvider.getConnection(BasicConnectionProvider.scala:49)
    at org.apache.spark.sql.execution.datasources.jdbc.connection.ConnectionProvider$.create(ConnectionProvider.scala:63)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$.$anonfun$createConnectionFactory$1(JdbcUtils.scala:62)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:48)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)

I used the bitnami/postgres helm chart to install Postgres and bitnami/spark helm chart to install the spark cluster.

I am submitting my spark app using this command -

kubectl run spark-base -it --rm --labels="app=spark-client"  --image-pull-policy Never --restart Never   --image sparklayer:latest -- bash ./spark/bin/spark-submit --master spark://spark-cluster-master-svc:7077  --executor-memory 512MB   --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1,org.postgresql:postgresql:9.4.1209  ./spark-process.py

from pyspark.sql import SparkSession
from pyspark.sql.functions import *

def foreach_batch_function(df, epoch_id):
    df.write.mode("append").format("jdbc").option("url", "jdbc:postgresql://postgres-postgresql.meetupstream.svc.cluster.local:5432/postgres")\
      .option("dbtable","postgres").option("user","postgres")\
      .option("password", "PV386AmWM0")\
      .option("driver", "org.postgresql.Driver")\
      .save()

def main():

    spark = SparkSession \
        .builder \
        .appName("SparkProcess") \
        .config("spark.dynamicAllocation.enabled", "false") \
        .config("spark.streaming.backpressure.enabled", "true") \
        .config("spark.streaming.kafka.maxRatePerPartition", 100) \
        .getOrCreate()

    df = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "kafka-local.meetupstream.svc.cluster.local:9092").option("subscribe", "meetup-rsvps-topic").option("startingOffsets", "earliest").load()

    df.writeStream.foreachBatch(foreach_batch_function).start().awaitTermination()

if __name__ == '__main__':
    main()

Here is some info I got about Postgres after installing it from the helm chart.

PostgreSQL can be accessed via port 5432 on the following DNS names from within your cluster:

    postgres-postgresql.meetupstream.svc.cluster.local - Read/Write connection

Note that I'm able to access the postgre database using this command -

kubectl run postgres-postgresql-client --rm --tty -i --restart='Never' --namespace meetupstream --image docker.io/bitnami/postgresql:15.1.0-debian-11-r7 --env="PGPASSWORD=$POSTGRES_PASSWORD"       --command -- psql --host postgres-postgresql -U postgres -d postgres -p 5432

But when I try to connect to Postgres database from spark it shows me error.


问:
Object Slicing in C++
I have 3 classes:

GameInfo, GameInfoFootball and GameInfoBasketball, the last of 2 of those inherit from GameInfo. GameInfo classes should be able to store Players -> Basketball players and Football Players in the vector team1 and vector team2 described below.

In GameInfo I have the following:

```<code>class GameInfo {
public:
    vector<Player*> &getTeam1();
    vector<Player*> &getTeam2();
protected:
    vector<Player*> team1;
    vector<Player*> team2; // players in team 2
    vector<Player*> team1Sup; // players in team 1
    vector<Player*> team2Sup; // players in team 2
</code>```

I would love to be able to add BasketballPlayers and FootballPlayers to the vector<Player*> without them being sliced to Player. I used a vector of pointers as I read somewhere here, but the object still gets sliced. For example, here's the BasketBallPlayer class:

```<code>class PlayerBasketball : public Player{
public:
    int getTempoEntrou() const;
    int getTempoSaiu() const;
    int getTotalPontos() const;
    PosicaoBAS getPos() const;
    PlayerBasketball(string nome, PosicaoBAS pos);
    void point();
</code>```

Whenever I fill the vector<Player*> with BasketBallPlayers references I am unable to access specific BasketBallPlayers methods/atributes. Can someone explain me what's going on?

This is the code that adds Players to the vector:

```<code>PlayerFootball p = PlayerFootball(split(line, ",", true),
                                  convertStringInEnumFUT(split(line, ",", false)));

GameInfo::addPlayerTitu("team1", Player *p)
</code>```
```<code>void GameInfo::addPlayerTitu(string team, Player *p) {
    if (team == "team1") {
        team1.emplace_back(p);
    } else if (team == "team2") {
        team2.emplace_back(p);
    }
}
</code>```

I tried mainly to use Base class pointers in the vector, but I still cannot access derived class specific methods, like getTempoEntrou(), only the Player methods.

Title: Object Slicing in C++

Body:
I have 3 classes:

GameInfo, GameInfoFootball and GameInfoBasketball, the last of 2 of those inherit from GameInfo. GameInfo classes should be able to store Players -> Basketball players and Football Players in the vector team1 and vector team2 described below.

In GameInfo I have the following:

class GameInfo {
public:
    vector<Player*> &getTeam1();
    vector<Player*> &getTeam2();
protected:
    vector<Player*> team1;
    vector<Player*> team2; // players in team 2
    vector<Player*> team1Sup; // players in team 1
    vector<Player*> team2Sup; // players in team 2

I would love to be able to add BasketballPlayers and FootballPlayers to the vector<Player*> without them being sliced to Player. I used a vector of pointers as I read somewhere here, but the object still gets sliced. For example, here's the BasketBallPlayer class:

class PlayerBasketball : public Player{
public:
    int getTempoEntrou() const;
    int getTempoSaiu() const;
    int getTotalPontos() const;
    PosicaoBAS getPos() const;
    PlayerBasketball(string nome, PosicaoBAS pos);
    void point();

Whenever I fill the vector<Player*> with BasketBallPlayers references I am unable to access specific BasketBallPlayers methods/atributes. Can someone explain me what's going on?

This is the code that adds Players to the vector:

PlayerFootball p = PlayerFootball(split(line, ",", true),
                                  convertStringInEnumFUT(split(line, ",", false)));

GameInfo::addPlayerTitu("team1", Player *p)

void GameInfo::addPlayerTitu(string team, Player *p) {
    if (team == "team1") {
        team1.emplace_back(p);
    } else if (team == "team2") {
        team2.emplace_back(p);
    }
}

I tried mainly to use Base class pointers in the vector, but I still cannot access derived class specific methods, like getTempoEntrou(), only the Player methods.


问:
Maven/Gradle submodule equivalent for python projects
Motivation:
I am developing a few python packages libraries with the following dependency tree:

```<code>bootstrap_library
├── library_a
│   └── library_utils
├── library_b
│   └── library_utils
└── library_utils
</code>```

Each library has a separate project, and separate pyproject.toml configuration (along with poetry). A consequence of rapid development is that if I have to make change in lower dependencies, I have to reinstall the newer versions of the library in other libraries, make changes there as well, and repeat the procedure. This along with the slow dependency resolution times for poetry and private repositories is VERY tedious and time consuming.

Maven/Gradle projects follow similar structure:

```<code>project
├── module_client
│   ├── src
│   └── [pom.xml|build.gradle]
├── module_server
│   ├── src
│   └── [pom.xml|build.gradle]
├── module_core
│   ├── src
│   └── [pom.xml|build.gradle]
└── [pom.xml|build.gradle]
</code>```

Using this structure modules inside a project act as smaller subprojects and can depend on sibling modules.
Version can also be shared my modules
A build command like mvn package will build all submodules into seperate jars/artifacts at once

I need to satisfy these goals:

A python project with provision of sub-projects

A way to depend on sibling sub-projects that is present in the project as it is.

Build the project so that all sub-project wheels/distributions are built together

Is there a similar way to setup a python project using pyproject.toml and setup.cfg that fulfills these goals?
If not, are there any tools that can support/scaffold such types of projects?

Body:
Motivation:
I am developing a few python packages libraries with the following dependency tree:

bootstrap_library
├── library_a
│   └── library_utils
├── library_b
│   └── library_utils
└── library_utils

Each library has a separate project, and separate pyproject.toml configuration (along with poetry). A consequence of rapid development is that if I have to make change in lower dependencies, I have to reinstall the newer versions of the library in other libraries, make changes there as well, and repeat the procedure. This along with the slow dependency resolution times for poetry and private repositories is VERY tedious and time consuming.

Maven/Gradle projects follow similar structure:

project
├── module_client
│   ├── src
│   └── [pom.xml|build.gradle]
├── module_server
│   ├── src
│   └── [pom.xml|build.gradle]
├── module_core
│   ├── src
│   └── [pom.xml|build.gradle]
└── [pom.xml|build.gradle]

Using this structure modules inside a project act as smaller subprojects and can depend on sibling modules.
Version can also be shared my modules
A build command like mvn package will build all submodules into seperate jars/artifacts at once

I need to satisfy these goals:

A python project with provision of sub-projects

A way to depend on sibling sub-projects that is present in the project as it is.

Build the project so that all sub-project wheels/distributions are built together

Is there a similar way to setup a python project using pyproject.toml and setup.cfg that fulfills these goals?
If not, are there any tools that can support/scaffold such types of projects?


问:
Devops publish test results when the unit tests fails
I'd like to publish the result of the unit tests in Azure Devops

When the tests pass all works nice, the problem is when some test fails, becuase de Docker image is not generate and I can`t get the trx file.

I see a lot of samples, and all the people configure the same way the Dockerfile and Azure Pipeline yaml, but I don't know what I have wrong.

Here an extract of my Dockerfile:

```<code>RUN dotnet restore "IESA.TC.Invoices/IESA.TC.Invoices.csproj" COPY . .

FROM build AS test LABEL test=true WORKDIR /src/IESA.TC.Invoices.Tests RUN dotnet test -c Release --logger trx

FROM build AS publish WORKDIR "/src/IESA.TC.Invoices" RUN dotnet publish "IESA.TC.Invoices.csproj" -c Release -o /app/publish

FROM base AS final WORKDIR /app COPY --from=publish /app/publish . COPY --from=test /src/IESA.TC.Invoices.Tests/TestResults ./TestResults
</code>```

Here yaml file:

```<code>
- stage: Build_Back_NewAKS
  displayName: Back - Build and push stage
  jobs:
  - job: Build
    displayName: Build
    pool: Dani test
    steps:
    - task: Docker@2
      inputs:
        containerRegistry: $(dockerRegistryServiceConnectionAcrack)
        repository: $(imageRepositoryBack)
        command: 'build'
        Dockerfile: $(dockerfilePathBack)

    - pwsh: |
       $id=docker images --filter "label=test=true"  -q | Select-Object -First 1
       docker create --name testinvoices $id
       docker cp testinvoices:/app/TestResults ./TestResults
       docker rm testinvoices
       condition: succeededOrFailed()
       displayName: 'Copy test results'

- task: PublishTestResults@2
  condition: always()
  inputs:
    testResultsFormat: 'VSTest'
    testResultsFiles: '**/*.trx'
    searchFolder: '$(System.DefaultWorkingDirectory)/TestResults'
  displayName: 'Publish test results'
</code>```

The docker build task ends with this error:

```<code>#19 16.74 Failed!  - Failed:     1, Passed:   128, Skipped:     0, Total:   129, Duration: 1 s - /src/IESA.TC.Invoices.Tests/bin/Release/net6.0/IESA.TC.Invoices.Tests.dll (net6.0) #19 ERROR: executor failed running [/bin/sh -c dotnet test -c Release --logger trx]: exit code: 1

[test 2/2] RUN dotnet test -c Release --logger trx:

executor failed running [/bin/sh -c dotnet test -c Release --logger trx]: exit code: 1 ##[error]The process 'C:\Program Files\Docker\Docker\resources\bin\docker.exe' failed with exit code 1
</code>```

The next step is unable to get the image

```<code>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent_work_temp\0f7433c8-e7e9-491e-bfc7-ba396cb81e70.ps1'" "docker create" requires at least 1 argument. See 'docker create --help'.

ocker create [OPTIONS] IMAGE [COMMAND] [ARG...]

Create a new container
Error: No such container:path: testinvoices:/app/TestResults
Error: No such container: testinvoices
</code>```

I tried to change "dotnet test run command " in Dockerfile to return exit code 0, but in this case I don't know when the tests fails.

Body:
I'd like to publish the result of the unit tests in Azure Devops

When the tests pass all works nice, the problem is when some test fails, becuase de Docker image is not generate and I can`t get the trx file.

I see a lot of samples, and all the people configure the same way the Dockerfile and Azure Pipeline yaml, but I don't know what I have wrong.

Here an extract of my Dockerfile:

RUN dotnet restore "IESA.TC.Invoices/IESA.TC.Invoices.csproj" COPY . .

FROM build AS test LABEL test=true WORKDIR /src/IESA.TC.Invoices.Tests RUN dotnet test -c Release --logger trx

FROM build AS publish WORKDIR "/src/IESA.TC.Invoices" RUN dotnet publish "IESA.TC.Invoices.csproj" -c Release -o /app/publish

FROM base AS final WORKDIR /app COPY --from=publish /app/publish . COPY --from=test /src/IESA.TC.Invoices.Tests/TestResults ./TestResults

Here yaml file:

- stage: Build_Back_NewAKS
  displayName: Back - Build and push stage
  jobs:
  - job: Build
    displayName: Build
    pool: Dani test
    steps:
    - task: Docker@2
      inputs:
        containerRegistry: $(dockerRegistryServiceConnectionAcrack)
        repository: $(imageRepositoryBack)
        command: 'build'
        Dockerfile: $(dockerfilePathBack)

    - pwsh: |
       $id=docker images --filter "label=test=true"  -q | Select-Object -First 1
       docker create --name testinvoices $id
       docker cp testinvoices:/app/TestResults ./TestResults
       docker rm testinvoices
       condition: succeededOrFailed()
       displayName: 'Copy test results'

- task: PublishTestResults@2
  condition: always()
  inputs:
    testResultsFormat: 'VSTest'
    testResultsFiles: '**/*.trx'
    searchFolder: '$(System.DefaultWorkingDirectory)/TestResults'
  displayName: 'Publish test results'

The docker build task ends with this error:

#19 16.74 Failed!  - Failed:     1, Passed:   128, Skipped:     0, Total:   129, Duration: 1 s - /src/IESA.TC.Invoices.Tests/bin/Release/net6.0/IESA.TC.Invoices.Tests.dll (net6.0) #19 ERROR: executor failed running [/bin/sh -c dotnet test -c Release --logger trx]: exit code: 1

[test 2/2] RUN dotnet test -c Release --logger trx:

executor failed running [/bin/sh -c dotnet test -c Release --logger trx]: exit code: 1 ##[error]The process 'C:\Program Files\Docker\Docker\resources\bin\docker.exe' failed with exit code 1

The next step is unable to get the image

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent_work_temp\0f7433c8-e7e9-491e-bfc7-ba396cb81e70.ps1'" "docker create" requires at least 1 argument. See 'docker create --help'.

ocker create [OPTIONS] IMAGE [COMMAND] [ARG...]

Create a new container
Error: No such container:path: testinvoices:/app/TestResults
Error: No such container: testinvoices

I tried to change "dotnet test run command " in Dockerfile to return exit code 0, but in this case I don't know when the tests fails.


问:
Handle http_proxy and https_proxy with urllib3
I intend to read env variables http_request and https_request, and use urllib3 to handle proxies.

Need to handle cases where none, either or both the env vars are present

Sounds like ProxyManager is ideal choice for this, but I have below issues:

ProxyManager doesn't support proxy_url=None. So, I need to manually check if either or both of https?_proxy are missing in env and if so, fall back to use PoolManager. Is there any better way to handle such cases within ProxyManager?

ProxyManager takes a param proxy_url. I couldn't find anything like ssl_proxy_url. So, how do we pass both http_proxy and https_proxy urls then?

ProxyManager doesn't honor the creds when the url is of form https://username:password@proxy.example.com:port . I need to parse the url, extract the creds and then build headers for the Basic Auth component. Is there a better way to handle it?

I am aware that requests handles all these issues, but due to some constraints, need to use urllib3.


问:
Client in java not receving the data, sent by a python server
So I am building a to-do app, that should remind the user of the tasks by location (when he's close it'll send all the tasks that are set to the location).

In the main screen of the app, I have a list view of all the locations the user added. I am saving them in the database as a json string.

The user log in's in the login activity screen, and everything works fine - the data is sent to the server, the server checks if the username and password are correct and sents an appropriate message.

Then, it creates an intent to move to the main screen of the app I described earlier. In the oncreate funciton, I create a listview, and pull the locations that belong to the user connected from the DB. But - the java client side for some reason, doesn't receive it.

I'll provide here my code and explain:

```<code>package com.example.yearprojectfinal;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketTask extends AsyncTask<String, Void, String>
{
    private final static String IP_ADDRESS = "192.168.1.218";

    private final static int PORT = 50001;

    private Socket socket;
    private String sendingStr = "";
    private String receivingStr = "";

    public SocketTask(String str1) {
        this.sendingStr = str1;
    }

    @Override
    protected String doInBackground(String... arrStrings)
    {
        try
        {
            this.socket = new Socket(IP_ADDRESS, PORT);
            send(this.sendingStr);
            receive();
            this.socket.close();
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
        return this.receivingStr;
    }

    private void send(String sendingStr)
    {
        try
        {
            OutputStream outputStream = this.socket.getOutputStream();
            byte[] bytes = sendingStr.getBytes(StandardCharsets.UTF_8);
            outputStream.write(bytes);
            outputStream.flush();
            System.out.println("sent");
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
    }

    private void receive()
    {
        try
        {
            System.out.println("trying to receive");
            InputStream inputStream = socket.getInputStream();
            System.out.println(inputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int c;
            while ((c = inputStream.read()) != -1)
            {
                baos.write((char) c);
            }
            System.out.println("hello");
            byte[] bytes = baos.toByteArray();
            receivingStr = new String(bytes, StandardCharsets.UTF_8);
            inputStream.close();
            Log.d("str received", receivingStr);
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
    }
}
</code>```

This is the class I use to send data and receive data from the server. It works fine with everything else other than what I explained.
I use it with this function:

```<code>private String sendAddLocationDataToServer(String strToSend)
    {
        try
        {
            SocketTask send1 = new SocketTask(strToSend);
            String strReceived = send1.execute().get();
            return strReceived;
        }

        catch (ExecutionException | InterruptedException e)
        {
            Log.e("Exception", e.toString());
        }
        return "something went wrong with execution";
    }
</code>```

The function creates a new SocketTask class, sends and receives the data.
Then returns the received data.

I call the function like so:

```<code>public ArrayList<Location> getLocationListForUser()
    {
        String dataStrToSend = "requesting location list," + connectedUsername;

        // send length header
        String resultStr = sendAddLocationDataToServer(
                String.format("%05d", activityName.length()) + activityName
                        + String.format("%05d", dataStrToSend.length()) + dataStrToSend);

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Location>>(){}.getType();
        ArrayList<Location> locationsListByUsername = gson.fromJson(resultStr, listType);

        return locationsListByUsername;
    }
</code>```

In the python side, everything works fine - i checked it, printed, logged, and it sends everything as needed.
But when it comes to the java side, the program seems to break when I try to receive a string, here (In the receive function of the SocketTask class):

```<code>int c;
while ((c = inputStream.read()) != -1)
{
    baos.write((char) c);
}
</code>```

It looks like the inputStream.read() function throws and exception somewhere in it. But I do not see anything in the logcat, except for:

2022-12-21 15:55:43.640 14239-14242/com.example.yearprojectfinal I/earprojectfina: Thread[3,tid=14242,WaitingInMainSignalCatcherLoop,Thread*=0x7a3c35e33a60,peer=0x13200238,"Signal Catcher"]: reacting to signal 3

2022-12-21 15:55:43.640 14239-14242/com.example.yearprojectfinal I/earprojectfina:

2022-12-21 15:55:43.696 14239-14242/com.example.yearprojectfinal I/earprojectfina: Wrote stack traces to tombstoned

I have no idea of how to solve it, or how to troubleshoot it anymore.

Any help or idea would be greatly appreciated.

Body:
So I am building a to-do app, that should remind the user of the tasks by location (when he's close it'll send all the tasks that are set to the location).

In the main screen of the app, I have a list view of all the locations the user added. I am saving them in the database as a json string.

The user log in's in the login activity screen, and everything works fine - the data is sent to the server, the server checks if the username and password are correct and sents an appropriate message.

Then, it creates an intent to move to the main screen of the app I described earlier. In the oncreate funciton, I create a listview, and pull the locations that belong to the user connected from the DB. But - the java client side for some reason, doesn't receive it.

I'll provide here my code and explain:

package com.example.yearprojectfinal;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketTask extends AsyncTask<String, Void, String>
{
    private final static String IP_ADDRESS = "192.168.1.218";

    private final static int PORT = 50001;

    private Socket socket;
    private String sendingStr = "";
    private String receivingStr = "";

    public SocketTask(String str1) {
        this.sendingStr = str1;
    }

    @Override
    protected String doInBackground(String... arrStrings)
    {
        try
        {
            this.socket = new Socket(IP_ADDRESS, PORT);
            send(this.sendingStr);
            receive();
            this.socket.close();
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
        return this.receivingStr;
    }

    private void send(String sendingStr)
    {
        try
        {
            OutputStream outputStream = this.socket.getOutputStream();
            byte[] bytes = sendingStr.getBytes(StandardCharsets.UTF_8);
            outputStream.write(bytes);
            outputStream.flush();
            System.out.println("sent");
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
    }

    private void receive()
    {
        try
        {
            System.out.println("trying to receive");
            InputStream inputStream = socket.getInputStream();
            System.out.println(inputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int c;
            while ((c = inputStream.read()) != -1)
            {
                baos.write((char) c);
            }
            System.out.println("hello");
            byte[] bytes = baos.toByteArray();
            receivingStr = new String(bytes, StandardCharsets.UTF_8);
            inputStream.close();
            Log.d("str received", receivingStr);
        }
        catch (Exception e)
        {
            Log.e("Exception", e.toString());
        }
    }
}

This is the class I use to send data and receive data from the server. It works fine with everything else other than what I explained.
I use it with this function:

private String sendAddLocationDataToServer(String strToSend)
    {
        try
        {
            SocketTask send1 = new SocketTask(strToSend);
            String strReceived = send1.execute().get();
            return strReceived;
        }

        catch (ExecutionException | InterruptedException e)
        {
            Log.e("Exception", e.toString());
        }
        return "something went wrong with execution";
    }

The function creates a new SocketTask class, sends and receives the data.
Then returns the received data.

I call the function like so:

public ArrayList<Location> getLocationListForUser()
    {
        String dataStrToSend = "requesting location list," + connectedUsername;

        // send length header
        String resultStr = sendAddLocationDataToServer(
                String.format("%05d", activityName.length()) + activityName
                        + String.format("%05d", dataStrToSend.length()) + dataStrToSend);

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Location>>(){}.getType();
        ArrayList<Location> locationsListByUsername = gson.fromJson(resultStr, listType);

        return locationsListByUsername;
    }

In the python side, everything works fine - i checked it, printed, logged, and it sends everything as needed.
But when it comes to the java side, the program seems to break when I try to receive a string, here (In the receive function of the SocketTask class):

int c;
while ((c = inputStream.read()) != -1)
{
    baos.write((char) c);
}

It looks like the inputStream.read() function throws and exception somewhere in it. But I do not see anything in the logcat, except for:

2022-12-21 15:55:43.640 14239-14242/com.example.yearprojectfinal I/earprojectfina: Thread[3,tid=14242,WaitingInMainSignalCatcherLoop,Thread*=0x7a3c35e33a60,peer=0x13200238,"Signal Catcher"]: reacting to signal 3

2022-12-21 15:55:43.640 14239-14242/com.example.yearprojectfinal I/earprojectfina:

2022-12-21 15:55:43.696 14239-14242/com.example.yearprojectfinal I/earprojectfina: Wrote stack traces to tombstoned

I have no idea of how to solve it, or how to troubleshoot it anymore.

Any help or idea would be greatly appreciated.


问:
Telegram Bot: Send A message to multiple chat ids
I've been trying to send a message to multiple chat IDs using telegram bot

I've this code

```<code>from telegram import Bot, InputMediaDocument

BOT_TOKEN = "xxxxxx"
CHAT_IDs = [-1001xxx,-100177xxx,-100188xxx]

for CHAT_ID in CHAT_IDs:
  x
  x
  x
  bot.send_media_group(CHAT_ID, media=media_group)
</code>```

The problem is message is only been sent to the last chat id in CHAT_IDs  array and skipping all infront

[I've referred this, but not much helpful](Telegram BotApi, Send message to multiple chat_id

Body:
I've been trying to send a message to multiple chat IDs using telegram bot

I've this code

from telegram import Bot, InputMediaDocument

BOT_TOKEN = "xxxxxx"
CHAT_IDs = [-1001xxx,-100177xxx,-100188xxx]

for CHAT_ID in CHAT_IDs:
  x
  x
  x
  bot.send_media_group(CHAT_ID, media=media_group)

The problem is message is only been sent to the last chat id in CHAT_IDs  array and skipping all infront

[I've referred this, but not much helpful](Telegram BotApi, Send message to multiple chat_id


问:
Retrieving PPI from byte[] or file directly
I read How to get the dpi of an image(Java) and found two ways: iterate over IIOMetadata Node list and calculate xDpi; another alternative is to use org.apache.sanselan lib, which seems outdated, unsupported and obtaining known CVE's. Any reasonable alternatives I missed?</p>


问:
Argon2 hasher not releasing memory
I searched for one of the best hash functions for passwords and I found Argon2.
But implementing it I crashed my dev server, then analyzed and I found out that the memory is not released (not immediately):

This is the class I have:

```<code>public class Argon2Hasher
    {
        public byte[] CreateSalt()
        {
            byte[] randomNumber = new byte[16];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
            }
            return randomNumber;
        }

        public byte[] HashPassword(string password, byte[] salt)
        {
            byte[] result = null;
            using (Argon2id argon2 = new Argon2id(Encoding.UTF8.GetBytes(password)))
            {
                argon2.Salt = salt;
                argon2.DegreeOfParallelism = 2; //cores
                argon2.Iterations = 8;
                argon2.MemorySize = 1024 * 256; //256 MB
                result = argon2.GetBytes(16);
            }
            //GC.Collect();
            return result;
        }
    }
</code>```

As you can see CG.Collect(); is commented, I tested with it and looks okay, the memory is released immediately, if I dont use GC.Collect();, sometimes is okay sometimes the memory is not released for multiple minutes, this makes it very bad for production use, actually for any use, since for example if you try multiple logins you will most probably use all of the RAM.

Where is the problem, is it in my implementation?

Any help is welcome.

Title: Argon2 hasher not releasing memory

Body:
I searched for one of the best hash functions for passwords and I found Argon2.
But implementing it I crashed my dev server, then analyzed and I found out that the memory is not released (not immediately):

This is the class I have:

public class Argon2Hasher
    {
        public byte[] CreateSalt()
        {
            byte[] randomNumber = new byte[16];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
            }
            return randomNumber;
        }

        public byte[] HashPassword(string password, byte[] salt)
        {
            byte[] result = null;
            using (Argon2id argon2 = new Argon2id(Encoding.UTF8.GetBytes(password)))
            {
                argon2.Salt = salt;
                argon2.DegreeOfParallelism = 2; //cores
                argon2.Iterations = 8;
                argon2.MemorySize = 1024 * 256; //256 MB
                result = argon2.GetBytes(16);
            }
            //GC.Collect();
            return result;
        }
    }

As you can see CG.Collect(); is commented, I tested with it and looks okay, the memory is released immediately, if I dont use GC.Collect();, sometimes is okay sometimes the memory is not released for multiple minutes, this makes it very bad for production use, actually for any use, since for example if you try multiple logins you will most probably use all of the RAM.

Where is the problem, is it in my implementation?

Any help is welcome.