问:
GeometryReader sometimes gives wrong .global frame origin for Map annotations
Test setup:

I have a View that displays modally a Map with annotations:

```<code>struct Annotation: Identifiable {
    let id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
}

struct MapViewSWUI: View {
    @Binding var show_map_modal: Bool
    @State var region: MKCoordinateRegion

    var body: some View {
        let _ = Self._printChanges()
        VStack {
            ZStack { // Top bar
                Text("Oo")
                    .bold()
                HStack {
                    Button(action: {
                        show_map_modal = false
                    }) {
                        HStack(spacing: 10) {
                            Image(systemName: "chevron.left")
                            Text(NSLocalizedString("BACK", comment: " "))
                        }
                        .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
                    }
                    Spacer()
                }
            }
            let annotations = [Annotation(name: "0",
                                          coordinate: CLLocationCoordinate2D(latitude: 49.450534, longitude: 8.6694930)),
                               Annotation(name: "1",
                                          coordinate: CLLocationCoordinate2D(latitude: 49.450701, longitude: 8.6677427))
            ]
            Map(coordinateRegion: $region,
                    interactionModes: .all,
                    showsUserLocation: false,
                    annotationItems: annotations) { annotation in
                MapAnnotation(coordinate: annotation.coordinate, anchorPoint: CGPoint(x: 0.5, y: 1)) {
                    GeometryReader { geo in
                        Color(.green)
                        .onAppear {
                            print("Annotation coordinate: (\(annotation.coordinate.latitude),\(annotation.coordinate.longitude))")
                            print(".global origin: \(geo.frame(in: .global).origin)")
                        }
                    }
                    .frame(width: 30, height: 30)
                }
            }
        } // VStack
    }
}
</code>```

When show_map_modal is set to true, the map is shown with the test annotations:

Problem:

When the map is shown the following is normally logged:

```<code>MapViewSWUI: @self, @identity, _region, _annotationDragged changed.
2023-01-07 09:19:17.254324+0100 ShopEasy![47736:11270478] Metal API Validation Enabled
MapViewSWUI: _region changed.
Annotation coordinate: (49.450534,8.669493)
.global origin: (271.94092664926427, 438.1697202246186)
Annotation coordinate: (49.450701,8.6677427)
.global origin: (91.00613205620596, 411.6026828329208)
</code>```

However it may also happen that the following is logged:

```<code>MapViewSWUI: @self, @identity, _region, _annotationDragged changed.
MapViewSWUI: _region changed.
Annotation coordinate: (49.450701,8.6677427)
.global origin: (-15.0, 76.66666666666666)
Annotation coordinate: (49.450534,8.669493)
.global origin: (-15.0, 76.66666666666666)
</code>```

When I dismiss the modally shown map using the back button ("Zurück"), and display the map again, the same happens (one of the logs above).

Workarounds tried:

When, within GeometryReader .onAppear, I embed the print statements in  DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // … }, the .global frame coordinates seem always to be correct. But this seems to be a hack.

When I replace .onAppear by .onTapGesture, the .global frame coordinates also seem always to be correct. Unfortunately, I need the coordinates when the annotations appear on the screen, without further user interaction.

Questions:

How is it possible that the annotations (green square) are correctly placed on the map, but the GeometryReader gives sometimes the correct .global screen coordinates, but sometimes another strange value (-15.0, 76.66666666666666) that is, if it is given, always the same? Is this a SwiftUI bug?

Is something wrong with my code? And if so, how to do it right?

Body:
Test setup:

I have a View that displays modally a Map with annotations:

struct Annotation: Identifiable {
    let id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
}

struct MapViewSWUI: View {
    @Binding var show_map_modal: Bool
    @State var region: MKCoordinateRegion

    var body: some View {
        let _ = Self._printChanges()
        VStack {
            ZStack { // Top bar
                Text("Oo")
                    .bold()
                HStack {
                    Button(action: {
                        show_map_modal = false
                    }) {
                        HStack(spacing: 10) {
                            Image(systemName: "chevron.left")
                            Text(NSLocalizedString("BACK", comment: " "))
                        }
                        .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
                    }
                    Spacer()
                }
            }
            let annotations = [Annotation(name: "0",
                                          coordinate: CLLocationCoordinate2D(latitude: 49.450534, longitude: 8.6694930)),
                               Annotation(name: "1",
                                          coordinate: CLLocationCoordinate2D(latitude: 49.450701, longitude: 8.6677427))
            ]
            Map(coordinateRegion: $region,
                    interactionModes: .all,
                    showsUserLocation: false,
                    annotationItems: annotations) { annotation in
                MapAnnotation(coordinate: annotation.coordinate, anchorPoint: CGPoint(x: 0.5, y: 1)) {
                    GeometryReader { geo in
                        Color(.green)
                        .onAppear {
                            print("Annotation coordinate: (\(annotation.coordinate.latitude),\(annotation.coordinate.longitude))")
                            print(".global origin: \(geo.frame(in: .global).origin)")
                        }
                    }
                    .frame(width: 30, height: 30)
                }
            }
        } // VStack
    }
}

When show_map_modal is set to true, the map is shown with the test annotations:

Problem:

When the map is shown the following is normally logged:

MapViewSWUI: @self, @identity, _region, _annotationDragged changed.
2023-01-07 09:19:17.254324+0100 ShopEasy![47736:11270478] Metal API Validation Enabled
MapViewSWUI: _region changed.
Annotation coordinate: (49.450534,8.669493)
.global origin: (271.94092664926427, 438.1697202246186)
Annotation coordinate: (49.450701,8.6677427)
.global origin: (91.00613205620596, 411.6026828329208)

However it may also happen that the following is logged:

MapViewSWUI: @self, @identity, _region, _annotationDragged changed.
MapViewSWUI: _region changed.
Annotation coordinate: (49.450701,8.6677427)
.global origin: (-15.0, 76.66666666666666)
Annotation coordinate: (49.450534,8.669493)
.global origin: (-15.0, 76.66666666666666)

When I dismiss the modally shown map using the back button ("Zurück"), and display the map again, the same happens (one of the logs above).

Workarounds tried:

When, within GeometryReader .onAppear, I embed the print statements in  DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // … }, the .global frame coordinates seem always to be correct. But this seems to be a hack.

When I replace .onAppear by .onTapGesture, the .global frame coordinates also seem always to be correct. Unfortunately, I need the coordinates when the annotations appear on the screen, without further user interaction.

Questions:

How is it possible that the annotations (green square) are correctly placed on the map, but the GeometryReader gives sometimes the correct .global screen coordinates, but sometimes another strange value (-15.0, 76.66666666666666) that is, if it is given, always the same? Is this a SwiftUI bug?

Is something wrong with my code? And if so, how to do it right?


来源: stackexchange

问:
Nutritionix API store the food item wanted in a variable
I am developing a java mobile application to get the calorie information of a food.
So basically a food name is entered through an edit text and by tapping a button get the information from the nutritionix api.

So far this is the code that I have to make the request using okhttp:

```<code>OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \"query\":\"burger\"\r\n}");
Request request = new Request.Builder()
    .url("https://trackapi.nutritionix.com/v2/natural/nutrients")
    .method("POST", body)
    .addHeader("x-app-id", "my-id")
    .addHeader("x-app-key", "app-key")
    .addHeader("Content-Type", "application/json")
    .build();
</code>```

and instead of having burger in the request body i would like to add a variable. I am getting all the  information I need if the food item is hard coded in the request body so now i want it to be selected by the user
Could anyone help me or direct me in any resources that could help me solve this?
Thanks

ContentLicense: CC BY-SA 4.0

Body:
I am developing a java mobile application to get the calorie information of a food.
So basically a food name is entered through an edit text and by tapping a button get the information from the nutritionix api.

So far this is the code that I have to make the request using okhttp:

OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \"query\":\"burger\"\r\n}");
Request request = new Request.Builder()
    .url("https://trackapi.nutritionix.com/v2/natural/nutrients")
    .method("POST", body)
    .addHeader("x-app-id", "my-id")
    .addHeader("x-app-key", "app-key")
    .addHeader("Content-Type", "application/json")
    .build();

and instead of having burger in the request body i would like to add a variable. I am getting all the  information I need if the food item is hard coded in the request body so now i want it to be selected by the user
Could anyone help me or direct me in any resources that could help me solve this?
Thanks


问:
How to fix this 'unexpected end of JSON input' bug?
Just started a 'Writing JS for the Web' course with following exercise and code, but getting 'unexpected end of JSON input' message upon completion of the exercise. Any idea what's going wrong? I'm coding in the following Codepen: https://codepen.io/nicolaspatschkowski/pen/GRJBZjy?editors=1111</p>
```<code>// Get form elements
const titleInput = document.getElementById('title');
const contentInput = document.getElementById('content');
const submitButton = document.getElementById('submit-button');

const url = 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets';

// Get DOM elements for showing response
const responseMessage = document.getElementById('response-message');
const responseTitle = document.getElementById('response-title');
const responseId = document.getElementById('response-id');
const responseContent = document.getElementById('response-content');

submitButton.addEventListener('click', ($event) => {
  $event.preventDefault();
  const post = {
    title: titleInput.value,
    content: contentInput.value
  };
  submitFormData(post);
});

function makeRequest(data) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.open('POST', url + '/create-post');
    request.onreadystatechange = () => {
      if (request.readyState === 4) {
        if (request.status === 201) {
          resolve(JSON.parse(request.response));
        } else {
          reject(JSON.parse(request.response));
        }
      }
    };
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(JSON.stringify(data));
  });
}

async function submitFormData(post) {
  try {
const requestPromise = makeRequest(post);
const response = await requestPromise;
responseMessage.textContent = response.message;
responseTitle.textContent = response.post.title;
responseId.textContent = response.post.id;
responseContent.textContent = response.post.content;
  } catch (errorResponse) { responseMessage.textContent = errorResponse.error;
  }
};
</code>```

Body:
Just started a 'Writing JS for the Web' course with following exercise and code, but getting 'unexpected end of JSON input' message upon completion of the exercise. Any idea what's going wrong? I'm coding in the following Codepen: https://codepen.io/nicolaspatschkowski/pen/GRJBZjy?editors=1111

// Get form elements
const titleInput = document.getElementById('title');
const contentInput = document.getElementById('content');
const submitButton = document.getElementById('submit-button');

const url = 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets';

// Get DOM elements for showing response
const responseMessage = document.getElementById('response-message');
const responseTitle = document.getElementById('response-title');
const responseId = document.getElementById('response-id');
const responseContent = document.getElementById('response-content');

submitButton.addEventListener('click', ($event) => {
  $event.preventDefault();
  const post = {
    title: titleInput.value,
    content: contentInput.value
  };
  submitFormData(post);
});

function makeRequest(data) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.open('POST', url + '/create-post');
    request.onreadystatechange = () => {
      if (request.readyState === 4) {
        if (request.status === 201) {
          resolve(JSON.parse(request.response));
        } else {
          reject(JSON.parse(request.response));
        }
      }
    };
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(JSON.stringify(data));
  });
}

async function submitFormData(post) {
  try {
const requestPromise = makeRequest(post);
const response = await requestPromise;
responseMessage.textContent = response.message;
responseTitle.textContent = response.post.title;
responseId.textContent = response.post.id;
responseContent.textContent = response.post.content;
  } catch (errorResponse) { responseMessage.textContent = errorResponse.error;
  }
};


问:
column "session_length" is of type integer but expression is of type character varying
I want to add an entry to the postgres DB with the data entered in this form

```<code><Form onSubmit={this.handleSubmit}>
                    <FormGroup>
                        <Label for="name">Name</Label>
                        <Input type="text" name="session_name" id="session_name"
                               onChange={this.handleChange} autoComplete="session_name"/>
                    </FormGroup>
                    <FormGroup>
                        <Label for="email">ID</Label>
                        <Input type="text" name="session_id" id="session_id"
                               onChange={this.handleChange} autoComplete="session_id"/>
                    </FormGroup>
                    <FormGroup>
                        <Label for="email">Length</Label>
                        <Input type="integer" name="session_length" id="session_length"
                               onChange={this.handleChange} autoComplete="session_length"/>
                    </FormGroup>
                    <FormGroup>
                        <Button color="primary" type="submit">Save</Button>{' '}
                        <Button color="secondary" tag={Link} to="/clients">Cancel</Button>
                    </FormGroup>
</code>```

Below are the methods used to handle change and submission

```<code>    handleChange(event) {
        const target = event.target;
        const name = target.name;
        const value = target.value;
        let item = {...this.state.item};
        item[name] = value;
        this.setState({item});
    }
    async handleSubmit(event) {
        event.preventDefault();
        const {item} = this.state;

        await fetch('/api/v1/sessions' + (item.id ? '/' + item.id : ''), {
            method: (item.id) ? 'PUT' : 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item),
        });
        this.props.history.push('/api/v1/sessions');
    }
</code>```

"session_length" and "session_id" are of type integers. I tried converting the input from the form to integers in the handleChange method but that didn't work.

Body:
I want to add an entry to the postgres DB with the data entered in this form

<Form onSubmit={this.handleSubmit}>
                    <FormGroup>
                        Name
                        <Input type="text" name="session_name" id="session_name"
                               onChange={this.handleChange} autoComplete="session_name"/>
                    </FormGroup>
                    <FormGroup>
                        ID
                        <Input type="text" name="session_id" id="session_id"
                               onChange={this.handleChange} autoComplete="session_id"/>
                    </FormGroup>
                    <FormGroup>
                        Length
                        <Input type="integer" name="session_length" id="session_length"
                               onChange={this.handleChange} autoComplete="session_length"/>
                    </FormGroup>
                    <FormGroup>
                        <Button color="primary" type="submit">Save</Button>{' '}
                        <Button color="secondary" tag={Link} to="/clients">Cancel</Button>
                    </FormGroup>

Below are the methods used to handle change and submission

    handleChange(event) {
        const target = event.target;
        const name = target.name;
        const value = target.value;
        let item = {...this.state.item};
        item[name] = value;
        this.setState({item});
    }
    async handleSubmit(event) {
        event.preventDefault();
        const {item} = this.state;

        await fetch('/api/v1/sessions' + (item.id ? '/' + item.id : ''), {
            method: (item.id) ? 'PUT' : 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item),
        });
        this.props.history.push('/api/v1/sessions');
    }

"session_length" and "session_id" are of type integers. I tried converting the input from the form to integers in the handleChange method but that didn't work.


问:
How to select dynamic column in Xamarin forms SQL Lite
I using Xamarin forms. I would like to select my dynamic column using SQL Lite Query but I got an error.

Here is My model :

```<code>public class MyWords
{

[PrimaryKey, AutoIncrement]
public int ID { get; set; }

[JsonProperty(PropertyName = "id")]
public Guid MyId { get; set; } = Guid.NewGuid();

[JsonProperty(PropertyName = "languagevalue1")]
public string LanguageValue1 { get; set; }

[JsonProperty(PropertyName = "languagevalue2")]
public string LanguageValue2 { get; set; }

[JsonProperty(PropertyName = "languagevaluecombine")]
public string LanguageValueCombine { get { return LanguageValue1 + "  " + Separator + "  " + LanguageValue2; } }

}
</code>```

I would like to get the value of the column "languagevaluecombine" but I have an error.

Here is how I query my column "languagevaluecombine"  table :

```<code>var ListCombine = conn.QueryAsync<MyWords>("select DISTINCT languagevaluecombine from MyWords ");
</code>```

Here is the error that got :

```<code>SQLite.SQLiteException has been thrown
no such column: languagevaluecombine
</code>```

But When I try with the column "languagevalue2" I works as it is not a dynamic columns

Thanks for your help

Body:
I using Xamarin forms. I would like to select my dynamic column using SQL Lite Query but I got an error.

Here is My model :

public class MyWords
{

[PrimaryKey, AutoIncrement]
public int ID { get; set; }

[JsonProperty(PropertyName = "id")]
public Guid MyId { get; set; } = Guid.NewGuid();

[JsonProperty(PropertyName = "languagevalue1")]
public string LanguageValue1 { get; set; }

[JsonProperty(PropertyName = "languagevalue2")]
public string LanguageValue2 { get; set; }

[JsonProperty(PropertyName = "languagevaluecombine")]
public string LanguageValueCombine { get { return LanguageValue1 + "  " + Separator + "  " + LanguageValue2; } }

}

I would like to get the value of the column "languagevaluecombine" but I have an error.

Here is how I query my column "languagevaluecombine"  table :

var ListCombine = conn.QueryAsync<MyWords>("select DISTINCT languagevaluecombine from MyWords ");

Here is the error that got :

SQLite.SQLiteException has been thrown
no such column: languagevaluecombine

But When I try with the column "languagevalue2" I works as it is not a dynamic columns

Thanks for your help


问:
Discord.js fs level system adding } at ends of .json
I'm currently working on a discord bot that includes an economy and a level system.
When user levels up, he should get beans (currency).
The level system works so far, but when I start the add bean code, a } is placed at the end of my user.json and the consol says "End of file expected." and the bot crashes

Index.js:

```<code> if(udb[message.author.id].xp > udb[message.author.id].reqxp-1){
    udb[message.author.id].reqxp = udb[message.author.id].reqxp + 50
    udb[message.author.id].xp = 1
    udb[message.author.id].level = udb[message.author.id].level + 1
    const nl = udb[message.author.id].level
var addbeans = 0
if(botdb.beans.type === "amount"){
  var addbeans = addbeans + botdb.beans.amount
} else if(botdb.beans.type === "TimesTheLevel"){
  var addbeans = amount * nl
}
const b = udb[message.author.id].beans + addbeans
console.log(b)
udb[message.author.id].beans = b
    fs.writeFile("./database/user.json", JSON.stringify(udb), err =>{
      if(err){
          console.log(err);
      }
  });
</code>```

user.json befor addbeans:

```<code>{"779054848346685482":{"level":1,"xp":1,"reqxp":25,"beans":100}}
</code>```

user.json after addbeans:

```<code>{"779054848346685482":{"level":2,"xp":1,"reqxp":75,"beans":200}}}
</code>```

I don't know what to do and need help

Body:
I'm currently working on a discord bot that includes an economy and a level system.
When user levels up, he should get beans (currency).
The level system works so far, but when I start the add bean code, a } is placed at the end of my user.json and the consol says "End of file expected." and the bot crashes

Index.js:

 if(udb[message.author.id].xp > udb[message.author.id].reqxp-1){
    udb[message.author.id].reqxp = udb[message.author.id].reqxp + 50
    udb[message.author.id].xp = 1
    udb[message.author.id].level = udb[message.author.id].level + 1
    const nl = udb[message.author.id].level
var addbeans = 0
if(botdb.beans.type === "amount"){
  var addbeans = addbeans + botdb.beans.amount
} else if(botdb.beans.type === "TimesTheLevel"){
  var addbeans = amount * nl
}
const b = udb[message.author.id].beans + addbeans
console.log(b)
udb[message.author.id].beans = b
    fs.writeFile("./database/user.json", JSON.stringify(udb), err =>{
      if(err){
          console.log(err);
      }
  });

user.json befor addbeans:

{"779054848346685482":{"level":1,"xp":1,"reqxp":25,"beans":100}}

user.json after addbeans:

{"779054848346685482":{"level":2,"xp":1,"reqxp":75,"beans":200}}}

I don't know what to do and need help


问:
How to use sprite mask on animated sprite?
I'm trying to add the sprite mask component to my animated sprite with sprite skin but it let me choose only one sprite as a mask and there's no option for adding animation on the sprite mask. Is there any way to do this?</p>


问:
How to check if checkboxes are checked in an image with python?
I have an image with some text, a table with checkboxes and then again a text as shown in the following
image.

I would like to write a python script that scans the image and checks witch checkbox is checked and write the result into a variable. Do you have any suggestions or advice on how to do this?

So far I've used pytesseract to exctract all the text in the image returning everything except the content of the table. Next, I've tried cv2 but could only modify the image itself. I was able to erase everything except the table structure. However I also lost the content inside the table.

My current thought is, ideally I'm able to convert the table into a 2D list and then use a "for each loop" to iterate over them. But at the moment I have no idea how to do it and I would appreciate any suggestions to push me into the right direction. Any advice would be appreciated :).


问:
React, Tailwind and Application of Viewport-Specific Classes
I am trying to apply an onhover effect for a viewport larger than 768px. Below 768px it should look like the elements are "always onhover".
Specifically, on desktop or larger devices in general, there should be a background in a box at onhover. This background should always be shown on mobile, i.e. <768px in my case.

What am I doing wrong?
Here are the snippets.

JSX-Snippet:

```<code>import { features } from "../constants"; import styles from "../style";

const FeatureCard = ({ icon, title, content, index }) => (
<div className=
 {`
   flex flex-row p-6 rounded-[20px]
   ss:max-sm:feature-card-small
   sm:feature-card
   ${index !== features.length - 1 ? "mb-6" : "mb-0"}
 `}
>
<div className={`
    w-[64px]
    h-[64px]
    rounded-full
    ${styles.flexCenter}
    bg-dimBlue`
}>
    <img
        src={icon}
        alt="star"
        className="
            w-[50%]
            h-[50%]
            object-contain"
    />
</div>
    <div className="flex-1 flex flex-col ml-3">
       <h4 className="
           font-poppins
           font-semibold
           text-white
           text-[18px]
           leading-[23.4px]
           mb-1">
        {title}
       </h4>
      <p className="
          font-poppins
          font-normal
          text-dimWhite
          text-[16px]
          leading-[24px]
      ">
        {content}
      </p>
    );

    export default FeatureCard;
</code>```

CSS-Snippet:

```<code>.feature-card:hover { background: var(--black-gradient); box-shadow: var(--card-shadow); }

.feature-card-small { background: var(--black-gradient); box-shadow: var(--card-shadow); }
</code>```

simply apply feature-card as class without viewport specification works as expected; onhover --> background changes

different viewport-specifications (sm:..., ss:max-sm and sm:) and creation of different CSS classes (so there can be no overlap for sure) did not work

sorry if the code block looks like a mess here on stackoverflow. my first post, still learning.

Body:
I am trying to apply an onhover effect for a viewport larger than 768px. Below 768px it should look like the elements are "always onhover".
Specifically, on desktop or larger devices in general, there should be a background in a box at onhover. This background should always be shown on mobile, i.e. <768px in my case.

What am I doing wrong?
Here are the snippets.

JSX-Snippet:

import { features } from "../constants"; import styles from "../style";

const FeatureCard = ({ icon, title, content, index }) => (

        {title}

        {content}

    );

    export default FeatureCard;

CSS-Snippet:

.feature-card:hover { background: var(--black-gradient); box-shadow: var(--card-shadow); }

.feature-card-small { background: var(--black-gradient); box-shadow: var(--card-shadow); }

simply apply feature-card as class without viewport specification works as expected; onhover --> background changes

different viewport-specifications (sm:..., ss:max-sm and sm:) and creation of different CSS classes (so there can be no overlap for sure) did not work

sorry if the code block looks like a mess here on stackoverflow. my first post, still learning.


问:
How to import all default types in a TypeScript Definition file?
Current situation (simplified):

```<code>type OneCtrl = import("some-package").default.OneCtrl
type TwoCtrl = import("some-package").default.TwoCtrl

declare module "my-package" {
    export function useUtils(options: OneCtrl): TwoCtrl
}
</code>```

I am having to repeatedly import individual types from the default import.

Using <reference> didn't work.

I tried type g = import("some-package").default and then using g.OneCtrl but that didn't work either.

I am importing from a package that has a namespace. Direct ES6 imports would result in the definition file not being an ambient definition anymore which is what I need otherwise the project gives errors.

Environment (For Context): Vite + Vue 3 + TS Project

Update on specifics

I am trying to add types to this external package vue-grapesjs-composables which is based on the original grapesjs package which does have types.

What I mean by having tried ES6 imports is that this would work in the definition file:

```<code>import type grapes from 'grapesjs'

declare module "vue-grapesjs-composables" {
    export function useGrapes(editorConfig: grapes.EditorConfig): grapes.Editor;
}
</code>```

but gives this error when I import it in a component:
Could not find a declaration file for module 'vue-grapesjs-composables'

Body:
Current situation (simplified):

type OneCtrl = import("some-package").default.OneCtrl
type TwoCtrl = import("some-package").default.TwoCtrl

declare module "my-package" {
    export function useUtils(options: OneCtrl): TwoCtrl
}

I am having to repeatedly import individual types from the default import.

Using <reference> didn't work.

I tried type g = import("some-package").default and then using g.OneCtrl but that didn't work either.

I am importing from a package that has a namespace. Direct ES6 imports would result in the definition file not being an ambient definition anymore which is what I need otherwise the project gives errors.

Environment (For Context): Vite + Vue 3 + TS Project

Update on specifics

I am trying to add types to this external package vue-grapesjs-composables which is based on the original grapesjs package which does have types.

What I mean by having tried ES6 imports is that this would work in the definition file:

import type grapes from 'grapesjs'

declare module "vue-grapesjs-composables" {
    export function useGrapes(editorConfig: grapes.EditorConfig): grapes.Editor;
}

but gives this error when I import it in a component:
Could not find a declaration file for module 'vue-grapesjs-composables'


问:
How can I disable a item in the suggested list?
I'm using the React Autosuggest package to render a list contains some disabled items.
How can I prevent disabled items on clicked?

I am read the document, but I did not find an event to solve my problem.
And I also used the event listener, which didn't work properly either
I am looking for a way to disable the click event of a list item.


问:
write external storage problem android stufio
WRITE_EXTERNAL_STORAGE not working in android 13 so how to save image in the storage from an application
android studio code

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
and checked in my android 13 device
but not working I want it to work so save my image of application in my phone


问:
Undefined value with customized radio input using react-hook-form
I want to make radio button input forms without radio button circles. I am able to make the interface of the form, but the form is sending undefined data.

Additionally, I added CSS that put a solid black border when radio buttons are checked, but this is not working either.

If I remove the CSS display: none, the form works fine; the data shows value, not undefined.

can anyone help me with this?  Thank you so much in advance!

The form consists of three components

CustomRadioBtn.module.css

.radioInput + .radioLabel:before{
    content: "";
    display: inline-block;
    background-size: contain;
    width: 140px;
    height: 140px;
}

.radioLabel {
  border-radius: 10px;
  color: gray;
  cursor: pointer;
  margin: auto;
  position: relative;
  text-align: center;
  transition: 0.5s;
}

.radioInput[value="slept less than 7hrs"]+.radioLabel:before{
    background-image: url(../../../public/images/sleep/lessThan7hrs.png);
}
.radioInput[value="slept more than 7hrs"]+.radioLabel:before{
    background-image: url(../../../public/images/sleep/moreThan7hrs.png);
}

/* below styling is not working */
.radioInput:checked + .radioLabel::before{
  border: 3px solid #000;
}
.radioInput{
  display: none;
}
```
<p><strong>CustomeIconContainer.tsx</strong></p>
<pre class="lang-ts prettyprint-override"><code>import { Controller, useForm } from "react-hook-form";
import styled from "styled-components";
import CustomIconInputForm from "../molecules/CustomIconInputForm";
import StyledFlexboxRow from "components/layouts/Flexbox/StyledFlexboxRow";

type Tdata = {
  sleep?: string;
  stool?: string;
  movement?: string;
};

interface IContainerProps {
  name: string;
  options: string[];
  desc: string;
  iconLog?: TIconValueData;
}

export type TIconValueData = {
  id?: number;
  sleep?: string;
  movement?: string;
  stool?: string;
};

/**
 * CustomIconContainer - handle icon input
 */
const CustomIconContainer = (props: IContainerProps) => {

  const { name, options, desc } = props;
  const { handleSubmit, control } = useForm();

  const onSubmit = (data: Tdata) => {
    if (data === undefined) {
      throw new Error("your log is undefined");
    }

    console.log(data);
  };

  const StyledLabel = styled.label`
    display: block;
  `;

  return (
    <div className="CustomIconContainer">
      <form onSubmit={handleSubmit(onSubmit)}>
        <StyledLabel>{desc}</StyledLabel>
        {/* mapping icon buttons */}
        <StyledFlexboxRow>
          {options.map((option, index) => (
            <Controller
              key={index}
              name={name}
              control={control}
              render={({ field: { onChange, ref, ...props } }) => (
                <CustomIconInputForm
                  {...props}
                  onChange={onChange}
                  value={option}
                  inputRef={ref}
                  desc={option}
                />
              )}
            />
          ))}
        </StyledFlexboxRow>
        <button type="submit">Save</button>
      </form>
    </div>
  );
};
export default CustomIconContainer;
</code>```

CustomIconInputForm.tsx

import { IconDefinition } from "@fortawesome/fontawesome-common-types";
import { RefCallBack } from "react-hook-form";
import styles from "./CustomRadioBtn.module.css";

interface ICustomIconProps {
  onChange?: () => void;
  name?: string;
  value?: string;
  icon?: IconDefinition;
  desc: string;
  inputRef?: RefCallBack;
}

const CustomIconInputForm = (props: ICustomIconProps) => {

  const { name, onChange, inputRef, value } = props;

  const onChangeHandler = () => {
    if (value !== undefined) {
      onChange && onChange();
    }
  };
  return (

      <input
        ref={inputRef}
        name={name}
        value={value}
        onChange={() => {
          onChangeHandler;
        }}
        type="radio"
        {...props}
        className={styles.radioInput}
      />

  );
};
export default CustomIconInputForm;
```

no radio button circles

with radio button circles

Body:
I want to make radio button input forms without radio button circles. I am able to make the interface of the form, but the form is sending undefined data.

Additionally, I added CSS that put a solid black border when radio buttons are checked, but this is not working either.

If I remove the CSS display: none, the form works fine; the data shows value, not undefined.

can anyone help me with this?  Thank you so much in advance!

The form consists of three components

CustomRadioBtn.module.css

.radioInput + .radioLabel:before{
    content: "";
    display: inline-block;
    background-size: contain;
    width: 140px;
    height: 140px;
}

.radioLabel {
  border-radius: 10px;
  color: gray;
  cursor: pointer;
  margin: auto;
  position: relative;
  text-align: center;
  transition: 0.5s;
}

.radioInput[value="slept less than 7hrs"]+.radioLabel:before{
    background-image: url(../../../public/images/sleep/lessThan7hrs.png);
}
.radioInput[value="slept more than 7hrs"]+.radioLabel:before{
    background-image: url(../../../public/images/sleep/moreThan7hrs.png);
}

/* below styling is not working */
.radioInput:checked + .radioLabel::before{
  border: 3px solid #000;
}
.radioInput{
  display: none;
}

CustomeIconContainer.tsx

import { Controller, useForm } from "react-hook-form";
import styled from "styled-components";
import CustomIconInputForm from "../molecules/CustomIconInputForm";
import StyledFlexboxRow from "components/layouts/Flexbox/StyledFlexboxRow";

type Tdata = {
  sleep?: string;
  stool?: string;
  movement?: string;
};

interface IContainerProps {
  name: string;
  options: string[];
  desc: string;
  iconLog?: TIconValueData;
}

export type TIconValueData = {
  id?: number;
  sleep?: string;
  movement?: string;
  stool?: string;
};

/**
 * CustomIconContainer - handle icon input
 */
const CustomIconContainer = (props: IContainerProps) => {

  const { name, options, desc } = props;
  const { handleSubmit, control } = useForm();

  const onSubmit = (data: Tdata) => {
    if (data === undefined) {
      throw new Error("your log is undefined");
    }

    console.log(data);
  };

  const StyledLabel = styled.label`
    display: block;
  `;

  return (

      <form onSubmit={handleSubmit(onSubmit)}>

        {/* mapping icon buttons */}

        <button type="submit">Save</button>
      </form>

  );
};
export default CustomIconContainer;

CustomIconInputForm.tsx

import { IconDefinition } from "@fortawesome/fontawesome-common-types";
import { RefCallBack } from "react-hook-form";
import styles from "./CustomRadioBtn.module.css";

interface ICustomIconProps {
  onChange?: () => void;
  name?: string;
  value?: string;
  icon?: IconDefinition;
  desc: string;
  inputRef?: RefCallBack;
}

const CustomIconInputForm = (props: ICustomIconProps) => {

  const { name, onChange, inputRef, value } = props;

  const onChangeHandler = () => {
    if (value !== undefined) {
      onChange && onChange();
    }
  };
  return (

      <input
        ref={inputRef}
        name={name}
        value={value}
        onChange={() => {
          onChangeHandler;
        }}
        type="radio"
        {...props}
        className={styles.radioInput}
      />

  );
};
export default CustomIconInputForm;

no radio button circles

with radio button circles


问:
How to create event on each column in row using ant design, Vuejs
I am using ANT design table, and my problem is that I need to add events to cells on a row, for example when I click on the column with the item named John Brown, a function A will be generated. , click on the age column and function B will be created. Currently I am using the below method and it requires me to click on the correct text tag to trigger the event instead of just clicking on the cell.

<template>

        <template #bodyCell="{ column, text }">
        <template  v-if="column.dataIndex === 'name'">
          {{ text }}
        </template>
        <template  v-if="column.dataIndex === 'age'" @click="test(text)">
          {{ text }}
        </template>
      </template>

  </template>

```

Is there any solution for me in this case?

Body:
I am using ANT design table, and my problem is that I need to add events to cells on a row, for example when I click on the column with the item named John Brown, a function A will be generated. , click on the age column and function B will be created. Currently I am using the below method and it requires me to click on the correct text tag to trigger the event instead of just clicking on the cell.

<template>

        <template #bodyCell="{ column, text }">
        <template  v-if="column.dataIndex === 'name'">
          {{ text }}
        </template>
        <template  v-if="column.dataIndex === 'age'" @click="test(text)">
          {{ text }}
        </template>
      </template>

  </template>

Is there any solution for me in this case?


问:
Why is it not necessary to dereference when operating on references of primitive types in Rust?
So I can do this:

```<code>fn main() {

   let a = 2;
   let b = &a;
   let c = b * 2; // I did not have to de-reference b by typing *b
   dbg!(c);
}
</code>```

I created b to be a reference (pointer) to a, and I was able to use the value b points to without having to de-reference first.

It works but in trying to understand Rust more, I am curious why this automatic de-referencing occur? And what other scenario can I expect such automatic de-referencing?

Body:
So I can do this:

fn main() {

   let a = 2;
   let b = &a;
   let c = b * 2; // I did not have to de-reference b by typing *b
   dbg!(c);
}

I created b to be a reference (pointer) to a, and I was able to use the value b points to without having to de-reference first.

It works but in trying to understand Rust more, I am curious why this automatic de-referencing occur? And what other scenario can I expect such automatic de-referencing?


问:
How to erase memory while using watchdog in python
I used watchdog to monitor file creating in a folder.
Whenever a parquet file is created, watchdog will call python script to read the parquet file.

When the watchdog program is first run, the memory usage is 90KB.
After finished reading first parquet file, the memory usage is 100KB. I delete all the dataframe when the python script finished executing.

When 2nd parquet file is created, watchdog run the python script by staring memory usage of 100KB and after finished reading 2nd parquet file, the memory usage is 101KB.

Why the watchdog does not release memory when the first file finished executing?

How to write the script if I want the watchdog script to reset the memory after finished executing every file? i.e., When 1st parquet file is created, watchdog call python script by starting memory 90KB and ending with 100KB. When 2nd parquet file is created, watchdog call python script by starting memory 90KB and ending with 100KB instead of starting memory 100KB and ending with 101KB.

The following is the watchdog script and reading parquet file python script:

Reading parquet file python script

```<code>import os
import pandas as pd
import gc, psutil

def usage():
  process = psutil.Process(os.getpid())
  return process.memory_info()[0]/float(2**20)

def readfile(filename):
   gc.enable()
   gc.get_threshold()
   gc.get_count()
   print("Before reading parquet: "+str(usage()))
   df = pd.read_parquet(filename)
   print("After reading parquet: "+str(usage()))
   del df
   gc.collect()
   print("After deleting df: "+str(usage()))
</code>```

Watchdog script

```<code>import os, sys, time
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from watchdog.events import FileSystemEventHandler
from utility.python_script import readfile as rf
class MonitorFolder(FileSystemEventHandler):
  def on_created(self,event):
     filename = event.src_path
     rf(filename)
if __name__=="__main__":
  path_ = "C:\\folder1\\folder2"
  event_handler_=MonitorFolder()
  observer = PollingObserver(timeout=0.1)
  observer.schedule(event_handler,path=path_, recursive = True)
  observer.start()
  try:
    while (True):
        time.sleep(0.1)
  except KeyboardInterrupt:
    observer.stop()
    observer.join()
</code>```

Body:
I used watchdog to monitor file creating in a folder.
Whenever a parquet file is created, watchdog will call python script to read the parquet file.

When the watchdog program is first run, the memory usage is 90KB.
After finished reading first parquet file, the memory usage is 100KB. I delete all the dataframe when the python script finished executing.

When 2nd parquet file is created, watchdog run the python script by staring memory usage of 100KB and after finished reading 2nd parquet file, the memory usage is 101KB.

Why the watchdog does not release memory when the first file finished executing?

How to write the script if I want the watchdog script to reset the memory after finished executing every file? i.e., When 1st parquet file is created, watchdog call python script by starting memory 90KB and ending with 100KB. When 2nd parquet file is created, watchdog call python script by starting memory 90KB and ending with 100KB instead of starting memory 100KB and ending with 101KB.

The following is the watchdog script and reading parquet file python script:

Reading parquet file python script

import os
import pandas as pd
import gc, psutil

def usage():
  process = psutil.Process(os.getpid())
  return process.memory_info()[0]/float(2**20)

def readfile(filename):
   gc.enable()
   gc.get_threshold()
   gc.get_count()
   print("Before reading parquet: "+str(usage()))
   df = pd.read_parquet(filename)
   print("After reading parquet: "+str(usage()))
   del df
   gc.collect()
   print("After deleting df: "+str(usage()))

Watchdog script

import os, sys, time
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from watchdog.events import FileSystemEventHandler
from utility.python_script import readfile as rf
class MonitorFolder(FileSystemEventHandler):
  def on_created(self,event):
     filename = event.src_path
     rf(filename)
if __name__=="__main__":
  path_ = "C:\\folder1\\folder2"
  event_handler_=MonitorFolder()
  observer = PollingObserver(timeout=0.1)
  observer.schedule(event_handler,path=path_, recursive = True)
  observer.start()
  try:
    while (True):
        time.sleep(0.1)
  except KeyboardInterrupt:
    observer.stop()
    observer.join()


问:
Unable to resolve dependency tree error with legacy peer deps
I made an app in react with BuilderX and this happens when I type npm install in terminal:

And these are the dependencies

I would appreciate your help :)

I tried using npm install --save --legacy-peer-deps but it doesn't work


问:
How to change the range of values on the y axis in the python cufflinks library?
Code:

```<code>import cufflinks as cf

cf.set_config_file(offline=True)
qf=cf.QuantFig(table,title='BNBBTC',legend='top',name='GS', color='green')
qf.add_ema(periods=60, name='EMA', color='yellow')
qf.add_volume(title='Volume', name='Volume',up_color='green', down_color='red')
qf.iplot()
</code>```

The "Volume" graph shows an incorrect range of values on the "Y" scale. They are increasing. In reality, this is not the case.

enter image description here

It didn't help:
qf.add_volume(title='Volume', name='Volume',up_color='green', down_color='red',             layout_yaxis_range=[0,2000000]).

Body:
Code:

import cufflinks as cf

cf.set_config_file(offline=True)
qf=cf.QuantFig(table,title='BNBBTC',legend='top',name='GS', color='green')
qf.add_ema(periods=60, name='EMA', color='yellow')
qf.add_volume(title='Volume', name='Volume',up_color='green', down_color='red')
qf.iplot()

The "Volume" graph shows an incorrect range of values on the "Y" scale. They are increasing. In reality, this is not the case.

enter image description here

It didn't help:
qf.add_volume(title='Volume', name='Volume',up_color='green', down_color='red',             layout_yaxis_range=[0,2000000]).


问:
Openssl error while running the React Native Project
I created a react native app in vs code using command of npx create-expo-app appname and then run the project. After a while, I got this error. How can I sovle this?

Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:71:19)
at Object.createHash (node:crypto:133:10)
at module.exports (C:\Users\Hp\Desktop\react_native\node_modules\webpack\lib\util\createHash.js:135:53)
at NormalModule._initBuildHash (C:\Users\Hp\Desktop\react_native\node_modules\webpack\lib\NormalModule.js:417:16)
at handleParseError (C:\Users\Hp\Desktop\react_native\node_modules\webpack\lib\NormalModule.js:471:10)
at C:\Users\Hp\Desktop\react_native\node_modules\webpack\lib\NormalModule.js:503:5
at C:\Users\Hp\Desktop\react_native\node_modules\webpack\lib\NormalModule.js:358:12
at C:\Users\Hp\Desktop\react_native\node_modules\loader-runner\lib\LoaderRunner.js:373:3
at iterateNormalLoaders (C:\Users\Hp\Desktop\react_native\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
at Array. (C:\Users\Hp\Desktop\react_native\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
at Storage.finished (C:\Users\Hp\Desktop\react_native\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)
at C:\Users\Hp\Desktop\react_native\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9
at C:\Users\Hp\Desktop\react_native\node_modules\graceful-fs\graceful-fs.js:123:16
at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.11.0

Some solutions suggest that the node version should be downgraded. So I tried it, but it did not work.


问:
How to create F# Console Application targeting .Net Framework 4.5.2. in Visual Studio 2019

Q: How to create F# Console Application targeting .NET Framework 4.5.2. in Visual Studio 2019? Is that even possible?

Selected F# + Windows + Console:

Selected .NET Framework 4.5.2.:

When then project gets created it has no target framework:

and in Solution Explorer it looks like this:

and the following message is displayed :

Q: Which .NET SDK do I need to be able to create F# Console Application targeting .NET Framework 4.5.2.?

Based on comment from Bent Tranberg I created Console Application which used target Framework 4.7.2 and edited the project file:

<TargetFramework>net472</TargetFramework>
was changed to
<TargetFramework>net452</TargetFramework>

And then the NuGet package FSharp.Core  was downgraded from version 5.0.0 to version 4.5.2.

On my machine where Visual Studio 2019 is installed I see this version of .NET SDK:

I used FSharp.Core.4.5.2 which seems to work so far.

But here the minimum F# language version and the minimum FSharp.Core package version can be found.

Q: My F# Interactive shows F# 5.0 so I should use FSharp.Core.5.0.0 but that doesn't seem to work with .NET Framework 4.5.2 so what to do?


问:
Paypal payment failed with saved card
#SOLVED [from first comment answer]

I am try to build paypal advance payment and card save during payment with nodejs. I successfully build paypal advance payment and store card in vault. but the problem is while I try to pay with previously saved card, it fails. Order is created successfully then the error occurred.

checkout html (ejs)

```<code><html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" type="text/css"
    href="https://www.paypalobjects.com/webstatic/en_US/developer/docs/css/cardfields.css" />
  <script src="https://www.paypal.com/sdk/js?components=buttons,hosted-fields&client-id=<%= clientId %>"
    data-client-token="<%= clientToken %>"></script>
</head>

<body>
  <div id="paypal-button-container" class="paypal-button-container"></div>
  <div class="card_container">
    <form id="card-form">
      <label for="card-number">Card Number</label>
      <div id="card-number" class="card_field"></div>
      <div style="display: flex; flex-direction: row;">
        <div>
          <label for="expiration-date">Expiration Date</label>
          <div id="expiration-date" class="card_field"></div>
        </div>
        <div style="margin-left: 10px;">
          <label for="cvv">CVV</label>
          <div id="cvv" class="card_field"></div>
        </div>
      </div>
      <label for="card-holder-name">Name on Card</label>
      <input type="text" id="card-holder-name" name="card-holder-name" autocomplete="off"
        placeholder="card holder name" />
      <div>
        <label for="card-billing-address-street">Billing Address</label>
        <input type="text" id="card-billing-address-street" name="card-billing-address-street" autocomplete="off"
          placeholder="street address" />
      </div>
      <div>
        <label for="card-billing-address-unit"> </label>
        <input type="text" id="card-billing-address-unit" name="card-billing-address-unit" autocomplete="off"
          placeholder="unit" />
      </div>
      <div>
        <input type="text" id="card-billing-address-city" name="card-billing-address-city" autocomplete="off"
          placeholder="city" />
      </div>
      <div>
        <input type="text" id="card-billing-address-state" name="card-billing-address-state" autocomplete="off"
          placeholder="state" />
      </div>
      <div>
        <input type="text" id="card-billing-address-zip" name="card-billing-address-zip" autocomplete="off"
          placeholder="zip / postal code" />
      </div>
      <div>
        <input type="text" id="card-billing-address-country" name="card-billing-address-country" autocomplete="off"
          placeholder="country code" />
      </div>
      <div>
        <input type="checkbox" id="save" name="save">
        <label for="save">Save your card</label>
      </div>
      <br /><br />
      <button value="submit" id="submit" class="btn">Pay</button>
    </form>
  </div>
  <script src="app.js"></script>
</body>

</html>
</code>```

app.js

```<code>paypal
  .Buttons({
    // Sets up the transaction when a payment button is clicked
    createOrder: function (data, actions) {
      return fetch("/api/orders", {
        method: "post"
        // use the "body" param to optionally pass additional order information
        // like product ids or amount
      })
        .then((response) => response.json())
        .then((order) => order.id);
    },
    // Finalize the transaction after payer approval
    onApprove: function (data, actions) {
      return fetch(`/api/orders/${data.orderID}/capture`, {
        method: "post",
      })
        .then((response) => response.json())
        .then((orderData) => {
          // Successful capture! For dev/demo purposes:
          console.log(
            "Capture result",
            orderData,
            JSON.stringify(orderData, null, 2)
          );
          const transaction = orderData.purchase_units[0].payments.captures[0];
          alert(`Transaction ${transaction.status}: ${transaction.id}

            See console for all available details
          `);
          // When ready to go live, remove the alert and show a success message within this page. For example:
          // var element = document.getElementById('paypal-button-container');
          // element.innerHTML = '<h3>Thank you for your payment!</h3>';
          // Or go to another URL:  actions.redirect('thank_you.html');
        });
    },
  })
  .render("#paypal-button-container");

// If this returns false or the card fields aren't visible, see Step #1.
if (paypal.HostedFields.isEligible()) {
  let orderId;

  // Renders card fields
  paypal.HostedFields.render({
    // Call your server to set up the transaction
    createOrder: () => {
      return fetch("/api/orders", {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          save: document.querySelector('#save').checked,
          card_name: document.getElementById("card-holder-name").value,
          billing_address: {
            address_line_1: document.getElementById("card-billing-address-street").value,
            address_line_2: document.getElementById("card-billing-address-unit").value,
            admin_area_2: document.getElementById("card-billing-address-city").value,
            admin_area_1: document.getElementById("card-billing-address-state").value,
            postal_code: document.getElementById("card-billing-address-zip").value,
            country_code: document.getElementById("card-billing-address-country").value
          }
        })
        // use the "body" param to optionally pass additional order information like
        // product ids or amount.
      })
        .then((res) => res.json())
        .then((orderData) => {
          console.log("==============>create order response<==============");
          console.log(orderData);
          orderId = orderData.id; // needed later to complete capture
          return orderData.id;
        });
    },
    styles: {
      ".valid": {
        color: "green",
      },
      ".invalid": {
        color: "red",
      },
    },
    fields: {
      number: {
        selector: "#card-number",
        placeholder: "4111 1111 1111 1111",
      },
      cvv: {
        selector: "#cvv",
        placeholder: "123",
      },
      expirationDate: {
        selector: "#expiration-date",
        placeholder: "MM/YY",
      },
    },
  }).then((cardFields) => {
    document.querySelector("#card-form").addEventListener("submit", (event) => {
      event.preventDefault();
      cardFields
        .submit({
          save: document.querySelector('#save').checked,
          // Cardholder's first and last name
          cardholderName: document.getElementById("card-holder-name").value,
          // Billing Address
          billingAddress: {
            // Street address, line 1
            streetAddress: document.getElementById(
              "card-billing-address-street"
            ).value,
            // Street address, line 2 (Ex: Unit, Apartment, etc.)
            extendedAddress: document.getElementById(
              "card-billing-address-unit"
            ).value,
            // State
            region: document.getElementById("card-billing-address-state").value,
            // City
            locality: document.getElementById("card-billing-address-city")
              .value,
            // Postal Code
            postalCode: document.getElementById("card-billing-address-zip")
              .value,
            // Country Code
            countryCodeAlpha2: document.getElementById(
              "card-billing-address-country"
            ).value,
          },
        })
        .then(() => {
          fetch(`/api/orders/${orderId}/capture`, {
            method: "post",
          })
            .then((res) => res.json())
            .then((orderData) => {
              console.log("==============>capture order response<==============");
              console.log(orderData);
              // Two cases to handle:
              //   (1) Other non-recoverable errors -> Show a failure message
              //   (2) Successful transaction -> Show confirmation or thank you
              // This example reads a v2/checkout/orders capture response, propagated from the server
              // You could use a different API or structure for your 'orderData'
              const errorDetail =
                Array.isArray(orderData.details) && orderData.details[0];
              if (errorDetail) {
                var msg = "Sorry, your transaction could not be processed.";
                if (errorDetail.description)
                  msg += "\n\n" + errorDetail.description;
                if (orderData.debug_id) msg += " (" + orderData.debug_id + ")";
                return alert(msg); // Show a failure message
              }
              // Show a success message or redirect
              alert("Transaction completed!");
            });
        })
        .catch((err) => {
          alert("Payment could not be captured! " + JSON.stringify(err));
        });
    });
  });
} else {
  // Hides card fields if the merchant isn't eligible
  document.querySelector("#card-form").style = "display: none";
}
</code>```

paypal-api.js

```<code>import fetch from "node-fetch";

// set some important variables
const { CLIENT_ID, APP_SECRET } = process.env;
const base = "https://api-m.sandbox.paypal.com";

// call the create order method
export async function createOrder(body) {
  const purchaseAmount = "100.00"; // TODO: pull prices from a database
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
    body: body ? JSON.stringify({
      intent: "CAPTURE",
      purchase_units: [
        {
          amount: {
            currency_code: "USD",
            value: purchaseAmount,
          },
        },
      ],
      payment_source: {
        card: {
          name: body.card_name,
          billing_address: body.billing_address,
          attributes: {
            vault: {
              store_in_vault: 'ON_SUCCESS'
            }
          }
        }
      }
    }) : undefined,
  });

  return handleResponse(response);
}

// capture payment for an order
export async function capturePayment(orderId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders/${orderId}/capture`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
  });

  return handleResponse(response);
}

// generate access token
export async function generateAccessToken() {
  const auth = Buffer.from(CLIENT_ID + ":" + APP_SECRET).toString("base64");
  const response = await fetch(`${base}/v1/oauth2/token`, {
    method: "post",
    body: "grant_type=client_credentials",
    headers: {
      Authorization: `Basic ${auth}`,
    },
  });
  const jsonData = await handleResponse(response);
  return jsonData.access_token;
}

// generate client token
export async function generateClientToken() {
  const accessToken = await generateAccessToken();
  const response = await fetch(`${base}/v1/identity/generate-token`, {
    method: "post",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Accept-Language": "en_US",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      customer_id: 'kxIaZbNwOZ'
    })
  });
  const jsonData = await handleResponse(response);
  return jsonData.client_token;
}

async function handleResponse(response) {
  if (response.status === 200 || response.status === 201) {
    return response.json();
  }

  const errorMessage = await response.text();
  throw new Error(errorMessage);
}
</code>```

server.js

```<code>import "dotenv/config";
import express from "express";
import * as paypal from "./paypal-api.js";

const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.json());

// render checkout page with client id & unique client token
app.get("/", async (req, res) => {
  const clientId = process.env.CLIENT_ID;
  try {
    const clientToken = await paypal.generateClientToken();
    res.render("checkout", { clientId, clientToken });
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// create order
app.post("/api/orders", async (req, res) => {
  try {
    const order = await paypal.createOrder(req.body);
    res.json(order);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// capture payment
app.post("/api/orders/:orderID/capture", async (req, res) => {
  const { orderID } = req.params;
  try {
    const captureData = await paypal.capturePayment(orderID);
    res.json(captureData);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

app.listen(8888, () => console.log("App Started."));
</code>```

Error:

```<code>{
    "err": "Error: Shipping address requested for card payment\n...",
    "timestamp": "1673098647388",
    "referer": "www.sandbox.paypal.com",
    "sdkCorrelationID": "04103b485b692",
    "sessionID": "uid_82aff76087_mtm6mzu6mzk",
    "clientID": "AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C",
    "env": "sandbox",
    "buttonSessionID": "uid_05c2d7e1ec_mtm6mzc6mtq",
    "buttonCorrelationID": "a17486c9208f5",
    "time": "1673098647388",
    "user_id": "uid_05c2d7e1ec_mtm6mzc6mtq",
    "token": "2VY75292WT2863902"
}
</code>```
```<code>Uncaught Error: Shipping address requested for card payment
    at https://www.sandbox.paypal.com/smart/buttons?sdkVersion=5.0.344&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&components.1=hosted-fields&locale.country=US&locale.lang=en&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jb21wb25lbnRzPWJ1dHRvbnMsaG9zdGVkLWZpZWxkcyZjbGllbnQtaWQ9QVVVYmtaaVExYWtVN0NoUDBVeGJXTjlVOC13UjBwWW1PVUY4Z3prWHRzcmNibjlHWERMQjBmak9UMTR2Ry1ydldZd0dtTTdMemo4TERLLUMiLCJhdHRycyI6eyJkYXRhLXVpZCI6InVpZF9laWVpbXFteW9tY3F4am1xeWd4dGxsZWlld2FvcmIifX0&clientID=AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C&clientAccessToken=A21AALuiYv6v0yKLvGRKk4KoMModxjNd_Ph185k19xRLIjbptX_pGsMmYPvM9pTdyuKBwJbDm33J9zeRmkwl9_FbdGY1WtwIw&sdkCorrelationID=04103b485b692&storageID=uid_e93c1270fe_mtm6mzu6mzk&sessionID=uid_82aff76087_mtm6mzu6mzk&buttonSessionID=uid_05c2d7e1ec_mtm6mzc6mtq&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJwcm9kdWN0cyI6eyJwYXlJbjMiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5SW40Ijp7ImVsaWdpYmxlIjpmYWxzZSwidmFyaWFudCI6bnVsbH0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJicmFuZGVkIjpmYWxzZSwiaW5zdGFsbG1lbnRzIjpmYWxzZSwidmVuZG9ycyI6eyJ2aXNhIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJtYXN0ZXJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJhbWV4Ijp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJkaXNjb3ZlciI6eyJlbGlnaWJsZSI6dHJ1ZSwidmF1bHRhYmxlIjp0cnVlfSwiaGlwZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXVsdGFibGUiOmZhbHNlfSwiZWxvIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfSwiamNiIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfX0sImd1ZXN0RW5hYmxlZCI6ZmFsc2V9LCJ2ZW5tbyI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJpdGF1Ijp7ImVsaWdpYmxlIjpmYWxzZX0sImNyZWRpdCI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJhcHBsZXBheSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJzZXBhIjp7ImVsaWdpYmxlIjpmYWxzZX0sImlkZWFsIjp7ImVsaWdpYmxlIjpmYWxzZX0sImJhbmNvbnRhY3QiOnsiZWxpZ2libGUiOmZhbHNlfSwiZ2lyb3BheSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJlcHMiOnsiZWxpZ2libGUiOmZhbHNlfSwic29mb3J0Ijp7ImVsaWdpYmxlIjpmYWxzZX0sIm15YmFuayI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJwMjQiOnsiZWxpZ2libGUiOmZhbHNlfSwiemltcGxlciI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJ3ZWNoYXRwYXkiOnsiZWxpZ2libGUiOmZhbHNlfSwicGF5dSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJibGlrIjp7ImVsaWdpYmxlIjpmYWxzZX0sInRydXN0bHkiOnsiZWxpZ2libGUiOmZhbHNlfSwib3h4byI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJtYXhpbWEiOnsiZWxpZ2libGUiOmZhbHNlfSwiYm9sZXRvIjp7ImVsaWdpYmxlIjpmYWxzZX0sImJvbGV0b2JhbmNhcmlvIjp7ImVsaWdpYmxlIjpmYWxzZX0sIm1lcmNhZG9wYWdvIjp7ImVsaWdpYmxlIjpmYWxzZX0sIm11bHRpYmFuY28iOnsiZWxpZ2libGUiOmZhbHNlfSwic2F0aXNwYXkiOnsiZWxpZ2libGUiOmZhbHNlfX0&platform=desktop&experiment.enableVenmo=false&experiment.enableVenmoAppLabel=false&flow=purchase&currency=USD&intent=capture&commit=true&vault=false&renderedButtons.0=paypal&renderedButtons.1=paylater&debug=false&applePaySupport=false&supportsPopups=true&supportedNativeBrowser=false&experience=&allowBillingPayments=true:1492:261589
    at n.dispatch (https://www.sandbox.paypal.com/smart/buttons?sdkVersion=5.0.344&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&components.1=hosted-fields&locale.country=US&locale.lang=en&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jb21wb25lbnRzPWJ1dHRvbnMsaG9zdGVkLWZpZWxkcyZjbGllbnQtaWQ9QVVVYmtaaVExYWtVN0NoUDBVeGJXTjlVOC13UjBwWW1PVUY4Z3prWHRzcmNibjlHWERMQjBmak9UMTR2Ry1ydldZd0dtTTdMemo4TERLLUMiLCJhdHRycyI6eyJkYXRhLXVpZCI6InVpZF9laWVpbXFteW9tY3F4am1xeWd4dGxsZWlld2FvcmIifX0&clientID=AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C&clientAccessToken=A21AALuiYv6v0yKLvGRKk4KoMModxjNd_Ph185k19xRLIjbptX_pGsMmYPvM9pTdyuKBwJbDm33J9zeRmkwl9_FbdGY1WtwIw&sdkCorrelationID=04103b485b692&storageID=uid_e93c1270fe_mtm6mzu6mzk&sessionID=uid_82aff76087_mtm6mzu6mzk&buttonSessionID=uid_05c2d7e1ec_mtm6mzc6mtq&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJwcm9kdWN0cyI6eyJwYXlJbjMiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5SW40Ijp7ImVsaWdpYmxlIjpmYWxzZSwidmFyaWFudCI6bnVsbH0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJicmFuZGVkIjpmYWxzZSwiaW5zdGFsbG1lbnRzIjpmYWxzZSwidmVuZG9ycyI6eyJ2aXNhIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJtYXN0ZXJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJhbWV4Ijp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJkaXNjb3ZlciI6eyJlbGlnaWJsZSI6dHJ1ZSwidmF1bHRhYmxlIjp0cnVlfSwiaGlwZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXVsdGFibGUiOmZhbHNlfSwiZWxvIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfSwiamNiIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfX0sImd1ZXN0RW5hYmxlZCI6ZmFsc2V9LCJ2ZW5tbyI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJpdGF1Ijp7ImVsaWdpYmxlIjpmYWxzZX0sImNyZWRpdCI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJhcHBsZXBhe
</code>```

Expecting the payment success

Title: Paypal payment failed with saved card

Body:
#SOLVED [from first comment answer]

I am try to build paypal advance payment and card save during payment with nodejs. I successfully build paypal advance payment and store card in vault. but the problem is while I try to pay with previously saved card, it fails. Order is created successfully then the error occurred.

checkout html (ejs)

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" type="text/css"
    href="https://www.paypalobjects.com/webstatic/en_US/developer/docs/css/cardfields.css" />

    <form id="card-form">
      Card Number

          Expiration Date

          CVV

      Name on Card
      <input type="text" id="card-holder-name" name="card-holder-name" autocomplete="off"
        placeholder="card holder name" />

        Billing Address
        <input type="text" id="card-billing-address-street" name="card-billing-address-street" autocomplete="off"
          placeholder="street address" />

        <input type="text" id="card-billing-address-unit" name="card-billing-address-unit" autocomplete="off"
          placeholder="unit" />

        <input type="text" id="card-billing-address-city" name="card-billing-address-city" autocomplete="off"
          placeholder="city" />

        <input type="text" id="card-billing-address-state" name="card-billing-address-state" autocomplete="off"
          placeholder="state" />

        <input type="text" id="card-billing-address-zip" name="card-billing-address-zip" autocomplete="off"
          placeholder="zip / postal code" />

        <input type="text" id="card-billing-address-country" name="card-billing-address-country" autocomplete="off"
          placeholder="country code" />

        <input type="checkbox" id="save" name="save">
        Save your card

      <button value="submit" id="submit" class="btn">Pay</button>
    </form>

app.js

paypal
  .Buttons({
    // Sets up the transaction when a payment button is clicked
    createOrder: function (data, actions) {
      return fetch("/api/orders", {
        method: "post"
        // use the "body" param to optionally pass additional order information
        // like product ids or amount
      })
        .then((response) => response.json())
        .then((order) => order.id);
    },
    // Finalize the transaction after payer approval
    onApprove: function (data, actions) {
      return fetch(`/api/orders/${data.orderID}/capture`, {
        method: "post",
      })
        .then((response) => response.json())
        .then((orderData) => {
          // Successful capture! For dev/demo purposes:
          console.log(
            "Capture result",
            orderData,
            JSON.stringify(orderData, null, 2)
          );
          const transaction = orderData.purchase_units[0].payments.captures[0];
          alert(`Transaction ${transaction.status}: ${transaction.id}

            See console for all available details
          `);
          // When ready to go live, remove the alert and show a success message within this page. For example:
          // var element = document.getElementById('paypal-button-container');
          // element.innerHTML = '
Thank you for your payment!
';
          // Or go to another URL:  actions.redirect('thank_you.html');
        });
    },
  })
  .render("#paypal-button-container");

// If this returns false or the card fields aren't visible, see Step #1.
if (paypal.HostedFields.isEligible()) {
  let orderId;

  // Renders card fields
  paypal.HostedFields.render({
    // Call your server to set up the transaction
    createOrder: () => {
      return fetch("/api/orders", {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          save: document.querySelector('#save').checked,
          card_name: document.getElementById("card-holder-name").value,
          billing_address: {
            address_line_1: document.getElementById("card-billing-address-street").value,
            address_line_2: document.getElementById("card-billing-address-unit").value,
            admin_area_2: document.getElementById("card-billing-address-city").value,
            admin_area_1: document.getElementById("card-billing-address-state").value,
            postal_code: document.getElementById("card-billing-address-zip").value,
            country_code: document.getElementById("card-billing-address-country").value
          }
        })
        // use the "body" param to optionally pass additional order information like
        // product ids or amount.
      })
        .then((res) => res.json())
        .then((orderData) => {
          console.log("==============>create order response<==============");
          console.log(orderData);
          orderId = orderData.id; // needed later to complete capture
          return orderData.id;
        });
    },
    styles: {
      ".valid": {
        color: "green",
      },
      ".invalid": {
        color: "red",
      },
    },
    fields: {
      number: {
        selector: "#card-number",
        placeholder: "4111 1111 1111 1111",
      },
      cvv: {
        selector: "#cvv",
        placeholder: "123",
      },
      expirationDate: {
        selector: "#expiration-date",
        placeholder: "MM/YY",
      },
    },
  }).then((cardFields) => {
    document.querySelector("#card-form").addEventListener("submit", (event) => {
      event.preventDefault();
      cardFields
        .submit({
          save: document.querySelector('#save').checked,
          // Cardholder's first and last name
          cardholderName: document.getElementById("card-holder-name").value,
          // Billing Address
          billingAddress: {
            // Street address, line 1
            streetAddress: document.getElementById(
              "card-billing-address-street"
            ).value,
            // Street address, line 2 (Ex: Unit, Apartment, etc.)
            extendedAddress: document.getElementById(
              "card-billing-address-unit"
            ).value,
            // State
            region: document.getElementById("card-billing-address-state").value,
            // City
            locality: document.getElementById("card-billing-address-city")
              .value,
            // Postal Code
            postalCode: document.getElementById("card-billing-address-zip")
              .value,
            // Country Code
            countryCodeAlpha2: document.getElementById(
              "card-billing-address-country"
            ).value,
          },
        })
        .then(() => {
          fetch(`/api/orders/${orderId}/capture`, {
            method: "post",
          })
            .then((res) => res.json())
            .then((orderData) => {
              console.log("==============>capture order response<==============");
              console.log(orderData);
              // Two cases to handle:
              //   (1) Other non-recoverable errors -> Show a failure message
              //   (2) Successful transaction -> Show confirmation or thank you
              // This example reads a v2/checkout/orders capture response, propagated from the server
              // You could use a different API or structure for your 'orderData'
              const errorDetail =
                Array.isArray(orderData.details) && orderData.details[0];
              if (errorDetail) {
                var msg = "Sorry, your transaction could not be processed.";
                if (errorDetail.description)
                  msg += "\n\n" + errorDetail.description;
                if (orderData.debug_id) msg += " (" + orderData.debug_id + ")";
                return alert(msg); // Show a failure message
              }
              // Show a success message or redirect
              alert("Transaction completed!");
            });
        })
        .catch((err) => {
          alert("Payment could not be captured! " + JSON.stringify(err));
        });
    });
  });
} else {
  // Hides card fields if the merchant isn't eligible
  document.querySelector("#card-form").style = "display: none";
}

paypal-api.js

import fetch from "node-fetch";

// set some important variables
const { CLIENT_ID, APP_SECRET } = process.env;
const base = "https://api-m.sandbox.paypal.com";

// call the create order method
export async function createOrder(body) {
  const purchaseAmount = "100.00"; // TODO: pull prices from a database
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
    body: body ? JSON.stringify({
      intent: "CAPTURE",
      purchase_units: [
        {
          amount: {
            currency_code: "USD",
            value: purchaseAmount,
          },
        },
      ],
      payment_source: {
        card: {
          name: body.card_name,
          billing_address: body.billing_address,
          attributes: {
            vault: {
              store_in_vault: 'ON_SUCCESS'
            }
          }
        }
      }
    }) : undefined,
  });

  return handleResponse(response);
}

// capture payment for an order
export async function capturePayment(orderId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v2/checkout/orders/${orderId}/capture`;
  const response = await fetch(url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
  });

  return handleResponse(response);
}

// generate access token
export async function generateAccessToken() {
  const auth = Buffer.from(CLIENT_ID + ":" + APP_SECRET).toString("base64");
  const response = await fetch(`${base}/v1/oauth2/token`, {
    method: "post",
    body: "grant_type=client_credentials",
    headers: {
      Authorization: `Basic ${auth}`,
    },
  });
  const jsonData = await handleResponse(response);
  return jsonData.access_token;
}

// generate client token
export async function generateClientToken() {
  const accessToken = await generateAccessToken();
  const response = await fetch(`${base}/v1/identity/generate-token`, {
    method: "post",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Accept-Language": "en_US",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      customer_id: 'kxIaZbNwOZ'
    })
  });
  const jsonData = await handleResponse(response);
  return jsonData.client_token;
}

async function handleResponse(response) {
  if (response.status === 200 || response.status === 201) {
    return response.json();
  }

  const errorMessage = await response.text();
  throw new Error(errorMessage);
}

server.js

import "dotenv/config";
import express from "express";
import * as paypal from "./paypal-api.js";

const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.json());

// render checkout page with client id & unique client token
app.get("/", async (req, res) => {
  const clientId = process.env.CLIENT_ID;
  try {
    const clientToken = await paypal.generateClientToken();
    res.render("checkout", { clientId, clientToken });
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// create order
app.post("/api/orders", async (req, res) => {
  try {
    const order = await paypal.createOrder(req.body);
    res.json(order);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// capture payment
app.post("/api/orders/:orderID/capture", async (req, res) => {
  const { orderID } = req.params;
  try {
    const captureData = await paypal.capturePayment(orderID);
    res.json(captureData);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

app.listen(8888, () => console.log("App Started."));

Error:

{
    "err": "Error: Shipping address requested for card payment\n...",
    "timestamp": "1673098647388",
    "referer": "www.sandbox.paypal.com",
    "sdkCorrelationID": "04103b485b692",
    "sessionID": "uid_82aff76087_mtm6mzu6mzk",
    "clientID": "AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C",
    "env": "sandbox",
    "buttonSessionID": "uid_05c2d7e1ec_mtm6mzc6mtq",
    "buttonCorrelationID": "a17486c9208f5",
    "time": "1673098647388",
    "user_id": "uid_05c2d7e1ec_mtm6mzc6mtq",
    "token": "2VY75292WT2863902"
}

Uncaught Error: Shipping address requested for card payment
    at https://www.sandbox.paypal.com/smart/buttons?sdkVersion=5.0.344&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&components.1=hosted-fields&locale.country=US&locale.lang=en&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jb21wb25lbnRzPWJ1dHRvbnMsaG9zdGVkLWZpZWxkcyZjbGllbnQtaWQ9QVVVYmtaaVExYWtVN0NoUDBVeGJXTjlVOC13UjBwWW1PVUY4Z3prWHRzcmNibjlHWERMQjBmak9UMTR2Ry1ydldZd0dtTTdMemo4TERLLUMiLCJhdHRycyI6eyJkYXRhLXVpZCI6InVpZF9laWVpbXFteW9tY3F4am1xeWd4dGxsZWlld2FvcmIifX0&clientID=AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C&clientAccessToken=A21AALuiYv6v0yKLvGRKk4KoMModxjNd_Ph185k19xRLIjbptX_pGsMmYPvM9pTdyuKBwJbDm33J9zeRmkwl9_FbdGY1WtwIw&sdkCorrelationID=04103b485b692&storageID=uid_e93c1270fe_mtm6mzu6mzk&sessionID=uid_82aff76087_mtm6mzu6mzk&buttonSessionID=uid_05c2d7e1ec_mtm6mzc6mtq&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJwcm9kdWN0cyI6eyJwYXlJbjMiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5SW40Ijp7ImVsaWdpYmxlIjpmYWxzZSwidmFyaWFudCI6bnVsbH0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJicmFuZGVkIjpmYWxzZSwiaW5zdGFsbG1lbnRzIjpmYWxzZSwidmVuZG9ycyI6eyJ2aXNhIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJtYXN0ZXJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJhbWV4Ijp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJkaXNjb3ZlciI6eyJlbGlnaWJsZSI6dHJ1ZSwidmF1bHRhYmxlIjp0cnVlfSwiaGlwZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXVsdGFibGUiOmZhbHNlfSwiZWxvIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfSwiamNiIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfX0sImd1ZXN0RW5hYmxlZCI6ZmFsc2V9LCJ2ZW5tbyI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJpdGF1Ijp7ImVsaWdpYmxlIjpmYWxzZX0sImNyZWRpdCI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJhcHBsZXBheSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJzZXBhIjp7ImVsaWdpYmxlIjpmYWxzZX0sImlkZWFsIjp7ImVsaWdpYmxlIjpmYWxzZX0sImJhbmNvbnRhY3QiOnsiZWxpZ2libGUiOmZhbHNlfSwiZ2lyb3BheSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJlcHMiOnsiZWxpZ2libGUiOmZhbHNlfSwic29mb3J0Ijp7ImVsaWdpYmxlIjpmYWxzZX0sIm15YmFuayI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJwMjQiOnsiZWxpZ2libGUiOmZhbHNlfSwiemltcGxlciI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJ3ZWNoYXRwYXkiOnsiZWxpZ2libGUiOmZhbHNlfSwicGF5dSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJibGlrIjp7ImVsaWdpYmxlIjpmYWxzZX0sInRydXN0bHkiOnsiZWxpZ2libGUiOmZhbHNlfSwib3h4byI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJtYXhpbWEiOnsiZWxpZ2libGUiOmZhbHNlfSwiYm9sZXRvIjp7ImVsaWdpYmxlIjpmYWxzZX0sImJvbGV0b2JhbmNhcmlvIjp7ImVsaWdpYmxlIjpmYWxzZX0sIm1lcmNhZG9wYWdvIjp7ImVsaWdpYmxlIjpmYWxzZX0sIm11bHRpYmFuY28iOnsiZWxpZ2libGUiOmZhbHNlfSwic2F0aXNwYXkiOnsiZWxpZ2libGUiOmZhbHNlfX0&platform=desktop&experiment.enableVenmo=false&experiment.enableVenmoAppLabel=false&flow=purchase&currency=USD&intent=capture&commit=true&vault=false&renderedButtons.0=paypal&renderedButtons.1=paylater&debug=false&applePaySupport=false&supportsPopups=true&supportedNativeBrowser=false&experience=&allowBillingPayments=true:1492:261589
    at n.dispatch (https://www.sandbox.paypal.com/smart/buttons?sdkVersion=5.0.344&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&components.1=hosted-fields&locale.country=US&locale.lang=en&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jb21wb25lbnRzPWJ1dHRvbnMsaG9zdGVkLWZpZWxkcyZjbGllbnQtaWQ9QVVVYmtaaVExYWtVN0NoUDBVeGJXTjlVOC13UjBwWW1PVUY4Z3prWHRzcmNibjlHWERMQjBmak9UMTR2Ry1ydldZd0dtTTdMemo4TERLLUMiLCJhdHRycyI6eyJkYXRhLXVpZCI6InVpZF9laWVpbXFteW9tY3F4am1xeWd4dGxsZWlld2FvcmIifX0&clientID=AUUbkZiQ1akU7ChP0UxbWN9U8-wR0pYmOUF8gzkXtsrcbn9GXDLB0fjOT14vG-rvWYwGmM7Lzj8LDK-C&clientAccessToken=A21AALuiYv6v0yKLvGRKk4KoMModxjNd_Ph185k19xRLIjbptX_pGsMmYPvM9pTdyuKBwJbDm33J9zeRmkwl9_FbdGY1WtwIw&sdkCorrelationID=04103b485b692&storageID=uid_e93c1270fe_mtm6mzu6mzk&sessionID=uid_82aff76087_mtm6mzu6mzk&buttonSessionID=uid_05c2d7e1ec_mtm6mzc6mtq&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJwcm9kdWN0cyI6eyJwYXlJbjMiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5SW40Ijp7ImVsaWdpYmxlIjpmYWxzZSwidmFyaWFudCI6bnVsbH0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJicmFuZGVkIjpmYWxzZSwiaW5zdGFsbG1lbnRzIjpmYWxzZSwidmVuZG9ycyI6eyJ2aXNhIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJtYXN0ZXJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJhbWV4Ijp7ImVsaWdpYmxlIjp0cnVlLCJ2YXVsdGFibGUiOnRydWV9LCJkaXNjb3ZlciI6eyJlbGlnaWJsZSI6dHJ1ZSwidmF1bHRhYmxlIjp0cnVlfSwiaGlwZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXVsdGFibGUiOmZhbHNlfSwiZWxvIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfSwiamNiIjp7ImVsaWdpYmxlIjpmYWxzZSwidmF1bHRhYmxlIjp0cnVlfX0sImd1ZXN0RW5hYmxlZCI6ZmFsc2V9LCJ2ZW5tbyI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJpdGF1Ijp7ImVsaWdpYmxlIjpmYWxzZX0sImNyZWRpdCI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJhcHBsZXBhe

Expecting the payment success


问:
Python and cgi output in the same html page
From inside a web page I define short python code in a texarea field which should be run via cgi. I have no problem to create a new web page with the output of the external python run. What I like is instead the output below the textarea field in an iframe or whatever. But not as a new html page.

I have a html page:

```<code><!DOCTYPE html>
<html lang="en-US">
<body>

<style>
  textarea {white-space: pre-wrap; overflow-wrap: break-word;}
</style>
<form action="/cgi-bin/getword3.py" method="post" >
<textarea name="py-code" cols="40" rows="4"></textarea></br>
<input type="submit" value="Submit" />
</form>

*** the output of the cgi should appear here ***

</body>
</html>
</code>```

my not working python cgi is:

```<code>#!/usr/bin/env python3
import cgi, cgitb
cgitb.enable()

from subprocess import Popen, PIPE

form = cgi.FieldStorage()

if form.getlist('py-code'):
   text_content = form.getvalue('py-code')
else:
   text_content = "Not entered"

process = Popen(["python3", "-c", text_content], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

return stdout.decode())
</code>```

Body:
From inside a web page I define short python code in a texarea field which should be run via cgi. I have no problem to create a new web page with the output of the external python run. What I like is instead the output below the textarea field in an iframe or whatever. But not as a new html page.

I have a html page:

<!DOCTYPE html>

<form action="/cgi-bin/getword3.py" method="post" >
<textarea name="py-code" cols="40" rows="4"></textarea>

<input type="submit" value="Submit" />
</form>

*** the output of the cgi should appear here ***

my not working python cgi is:

#!/usr/bin/env python3
import cgi, cgitb
cgitb.enable()

from subprocess import Popen, PIPE

form = cgi.FieldStorage()

if form.getlist('py-code'):
   text_content = form.getvalue('py-code')
else:
   text_content = "Not entered"

process = Popen(["python3", "-c", text_content], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

return stdout.decode())


问:
Not getting expected result from wsprintf
I'm trying to use wpsrintf to write a float to two decimal places, but the output only shows f

When I use sprintf:

```<code>float fValue = 1.00F;
char value[16];
sprintf(value, "%0.2f", fValue);
</code>```

I get the exepected output 1.00

However when try to do the same with wsprintf to write the value to WCHAR using:

```<code>float fValue = 1.00F;
WCHAR value[16];
wsprintf(value, L"%0.2f", fValue);
</code>```

The output just shows f

Body:
I'm trying to use wpsrintf to write a float to two decimal places, but the output only shows f

When I use sprintf:

float fValue = 1.00F;
char value[16];
sprintf(value, "%0.2f", fValue);

I get the exepected output 1.00

However when try to do the same with wsprintf to write the value to WCHAR using:

float fValue = 1.00F;
WCHAR value[16];
wsprintf(value, L"%0.2f", fValue);

The output just shows f


问:
API request types PATCH and DELETE 404 error typescript
I'm a tester and I got an exercise to test API requests in typescript. I'm trying to send request type PATCH to server to update some information of existing restaurant(I create it in the code and immediately try to update the data) but every time get 404 error. The same happens when I do DELETE request. I've already tried to execute these requests in Postman. Everything is working fine

These are the tests

```<code>   it('Edit the existing restaurant', async () => {

        const dataToUpdate = { address: "Holon" };

        //Act
        const updateRestaurantById = await restaurantsAPI.updateRestaurantById(42, dataToUpdate);

        //Assert
        expect(updateRestaurantById.status).to.equal(200);
        expect(updateRestaurantById.success).to.be.true;
    })
   it('Delete existing restaurant', async () => {
        //Act
        const deleteByIdResponse = await restaurantsAPI.deleteRestaurantById(365);

        //Assert
        expect(deleteByIdResponse.success).to.be.true;
        expect(deleteByIdResponse.status).to.equal(200);
    })`
</code>```

And requests

```<code>  const updateRestaurantById = async (id: number, body: Updates): Promise<ApiResponse<Updates>> => {
    return HttpRequest.networkRequest({ url: baseUrl + 'restaurant', method: HttpRequest.HttpMethod.PATCH, queryParams: { id: id }, body: body });

}
   const deleteRestaurantById = async (id: number): Promise<ApiResponse<null>> => {
    return HttpRequest.networkRequest({ url: baseUrl + 'restaurant', method: HttpRequest.HttpMethod.DELETE, queryParams: { id: id } });
}`
</code>```

Body:
I'm a tester and I got an exercise to test API requests in typescript. I'm trying to send request type PATCH to server to update some information of existing restaurant(I create it in the code and immediately try to update the data) but every time get 404 error. The same happens when I do DELETE request. I've already tried to execute these requests in Postman. Everything is working fine

These are the tests

   it('Edit the existing restaurant', async () => {

        const dataToUpdate = { address: "Holon" };

        //Act
        const updateRestaurantById = await restaurantsAPI.updateRestaurantById(42, dataToUpdate);

        //Assert
        expect(updateRestaurantById.status).to.equal(200);
        expect(updateRestaurantById.success).to.be.true;
    })
   it('Delete existing restaurant', async () => {
        //Act
        const deleteByIdResponse = await restaurantsAPI.deleteRestaurantById(365);

        //Assert
        expect(deleteByIdResponse.success).to.be.true;
        expect(deleteByIdResponse.status).to.equal(200);
    })`

And requests

  const updateRestaurantById = async (id: number, body: Updates): Promise<ApiResponse<Updates>> => {
    return HttpRequest.networkRequest({ url: baseUrl + 'restaurant', method: HttpRequest.HttpMethod.PATCH, queryParams: { id: id }, body: body });

}
   const deleteRestaurantById = async (id: number): Promise<ApiResponse<null>> => {
    return HttpRequest.networkRequest({ url: baseUrl + 'restaurant', method: HttpRequest.HttpMethod.DELETE, queryParams: { id: id } });
}`


问:
Next/Link keeps reload in components
It is said that in next js we don't need to install react-router-dom because the path of our pages depend on the pages folder. Well, it actually works when I create button to move to another pages. But when I create components folder and create navbar component, it doesn't work properly as it was. The next/link keeps reloading when it moves to another pages.

```<code>import Link from "next/link";

export default function Navbar() {
  return (
    <nav className="bg-black flex justify-between p-5 text-white">
      <h1 className="font-bold text-sky-400">
        <Link href="/">Furniture App</Link>
      </h1>
      <div>
        <Link href="about">About</Link>
        <Link href="promos">Promos</Link>
      </div>
    </nav>
  );
}

</code>```

Do I have to create components in pages folder in order to make Next/Link works without reload the browser?

Title: Next/Link keeps reload in components

Body:
It is said that in next js we don't need to install react-router-dom because the path of our pages depend on the pages folder. Well, it actually works when I create button to move to another pages. But when I create components folder and create navbar component, it doesn't work properly as it was. The next/link keeps reloading when it moves to another pages.

import Link from "next/link";

export default function Navbar() {
  return (

        <Link href="/">Furniture App</Link>

        <Link href="about">About</Link>
        <Link href="promos">Promos</Link>

  );
}

Do I have to create components in pages folder in order to make Next/Link works without reload the browser?


问:
convert ms sql sub query in select clause to linq2db C#
Can some one help me in converting below ms sql query to linq2db c# query?
I could not find any reference in linq2db documentation.

Any help or url to an example is highly appreciated.

```<code>SELECT
p.Id as ProductId,
(SELECT STRING_AGG(sao.Name, ',')
  FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=7 and ps.ProductId=p.Id) AS 'PrimaryTechnology',
(SELECT STRING_AGG(sao.Name, ',')
                                FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=8 and ps.ProductId=p.Id) AS 'SecondaryTechnology',
(SELECT sao.Name
    FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=1 and ps.ProductId=p.Id) AS 'ProfileType'
FROM [Product] p
order by P.Id asc
</code>```

Body:
Can some one help me in converting below ms sql query to linq2db c# query?
I could not find any reference in linq2db documentation.

Any help or url to an example is highly appreciated.

SELECT
p.Id as ProductId,
(SELECT STRING_AGG(sao.Name, ',')
  FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=7 and ps.ProductId=p.Id) AS 'PrimaryTechnology',
(SELECT STRING_AGG(sao.Name, ',')
                                FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=8 and ps.ProductId=p.Id) AS 'SecondaryTechnology',
(SELECT sao.Name
    FROM [Product_SpecificationAttribute_Mapping] PS
    JOIN [SpecificationAttributeOption] sao on sao.id=ps.SpecificationAttributeOptionId
    JOIN [SpecificationAttribute] sa on sa.id=sao.SpecificationAttributeId
    WHERE sa.Id=1 and ps.ProductId=p.Id) AS 'ProfileType'
FROM [Product] p
order by P.Id asc


问:
RSelenium cannot scroll selection with down key
So my objective here is to make the desired selection button pick successfully to "Weekly"

While I am directly using the Chrome browser, when I click the button, I can also input Down key (1x) and enter to get it

But with RSelenium its not giving the same response, here is the snippets I use to test:

```<code>link <- "https://www.investing.com/commodities/copper-historical-data"
rD <- rsDriver(browser="chrome", verbose=F, chromever = "108.0.5359.22")
remDr <- rD[["client"]]
remDr$navigate(link)
webElem <- remDr$findElement("css", "body")

for(x in 1:21){
   webElem$sendKeysToElement(list(key = "down_arrow"))
}

time_frame <- remDr$findElement(using = 'id', value = 'history-timeframe-selector')
time_frame$clickElement()

webElem$sendKeysToElement(list(key = "down_arrow"))
webElem$sendKeysToElement(list(key = "enter"))
</code>```

How to mitigate this in RSelenium?

Body:
So my objective here is to make the desired selection button pick successfully to "Weekly"

While I am directly using the Chrome browser, when I click the button, I can also input Down key (1x) and enter to get it

But with RSelenium its not giving the same response, here is the snippets I use to test:

link <- "https://www.investing.com/commodities/copper-historical-data"
rD <- rsDriver(browser="chrome", verbose=F, chromever = "108.0.5359.22")
remDr <- rD[["client"]]
remDr$navigate(link)
webElem <- remDr$findElement("css", "body")

for(x in 1:21){
   webElem$sendKeysToElement(list(key = "down_arrow"))
}

time_frame <- remDr$findElement(using = 'id', value = 'history-timeframe-selector')
time_frame$clickElement()

webElem$sendKeysToElement(list(key = "down_arrow"))
webElem$sendKeysToElement(list(key = "enter"))

How to mitigate this in RSelenium?


问:
Can disable pushing branches that don't exist in the GitHub repo?
Such as the title, I hope someone is able to push the branch only if it has been created in the GitHub repo.</p>