问:
How to pivot wider in SQL or use a more "dynamic" form of the LEAD function?
I have a table that looks as follows:

```<code>Policy Number Benefit Code Transaction Code
1             A            2
1             B            1
2             A            3
3             A            2
1             C            2
</code>```

For analysis purposes, it would be much more convenient to have the table in the following form:

```<code>PN BC 1 TC 1 BC 2 TC 2 BC 3 TC 3
1  A    2    B    1    C    2
2  A    3    NULL NULL NULL NULL
3  A    2    NULL NULL NULL NULL
</code>```

I believe this can be done, for example, in R using the tidyverse package, where the concept is basically pivoting the table from long-form to wide-form. Now, I know that I could possibly use the LEAD function in SQL, but the problem/issue is that I do not know how many benefit codes and transaction codes each policy has (i.e. they are not fixed).

Thus, my query is:

How can I "pivot wider" my table to achieve something like the above?

Other than "pivoting wider", is there a more dynamic form of the LEAD function in SQL, where it takes all subsequent rows of a group (in my case, each policy number) and puts them in new columns?

Any intuitive explanations or suggestions will be greatly appreciated :)

Body:
I have a table that looks as follows:

Policy Number Benefit Code Transaction Code
1             A            2
1             B            1
2             A            3
3             A            2
1             C            2

For analysis purposes, it would be much more convenient to have the table in the following form:

PN BC 1 TC 1 BC 2 TC 2 BC 3 TC 3
1  A    2    B    1    C    2
2  A    3    NULL NULL NULL NULL
3  A    2    NULL NULL NULL NULL

I believe this can be done, for example, in R using the tidyverse package, where the concept is basically pivoting the table from long-form to wide-form. Now, I know that I could possibly use the LEAD function in SQL, but the problem/issue is that I do not know how many benefit codes and transaction codes each policy has (i.e. they are not fixed).

Thus, my query is:

How can I "pivot wider" my table to achieve something like the above?

Other than "pivoting wider", is there a more dynamic form of the LEAD function in SQL, where it takes all subsequent rows of a group (in my case, each policy number) and puts them in new columns?

Any intuitive explanations or suggestions will be greatly appreciated :)


来源: stackexchange

问:
SplashScreen View to TabView View in SwiftUI
I am having difficulty transitioning from my SplashScreen View to my TabView View.  I found that I could transition any of my other views, but crash occurs with transition to TabView.

SplashScreen code (from youTube video)

```<code>struct SplashScreenView: View {

    @State private var isActive = false
    @State private var size = 0.8
    @State private var opacity = 0.5

    var body: some View {

        if isActive == true {
            TabView()
        }
        else {
            VStack {
                VStack{
                    Image(systemName: "hare.fill")
                        .font(.system(size: 80))
                        .foregroundColor(.red)
                    Text("IALVS App")
                        .font(Font.custom("Baskerville-Bold", size: 26))
                        .foregroundColor(.black.opacity(0.80))
                }
                .scaleEffect(size)
                .opacity(opacity)
                .onAppear{
                    withAnimation(.easeIn(duration: 1.2)) {
                        self.size = 0.9
                        self.opacity = 1.0
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    withAnimation {
                        self.isActive = true
                    }
                }
            }
        }
    }
}
</code>```

TabView code

```<code>struct MembersTabView: View {

    @EnvironmentObject var modelMember:MemberModel

    var body: some View {
        VStack{

            TabView {

                MembersListView()
                    .tabItem {
                        Image(systemName: "person.2")
                    }

                MapView()
                    .tabItem {
                        Image(systemName: "map")
                    }

                MainCalcView()
                    .tabItem {
                        Image(systemName: "wrench.adjustable.fill")
                    }
            }
        }

    }
}
</code>```

Tried transitioning to other views.  Worked fine.

ContentLicense: CC BY-SA 4.0

Body:
I am having difficulty transitioning from my SplashScreen View to my TabView View.  I found that I could transition any of my other views, but crash occurs with transition to TabView.

SplashScreen code (from youTube video)

struct SplashScreenView: View {

    @State private var isActive = false
    @State private var size = 0.8
    @State private var opacity = 0.5

    var body: some View {

        if isActive == true {
            TabView()
        }
        else {
            VStack {
                VStack{
                    Image(systemName: "hare.fill")
                        .font(.system(size: 80))
                        .foregroundColor(.red)
                    Text("IALVS App")
                        .font(Font.custom("Baskerville-Bold", size: 26))
                        .foregroundColor(.black.opacity(0.80))
                }
                .scaleEffect(size)
                .opacity(opacity)
                .onAppear{
                    withAnimation(.easeIn(duration: 1.2)) {
                        self.size = 0.9
                        self.opacity = 1.0
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    withAnimation {
                        self.isActive = true
                    }
                }
            }
        }
    }
}

TabView code

struct MembersTabView: View {

    @EnvironmentObject var modelMember:MemberModel

    var body: some View {
        VStack{

            TabView {

                MembersListView()
                    .tabItem {
                        Image(systemName: "person.2")
                    }

                MapView()
                    .tabItem {
                        Image(systemName: "map")
                    }

                MainCalcView()
                    .tabItem {
                        Image(systemName: "wrench.adjustable.fill")
                    }
            }
        }

    }
}

Tried transitioning to other views.  Worked fine.


问:
How can I do the reset event? Controllers that can move in 4 directions and can be reset when they reach the end. React - Next.js
I made it move in 4 directions, but when it reaches the end of the directions, I want it to reset and return to the centre, Can anyone help me ?

CodeSandbox --> https://codesandbox.io/p/sandbox/empty-leftpad-2ku87j


问:
tippy.js html content / multiline text
I am having problems with tippy.js tooltip and multiline html content. I cannot get the line breaks to work at all. HTML template below:

```<code><div id="div_id_criticality" class="form-group">
  <label for="id_criticality" class="requiredField">
  Criticality<span class="asteriskField">*</span>
  </label>
  <span class="formHelp" tippy-message="tippy-criticality" id="formHelp-criticality"><i class="fas fa-question-circle"></i></span>
  <div>
    <select name="criticality" class="select form-control" required="" id="id_criticality">

      <option value="">-- Select criticality --</option>

        {% for key, value in criticality.items %}
          <option value="{{ key }}">{{ value }}</option>
        {% endfor %}

    </select>
  </div>
</div>

<div id="tippy-criticality" class="tippy-multiline" style="display: none;">
  Line 1<br>
  Line 2<br>
  Line 3<br>
  Line 4
</div>

<script>
  tippy('#formHelp-criticality', {
    content(reference) {
    const id = reference.getAttribute('tippy-message');
    const template = document.getElementById(id);
    return template.innerHTML;
    allowHTML=true;
    }
  });
</script>
</code>```

I also have CSS file containing:

```<code>.tippy-multiline {
    white-space:pre !important;
}
</code>```

Also tried:

```<code>.tippy-multiline {
    white-space:pre-wrap !important;
}
</code>```

What happens is that the tooltip shows single line of text "Line 1
Line 2
Line 3
Line 4".

What I am missing here?

Title: tippy.js html content / multiline text

Body:
I am having problems with tippy.js tooltip and multiline html content. I cannot get the line breaks to work at all. HTML template below:

  Criticality*

    <select name="criticality" class="select form-control" required="" id="id_criticality">

      <option value="">-- Select criticality --</option>

        {% for key, value in criticality.items %}
          <option value="{{ key }}">{{ value }}</option>
        {% endfor %}

    </select>

  Line 1

  Line 2

  Line 3

  Line 4

I also have CSS file containing:

.tippy-multiline {
    white-space:pre !important;
}

Also tried:

.tippy-multiline {
    white-space:pre-wrap !important;
}

What happens is that the tooltip shows single line of text "Line 1
Line 2
Line 3
Line 4".

What I am missing here?


问:
The push notification system handle for the registration is invalid
I have implemented push notifications in my ASP.ET Web API project. Push notifications are working almost for all devices but in some specific devices I am getting an exception like this 'The push notification system handle for the registration is invalid' along with PnsHandle and registration id. I do not know what is wrong. I have the correct deviceId which I am fetching from Db.

`
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["HubConnectionString"], ConfigurationManager.AppSettings["HubName"], true);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (!string.IsNullOrEmpty(mailInformation.DeviceId) && !string.IsNullOrEmpty(mailInformation.DeviceType))
{ var registationDescriptions = hub.GetRegistrationsByTagAsync(mailInformation.ToUserEmail, 100).Result; foreach (var registrationDescription in registationDescriptions)
{
await hub.DeleteRegistrationAsync(registrationDescription);

```<code>                    }

                  if (mailInformations.DeviceType.ToLower().Contains("android"))
                    {
                        var registeredNewDevice = hub.CreateGcmNativeRegistrationAsync(mailInformation.DeviceId, new[] { mailInformation.ToUserEmail }).Result;
                    }
                    else
                    {
                      var registeredNewDevice = hub.CreateAppleNativeRegistrationAsync(mailInformation.DeviceId.Replace("-", ""), new[] { mailInformation.ToUserEmail }).Result; }outcome = hub.SendAppleNativeNotificationAsync(jsonPayLoad, mailInformation.ToUserEmail).Result;
</code>```

`

Body:
I have implemented push notifications in my ASP.ET Web API project. Push notifications are working almost for all devices but in some specific devices I am getting an exception like this 'The push notification system handle for the registration is invalid' along with PnsHandle and registration id. I do not know what is wrong. I have the correct deviceId which I am fetching from Db.

`
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["HubConnectionString"], ConfigurationManager.AppSettings["HubName"], true);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (!string.IsNullOrEmpty(mailInformation.DeviceId) && !string.IsNullOrEmpty(mailInformation.DeviceType))
{ var registationDescriptions = hub.GetRegistrationsByTagAsync(mailInformation.ToUserEmail, 100).Result; foreach (var registrationDescription in registationDescriptions)
{
await hub.DeleteRegistrationAsync(registrationDescription);

                    }

                  if (mailInformations.DeviceType.ToLower().Contains("android"))
                    {
                        var registeredNewDevice = hub.CreateGcmNativeRegistrationAsync(mailInformation.DeviceId, new[] { mailInformation.ToUserEmail }).Result;
                    }
                    else
                    {
                      var registeredNewDevice = hub.CreateAppleNativeRegistrationAsync(mailInformation.DeviceId.Replace("-", ""), new[] { mailInformation.ToUserEmail }).Result; }outcome = hub.SendAppleNativeNotificationAsync(jsonPayLoad, mailInformation.ToUserEmail).Result;

`


问:
Is there any way to reduce multiple try catch conditions in ES6 js
Wanted to have simplified version of code using latest ES6 JS frameworks

```<code>async function ElementAttributeShouldBe(page, selector, attribute, attributeValue, fullMatch) {
    debugger
    let result = false
    let currentAttrValue
    try {
        currentAttrValue = await page.evaluate((_sel, _attr) => {
            let element = document.querySelector(_sel)
            return element.getAttribute(_attr)
        }, selector, attribute)
    } catch (error) {
        throw new Error(`Unable to fetch the attribute (${attribute}) value (${attributeValue}) on selector (${selector})`)
    }
    if (fullMatch == true && currentAttrValue != null) {
        try {
            currentAttrValue.toLocaleLowerCase() == attributeValue.toLocaleLowerCase() ? result = true : result = false
            assert.isTrue(result)

        } catch (error) {
            throw new Error(`Element attribute value is not expected for the selector ${selector}`)
        }
    }
    else {
        try {
            currentAttrValue.toLocaleLowerCase().includes(attributeValue.toLocaleLowerCase()) ? result = true : result = false
            assert.isTrue(result)
        } catch (error) {
            throw new Error(`Element attribute value do not have expected value for the selector ${selector}`)
        }
    }
}
</code>```

Was there any simplified way to reduce the number of try catch blocks. The above code is written using puppeteer and mocha for automation.

Body:
Wanted to have simplified version of code using latest ES6 JS frameworks

async function ElementAttributeShouldBe(page, selector, attribute, attributeValue, fullMatch) {
    debugger
    let result = false
    let currentAttrValue
    try {
        currentAttrValue = await page.evaluate((_sel, _attr) => {
            let element = document.querySelector(_sel)
            return element.getAttribute(_attr)
        }, selector, attribute)
    } catch (error) {
        throw new Error(`Unable to fetch the attribute (${attribute}) value (${attributeValue}) on selector (${selector})`)
    }
    if (fullMatch == true && currentAttrValue != null) {
        try {
            currentAttrValue.toLocaleLowerCase() == attributeValue.toLocaleLowerCase() ? result = true : result = false
            assert.isTrue(result)

        } catch (error) {
            throw new Error(`Element attribute value is not expected for the selector ${selector}`)
        }
    }
    else {
        try {
            currentAttrValue.toLocaleLowerCase().includes(attributeValue.toLocaleLowerCase()) ? result = true : result = false
            assert.isTrue(result)
        } catch (error) {
            throw new Error(`Element attribute value do not have expected value for the selector ${selector}`)
        }
    }
}

Was there any simplified way to reduce the number of try catch blocks. The above code is written using puppeteer and mocha for automation.


问:
I can not open a spesific vue project on Control panel either VS code
i try to open a vue project already exist but i can't do this. I already try npm commands like npm install, npm run serve, npm build, but still doesn't work. Can you help me?
This is error screen on terminal.</p>
```<code>npm install
npm install --force
npm run serve
//still doesn't work
</code>```

Body:
i try to open a vue project already exist but i can't do this. I already try npm commands like npm install, npm run serve, npm build, but still doesn't work. Can you help me?
This is error screen on terminal.

npm install
npm install --force
npm run serve
//still doesn't work


问:
Array in postgres with text values when inserting them gets wrapped in double quotes ("")
I wanted to use the SELECT ARRAY['foo','bar','foo bar','foo,bar','foo.bar'] and the output of it to insert into a field with datatype of text[]. But the out ut of the above SELECT ARRAY query gave me a strange response where the text with spaces/commas were present it wrapped them in double quotes. Any help how to get data without double quotes.

I have tried with ARRAY_AGG function too still the same response


问:
How to load base64 images from database and show them in Glide?
Could you please help me? I got a list of images from the database that come in base64 format. I need to show those images using Glide. How can I convert base64 format so that Glide could understand them? Thank you.</p>


问:
How can I add geographic information to the data for the entire Arctic?
I would like to add geographic information to this dataset hereand turn it into a geotiff. This dataset has data for the entire Arctic and a corresponding latlonmap in NETCDF format.
I tried gdal_translate but it did not work.

I have also listed the data on google drivetext

gdal_translate -of "GTiff" -a_srs EPSG:4326 -135.001 60.444 45.003 60.430 lead.tif out.tif

The coordinates for the four corners used in gdaltranslate were the upper left and lower right coordinates from latlonmap.nc

I tried EPSG:4326, but is it appropriate for the Arctic-wide dataset in the first place?


问:
HTTP/1.1 503 Service Unavailable upstream connect error or disconnect/reset before headers. reset reason: connection failure
We have Spring Boot applications which use Kubernetes and Istio. The application connects to AWS OpenSearch for CRUD functionality. Recently, the requests to OpenSearch started failing and we encountered this error repeatedly in the application logs:

method [POST], host [http://vpc-application-name.us-east-1.es.amazonaws.com], URI [/dummy/uri?param1=dummy1&param2=dummy2], status line [HTTP/1.1 503 Service Unavailable] upstream connect error or disconnect/reset before headers. reset reason: connection failure

When we tried to hit this URL through Postman, it was working. We also tried to bash into the Kubernetes pods of this service and tried to curl this URL from there, but we were getting proper response. So it looks like an issue from the Java side. When we restarted the pods, the error was gone.

What could have caused this error?
How to identify or narrow down the root cause of this issue?

I am fairly new to Istio, Kubernetes and AWS, and I do not know what to expect. Any help is appreciated.


问:
How can I stub default method with BDDMockito?
I have an interface with defaults method.

interface MyInterface {

    default ByteBuffer put(ByteBuffer buffer) {
        // ...
    }
}
```
<p>And I used to stub the method with the following code.</p>
<pre class="lang-java prettyprint-override"><code>        doAnswer(i -> {
            return buffer;
        }).when(spy).put(any());
</code>```

Now I'm trying to use BDDMockito.

```<code>            given(spy.put(any()))
                    .willAnswer(i -> {
                        ByteBuffer buffer = i.getArgument(0);
                        assert buffer != null;
                        print(buffer);
                        assert buffer.capacity() == BYTES;
                        assert buffer.limit() == buffer.capacity();
                        assert buffer.remaining() == BYTES;
                        buffer.position(buffer.limit());
                        return buffer;
                    });
</code>```

It seems that it calls the real method.

How can I fix this?

Body:
I have an interface with defaults method.

interface MyInterface {

    default ByteBuffer put(ByteBuffer buffer) {
        // ...
    }
}

And I used to stub the method with the following code.

        doAnswer(i -> {
            return buffer;
        }).when(spy).put(any());

Now I'm trying to use BDDMockito.

            given(spy.put(any()))
                    .willAnswer(i -> {
                        ByteBuffer buffer = i.getArgument(0);
                        assert buffer != null;
                        print(buffer);
                        assert buffer.capacity() == BYTES;
                        assert buffer.limit() == buffer.capacity();
                        assert buffer.remaining() == BYTES;
                        buffer.position(buffer.limit());
                        return buffer;
                    });

It seems that it calls the real method.

How can I fix this?


问:
Make "find and replace" both refer to normal lines of code and commented out lines of code
Using RStudio

If I mark/select the part of the code below that doesn't have a 2 in it...

```<code># hello
hello <- hello

# hello2
hello2 <- hello2
</code>```

...And I then use command + F to get the search up, search for hello and replace with goodbye (and tick off 'in selection', what I would expect to get is this...

```<code># goodbye
goodbye <- goodbye

# hello2
hello2 <- hello2
</code>```

... however, what I actually get, is this...

```<code># hello
goodbye <- goodbye

# hello2
hello2 <- hello2
</code>```

Why does the text after the # not get replaced?

Body:
Using RStudio

If I mark/select the part of the code below that doesn't have a 2 in it...

# hello
hello <- hello

# hello2
hello2 <- hello2

...And I then use command + F to get the search up, search for hello and replace with goodbye (and tick off 'in selection', what I would expect to get is this...

# goodbye
goodbye <- goodbye

# hello2
hello2 <- hello2

... however, what I actually get, is this...

# hello
goodbye <- goodbye

# hello2
hello2 <- hello2

Why does the text after the # not get replaced?


问:
Best way to find active JavaScript code in string of code with JavaScript?
I am working on project, where I am supposed to extract parameter of certain function for use in further logic. Due to limited access, I am only able to get stringified JavaScript script, that user is able to input into the website (yes, safety features are in place). I did not find better solution to this, than to scan that string either by regex, or character by character. But the issue I am facing is, that I need to find out which code is "active" (not commented, not in quotes etc.). I did not want to go down the route of something like (this is only mock):

/*
for character in string
  if(character === "/")
      if(nextCharacter === *)
          ingore until === star/
      if(nextCharacter === /)
          ignore until \r\n
  else if(character === "`")
      ingore until === `
  else if(character === "'")
      ingore until === '
  else if(character === `"`)
      ingore until === "
*/
```

Because it could stop working/become incomplete with every new version of ES and the solution overall seems too brute forcy and like something that JavaScript might have built in solution for.

Is there a better solution to this?

Body:
I am working on project, where I am supposed to extract parameter of certain function for use in further logic. Due to limited access, I am only able to get stringified JavaScript script, that user is able to input into the website (yes, safety features are in place). I did not find better solution to this, than to scan that string either by regex, or character by character. But the issue I am facing is, that I need to find out which code is "active" (not commented, not in quotes etc.). I did not want to go down the route of something like (this is only mock):

/*
for character in string
  if(character === "/")
      if(nextCharacter === *)
          ingore until === star/
      if(nextCharacter === /)
          ignore until \r\n
  else if(character === "`")
      ingore until === `
  else if(character === "'")
      ingore until === '
  else if(character === `"`)
      ingore until === "
*/

Because it could stop working/become incomplete with every new version of ES and the solution overall seems too brute forcy and like something that JavaScript might have built in solution for.

Is there a better solution to this?


问:
How to create a Mongodb trigger through an API call?
I'm fairly new to Mongo-db,i have to create a trigger through the API call in nodejs. Is there any api to create a triggers in mongodb through a api.</p>


问:
Distinct by multiple properties with specific conditions
I have a class Animal with three properties

```<code>class Animal {
  String name;
  String type;
  String color;
}
</code>```

From a list of animals I need to find distinct animals.

The equality conditions are

if name is same both are equal

If both type and color are equal both are equal

So I wrote a wrapper animal and override the equals and hashcode

```<code>class WrapperAnimal {
    Animal insideDto;

    public WrapperAnimal(Animal dto) {
        this.insideDto = dto;
    }

    public Animal unwrap() {
        return insideDto;
    }

    @Override
    public boolean equals(Object o) {
        if(this == o) {
            return true;
        }
        if(o == null || getClass() != o.getClass()) {
            return false;
        }

        Animal dto = ((Animal) o).unwrap();

        if(dto.getName() != null && StringUtils.equals(dto.getName(), this.insideDto.getName())) {
            return true;
        }

        return StringUtils.equals(dto.getType(), this.insideDto.getType()) &&
                StringUtils.equals(dto.getColor(), this.insideDto.getColor());
    }

    @Override
    public int hashCode() {
        if(StringUtils.isNotEmpty(this.insideDto.getName())) {
            return Objects.hash(this.insideDto.getName());
        }

        return Objects.hash(this.insideDto.getType(),this.insideDto.getColor());
    }
}
</code>```

I used streams distinct to find distinct

```<code>List<Animal> distinctAnimals = animals.stream().map(WrapperAnimal::new).distinct().map(WrapperAnimal::unwrap).toList()
</code>```

This is not working when names are different but type and color are same.

Name
Type
Color

tiger1
type1
yellow

tiger2
type1
yellow

I understand this is issue with the hashcode function. How can I fix this?

Body:
I have a class Animal with three properties

class Animal {
  String name;
  String type;
  String color;
}

From a list of animals I need to find distinct animals.

The equality conditions are

if name is same both are equal

If both type and color are equal both are equal

So I wrote a wrapper animal and override the equals and hashcode

class WrapperAnimal {
    Animal insideDto;

    public WrapperAnimal(Animal dto) {
        this.insideDto = dto;
    }

    public Animal unwrap() {
        return insideDto;
    }

    @Override
    public boolean equals(Object o) {
        if(this == o) {
            return true;
        }
        if(o == null || getClass() != o.getClass()) {
            return false;
        }

        Animal dto = ((Animal) o).unwrap();

        if(dto.getName() != null && StringUtils.equals(dto.getName(), this.insideDto.getName())) {
            return true;
        }

        return StringUtils.equals(dto.getType(), this.insideDto.getType()) &&
                StringUtils.equals(dto.getColor(), this.insideDto.getColor());
    }

    @Override
    public int hashCode() {
        if(StringUtils.isNotEmpty(this.insideDto.getName())) {
            return Objects.hash(this.insideDto.getName());
        }

        return Objects.hash(this.insideDto.getType(),this.insideDto.getColor());
    }
}

I used streams distinct to find distinct

List<Animal> distinctAnimals = animals.stream().map(WrapperAnimal::new).distinct().map(WrapperAnimal::unwrap).toList()

This is not working when names are different but type and color are same.

Name
Type
Color

tiger1
type1
yellow

tiger2
type1
yellow

I understand this is issue with the hashcode function. How can I fix this?


问:
after android 13 in samsung one ui 5 update device's data/data not display in Android Studio Device File Explorer
i update my samsung mobile to one ui 5 android 13 after that i can't access my mobile's data/data folder in Android Studio`
how to access now ?


问:
How to add formulas in text under SSRS Report
Is there a way to add formulas in SSRS Report like below:


问:
How can I migrate from Forestry.io to Contentful CMS
I want to migrate from Forestry.io(https://forestry.io/)  to Contentful CMS as Forestry.io will be discontinued in March.
I had used Forestry.io and Hugo as static site generator, but now I want to migrate my CMS to Contentful.
Please help me how can I do this, I couldn't find any migration guide</p>


问:
Razor component System.nullreferenceexception at GetFromJsonAsync
Student studying FullSD encountered an error whilst following lab that my teacher can't figure out.

Have a page where I can create an entry that can be displayed. But when I refresh to view the newly added entry, I get a loading error. When looking at it from Developer Tools, it calls System.nullreferenceexception. Despite this, the entry can still be viewed from datatable in Visual Studios

The error references a block of code starting at line 37 of my Index.razor for this page, which my lecturer narrowed down to being this:

```<code> protected async override Task OnInitializedAsync()
    {
        Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}");
    }
</code>```

Entire Index.razor:

```<code>@page "/bookings/"
@inject HttpClient _client
@inject IJSRuntime js
@attribute [Authorize]

<h3 class="card-title">Car Bookings</h3>
<br />

<a href="/bookings/create" class="btn btn-secondary">
    <span class="oi oi-plus"></span>
    Create New Booking
</a>
<br />
<br />

@if (Bookings == null)
{
    <div class="alert alert-info">Loading Bookings...</div>
}

else
{
    <table class="table table-responsive">
        <thead>
            <tr>
                <th>Booking Id</th>
                <th>Customer License</th>
                <th>Date</th>
                <th>Duration in days</th>
                <th>Plate Number</th>
                <th>Actions</th>

            </tr>
        </thead>
        <tbody>
            @foreach (var booking in Bookings)
            {
                <tr>
                    <td>@booking.Id</td>
                    <td>@booking.CustomerId</td>
                    <td>@booking.DateCreated.Date.ToString("dd/mm/yyyy")</td>
                    <td>@(booking.DateIn != nullDT ? (booking.DateIn - booking.DateOut).TotalDays.ToString() : "To Be Determined")</td>
                    <td>@booking.Vehicle.LicensePlateNumber</td>
                    <td>
                        <a href="/bookings/view/@booking.Id" class="btn btn-primary">
                            <span class="oi oi-book"></span>
                        </a>
                        <a href="/bookings/edit/@booking.Id" class="btn btn-warning">
                            <span class="oi oi-pencil"></span>
                        </a>
                        <button class="btn btn-danger" @onclick="@(()=>Delete(booking.Id))">
                            <span class="oi oi-delete"></span>
                        </button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private List<Booking> Bookings;
    private DateTime nullDT = new DateTime(1, 1, 1, 0, 0, 0);

    protected async override Task OnInitializedAsync()
    {
        Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}");
    }

    async Task Delete(int bookingId)
    {
        var booking = Bookings.First(q => q.Id == bookingId);
        var confirm = await js.InvokeAsync<bool>("confirm", $"Do you want to delete {booking.Id}?");

        if (confirm)
        {
            await _client.DeleteAsync($"{Endpoints.BookingsEndpoint}/{bookingId}");
            await OnInitializedAsync();
        }
    }
}

</code>```

I expected the page to display the newly created entry as I have done with previously created pages in my Lab Workbook

Can anyone else provide some insight?

Edit: Here's my Booking class

```<code>using System;
namespace CarRentalManagement.Shared.Domain
{
    public class Booking:BaseDomainModel
    {
        public DateTime DateOut { get; set; }
        public DateTime DateIn { get; set; }
        public int VehicleId { get; set; }
        public virtual Vehicle Vehicle { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }

    }
}
</code>```

Body:
Student studying FullSD encountered an error whilst following lab that my teacher can't figure out.

Have a page where I can create an entry that can be displayed. But when I refresh to view the newly added entry, I get a loading error. When looking at it from Developer Tools, it calls System.nullreferenceexception. Despite this, the entry can still be viewed from datatable in Visual Studios

The error references a block of code starting at line 37 of my Index.razor for this page, which my lecturer narrowed down to being this:

 protected async override Task OnInitializedAsync()
    {
        Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}");
    }

Entire Index.razor:

@page "/bookings/"
@inject HttpClient _client
@inject IJSRuntime js
@attribute [Authorize]

Car Bookings

    Create New Booking

@if (Bookings == null)
{

Loading Bookings...

}

else
{

                Booking Id
                Customer License
                Date
                Duration in days
                Plate Number
                Actions

            @foreach (var booking in Bookings)
            {

                    @booking.Id
                    @booking.CustomerId
                    @booking.DateCreated.Date.ToString("dd/mm/yyyy")
                    @(booking.DateIn != nullDT ? (booking.DateIn - booking.DateOut).TotalDays.ToString() : "To Be Determined")
                    @booking.Vehicle.LicensePlateNumber

                        <button class="btn btn-danger" @onclick="@(()=>Delete(booking.Id))">

                        </button>

            }

}

@code {
    private List<Booking> Bookings;
    private DateTime nullDT = new DateTime(1, 1, 1, 0, 0, 0);

    protected async override Task OnInitializedAsync()
    {
        Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}");
    }

    async Task Delete(int bookingId)
    {
        var booking = Bookings.First(q => q.Id == bookingId);
        var confirm = await js.InvokeAsync<bool>("confirm", $"Do you want to delete {booking.Id}?");

        if (confirm)
        {
            await _client.DeleteAsync($"{Endpoints.BookingsEndpoint}/{bookingId}");
            await OnInitializedAsync();
        }
    }
}

I expected the page to display the newly created entry as I have done with previously created pages in my Lab Workbook

Can anyone else provide some insight?

Edit: Here's my Booking class

using System;
namespace CarRentalManagement.Shared.Domain
{
    public class Booking:BaseDomainModel
    {
        public DateTime DateOut { get; set; }
        public DateTime DateIn { get; set; }
        public int VehicleId { get; set; }
        public virtual Vehicle Vehicle { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }

    }
}


问:
Blazor one-way binding from child to parent component
I would like to ask whether it is possible to implement one-way binding from child to parent component. Meaning that when I change property in child component it also changes in parent component but when I change property in parent component it doesn't change in child component.

In ParentComponent.razor I want to have:

```<code>    <ChildComponent @bind-one-way-Token="Token">
</code>```

I know that in Blazor I can implement Two-Way binding via implementation of Property + PropertyChanged event. But two way binding is not suitable for my use case. I know I can pass value from child component to parent component via EventCallback / StateContainer, but these are not as elegant as binding.

Body:
I would like to ask whether it is possible to implement one-way binding from child to parent component. Meaning that when I change property in child component it also changes in parent component but when I change property in parent component it doesn't change in child component.

In ParentComponent.razor I want to have:

    <ChildComponent @bind-one-way-Token="Token">

I know that in Blazor I can implement Two-Way binding via implementation of Property + PropertyChanged event. But two way binding is not suitable for my use case. I know I can pass value from child component to parent component via EventCallback / StateContainer, but these are not as elegant as binding.


问:
How to create a git pull request using power shell script via Teamcity build step
I am still a beginner when it comes to TeamCity and GitHub.

What I have?

I have an exe file as part of my repository that runs to update a
text file within the same repository every time a build is triggered
in TeamCity.

A build step is configured in TeamCity that has the    script to run
the exe.

What I need?

I want to push the updated text file to the origin repository in
GitHub by creating a pull request between teamcity branch and origin
in github via PowerShell script which will be a part of the teamcity
build step.

I am unable to create a pull request through the build step. I've tried the below commands in powershell script:

```<code>git push
git request-pull origin/master $branch
</code>```

Body:
I am still a beginner when it comes to TeamCity and GitHub.

What I have?

I have an exe file as part of my repository that runs to update a
text file within the same repository every time a build is triggered
in TeamCity.

A build step is configured in TeamCity that has the    script to run
the exe.

What I need?

I want to push the updated text file to the origin repository in
GitHub by creating a pull request between teamcity branch and origin
in github via PowerShell script which will be a part of the teamcity
build step.

I am unable to create a pull request through the build step. I've tried the below commands in powershell script:

git push
git request-pull origin/master $branch


问:
VisNetwork: nodesIdSelection argument in VisOptions does not behave similarly to selectNode argument in visEvents
I am having a hard time figuring out why in VisNetwork, the nodesIdSelection argument in VisOptions does not behave similarly to the selectNode argument in visEvents.

Basically, when I click on any node, the R console returns as expected "The selected node ID is: X" but when I select the node from the dropdown list (generated with visOptions) then the message is not issued in the console.

Here is a reproducible example:

```<code>library(shiny)
library(visNetwork)
ui <- fluidPage(
  visNetworkOutput('network')
)

server <- function(input, output, session) {
  getDiagramPlot <- function(nodes, edges){
    v <- visNetwork(
      nodes,
      edges
    ) %>%
      visPhysics(stabilization = TRUE, enabled = TRUE) %>%
      visOptions(highlightNearest = list(enabled = T, degree = 1, hover = F),
                 nodesIdSelection = list(enabled = TRUE, main = "Select ID"),
                 autoResize = TRUE, collapse = FALSE) %>%
      visEdges(color = list(highlight = "red")) %>% # The colour of the edge linking nodes
      visLayout(improvedLayout = TRUE) %>%
      visEdges(arrows = edges$arrows) %>%
      visInteraction(multiselect = F) %>%
      visEvents(selectNode = "function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}")
    return(v)
  }

  testFunction <- function(node_id){
    print(paste("The selected node ID is:", node_id))
  }

  nodes <- data.frame(id = 1:3, label = 1:3)
  edges <- data.frame(from = c(1,2), to = c(1,3))

  output$network <- renderVisNetwork(
    getDiagramPlot(nodes, edges)
  )

  observeEvent(input$current_node_id,{
    testFunction(input$current_node_id)
  })
}

shinyApp(ui, server)
</code>```

Is there a way to pass the same javascript code in visEvents to nodesIdSelection?

Best,

C.

I tried to pass the javascript code from visEvents:

```<code>"function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}"
</code>```

to the style HTML argument (in nodesIdSelection) but this had not effect.

Body:
I am having a hard time figuring out why in VisNetwork, the nodesIdSelection argument in VisOptions does not behave similarly to the selectNode argument in visEvents.

Basically, when I click on any node, the R console returns as expected "The selected node ID is: X" but when I select the node from the dropdown list (generated with visOptions) then the message is not issued in the console.

Here is a reproducible example:

library(shiny)
library(visNetwork)
ui <- fluidPage(
  visNetworkOutput('network')
)

server <- function(input, output, session) {
  getDiagramPlot <- function(nodes, edges){
    v <- visNetwork(
      nodes,
      edges
    ) %>%
      visPhysics(stabilization = TRUE, enabled = TRUE) %>%
      visOptions(highlightNearest = list(enabled = T, degree = 1, hover = F),
                 nodesIdSelection = list(enabled = TRUE, main = "Select ID"),
                 autoResize = TRUE, collapse = FALSE) %>%
      visEdges(color = list(highlight = "red")) %>% # The colour of the edge linking nodes
      visLayout(improvedLayout = TRUE) %>%
      visEdges(arrows = edges$arrows) %>%
      visInteraction(multiselect = F) %>%
      visEvents(selectNode = "function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}")
    return(v)
  }

  testFunction <- function(node_id){
    print(paste("The selected node ID is:", node_id))
  }

  nodes <- data.frame(id = 1:3, label = 1:3)
  edges <- data.frame(from = c(1,2), to = c(1,3))

  output$network <- renderVisNetwork(
    getDiagramPlot(nodes, edges)
  )

  observeEvent(input$current_node_id,{
    testFunction(input$current_node_id)
  })
}

shinyApp(ui, server)

Is there a way to pass the same javascript code in visEvents to nodesIdSelection?

Best,

C.

I tried to pass the javascript code from visEvents:

"function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}"

to the style HTML argument (in nodesIdSelection) but this had not effect.


问:
Creating a grid slider in javascript
I am trying to create a grid slider where there is one big image left and 4 smaller on the right. So 5 elements that are part of the same slider that change one by one. First the big image fades to a new one then the first smaller image and so on, at the end start again.

How can I do this? Is there a carousel that can do this? Or does this have to be custom made?

I've tried this:

```<code>function homeCarousel() {
    // Create an array of the current image sources
    var currentImageUrls = [];
    $('.img-container img').each(function() {
        currentImageUrls.push($(this).attr('src'));
    });

    $.ajax({
        url: '/get-image-urls',
        type: 'GET',
        success: function(data) {
            var newImageUrls = data;

            var previousIndex = 0;
            var usedIndices = [];

            // Create an array to store the preloaded images
            var preloadedImages = [];

            // Preload the images by creating new Image objects and setting
            // their src attributes to the image URLs
            for (var i = 0; i < newImageUrls.length; i++) {
                var img = new Image();
                img.src = newImageUrls[i];
                preloadedImages.push(img);
            }

            function changeImage(index) {
                setTimeout(function() {
                    var currentIndex = previousIndex;
                    while (usedIndices.includes(currentIndex) || currentImageUrls.includes(newImageUrls[currentIndex])) {
                        currentIndex = Math.floor(Math.random() * newImageUrls.length);
                    }
                    usedIndices.push(currentIndex);

                    // Use the preloaded image for the current index
                    var currentImage = preloadedImages[currentIndex];

                    // Check if the screen is small enough to only update the first image
                    if (window.matchMedia('only screen and (max-width: 600px)').matches) {
                        // The screen is small, so only update the first image
                        $('.img-container img').eq(0).attr('src', currentImage.src);
                        $('.img-container img').eq(0).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });
                        changeImage(0);
                    } else {
                        // The screen is not small, so update all of the images
                        $('.img-container img').eq(index).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });

                        if (index + 1 < $('.img-container img').length) {
                            changeImage(index + 1);
                        } else {
                            usedIndices = [];
                            changeImage(0);
                        }
                    }
                }, 3000);
            }

            changeImage(0);
        }
    });
}
</code>```

But there are a lot of bugs. For example I load 5 images by default at the start, sometimes a new image is loaded which already is loaded at the beginning so double images are visible, I want all to be unique at any given time. Also sometimes an image gets replaced by an image that was already there so it fades into the same image.

Is there something like slick slider that can achieve this more easily?

Title: Creating a grid slider in javascript

Body:
I am trying to create a grid slider where there is one big image left and 4 smaller on the right. So 5 elements that are part of the same slider that change one by one. First the big image fades to a new one then the first smaller image and so on, at the end start again.

How can I do this? Is there a carousel that can do this? Or does this have to be custom made?

I've tried this:

function homeCarousel() {
    // Create an array of the current image sources
    var currentImageUrls = [];
    $('.img-container img').each(function() {
        currentImageUrls.push($(this).attr('src'));
    });

    $.ajax({
        url: '/get-image-urls',
        type: 'GET',
        success: function(data) {
            var newImageUrls = data;

            var previousIndex = 0;
            var usedIndices = [];

            // Create an array to store the preloaded images
            var preloadedImages = [];

            // Preload the images by creating new Image objects and setting
            // their src attributes to the image URLs
            for (var i = 0; i < newImageUrls.length; i++) {
                var img = new Image();
                img.src = newImageUrls[i];
                preloadedImages.push(img);
            }

            function changeImage(index) {
                setTimeout(function() {
                    var currentIndex = previousIndex;
                    while (usedIndices.includes(currentIndex) || currentImageUrls.includes(newImageUrls[currentIndex])) {
                        currentIndex = Math.floor(Math.random() * newImageUrls.length);
                    }
                    usedIndices.push(currentIndex);

                    // Use the preloaded image for the current index
                    var currentImage = preloadedImages[currentIndex];

                    // Check if the screen is small enough to only update the first image
                    if (window.matchMedia('only screen and (max-width: 600px)').matches) {
                        // The screen is small, so only update the first image
                        $('.img-container img').eq(0).attr('src', currentImage.src);
                        $('.img-container img').eq(0).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });
                        changeImage(0);
                    } else {
                        // The screen is not small, so update all of the images
                        $('.img-container img').eq(index).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });

                        if (index + 1 < $('.img-container img').length) {
                            changeImage(index + 1);
                        } else {
                            usedIndices = [];
                            changeImage(0);
                        }
                    }
                }, 3000);
            }

            changeImage(0);
        }
    });
}

But there are a lot of bugs. For example I load 5 images by default at the start, sometimes a new image is loaded which already is loaded at the beginning so double images are visible, I want all to be unique at any given time. Also sometimes an image gets replaced by an image that was already there so it fades into the same image.

Is there something like slick slider that can achieve this more easily?


问:
Doxygen documentation variable
I am creating design documentation with Doxygen and there is one issue I am facing every time.

This is my code:

```<code>## Function which returns list of project_kpi instances based on project_kpi.kpi_type_ID
## @param session: Session -> already created session
## @param kpi: project_kpi -> project_kpi instance which must have set project_kpi.kpi_type_ID
## @return list[project_kpi] -> list of found project_kpi (results per kpi type)
## @return None -> if no results were found
## @note Not in use
def select_project_kpi_by_kpi_type(session: Session, kpi: project_kpi) -> list[project_kpi] | None: ...
</code>```

I would like to create variable (if it is even possible, but I saw that you can even type functions in Doxygen) which I can call in every function description.

Exactly this parameter:

```<code>## @param session: Session -> already created session
</code>```

So the code could look like this:

```<code>## @my_var_name
</code>```

Title: Doxygen documentation variable

Body:
I am creating design documentation with Doxygen and there is one issue I am facing every time.

This is my code:

## Function which returns list of project_kpi instances based on project_kpi.kpi_type_ID
## @param session: Session -> already created session
## @param kpi: project_kpi -> project_kpi instance which must have set project_kpi.kpi_type_ID
## @return list[project_kpi] -> list of found project_kpi (results per kpi type)
## @return None -> if no results were found
## @note Not in use
def select_project_kpi_by_kpi_type(session: Session, kpi: project_kpi) -> list[project_kpi] | None: ...

I would like to create variable (if it is even possible, but I saw that you can even type functions in Doxygen) which I can call in every function description.

Exactly this parameter:

## @param session: Session -> already created session

So the code could look like this:

## @my_var_name


问:
How many routes are we allowed to have in Traefik?
We have a server that handles for example 10k users, and every user has his own domain

Now when every user wants to reach his domain we should put some ID to his request's header, we used Traefik for this scenario.

And now we have for example 10k Routes in our Traefik and this issue is increasing in the form of a linear graph.

The question:

What is the benchmark of Traefik for a high amount of Routes?

Is there any better solution or tool that we can use instead of Traefik in this scenario?


问:
Django Unit test is written but coverage report says there are missing statements
I try to get coverage reports using a simple django model.

Unit test for model was written but report says there are missing statements.

The model:

```<code>from django.db import models
from model_utils import FieldTracker

from generics.base_model import BaseModelMixin

class AModel(BaseModelMixin):
    record_name = models.CharField(max_length=255)
    tracker = FieldTracker()

    class Meta(BaseModelMixin.Meta):
        db_table = 'a_model_records'

    def __str__(self):
        record _name = self. record_ name
        if record_name is None:
            record_name = "N/A"
        return record name
</code>```

The unit test:

```<code>class TestAModel(TestCase):

    def setUp(self):
        super().setUp()

    def test_amodel(self):
        record_name = "some name"
        is_active = True

        user = User.objects.first()
        record = AModel.objects.create(
            record_name=record_name,
            is_active=is_active,
            created_by_id=user.id,
        )
        self.assertEqual(str(record), record_name)
        self.assertEqual(record.name, record_name)
        self.assertEqual(record.is_active, is_active)
</code>```

The command line code I run:

```<code>source activate
set -a
source local.env
set +a
coverage run --source="unit_test_app" --rcfile=.coveragerc project/manage.py test -v 2
coverage report
coverage html
</code>```

The coverage configuration is like this:

```<code>[run]
omit=
    */migrations/*
    */tests/*
    */manage.py
    */apps.py
    */settings.py
    */urls.py
    */filters.py
    */serializers.py
    */generics/*

[report]
show_missing = true
</code>```

Coverage result shows missing statements:

This is the simplest example.

There are many ignored functions by coverage which descends percentage average, but actually covered by unit tests.

Why does coverage act like this?

Body:
I try to get coverage reports using a simple django model.

Unit test for model was written but report says there are missing statements.

The model:

from django.db import models
from model_utils import FieldTracker

from generics.base_model import BaseModelMixin

class AModel(BaseModelMixin):
    record_name = models.CharField(max_length=255)
    tracker = FieldTracker()

    class Meta(BaseModelMixin.Meta):
        db_table = 'a_model_records'

    def __str__(self):
        record _name = self. record_ name
        if record_name is None:
            record_name = "N/A"
        return record name

The unit test:

class TestAModel(TestCase):

    def setUp(self):
        super().setUp()

    def test_amodel(self):
        record_name = "some name"
        is_active = True

        user = User.objects.first()
        record = AModel.objects.create(
            record_name=record_name,
            is_active=is_active,
            created_by_id=user.id,
        )
        self.assertEqual(str(record), record_name)
        self.assertEqual(record.name, record_name)
        self.assertEqual(record.is_active, is_active)

The command line code I run:

source activate
set -a
source local.env
set +a
coverage run --source="unit_test_app" --rcfile=.coveragerc project/manage.py test -v 2
coverage report
coverage html

The coverage configuration is like this:

[run]
omit=
    */migrations/*
    */tests/*
    */manage.py
    */apps.py
    */settings.py
    */urls.py
    */filters.py
    */serializers.py
    */generics/*

[report]
show_missing = true

Coverage result shows missing statements:

This is the simplest example.

There are many ignored functions by coverage which descends percentage average, but actually covered by unit tests.

Why does coverage act like this?


问:
fit pc web view to phone web view html
My HTML file creates an iframe for each YouTube video specified in the URL's query parameters and inserts the iframes into a div element with the ID videos.

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Video Embedder</title>

```

I'd like that the video view fit the same in my phone web browser.

I mean by that dezoom or adjust height and width keeping the 500px and 281px ratio.

What I want

What I have

Title: fit pc web view to phone web view html

Body:
My HTML file creates an iframe for each YouTube video specified in the URL's query parameters and inserts the iframes into a div element with the ID videos.

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Video Embedder</title>

I'd like that the video view fit the same in my phone web browser.

I mean by that dezoom or adjust height and width keeping the 500px and 281px ratio.

What I want

What I have


问:
i want to make drag-drop for child components inside parent component
i have a parent component with multi child components, i want to make drag-drop for these child components them selves. Not drag-drop for divs that inside child.

i have parent component with these child components.
enter image description here

i want to Rearrange these child components dynamically by drag drop.

enter image description here

without using array or ngfor
all sources in internet use array


问:
How to find between two lines using python
What is the best way to find the angle between the Blue and Green lines in this image?

The Blue line is straight, but the Green line is slightly tilted.

Green line coordinates are [(923, 286), (1495, 306)].

Blue line coordinates are [(901, 259), (901, 197)].

Here is my code of to calculate the angle:

```<code>def find_angle(A, B):
    # Calculate the slope of line A
    slope_A = (A[1][1] - A[0][1]) / (A[1][0] - A[0][0])
    # Calculate the slope of line B
    slope_B = (B[1][1] - B[0][1]) / (B[1][0] - B[0][0])
    # Calculate the angle between the lines
    print(slope_A,slope_B)
    angle = math.atan2(slope_B, slope_A)
    # Convert the angle from radians to degrees
    print(angle)
    angle_degrees = angle * 180 / math.pi
    return angle_degrees
</code>```

My calculation result is 90 or 89, but the Green line is a little bit tilted, so the angle should be 91 or 93.

Here's another image.

What is the problem with my code and how to improve that?

Body:
What is the best way to find the angle between the Blue and Green lines in this image?

The Blue line is straight, but the Green line is slightly tilted.

Green line coordinates are [(923, 286), (1495, 306)].

Blue line coordinates are [(901, 259), (901, 197)].

Here is my code of to calculate the angle:

def find_angle(A, B):
    # Calculate the slope of line A
    slope_A = (A[1][1] - A[0][1]) / (A[1][0] - A[0][0])
    # Calculate the slope of line B
    slope_B = (B[1][1] - B[0][1]) / (B[1][0] - B[0][0])
    # Calculate the angle between the lines
    print(slope_A,slope_B)
    angle = math.atan2(slope_B, slope_A)
    # Convert the angle from radians to degrees
    print(angle)
    angle_degrees = angle * 180 / math.pi
    return angle_degrees

My calculation result is 90 or 89, but the Green line is a little bit tilted, so the angle should be 91 or 93.

Here's another image.

What is the problem with my code and how to improve that?


问:
How to fix: AttributeError: 'spacy.tokens.span.Span' object has no attribute 'is_question'
This is the code I have written

```<code>
import spacy
nlp = spacy.load("en_core_web_lg")
passage="Natural language processing (NLP) refers to the branch of computer science—and more specifically, the branch of artificial intelligence or AI—concerned with giving computers the ability to understand text and spoken words in much the same way human beings can. NLP combines computational linguistics—rule-based modeling of human language—with statistical, machine learning, and deep learning models. Together, these technologies enable computers to process human language in the form of text or voice data and to ‘understand’ its full meaning, complete with the speaker or writer’s intent and sentiment. NLP drives computer programs that translate text from one language to another, respond to spoken commands, and summarize large volumes of text rapidly—even in real time. There’s a good chance you’ve interacted with NLP in the form of voice-operated GPS systems, digital assistants, speech-to-text dictation software, customer service chatbots, and other consumer conveniences. But NLP also plays a growing role in enterprise solutions that help streamline business operations, increase employee productivity, and simplify mission-critical business processes."
doc = nlp(passage)
questions = []
for sent in doc.sents:
    if sent.is_question:
        questions.append(sent.text)
print(questions)

</code>```

But An Error had encountered  as AttributeError: 'spacy.tokens.span.Span' object has no attribute 'is_question', Any one please help to fix this issue

I am expecting to solve the AttributeError: 'spacy.tokens.span.Span' object has no attribute 'is_question'

Body:
This is the code I have written

import spacy
nlp = spacy.load("en_core_web_lg")
passage="Natural language processing (NLP) refers to the branch of computer science—and more specifically, the branch of artificial intelligence or AI—concerned with giving computers the ability to understand text and spoken words in much the same way human beings can. NLP combines computational linguistics—rule-based modeling of human language—with statistical, machine learning, and deep learning models. Together, these technologies enable computers to process human language in the form of text or voice data and to ‘understand’ its full meaning, complete with the speaker or writer’s intent and sentiment. NLP drives computer programs that translate text from one language to another, respond to spoken commands, and summarize large volumes of text rapidly—even in real time. There’s a good chance you’ve interacted with NLP in the form of voice-operated GPS systems, digital assistants, speech-to-text dictation software, customer service chatbots, and other consumer conveniences. But NLP also plays a growing role in enterprise solutions that help streamline business operations, increase employee productivity, and simplify mission-critical business processes."
doc = nlp(passage)
questions = []
for sent in doc.sents:
    if sent.is_question:
        questions.append(sent.text)
print(questions)

But An Error had encountered  as AttributeError: 'spacy.tokens.span.Span' object has no attribute 'is_question', Any one please help to fix this issue

I am expecting to solve the AttributeError: 'spacy.tokens.span.Span' object has no attribute 'is_question'


问:
How to collect the pivot borders in K-Way Partitioning Algorithm?
I have implemented the K-Way Partitioning Quick Sort which is based on the Peter Taylor's solution.

How can i fill the given q array in the partitioning to be the borders of each pivot (<pivot and ==pivot values):

```<code>#pragma once
template <class T>
class KWayPartition {
private:
    void swap(T* a, T* b) { T temp = *a; *a = *b; *b = temp; }
    int partition(T* A, int low, int high, T* lp,int* q)
    {
        if (A[low] > A[high]){
            swap(&A[low], &A[high]);
        }
        int j = low + 1;
        int g = high - 1, k = low + 1;
        T p = A[low], qq = A[high];
        while (k <= g) {
            if (A[k] < p) {
                swap(&A[k], &A[j]);
                j++;
            }
            else if (A[k] >= qq) {
                while (A[g] > qq && k < g){
                    g--;
                }
                swap(&A[k], &A[g]);
                g--;
                if (A[k] < p) {
                    swap(&A[k], &A[j]);
                    j++;
                }
            }
            k++;
        }
        j--;
        g++;
        swap(&A[low], &A[j]);
        swap(&A[high], &A[g]);
        *lp = j;
        return g;
    }
    void insertionSort(T A[], T r) {
        T ki;
        int j=0;
        for (int i=1;i<r;i++) {
            ki = A[i];
            j = i - 1;
            while (j >= 0 && A[j] > ki) {
                A[j+1] = A[j];
                j--;
            }
            A[j+1] = ki;
        }
    }
    void KPartition (T* A, T* pivots,int *q, int p, int r, int sp, int sr) {
        if (r<=p) {
            return;
        }
        if (sp<sr) {
            insertionSort(A,r);
        }
        else {
            int mid = p+(r-p)/2;
            int idx = partition(A, p, r, &pivots[mid],q);
            KPartition(A, pivots,q,p, idx - 1,r,mid - 1);
            KPartition(A, pivots,q,idx + 1, r ,mid+1,sr);
        }
    }
public:
    virtual void Partition (T* A, T* pivots, int* q, int p, int r, int k) {
        KPartition(A, pivots,q, p,r+1, 0,0);
    }
};
</code>```

note that the array of pivots is already given and i need to implement it without the use of std functions.

I think it should be similar to sorted in python(sorted(l,key=lambda x:[x[y]for y in k]) that's not doing it in-place.

The equivalent key function to the python version would be:

```<code>[](T* a, T* b) {
    for (auto i : pivots) if (a[i] != b[i]) return a[i] < b[i];
    return false;
}
</code>```

please have a look at my test cases.

It needs to satisfy this properties at the end:

```<code>    A[p .. r]
    pivots[0 .. (k-1)]  an array of k ordered values (in ascending order)
    q[0 .. (2k-1)]      output array of borders
    At the end:
        A[p .. q[0]-1] < pivots[0]
        A[q[0] .. q[1]-] = pivots[0]
        pivots[0] < A[q[1] .. q[2]-1] < pivots[1]
        A[q[2] .. q[3]-1] = pivots[1]
        ...
        pivots[i-1] < A[q[2i-1] .. q[2i]-1] < pivots[i] 0 < i < k-1
        A[q[2i] .. q[2i+1]-1] = pivots[i]       0 < i < k-1
        ...
        pivots[k-2] < A[q[2k-3] .. q[2k-2]-1] < pivots[k-1]
        A[q[2k-2] .. q[2k-1]-1] = pivots[k-1]
        A[q[2k-1] .. r] > pivots[k-1]

</code>```

Body:
I have implemented the K-Way Partitioning Quick Sort which is based on the Peter Taylor's solution.

How can i fill the given q array in the partitioning to be the borders of each pivot (<pivot and ==pivot values):

#pragma once
template <class T>
class KWayPartition {
private:
    void swap(T* a, T* b) { T temp = *a; *a = *b; *b = temp; }
    int partition(T* A, int low, int high, T* lp,int* q)
    {
        if (A[low] > A[high]){
            swap(&A[low], &A[high]);
        }
        int j = low + 1;
        int g = high - 1, k = low + 1;
        T p = A[low], qq = A[high];
        while (k <= g) {
            if (A[k]
= qq) {
                while (A[g] > qq && k < g){
                    g--;
                }
                swap(&A[k], &A[g]);
                g--;
                if (A[k] < p) {
                    swap(&A[k], &A[j]);
                    j++;
                }
            }
            k++;
        }
        j--;
        g++;
        swap(&A[low], &A[j]);
        swap(&A[high], &A[g]);
        *lp = j;
        return g;
    }
    void insertionSort(T A[], T r) {
        T ki;
        int j=0;
        for (int i=1;i<r;i++) {
            ki = A[i];
            j = i - 1;
            while (j >= 0 && A[j] > ki) {
                A[j+1] = A[j];
                j--;
            }
            A[j+1] = ki;
        }
    }
    void KPartition (T* A, T* pivots,int *q, int p, int r, int sp, int sr) {
        if (r<=p) {
            return;
        }
        if (sp<sr) {
            insertionSort(A,r);
        }
        else {
            int mid = p+(r-p)/2;
            int idx = partition(A, p, r, &pivots[mid],q);
            KPartition(A, pivots,q,p, idx - 1,r,mid - 1);
            KPartition(A, pivots,q,idx + 1, r ,mid+1,sr);
        }
    }
public:
    virtual void Partition (T* A, T* pivots, int* q, int p, int r, int k) {
        KPartition(A, pivots,q, p,r+1, 0,0);
    }
};

note that the array of pivots is already given and i need to implement it without the use of std functions.

I think it should be similar to sorted in python(sorted(l,key=lambda x:[x[y]for y in k]) that's not doing it in-place.

The equivalent key function to the python version would be:

[](T* a, T* b) {
    for (auto i : pivots) if (a[i] != b[i]) return a[i] < b[i];
    return false;
}

please have a look at my <a href="https://tio.run/##rRjbbtpI9Bl/xWmqRbYxTWzIS4yReKmEWq0qLbv7wPLgGJcMNsY3klYR/fXsOTO@2zRu1Eg1M@c25z5n6oTheOc4L@9Z4PinrQszdkzS2LUPc6mEOXaSuHFaBaXs4H54mEvSKWHBDgL74Cah7biQpFtTkt6Hsb072HAMHFeSHB8FwPJZCmP2aKfunTRgQQqPtn9ykTg83fvMQWCS2ilzgHDO8RSkblzFLmXnGCQpLIfAFJP2mRCxoe8P/iMN7o9HH46hG9vpMZ6XfDHbPaQK8L3ZIJv1I5tbPcX1pLN60r27TIeQQlqTqBu9PaJT3ZIkx2cIuZAtArVz038oViX8jChpeXdXi8mzNEgfWDKe88CCBexDFuKzoM3j1SLE34JIeeaLH2IlcSfg/pVoosjYTU9xALIQOhdooYFC0luiZj1FzV4XdSkr2mpZPfTqK2zWQ5jVV5jVQ9i7vsLedQhDnqpeLUmtrKhIMMsDVCL6mcRacl@QekFeKaxRCVLFQoFRitSWKK2RtVklJUtFAWR4qTXH1D2EPvZE7LK8S67mWbv89K/9/YsdpyxlxwAqvRPw7/HItpA82aG8UsHWAL/3aCusgOShlapt4j9a3OPiHheEMOHM2UnjMJdNIhYah/nHJ7F4QCdxqX6o4V6FSOGMz/zLRXwFebFGhg2W2mJNDBulRNMf128oiDQY5kRmQXQupeGZe1QSSWEEullD7BBBrDAGXQOvi2wFZHR@VBTxDT@upHl6YJgWskdls1Ogrqswx9tgsYdNXNUWT1iyr5qR/@1HozrwXNu5fuKW52AjiKKukzI1F@sdeRZNGQ7R5hmq3Kalv9143Fbl/JoBuy4DOkW95pm@3un0UFvX@s6rMpSofVXRXZWmlXM1XXIsz4y2H1SfsmhfArL63QkIlnpReyygiQir569jnMorzDaUt4K46qEVeKyeyXvrpgR8xS7Dr0Rm6SabxSYbjZoO9hjPZLapu41KhVE51MFZ6uwpuW4ob8h8TCKPdQUOkSN9w@XvNx3Z3EyGemQK7qqNZ6n8cjd9KjtY1mbwG7LHY5pQXwE1Ev0mFD@x@EmybVJzJyUi3o2tJBRB6uwqyJGEs7oYEYtq9BZa3NmUeME2GVM4oF0WhCM5HofKtWG2CNj2GxEU/RWtRoPQtqGwfI0SNlrUqJHSVZxB@CjSyBUoj1pfrNHRuOrHSWwj6pgxEONI15K2nedivuYxY3F6sn0Ru5@EDsSd0BU7r@rrC5ohS4zqwI12o@SldTZfuHNtFsj81qZdgH6cYMnwDTV@fUIz6RLUBW4C9wmW62BDM26uWgH2NoIN1cxguFkbKsGlQe1ynS3nKnx9CjO6Jk48KZLYDrYyPXvkP//@/FmhsVkalDWMzDcm/szAABU8XGI1S4NBFnJGpTJFDMOYGCQQXzgpzGZwtQzwJHT6Io7t73dXBHODLQ7EndIDIZk8NFgIsVwzBf4AmQ7wSLNCOiehUzS4Qvh5gCejqeN5V2QoojcaBGO6ZpV8@heHV7TZC232qA3auc@1KS4uxu8KYTe2X0QNGPXowUC8I0GO1uQk7E04dPK3XI0ZgX24KblLCeeqS/8LPrLgTS695Leq9Ei8XJNXBXsdgq@@kGnAWcvcECdFM2AoFTdoolqCLQ6GHE59tzwYVTu/tKdIUcPuN@fBDnboWVgN@aA4hHtQJCrRFTiyrZhgWzgi3lsOn2UvjqMf2aPbmEiL1lH2@y@NoXIlbNSLldHRM4YQ6fnCyBeTfDGtNpTabco02GOianDQwDc7aKgLl/B9fevVtz4V0qhyoR6aAGlwrVaa4tZObUhOzgOO93aK2AGHZFHVwY5x2guoONH961CLdCWnyRO8SYRuiAylIckALG@8xLs5DC2atOQaTaqJhm7MqeYXiKbYkuONNFCvpfrMLHszX2mOy8VMyNXqmE0pQtljZMG7cXv@QAFW9/DBB5euyUcgedvjD5r2sV0jZufc6fUa14WdRcSUC08DMfv2fRj86vFF9PlMV/rd6FDnLWYZr5nlj/Uuw/yfz4higLq@rtpgvDVRMi260ATnBIcLBAdB0J0xfter53DZsnIV6TSHl3SRUX8@RBN6q1b2U9wfGp2KRh/pWpXwSusev/gTP8ZWKf57Azt43lPrgLe2VjVvp7pFvAb/Tvh3apGYWys2BZloB2xCT2g2VTJmSidUcM0m9YagZkaq2WsoC3JGauaInDXDGA2MUWD0BqYaUwFmOk/@bGNUN5Nyc85@81IoFLCayv8W3esa/qpS1dJvONloO/lXzKyw97Vv2sBM2/ZNeeH0Mel3nc9Xtw3MbVuz21KztppinWkc6RbDsokMi2HRRBOL0d2I9WKxWz4RZPREfi39Dw" rel="nofollow noreferrer">test cases.

It needs to satisfy this properties at the end:

    A[p .. r]
    pivots[0 .. (k-1)]  an array of k ordered values (in ascending order)
    q[0 .. (2k-1)]      output array of borders
    At the end:
        A[p .. q[0]-1] < pivots[0]
        A[q[0] .. q[1]-] = pivots[0]
        pivots[0] < A[q[1] .. q[2]-1] < pivots[1]
        A[q[2] .. q[3]-1] = pivots[1]
        ...
        pivots[i-1] < A[q[2i-1] .. q[2i]-1] < pivots[i] 0 < i < k-1
        A[q[2i] .. q[2i+1]-1] = pivots[i]       0 < i < k-1
        ...
        pivots[k-2] < A[q[2k-3] .. q[2k-2]-1] < pivots[k-1]
        A[q[2k-2] .. q[2k-1]-1] = pivots[k-1]
        A[q[2k-1] .. r] > pivots[k-1]


问:
SVN and Meld inside WSL
I want to use Meld as the diff tool for SVN under WSL on Windows 11.
Therefore I do

```<code>svn diff foo.c -r HEAD --diff-cmd meld
</code>```

but it seems meld tries to open the files from the WSL root with backslashes, e.g.

```<code>\mnt\e\bar\foo.c
</code>```

and then gives the error No such file or directory.

I also tried calling meld directly with absolute paths, e.g.

```<code>meld /mnt/e/bar/foo.c /mnt/e/bar/foo-alt.c
</code>```

but meld still tries to open the paths with backslashes.

Any idea why or how to resolve this?

Title: SVN and Meld inside WSL

Body:
I want to use Meld as the diff tool for SVN under WSL on Windows 11.
Therefore I do

svn diff foo.c -r HEAD --diff-cmd meld

but it seems meld tries to open the files from the WSL root with backslashes, e.g.

\mnt\e\bar\foo.c

and then gives the error No such file or directory.

I also tried calling meld directly with absolute paths, e.g.

meld /mnt/e/bar/foo.c /mnt/e/bar/foo-alt.c

but meld still tries to open the paths with backslashes.

Any idea why or how to resolve this?


问:
Cannot read properties of undefined while populating API results in drop down
I am trying to pull GA4 Accounts from listAccounts() function and want to populate the drop-down field with GA4 List accounts on the HTML front-end.

When I try to click on the custom menu in google sheets, I get this error - TypeError: Cannot read properties of undefined (reading 'length')

HTML

```<code>
<div class="form-group">

 <? var data = listAccounts() ?>

<optgroup label="Ad Accounts">

 <? for (i=0; i<data.propertyName.length; i++) { ?>
    <option value="<?= data.propertyName[i] ?>"> <?= data.propertyName[i] ?>) </option>

</optgroup>

    </div>
</code>```

Code.gs

```<code>function listAccounts () {

const summaries = AnalyticsAdmin.AccountSummaries.list();

for (let i=0; i<summaries.accountSummaries.length;i++) {

            let propertyName = summaries.accountSummaries[i].displayName;

            return propertyName;

}
}

//Console.log >>> summaries.accountSummaries[0];

{ propertySummaries:
   [ { parent: 'accounts/XXXX',
       property: 'properties/XXX',
       propertyType: 'PROPERTY_TYPE_ORDINARY',
       displayName: 'xxx' },
     { parent: 'accounts/xxxx',
       displayName: 'XXXX',
       property: 'properties/XXXX',
       propertyType: 'PROPERTY_TYPE_ORDINARY' } ],
  name: 'accountSummaries/XXXX',
  account: 'accounts/XXXX',
  displayName: 'SSSSSS' }

</code>```

List Function Execution Log

Body:
I am trying to pull GA4 Accounts from listAccounts() function and want to populate the drop-down field with GA4 List accounts on the HTML front-end.

When I try to click on the custom menu in google sheets, I get this error - TypeError: Cannot read properties of undefined (reading 'length')

HTML

 <? var data = listAccounts() ?>

<optgroup label="Ad Accounts">

 <? for (i=0; i<data.propertyName.length; i++) { ?>
    <option value="<?= data.propertyName[i] ?>"> <?= data.propertyName[i] ?>) </option>

</optgroup>

Code.gs

function listAccounts () {

const summaries = AnalyticsAdmin.AccountSummaries.list();

for (let i=0; i<summaries.accountSummaries.length;i++) {

            let propertyName = summaries.accountSummaries[i].displayName;

            return propertyName;

}
}

//Console.log >>> summaries.accountSummaries[0];

{ propertySummaries:
   [ { parent: 'accounts/XXXX',
       property: 'properties/XXX',
       propertyType: 'PROPERTY_TYPE_ORDINARY',
       displayName: 'xxx' },
     { parent: 'accounts/xxxx',
       displayName: 'XXXX',
       property: 'properties/XXXX',
       propertyType: 'PROPERTY_TYPE_ORDINARY' } ],
  name: 'accountSummaries/XXXX',
  account: 'accounts/XXXX',
  displayName: 'SSSSSS' }

List Function Execution Log


问:
How can I display all the data in a column in the console?
How can I display all the data in a column in the console? For example, I'm using the count() function, but it only shows me 10 cases out of 91.

I'm using the count() function, but it only shows me 10 cases out of 91.


问:
Bad State: No element BlocBuilder Flutter
DropDownButton value is causing this error but If I remove value it renders items without any problem. I am providing state.deviceKeys
inside bloc provider.

```<code>    return BlocProvider(
      create: (context) =>
          ConfigBloc(dashboardRepository: DashboardRepository())
            ..add(ConfigLoad()),
      child: const ConfigCard(),
    );
</code>```
```<code>    void _onConfigLoad(ConfigLoad event, Emitter<ConfigState> emit) {
    final keys = _dashboardRepository.motorList.map((e) => e.key).toList();
    print('KEYS>>>>>>>>>>>>>  $keys');
    emit(state.copyWith(deviceKeys: keys));
  }
</code>```

This Prints keys with no problem.

return BlocBuilder<ConfigBloc, ConfigState>(
   builder: (context, state){
                   return DropdownButton<String>(
                          icon: const Icon(Icons.arrow_downward),
                          elevation: 16,
                          underline: Container(
                            height: 2,
                            color: Colors.deepPurpleAccent,
                          ),
                          value: state.deviceKeys.first,
                          items: state.deviceKeys
                              .map(
                                (e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ),
                              )
                              .toList(),
                          onChanged: (value) {},
                        );
                      }
                    );
```

Body:
DropDownButton value is causing this error but If I remove value it renders items without any problem. I am providing state.deviceKeys
inside bloc provider.

    return BlocProvider(
      create: (context) =>
          ConfigBloc(dashboardRepository: DashboardRepository())
            ..add(ConfigLoad()),
      child: const ConfigCard(),
    );

    void _onConfigLoad(ConfigLoad event, Emitter<ConfigState> emit) {
    final keys = _dashboardRepository.motorList.map((e) => e.key).toList();
    print('KEYS>>>>>>>>>>>>>  $keys');
    emit(state.copyWith(deviceKeys: keys));
  }

This Prints keys with no problem.

return BlocBuilder<ConfigBloc, ConfigState>(
   builder: (context, state){
                   return DropdownButton<String>(
                          icon: const Icon(Icons.arrow_downward),
                          elevation: 16,
                          underline: Container(
                            height: 2,
                            color: Colors.deepPurpleAccent,
                          ),
                          value: state.deviceKeys.first,
                          items: state.deviceKeys
                              .map(
                                (e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ),
                              )
                              .toList(),
                          onChanged: (value) {},
                        );
                      }
                    );


问:
Pageview data not loading on initial page in Flutter until screen is pressed
When my PageView opens, the data does not load until i press anywhere on the screen.  Display data comes from a List and all displays fine once an initial gesture is made.

I'm new to Flutter, so any ideas what i'm missing?

My widget build code is below;

```<code>Expanded(
 child: Builder(
  builder: (context) {
   super.build(context);
      return Container(
         width: MediaQuery.of(context).size.height *
          0.9, //double.infinity,
         height:
          MediaQuery.of(context).size.height * 0.2,
          child: Stack(
           children: [
            Padding(
              padding: EdgeInsetsDirectional.fromSTEB(
                 0, 0, 0, 50),
              child: PageView.builder(
               controller: pageViewController ??=
                PageController(
                  initialPage: min(0, 3 - 1)),
                scrollDirection: Axis.horizontal,
                itemCount: dataLength,
                itemBuilder: (context, articleIndex) {
                 super.build(context); // 19/12/2022
                 Articles? articles = this
                  .getGroupedPosData()
                  ?.elementAt(articleIndex);
                    var currentPage = articleIndex += 1;
                    final tester = _orderInfo?.get(articleIndex);
                    return Row(
                     mainAxisSize: MainAxisSize.max,
                     mainAxisAlignment:
                         MainAxisAlignment.center,
                     crossAxisAlignment:
                          CrossAxisAlignment.start,
</code>```

Body:
When my PageView opens, the data does not load until i press anywhere on the screen.  Display data comes from a List and all displays fine once an initial gesture is made.

I'm new to Flutter, so any ideas what i'm missing?

My widget build code is below;

Expanded(
 child: Builder(
  builder: (context) {
   super.build(context);
      return Container(
         width: MediaQuery.of(context).size.height *
          0.9, //double.infinity,
         height:
          MediaQuery.of(context).size.height * 0.2,
          child: Stack(
           children: [
            Padding(
              padding: EdgeInsetsDirectional.fromSTEB(
                 0, 0, 0, 50),
              child: PageView.builder(
               controller: pageViewController ??=
                PageController(
                  initialPage: min(0, 3 - 1)),
                scrollDirection: Axis.horizontal,
                itemCount: dataLength,
                itemBuilder: (context, articleIndex) {
                 super.build(context); // 19/12/2022
                 Articles? articles = this
                  .getGroupedPosData()
                  ?.elementAt(articleIndex);
                    var currentPage = articleIndex += 1;
                    final tester = _orderInfo?.get(articleIndex);
                    return Row(
                     mainAxisSize: MainAxisSize.max,
                     mainAxisAlignment:
                         MainAxisAlignment.center,
                     crossAxisAlignment:
                          CrossAxisAlignment.start,


问:
how to get the path of SRT file in andriod java
i am  developing an app that  add subtitle (srt file) to videos using ffmpeg

i want to know how the get the path on an .srt file

right now what i am doing this to get the srt file is

```<code> Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

            intent.setType("*/*");

             intent.addCategory(Intent.CATEGORY_OPENABLE);
             intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)

            startActivityForResult(intent, SELECT_SRT)
)
</code>```

so how can i use the startActivityForResult() to get the path?

i did get the path of the video doing this

```<code> String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            try {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } catch (RuntimeException e) {

                Log.d("TAG", "MainActivity :  catch (RuntimeException e)");

                return null;
            }
        } else return null;
</code>```

but this  will return null if its a SRT file

Body:
i am  developing an app that  add subtitle (srt file) to videos using ffmpeg

i want to know how the get the path on an .srt file

right now what i am doing this to get the srt file is

 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

            intent.setType("*/*");

             intent.addCategory(Intent.CATEGORY_OPENABLE);
             intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)

            startActivityForResult(intent, SELECT_SRT)
)

so how can i use the startActivityForResult() to get the path?

i did get the path of the video doing this

 String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            try {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } catch (RuntimeException e) {

                Log.d("TAG", "MainActivity :  catch (RuntimeException e)");

                return null;
            }
        } else return null;

but this  will return null if its a SRT file


问:
ASP.NET Core 3.1 app won't run while the 3.1 runtime is installed
When I attempt to run an ASP.NET Core 3.1 App with the command dotnet run it won't run due to the error below.

```<code>It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '6.0.12' was not found.
  - The following frameworks were found:
      3.1.32 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]
      5.0.17 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.
</code>```

It attempted to find 6.0.12 while the app has nothing to with .NET 6.

And this is how .csproj file look like.

```<code> <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>xxxxxx</RootNamespace>
    <AssemblyName>xxxxxxxx</AssemblyName>
    <AssemblyVersion>1.0.1.0</AssemblyVersion>
    <FileVersion>1.0.1.0</FileVersion>
    <Version>1.0.1</Version>
  </PropertyGroup>
</code>```

The OS is Ubuntu WSL.

```<code>$ dotnet --list-sdks
3.1.426 [/usr/share/dotnet/sdk]
5.0.408 [/usr/share/dotnet/sdk]
6.0.404 [/usr/share/dotnet/sdk]

$ dotnet --list-runtimes
Microsoft.AspNetCore.App 3.1.32 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 5.0.17 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.32 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Microsoft.NETCore.App 5.0.17 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
</code>```

Any ideas on why it won't run, and what needs to be done?
Thank you in advance!

I tried to check the installed runtimes with command dotnet --list-runtimes. And it turns out 3.1 is already installed.

Body:
When I attempt to run an ASP.NET Core 3.1 App with the command dotnet run it won't run due to the error below.

It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '6.0.12' was not found.
  - The following frameworks were found:
      3.1.32 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]
      5.0.17 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.

It attempted to find 6.0.12 while the app has nothing to with .NET 6.

And this is how .csproj file look like.

 <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>xxxxxx</RootNamespace>
    <AssemblyName>xxxxxxxx</AssemblyName>
    <AssemblyVersion>1.0.1.0</AssemblyVersion>
    <FileVersion>1.0.1.0</FileVersion>
    <Version>1.0.1</Version>
  </PropertyGroup>

The OS is Ubuntu WSL.

$ dotnet --list-sdks
3.1.426 [/usr/share/dotnet/sdk]
5.0.408 [/usr/share/dotnet/sdk]
6.0.404 [/usr/share/dotnet/sdk]

$ dotnet --list-runtimes
Microsoft.AspNetCore.App 3.1.32 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 5.0.17 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.32 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Microsoft.NETCore.App 5.0.17 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

Any ideas on why it won't run, and what needs to be done?
Thank you in advance!

I tried to check the installed runtimes with command dotnet --list-runtimes. And it turns out 3.1 is already installed.


问:
How warning setState(...) in formArray?
my code

In Field sum I get value from Field qty which is an array and calculate it.

```<code> const [result, setResult] = useState(0)
}
  const showForm = ({
    values,
    setFieldValue,
    isValid,

  }: FormikProps<ClaimData>) => {
 return (
      <Form >
          <FieldArray name="product">
              {({ insert, remove, push }) => (
                <Box>
                  {values.product.length > 0 &&
                    values.product.map((product, index) => (
                      <Grid container spacing={2} key={index} p={2} >
                      ...
                        <Grid item sm={12} lg={3} >
                          <Field
                            fullWidth
                            label="QTY"
                            component={TextField}
                            name={`product.${index}.qty`}
                            placeholder="qty"
                            type="text"
                            multiline
                          />
                        </Grid>
                      </Grid>
                    ))}
                  <Grid container
                    spacing={2}
                    direction="row"
                    justifyContent="center"
                    alignItems="center">
                    <Grid item sm={12} lg={3} >
                      <Field
                        fullWidth
                        label="sum"
                        component={TextField}
                        name={`sum`}
                        value={values.product?.reduce((sum,item)=>{

                          setResult(sum + item.qty *1)  //<------setState
                          return sum + item.qty *1

                        },0)}
                        placeholder="sum"
                        type="number"
                        disabled
                      />

                    </Grid>
                  </Grid>

                </Box>

              )}

            </FieldArray>
      </Form >

}}
return (
    <>
      <Formik
        initialValues={initialValues}
        onSubmit={async (values, { setSubmitting }) => {
        }}
       >
         {props => showForm(props)}
       </Formik>
    </>
)
</code>```

I want to calculate in formik without pressing the onsummit button.
but in the console shows

Warning: Cannot update a component (Add) while rendering a different component (FieldArrayInner). To locate the bad setState() call inside FieldArrayInner, follow the stack trace as described in

How can I solve this problem?

Title: How warning setState(...) in formArray?

Body:
my code

In Field sum I get value from Field qty which is an array and calculate it.

 const [result, setResult] = useState(0)
}
  const showForm = ({
    values,
    setFieldValue,
    isValid,

  }: FormikProps<ClaimData>) => {
 return (
      <Form >
          <FieldArray name="product">
              {({ insert, remove, push }) => (
                <Box>
                  {values.product.length > 0 &&
                    values.product.map((product, index) => (
                      <Grid container spacing={2} key={index} p={2} >
                      ...
                        <Grid item sm={12} lg={3} >
                          <Field
                            fullWidth
                            label="QTY"
                            component={TextField}
                            name={`product.${index}.qty`}
                            placeholder="qty"
                            type="text"
                            multiline
                          />
                        </Grid>
                      </Grid>
                    ))}
                  <Grid container
                    spacing={2}
                    direction="row"
                    justifyContent="center"
                    alignItems="center">
                    <Grid item sm={12} lg={3} >
                      <Field
                        fullWidth
                        label="sum"
                        component={TextField}
                        name={`sum`}
                        value={values.product?.reduce((sum,item)=>{

                          setResult(sum + item.qty *1)  //<------setState
                          return sum + item.qty *1

                        },0)}
                        placeholder="sum"
                        type="number"
                        disabled
                      />

                    </Grid>
                  </Grid>

                </Box>

              )}

            </FieldArray>
      </Form >

}}
return (
    <>
      <Formik
        initialValues={initialValues}
        onSubmit={async (values, { setSubmitting }) => {
        }}
       >
         {props => showForm(props)}
       </Formik>
    </>
)

I want to calculate in formik without pressing the onsummit button.
but in the console shows

Warning: Cannot update a component (Add) while rendering a different component (FieldArrayInner). To locate the bad setState() call inside FieldArrayInner, follow the stack trace as described in

How can I solve this problem?


问:
How can I run two different react apps by just one npm start
so, i have two paths
React Apps:
-my-first-app
-my-second-app
is it possible to start them by just one npm start
because now i need to create two different powershells by the path of current app
i tried to wrap them into another react-app with follow package.json
"start": "cd Projects/Project1 && export PORT=3001 & cd ../Project2 && export PORT=3000 & react-scripts start",
but it's doesn't work</p>