问:
List index out of range in function
I'm new to this and I tried googling but
I can't seem to fix this error inside "fingersUp" function.

Basically, each part of a finger has indexes and this function checks if the thumb finger is up based on these indexes. Each finger has 4 points.

I'm using PyCharm and Python 3.8, if that helps.

```<code>if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] -  1][1]: IndexError: list index out of range
</code>```

Here's the full code:

```<code>    import cv2
import mediapipe as mp
import time
import math
import numpy as np

class handDetector():
    def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands,
        self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils
        self.tipIds = [4, 8, 12, 16, 20]

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms,
                    self.mpHands.HAND_CONNECTIONS)

        return img

    def findPosition(self, img, handNo=0, draw=True):
        xList = []
        yList = []
        bbox = []
        self.lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id, lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                xList.append(cx)
                yList.append(cy)
                # print(id, cx, cy)
                self.lmList.append([id, cx, cy])
            if draw:
                cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)

                xmin, xmax = min(xList), max(xList)
                ymin, ymax = min(yList), max(yList)
                bbox = xmin, ymin, xmax, ymax

            if draw:
                cv2.rectangle(img, (xmin - 20, ymin - 20), (xmax + 20, ymax + 20),
                (0, 255, 0), 2)

        return self.lmList, bbox

    def fingersUp(self):
        fingers = []
        # Thumb
        if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:
            fingers.append(1)
        else:
            fingers.append(0)

        # Fingers
        for id in range(1, 5):

            if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:
                fingers.append(1)
            else:
                fingers.append(0)

    # totalFingers = fingers.count(1)

        return fingers

    def findDistance(self, p1, p2, img, draw=True,r=15, t=3):
        x1, y1 = self.lmList[p1][1:]
        x2, y2 = self.lmList[p2][1:]
        cx, cy = (x1 + x2) // 2, (y1 + y2) // 2

        if draw:
            cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), t)
            cv2.circle(img, (x1, y1), r, (255, 0, 255), cv2.FILLED)
            cv2.circle(img, (x2, y2), r, (255, 0, 255), cv2.FILLED)
            cv2.circle(img, (cx, cy), r, (0, 0, 255), cv2.FILLED)
            length = math.hypot(x2 - x1, y2 - y1)

        return length, img, [x1, y1, x2, y2, cx, cy]

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList, bbox = detector.findPosition(img)
        if len(lmList) != 0:

            cTime = time.time()
            fps = 1 / (cTime -  pTime)
            pTime = cTime

            cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
            (255, 0, 255), 3)

            cv2.imshow("Image", img)
            cv2.waitKey(1)

if __name__ == "__main_":
    main()
</code>```

答:
Try, this line:

the brackets aren't placed right that is why it shows the error.

```<code>if (self.lmList[self.tipIds[0][1]]
</code>```

Title: List index out of range in function

Body:
I'm new to this and I tried googling but
I can't seem to fix this error inside "fingersUp" function.

Basically, each part of a finger has indexes and this function checks if the thumb finger is up based on these indexes. Each finger has 4 points.

I'm using PyCharm and Python 3.8, if that helps.

if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] -  1][1]: IndexError: list index out of range

Here's the full code:

    import cv2
import mediapipe as mp
import time
import math
import numpy as np

class handDetector():
    def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands,
        self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils
        self.tipIds = [4, 8, 12, 16, 20]

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms,
                    self.mpHands.HAND_CONNECTIONS)

        return img

    def findPosition(self, img, handNo=0, draw=True):
        xList = []
        yList = []
        bbox = []
        self.lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id, lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                xList.append(cx)
                yList.append(cy)
                # print(id, cx, cy)
                self.lmList.append([id, cx, cy])
            if draw:
                cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)

                xmin, xmax = min(xList), max(xList)
                ymin, ymax = min(yList), max(yList)
                bbox = xmin, ymin, xmax, ymax

            if draw:
                cv2.rectangle(img, (xmin - 20, ymin - 20), (xmax + 20, ymax + 20),
                (0, 255, 0), 2)

        return self.lmList, bbox

    def fingersUp(self):
        fingers = []
        # Thumb
        if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:
            fingers.append(1)
        else:
            fingers.append(0)

        # Fingers
        for id in range(1, 5):

            if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:
                fingers.append(1)
            else:
                fingers.append(0)

    # totalFingers = fingers.count(1)

        return fingers

    def findDistance(self, p1, p2, img, draw=True,r=15, t=3):
        x1, y1 = self.lmList[p1][1:]
        x2, y2 = self.lmList[p2][1:]
        cx, cy = (x1 + x2) // 2, (y1 + y2) // 2

        if draw:
            cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), t)
            cv2.circle(img, (x1, y1), r, (255, 0, 255), cv2.FILLED)
            cv2.circle(img, (x2, y2), r, (255, 0, 255), cv2.FILLED)
            cv2.circle(img, (cx, cy), r, (0, 0, 255), cv2.FILLED)
            length = math.hypot(x2 - x1, y2 - y1)

        return length, img, [x1, y1, x2, y2, cx, cy]

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList, bbox = detector.findPosition(img)
        if len(lmList) != 0:

            cTime = time.time()
            fps = 1 / (cTime -  pTime)
            pTime = cTime

            cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
            (255, 0, 255), 3)

            cv2.imshow("Image", img)
            cv2.waitKey(1)

if __name__ == "__main_":
    main()

Body:
Try, this line:

the brackets aren't placed right that is why it shows the error.

if (self.lmList[self.tipIds[0][1]]


来源: stackexchange

问:
is it compulsory to write Html audio type?
Is it necessary to write audio type in html like .

I have tested it without writing audio type  and it is working fine then why should we have to write it?

答:
```<code><audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</code>```

ig unless an until it has it's default type... you could ignore the type attribute.

ContentLicense: CC BY-SA 4.0

Body:
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

ig unless an until it has it's default type... you could ignore the type attribute.


问:
How to trigger click event of anchor tag via jQuery for dynamic data?
Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `

${element.name}

${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}

`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section></code>```

Please do guide if possible. Thanks.

答:
Your code isn't working because your element isn't loaded with the page, so when jQuery runs $('.card a').click(function..., $('.card a') returns null, so the listener is not attached.

Add your listener to the document like so:

```<code>$(document).on("click", ".card a", function() { ... })
</code>```

When the user clicks on the document, jQuery will check if $(".card a") is the target, even if added after the page was initially loaded, and will execute your function if it is.

Body:
Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `

${element.name}

${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}

`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});

Please do guide if possible. Thanks.

Body:
Your code isn't working because your element isn't loaded with the page, so when jQuery runs $('.card a').click(function..., $('.card a') returns null, so the listener is not attached.

Add your listener to the document like so:

$(document).on("click", ".card a", function() { ... })

When the user clicks on the document, jQuery will check if $(".card a") is the target, even if added after the page was initially loaded, and will execute your function if it is.


问:
How to connecte to sql sever NET6 visual studio 2022 asp.net mvc project
i try to modify my local db connection (which works fine) in the appsettings.json :

```<code> "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

with the sql server connection :

```<code> "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

but when i run the project i got a strange error:

local host does  not exists..

and also

```<code>An unhandled exception occurred while processing the request.
</code>```

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks

答: Are you be able to connect SQL remotely? If it is working, then please double check your connection string or you can ask your provider about correct connection string that you need to use.</p>

Body:
i try to modify my local db connection (which works fine) in the appsettings.json :

 "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"

with the sql server connection :

 "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"

but when i run the project i got a strange error:

local host does  not exists..

and also

An unhandled exception occurred while processing the request.

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks


问:
SQL request : how to make a particular select with multi tables and calcul?
Here's my problem. I've 4 tables on an Oracle Database:

Team(teamID, teamName)

TeamMembers(membersID, teamID, membersStatusID)

Members(membersID, membersName)

Status(membersStatusID, statusName)

I need to gets the teamName, the numbers of teamMembers in these teams and the name of the members who have the status "Captain"... all of this in one SELECT in SQL.

Many hours on this and no solution... any idea?

Edit: I need to see all teams, even if there's no members in it.

答:
I'm unable to test this select now, but you can try this:</p>

```<code>select team.teamName,count(distinct members.membersID) numMembers,
MAX(CASE when status.statusName='CAPTAIN' then members.membersname else null END) Captain
from team,teammembers,members,status
where team.teamID=teammembers.teamID(+)
and teammembers.membersID=members.membersID(+)
and teamMembers.memberStatusID=status.memberstatusID(+)
group by team.teamName;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm unable to test this select now, but you can try this:

select team.teamName,count(distinct members.membersID) numMembers,
MAX(CASE when status.statusName='CAPTAIN' then members.membersname else null END) Captain
from team,teammembers,members,status
where team.teamID=teammembers.teamID(+)
and teammembers.membersID=members.membersID(+)
and teamMembers.memberStatusID=status.memberstatusID(+)
group by team.teamName;


问:
Performing operations across typescript objects by key
In typescript, I have two objects with matching keys, and the values are of type number[][], for example:

```<code>const A = {
    "X": [ [100, 20], [200, 35], [300, 30] ],
    "Y": [ [400, 20], [500, 15], [600, 25] ],
    "Z": [ [700, 30], [800, 35], [900, 40] ]
}

const B = {
    "X": [ [100, 2], [200, 3], [300, 2] ],
    "Y": [ [400, 1], [500, 3], [600, 2] ],
    "Z": [ [700, 3], [800, 3], [900, 2], [1000, 4 ]
}

</code>```

I would like a function which is able to match the keys in each of the objects, merge the values based on the first entry in the inner arrays, and then finally perform an operation on the 2nd entry in the arrays, for example multiply the values.

The desired output would be a third object in the same format as A and B, like so:

```<code>C = A * B

const C = {
    "X": [ [100, 40], [200, 105], [300, 60] ],
    "Y": [ [400, 20], [500, 45], [600, 50] ],
    "Z": [ [700, 90], [800, 105], [900, 160] ]
}
</code>```

Note that since the value of "1000" only appears in B, it is not included in C

This is my attempt so far:

```<code>C =  Object.keys(A).reduce((o,key)  => ({ ...o, [key]: A.key[1]*B.key[1]}), {})
</code>```

However, I am getting the error message "Cannot read properties of undefined (reading '1')"

Any help here would be greatly appreciated!

答:
You can try this, hope it will help

const A = {
  X: [
    [100, 20],
    [200, 35],
    [300, 30],
  ],
  Y: [
    [400, 20],
    [500, 15],
    [600, 25],
  ],
  Z: [
    [700, 30],
    [800, 35],
    [900, 40],
  ],
};

const B = {
  X: [
    [100, 2],
    [200, 3],
    [300, 2],
  ],
  Y: [
    [400, 1],
    [500, 3],
    [600, 2],
  ],
  Z: [
    [700, 3],
    [800, 3],
    [900, 2],
    [1000, 4],
  ],
};

const operation = (a, b) => a * b;

const mergeArrays = (arr1, arr2) => {
  const newArr = [];
  arr1.forEach(([key1, val1]) => {
    const val2 = arr2.find(([key2]) => key2 === key1)?.[1];
    if (val2) {
      // if item with the same key exeist in second array
      // pushing pair to new array
      newArr.push([key1, operation(val1, val2)]);
    }
  });
  return newArr;
};

const mergeObjects = (obj1, obj2) => {
  const newObj = {};
  for (const key in obj1) {
    // I assume you want intersection of object keys too
    if (key in obj2) {
      newObj[key] = mergeArrays(obj1[key], obj2[key]);
    }
  }
  return newObj;
};

console.log(mergeObjects(A, B));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{top:0;max-height:100%!important}</code>```

Body:
In typescript, I have two objects with matching keys, and the values are of type number[][], for example:

const A = {
    "X": [ [100, 20], [200, 35], [300, 30] ],
    "Y": [ [400, 20], [500, 15], [600, 25] ],
    "Z": [ [700, 30], [800, 35], [900, 40] ]
}

const B = {
    "X": [ [100, 2], [200, 3], [300, 2] ],
    "Y": [ [400, 1], [500, 3], [600, 2] ],
    "Z": [ [700, 3], [800, 3], [900, 2], [1000, 4 ]
}

I would like a function which is able to match the keys in each of the objects, merge the values based on the first entry in the inner arrays, and then finally perform an operation on the 2nd entry in the arrays, for example multiply the values.

The desired output would be a third object in the same format as A and B, like so:

C = A * B

const C = {
    "X": [ [100, 40], [200, 105], [300, 60] ],
    "Y": [ [400, 20], [500, 45], [600, 50] ],
    "Z": [ [700, 90], [800, 105], [900, 160] ]
}

Note that since the value of "1000" only appears in B, it is not included in C

This is my attempt so far:

C =  Object.keys(A).reduce((o,key)  => ({ ...o, [key]: A.key[1]*B.key[1]}), {})

However, I am getting the error message "Cannot read properties of undefined (reading '1')"

Any help here would be greatly appreciated!

Body:
You can try this, hope it will help

const A = {
  X: [
    [100, 20],
    [200, 35],
    [300, 30],
  ],
  Y: [
    [400, 20],
    [500, 15],
    [600, 25],
  ],
  Z: [
    [700, 30],
    [800, 35],
    [900, 40],
  ],
};

const B = {
  X: [
    [100, 2],
    [200, 3],
    [300, 2],
  ],
  Y: [
    [400, 1],
    [500, 3],
    [600, 2],
  ],
  Z: [
    [700, 3],
    [800, 3],
    [900, 2],
    [1000, 4],
  ],
};

const operation = (a, b) => a * b;

const mergeArrays = (arr1, arr2) => {
  const newArr = [];
  arr1.forEach(([key1, val1]) => {
    const val2 = arr2.find(([key2]) => key2 === key1)?.[1];
    if (val2) {
      // if item with the same key exeist in second array
      // pushing pair to new array
      newArr.push([key1, operation(val1, val2)]);
    }
  });
  return newArr;
};

const mergeObjects = (obj1, obj2) => {
  const newObj = {};
  for (const key in obj1) {
    // I assume you want intersection of object keys too
    if (key in obj2) {
      newObj[key] = mergeArrays(obj1[key], obj2[key]);
    }
  }
  return newObj;
};

console.log(mergeObjects(A, B));

.as-console-wrapper{top:0;max-height:100%!important}


问:
JavaScript function works, but not when I try expanded its functionality
I have this simple form in my HTML code to upload a file, and a JavaScript function to make sure the file is not too large, everything works fine. In fact the second false in my JavaScript is there just to keep me from submitting the form while I build up the validation function.

My error starts to occur when I try to check if a file has not been selected.

Just using the code below, if I select no file, then click submit, the form posts and calls the second script. Even though my JavaScript function always returns a false.

I'm guessing that I have a JavaScript error, hence why my code jumps out of the function and the form continues posting.

Am assuming there's a proper way to call document.getElementById('myFile').files[0].name and check it for NULL, without triggering an error?

HTML Form

```<code><form onsubmit="return checkFile()"
name ="uploadlist" action="http://www.example.com/cgi-bin/upload2.pl"
method="post" enctype="multipart/form-data">
</code>```

And the JavaScript

```<code><script>
    function checkFile(){

    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);

    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
        }
    return false;
    }
</script>
</body>
</code>```

答:
Try adding required attribute to your <input> field:

<input type='file' required />
```
<p>Or check <code>document.getElementById('myFile').files</code> length, e.g</p>
<pre class="lang-js prettyprint-override"><code>if (document.getElementById('myFile').files.length == 0) return false;
</code>```

Body:
I have this simple form in my HTML code to upload a file, and a JavaScript function to make sure the file is not too large, everything works fine. In fact the second false in my JavaScript is there just to keep me from submitting the form while I build up the validation function.

My error starts to occur when I try to check if a file has not been selected.

Just using the code below, if I select no file, then click submit, the form posts and calls the second script. Even though my JavaScript function always returns a false.

I'm guessing that I have a JavaScript error, hence why my code jumps out of the function and the form continues posting.

Am assuming there's a proper way to call document.getElementById('myFile').files[0].name and check it for NULL, without triggering an error?

HTML Form

<form onsubmit="return checkFile()"
name ="uploadlist" action="http://www.example.com/cgi-bin/upload2.pl"
method="post" enctype="multipart/form-data">

And the JavaScript

Body:
Try adding required attribute to your <input> field:

<input type='file' required />

Or check document.getElementById('myFile').files length, e.g

if (document.getElementById('myFile').files.length == 0) return false;


问:
regex repetitive parts in monetary amounts
In a monetary pattern I look for thousand separator

```<code>(?:[. ]\d{3})*
</code>```

In this case the thousand separator could either be . or  . But how to make sure that the pattern will not match patterns where the thousand separator is mixed?

Only match patterns like

```<code>.123.123.123
 123 123 123
</code>```

Do not match

```<code>.123 123 123.123
</code>```

答:
You can match the first separator and then use a backreference to match the same separator for the remaining digit groups:

```<code>^(?:([. ])\d{3}(\1\d{3})*)?$
</code>```

Demo: https://regex101.com/r/u4zPuf/1

Body:
In a monetary pattern I look for thousand separator

(?:[. ]\d{3})*

In this case the thousand separator could either be . or  . But how to make sure that the pattern will not match patterns where the thousand separator is mixed?

Only match patterns like

.123.123.123
 123 123 123

Do not match

.123 123 123.123

Body:
You can match the first separator and then use a backreference to match the same separator for the remaining digit groups:

^(?:([. ])\d{3}(\1\d{3})*)?$

Demo: https://regex101.com/r/u4zPuf/1


问:
Why I getting null Object in controller from Ajax call passing JSON object as data in ASP.NET Core?
Below code is view page and call Ajax method. I need to pass address object.

```<code>var address = {};

address.userId = parseInt($("#userID").val());
address.addressLine1 = $("#addAddressLine1").val();
address.addressLine2 = $("#addAddressLine2").val();
address.cityId = parseInt($("#addAddressCity").val());
address.zipCode = $("#addAddressPostCode").val();
address.mobileNo = $("#addAddressPhoneNumber").val();

$.ajax({
            type: "POST",
            url: "@Url.Action("AddAddress")",
            data:JSON.stringify(address),
            dataType: 'json',
            contentType: 'application/json',
            success: function (responce) {
                if (responce) {
                    alert("true");
                }
                else {
                    alert("fail");
                }
            },
            failure: function (response) {
                alert("failure");
            },
            error: function (response) {
                alert("Something went Wrong");
            }
});
</code>```

This is the code of my controller action method. I get a Null value of address object when it's called from Ajax:

```<code>public IActionResult AddAddress([FromBody] AddressViewModel address)
{
    return Json(address != null);
}
</code>```

This is my view model:

```<code>public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int CityId { get; set; }
}
</code>```

Where do I need to change my code? Do I need to change something in StartUp.cs ?

答:
You need to make sure the value of address.userId = parseInt($("#userID").val()); and address.cityId = parseInt($("#addAddressCity").val());.int type cannot accept null value,if address.userId or address.cityId is null,AddressViewModel address will be null.You can try to use #nullable enable or change the value of address.userId or address.cityId.

```<code>#nullable enable
public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int? UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int? CityId { get; set; }
}
</code>```

Body:
Below code is view page and call Ajax method. I need to pass address object.

var address = {};

address.userId = parseInt($("#userID").val());
address.addressLine1 = $("#addAddressLine1").val();
address.addressLine2 = $("#addAddressLine2").val();
address.cityId = parseInt($("#addAddressCity").val());
address.zipCode = $("#addAddressPostCode").val();
address.mobileNo = $("#addAddressPhoneNumber").val();

$.ajax({
            type: "POST",
            url: "@Url.Action("AddAddress")",
            data:JSON.stringify(address),
            dataType: 'json',
            contentType: 'application/json',
            success: function (responce) {
                if (responce) {
                    alert("true");
                }
                else {
                    alert("fail");
                }
            },
            failure: function (response) {
                alert("failure");
            },
            error: function (response) {
                alert("Something went Wrong");
            }
});

This is the code of my controller action method. I get a Null value of address object when it's called from Ajax:

public IActionResult AddAddress([FromBody] AddressViewModel address)
{
    return Json(address != null);
}

This is my view model:

public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int CityId { get; set; }
}

Where do I need to change my code? Do I need to change something in StartUp.cs ?

Body:
You need to make sure the value of address.userId = parseInt($("#userID").val()); and address.cityId = parseInt($("#addAddressCity").val());.int type cannot accept null value,if address.userId or address.cityId is null,AddressViewModel address will be null.You can try to use #nullable enable or change the value of address.userId or address.cityId.

#nullable enable
public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int? UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int? CityId { get; set; }
}


答:
As @will already pointed out: it is a timing problem. In your code the click event was attached before the contents form your $.getJSON() arrives. By using a delegated event attachment you can solve the problem:

const page=1, dataList=[], favouritesList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        // console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `

${element.name}

${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}

             click me

`
        temp += item;
    });
    return temp;
}

//this is now working:
 $('section').on("click",".card a",function () {
    favouritesList.push($(this).attr("id"));
    console.log(favouritesList);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.img-fluid {height:80px}</code>```

```

Title: How to trigger click event of anchor tag via jQuery for dynamic data?

Body:
As @will already pointed out: it is a timing problem. In your code the click event was attached before the contents form your $.getJSON() arrives. By using a delegated event attachment you can solve the problem:

const page=1, dataList=[], favouritesList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        // console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `
        <div class="card col-xs-12 col-lg-4 my-2">
            <div class="card-body">
                   <figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
            <article class="ms-3">
                    <h5 class="card-title">${element.name}</h5>
                    <p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
            </article>
<!--- This is what's suppose to give the event on click. --->
            <a href="javascript:void(0)"  id=${element.id}> <i class="fa fa-star-o usericon mt-3">click me</i></a>
            </div>
        </div>`
        temp += item;
    });
    return temp;
}

//this is now working:
 $('section').on("click",".card a",function () {
    favouritesList.push($(this).attr("id"));
    console.log(favouritesList);

});

.img-fluid {height:80px}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>


问:
How to read data from Microsoft Access .accdb database files into R?
The RODBC documentation suggests it is possible, but I am not sure how to read data from a Microsoft Access (the new .accdb format) file with this package into R (on Debian GNU/Linux). The vignette talks about drivers, but I do not quite understand how I can see which drivers are installed, and in particular, if I have a driver installed for me to access those .accdb files.

What code do you use to read data from .accdb files? And please indicate what platform you are on and if you had to install a special driver.

答:
You'll need the drivers to connect Access to the ODBC interface. These should be on your system if you have Access installed. If not, download the Access Database Engine from Microsoft. Then create your data connection in ODBC (You may need to run the 32-bit c:\windows\sysWOW64\odbcad32.exe if running 64-bit Windows). Note that this method doesn't work on GNU/Linux. The runtimes are Windows only, as mentioned by @HansUp below.

As for code, you'll probably start with odbcConnect(dsn, uid = "", pwd = "", ...), and the documentation can help with the details.

OwnerDisplayName: Egon Willighagen


问:
Added code and now it's not print correctly to CSV file
I have the first code that is working and printing to csv, however it included a lot of data I didn't need.  A paragraph of code was then added to only include the data I wanted.  The problem is it prints to the screen correctly but still includes all the data in the CSV file.  I've tried everything I could think of in this line but it won't either won't print or still prints everything.

data = pd.DataFrame(stock_info)

Could someone show me where I'm going wrong so it will print only the portion I want it to?

Old Working Code

```<code>import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)
</code>```

New Non-Working Code

```<code>import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break
</code>```

答:
If you don't need to keep those columns just slice them out by adding a line to your original code:

```<code>data = pd.DataFrame(stock_info)
data = data.iloc[:, 4:]
</code>```

In original code:

```<code>import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data = data.iloc[:, 4:]
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)
</code>```

Body:
I have the first code that is working and printing to csv, however it included a lot of data I didn't need.  A paragraph of code was then added to only include the data I wanted.  The problem is it prints to the screen correctly but still includes all the data in the CSV file.  I've tried everything I could think of in this line but it won't either won't print or still prints everything.

data = pd.DataFrame(stock_info)

Could someone show me where I'm going wrong so it will print only the portion I want it to?

Old Working Code

import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

New Non-Working Code

import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)

for info in stock_info:
    key = info[0]
    for i, sub in enumerate(info[1:], 1):
        if sub == key:
            print(info[i:])
            break

Body:
If you don't need to keep those columns just slice them out by adding a line to your original code:

data = pd.DataFrame(stock_info)
data = data.iloc[:, 4:]

In original code:

import requests
import pandas as pd

url = "https://www.stockrover.com/stock_infos/grid?_dc=1644769629231"

def stock_data(stock_info):
    data = pd.DataFrame(stock_info)
    data = data.iloc[:, 4:]
    data.to_csv("data.csv", index=False)

payload = "state=%7B%22sortInfo%22%3A%7B%7D%2C%22columns%22%3A%5B77%2C32%2C498%2C500%2C31%2C27%2C499%2C30%2C578%2C28%2C29%2C544%2C181%2C185%2C186%5D%2C%22view%22%3A281%2C%22priorPrimaryColumn%22%3A170%2C%22filterData%22%3A%5B%5D%2C%22name%22%3A%22New%201%22%2C%22cType%22%3A%22Screener%22%2C%22cNode%22%3A%22s_39%22%2C%22cIsFolder%22%3Afalse%2C%22gridSelection%22%3A%22BTU%22%2C%22lastActive%22%3A1396898415%2C%22primaryColumn%22%3A76%2C%22folderDisabledParams%22%3A%7B%22filterData%22%3A%5B%5D%7D%2C%22mainGridDateRange%22%3A%22ytd%22%2C%22groupState%22%3Anull%2C%22moversGridDateRange%22%3A%221_day%22%2C%22peersGridDateRange%22%3A%221_day%22%2C%22lastGridSelections%22%3A%5B%22BTU%22%5D%2C%22lastQuantNode%22%3A%5B%5D%2C%22includeQuotesInTable%22%3Afalse%2C%22includeAllQuotesLastValue%22%3Afalse%2C%22markets%22%3A%7B%22panel%22%3A%22summary%22%7D%2C%22researchPanel%22%3A%22tablePanel%22%2C%22recentSearchTickers%22%3A%5B%22SPY%22%2C%22AMZN%22%2C%22AAPL%22%2C%22s_32%22%2C%22%5ENDX%22%2C%22AXP%22%2C%22XOM%22%2C%22AFL%22%2C%22%5EDJX%22%2C%22AIT%22%2C%22ADVC%22%5D%2C%22quotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22checkedQuotesBoxTickers%22%3A%5B%22AMZN%22%2C%22AAPL%22%2C%22SPY%22%5D%2C%22dashboard%22%3A%7B%22buttonRef%22%3A%22272%22%7D%2C%22tickerSelectedFeeds%22%3A%5B%22Benzinga%20News%22%2C%22Yahoo%20News%22%5D%2C%22marketSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Stock%20Market%20News%20-%20Investing.com%22%5D%2C%22bondsSelectedFeeds%22%3A%5B%22Bonds%20Strategy%20-%20Investing.com%22%5D%2C%22commoditiesSelectedFeeds%22%3A%5B%22Commodities%20%26%20Futures%20News%20-%20Investing.com%22%2C%22Commodities%20Fundamental%20Analysis%20-%20Investing.com%22%2C%22Commodities%20Strategy%20Analysis%20-%20Investing.com%22%5D%2C%22stocksSelectedFeeds%22%3A%5B%22CNNMoney%20News%22%2C%22Google%20News%22%2C%22Seeking%20Alpha%20Top%20Stories%22%5D%2C%22etfsSelectedFeeds%22%3A%5B%22Economy%20News%20-%20Investing.com%22%2C%22ETF%20Analysis%20-%20Investing.com%22%2C%22Investing%20Ideas%20-%20Investing.com%22%5D%2C%22topPanel%22%3A%22researchPanel%22%2C%22maxRecordsNode%22%3Afalse%2C%22version%22%3A7%2C%22lastGridSelectionsRaw%22%3A%5B%22BTU%22%5D%2C%22lastSelectionScreeners%22%3A%22s_39%22%2C%22quotesDisabled%22%3Atrue%2C%22lastSelectionPortfolios%22%3A%22p_2%22%2C%22comparisonPanels%22%3A%7B%22Portfolio%22%3A%22p_2%22%2C%22Index%22%3A%22%5EDJX%22%2C%22Watchlist%22%3A%22Watchlists%22%2C%22Screener%22%3A%22s_39%22%7D%2C%22lastSelectionWatchlists%22%3A%22w_26%22%2C%22indicesSelectedFeeds%22%3A%5B%22Google%20News%22%2C%22Yahoo%20News%22%5D%2C%22newsActive%22%3A%22tickerNews%22%2C%22recentSearchMetrics%22%3A%5B%22Price%22%2C%22EPS%22%2C%22Sales%22%5D%2C%22editPanel%22%3A%22positionsPanel%22%2C%22newsType%22%3A%22marketNews%22%2C%22tableColumns%22%3A%5B%22ticker%22%2C%22rank%22%2C%22score_rank%22%2C%22filter_score%22%2C%22company%22%2C%22cash%22%2C%22currentassets%22%2C%22netppe%22%2C%22intangibles%22%2C%22totalassets%22%2C%22currentliabilities%22%2C%22longtermdebt%22%2C%22totaldebt%22%2C%22totalliabilities%22%2C%22equity%22%2C%22tangiblebookvalue%22%2C%22cash_short_term_p%22%2C%22net_ppe_p%22%2C%22intangibles_p%22%5D%2C%22last_save%22%3A1644769379%2C%22panels%22%3A%7B%22collapsed%22%3A%7B%22chp%22%3Atrue%2C%22ip%22%3Atrue%2C%22mp%22%3Afalse%2C%22qp%22%3Afalse%2C%22conp%22%3Atrue%2C%22fsp%22%3Afalse%7D%2C%22viewportWidth%22%3A%221920%22%2C%22viewportHeight%22%3A%221069%22%2C%22chartPanelHeight%22%3A483%2C%22controlPanelWidth%22%3A296%2C%22insightPanelWidth%22%3A%22485%22%2C%22quoteBoxHeight%22%3A200%2C%22navigationPanelWidth%22%3A277%7D%7D&updateMarket=true&page=1&start=0&limit=250"
headers = {
    'authority': 'www.stockrover.com',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'x-csrf-token': '7yR4pfI0kAArtjJak535+NJrpB0L212PAbXCg0kbyE4SyjFaQ73sMHJLiqAkPb5nGzfC8KvAa3kTADLAEQXyOQ==',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': 'application/json',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-platform': '"Windows"',
    'origin': 'https://www.stockrover.com',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.stockrover.com/research/table/281/s_39/BTU',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': 'remember_me_pref=0; user_name=test11964; plan=3; premiumBraintreeKey=MIIBCgKCAQEAzM4LJfrNnBOgRFB1dDJkmqTFCWT2Y%2BksOydD8xDH4R033WUzxbffMZb%2B3dqEyQvOVjLcwFIHByDc4Xwej7enas2E%2FVRyh7Cvyadn7M5zQeRyLcI9Ys5KCozMwxJPc0x76FlXPwiAo1Qlz3RcLb9wGHBag2R51FuTie%2BhVDCgzWajqDCREzRhi%2Fqlt3D%2FxXNo%2FiwJlpOUr%2Fx1QnkkILxgKlq1dD7KJ767O5ojYKXsO%2BV2Bfu7sSD3djsOxQJ1%2FRbaDm2E96EDkWhhOeOpPndQ6IuSl4NmnJg%2Fcq6f8csW8M3Ys%2BMZPFkdxPC4%2FfRM1XC9o76PjpVNBIO%2ByJEELKZedwIDAQAB; lr=1644769628; _Ruby2_session=Q1drcmlhazYvUFZLd0NydnRXUGpoUzArZDlxYWRCcW9sRUx5VDBydWVWRHdGWDZlMnlESURzbldwbFV1L0drbUlKaWt5MXRtaS9iR0ZYZEpPVHQ1N25qRnR1d3FrY0tzQW1qQm9CdTZ3MSs0d2c3MlpuMjRiQWhCOHI1cGNWekZ4cUdJd0ZFcGtpeng3MFlqZjFDUW9RYmpFMU9DeGdGMVZKR1EwMjVhSE9yVHl4VXFtQm9aYVBtNHF5d0pwMjJ1aVlNMUVRUzdnVFZWZ1AxQkY5Q0p6a2RKay9QL05tOWk4cHZiSERtaGRxeTlxTWZnV3Q0cjdwR3RndUtmeUp3QThhMnJaV2dGZjlPUUtjcGRidDhiajRxK2g0RUZTMWNZUDBaeGNCcUVxSDJ1QnZVRlRkWk9tUExJNWN3TDN5T1BQcmhVVGsycStVTzJRaUwvSkk2TnNVZldTOGU3Tm5wQ3RUMy9nazFqbzdrUWtvYzRwQWRpV3dnTVB3YzhodFV2U0FRR3VKdllMY01NZmdOdGtmOEJ4UT09LS1nTXBrYldhQ0pEeWJ3ak9qQjcrTGV3PT0%3D--1439f36a7f9362aee4b5b666747a2d63d72e81bd'
}

response = requests.request("POST", url, headers=headers, data=payload)
stock_info = response.json()['stock_infos']
stock_data(stock_info)


问:
Navigation Title is not showing on SwiftUI
The navigationTitle is not working.
I use Swift5.5.2
In the preview there is no sign of the navigation title just an empty space.

```<code>
struct ContentView: View {

    @State private var firstname = ""
    @State private var lastname = ""
    @State private var birthdate = Date()
    @State private var shouldSendNewsletter = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Personal Information")) {
                    TextField("First Name", text: $firstname)
                    TextField("Last Name", text: $lastname)
                    DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

                    Section(header: Text("Actions")) {
                        Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
                    }//:Actions

                }
            }//:Form
        }//: NAVIGATION VIEW
        .navigationTitle("ABC")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Preview of navigation title

答:
NavigationView is a container that hold ChildViews inside it. So .navigationTitle resides inside NavigationView, so in order to change navigationTitle we must call it from inside of NavigationView like this

```<code>NavigationView{
    VStack{
    }
    .navigationTitle("ABC")
}
</code>```

Body:
The navigationTitle is not working.
I use Swift5.5.2
In the preview there is no sign of the navigation title just an empty space.

struct ContentView: View {

    @State private var firstname = ""
    @State private var lastname = ""
    @State private var birthdate = Date()
    @State private var shouldSendNewsletter = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Personal Information")) {
                    TextField("First Name", text: $firstname)
                    TextField("Last Name", text: $lastname)
                    DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

                    Section(header: Text("Actions")) {
                        Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
                    }//:Actions

                }
            }//:Form
        }//: NAVIGATION VIEW
        .navigationTitle("ABC")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Preview of navigation title

Body:
NavigationView is a container that hold ChildViews inside it. So .navigationTitle resides inside NavigationView, so in order to change navigationTitle we must call it from inside of NavigationView like this

NavigationView{
    VStack{
    }
    .navigationTitle("ABC")
}


问:
Why arent my lists recording onto my graph? (or at all)
So I'm making code that supposed to track how the distance of an object impacts the force it makes, yet for some reason, my list function will only record my last value input into the while loop. In addition, the graph won't even show that value. Im using Matplotlib and SymPy, nothing really extreme for packages. Can someone please help me with these two issues?</p>
```<code>import sympy as sy
sy.init_printing()
from sympy import *
import matplotlib.pyplot as plt

x=1

print('Give it a minute please')

List_p = list()
List_x = list()

while x<=750:
    theta = atan(400/x)
    Fd=10*500*cos(theta)/(x/cos(theta))
    p=Fd*sin(theta)
    List_p.append(p)
    List_x.append(x)
    x=x+1

plt.plot([x],[p])
plt.xlim(1,750)
plt.xlabel('Distance')
plt.ylabel('Force of P')
plt.title('Distance V Force of P')
plt.show()
</code>```

答:
It seems to me that the issue is you're not plotting List_x and List_p but rather just x and p. Pass the lists to the plot method instead:

```<code>List_p = []
List_x = []

for x in range(1,751):
    theta = atan(400/x)
    Fd=10*500*cos(theta)/(x/cos(theta))
    p=Fd*sin(theta)
    List_p.append(p)
    List_x.append(x)

plt.plot(List_x, List_p)    # <--- here
plt.xlim(1,750)
plt.xlabel('Distance')
plt.ylabel('Force of P')
plt.title('Distance V Force of P')
plt.show()
</code>```

Body:
So I'm making code that supposed to track how the distance of an object impacts the force it makes, yet for some reason, my list function will only record my last value input into the while loop. In addition, the graph won't even show that value. Im using Matplotlib and SymPy, nothing really extreme for packages. Can someone please help me with these two issues?

import sympy as sy
sy.init_printing()
from sympy import *
import matplotlib.pyplot as plt

x=1

print('Give it a minute please')

List_p = list()
List_x = list()

while x<=750:
    theta = atan(400/x)
    Fd=10*500*cos(theta)/(x/cos(theta))
    p=Fd*sin(theta)
    List_p.append(p)
    List_x.append(x)
    x=x+1

plt.plot([x],[p])
plt.xlim(1,750)
plt.xlabel('Distance')
plt.ylabel('Force of P')
plt.title('Distance V Force of P')
plt.show()

Body:
It seems to me that the issue is you're not plotting List_x and List_p but rather just x and p. Pass the lists to the plot method instead:

List_p = []
List_x = []

for x in range(1,751):
    theta = atan(400/x)
    Fd=10*500*cos(theta)/(x/cos(theta))
    p=Fd*sin(theta)
    List_p.append(p)
    List_x.append(x)

plt.plot(List_x, List_p)    # <--- here
plt.xlim(1,750)
plt.xlabel('Distance')
plt.ylabel('Force of P')
plt.title('Distance V Force of P')
plt.show()


问:
how to upload image or pdf file with form-data in react-native?
i found some libraries but i am not sure which one is suitable and stable for me.

i am implementing like email attachment with form-data.

Choose uploading files from gallery or file Manage on Android device and upload to server.

could you recommend nice library? thank you !

what i have found

https://github.com/kaancelen/react-native-nononsense-file-picker

https://github.com/Elyx0/react-native-document-picker

https://github.com/farmisen/react-native-file-uploader

https://github.com/huangzuizui/react-native-file-opener

and so on..

答:
  const onSelectFile = async (type) => {
    // Opening Document Picker to select one file
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: "File Access",
          message:
            "We Need Your File Access to Upload Resume/Image" ,

          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK"
        }
      );
      if(granted===PermissionsAndroid.RESULTS.GRANTED){
        console.log(PermissionsAndroid.RESULTS)

      const res = await DocumentPicker.pickSingle({
        // Provide which type of file you want user to pick
        type: [DocumentPicker.types.allFiles],

      });

  let formData = new FormData();

  formData.append('myfile',{
   uri:res.uri,
   type:res.type,
   name:res.name

  });
  // const token = await AsyncStorage.getItem("token");
console.log('FORMDATA',{
  uri:res.uri,
  type:res.type,
  name:res.name

 });

let result = await fetch(
  YOUR_URL',
  {
    method: 'post',
    body: formData,
    headers: {
      'content-type': 'multipart/form-data',
      'Authorization': `Bearer ${TOKEN}`,

    },
  }
);
let responseJson = await result.json();
console.log('RESPONSE',responseJson)

    } catch (err) {

      // Handling any exception (If any)
      if (DocumentPicker.isCancel(err)) {
        // If user canceled the document selection
        console.log('Canceled');
      } else {
        // For Unknown Error
        console.log('Unknown Error: ' + JSON.stringify(err));

      }
    }
  };```


问:
React-select is going blank when the options array changes (codesandbox included)
I am trying to use react-select in combination with match-sorter as described in this stackoverflow answer (their working version). I have an initial array of objects that get mapped to an array of objects with the value and label properties required by react-select, which is stored in state. That array is passed directly to react-select, and when you first click the search box everything looks good, all the options are there. The onInputChange prop is given a call to matchSorter, which in turn is given the array, the new input value, and the key the objects should be sorted on. In my project, and reproduced in the sandbox, as soon as you type anything into the input field, all the options disappear and are replaced by the no options message. If you click out of the box and back into it, the sorted options show up the way they should. See my sandbox for the issue, and here's the sandbox code:

import "./styles.css";
import { matchSorter } from "match-sorter";
import { useState } from "react";
import Select from "react-select";

const objs = [
  { name: "hello", id: 1 },
  { name: "world", id: 2 },
  { name: "stack", id: 3 },
  { name: "other", id: 4 },
  { name: "name", id: 5 }
];

const myMapper = (obj) => {
  return {
    value: obj.id,
    label:
{obj.name}
,
    name: obj.name
  };
};

export default function App() {
  const [options, setOptions] = useState(objs.map((obj) => myMapper(obj)));
  return (
    <Select
      options={options}
      onInputChange={(val) => {
        setOptions(matchSorter(options, val, { keys: ["name", "value"] }));
      }}
    />
  );
}
```

I am sure that the array in state is not getting removed or anything, I've console logged each step of the way and the array is definitely getting properly sorted by match-sorter. It's just that as soon as you type anything, react-select stops rendering any options until you click out and back in again. Does it have something to do with using JSX as the label value? I'm doing that in my project in order to display an image along with the options.

答:
I had to do two things to make your code work:

Replaced label:
{obj.name}
 with label: obj.name in your mapper function.

I am not sure if react-select allows html nodes as labels. Their documentation just defines it as type OptionType = { [string]: any } which is way too generic for anything.

The list supplied to matchSorter for matching must be the full list (with all options). You were supplying the filtered list of previous match (from component's state).

```<code>const objs = [
  { name: "hello", id: 1 },
  { name: "world", id: 2 },
  { name: "stack", id: 3 },
  { name: "other", id: 4 },
  { name: "name", id: 5 }
];

const myMapper = (obj) => {
  return {
    value: obj.id,
    label: obj.name, // -------------------- (1)
    name: obj.name
  };
};

const allOptions = objs.map((obj) => myMapper(obj));

export default function App() {
  const [options, setOptions] = useState(allOptions);
  return (
    <Select
      options={options}
      onInputChange={(val) => {
        setOptions(
          matchSorter(
            allOptions, // ----------------> (2)
            val,
            { keys: ["name", "value"]
          }
        ));
      }}
    />
  );
}
</code>```

Body:
I am trying to use react-select in combination with match-sorter as described in this stackoverflow answer (their working version). I have an initial array of objects that get mapped to an array of objects with the value and label properties required by react-select, which is stored in state. That array is passed directly to react-select, and when you first click the search box everything looks good, all the options are there. The onInputChange prop is given a call to matchSorter, which in turn is given the array, the new input value, and the key the objects should be sorted on. In my project, and reproduced in the sandbox, as soon as you type anything into the input field, all the options disappear and are replaced by the no options message. If you click out of the box and back into it, the sorted options show up the way they should. See my sandbox for the issue, and here's the sandbox code:

import "./styles.css";
import { matchSorter } from "match-sorter";
import { useState } from "react";
import Select from "react-select";

const objs = [
  { name: "hello", id: 1 },
  { name: "world", id: 2 },
  { name: "stack", id: 3 },
  { name: "other", id: 4 },
  { name: "name", id: 5 }
];

const myMapper = (obj) => {
  return {
    value: obj.id,
    label:
{obj.name}
,
    name: obj.name
  };
};

export default function App() {
  const [options, setOptions] = useState(objs.map((obj) => myMapper(obj)));
  return (
    <Select
      options={options}
      onInputChange={(val) => {
        setOptions(matchSorter(options, val, { keys: ["name", "value"] }));
      }}
    />
  );
}

I am sure that the array in state is not getting removed or anything, I've console logged each step of the way and the array is definitely getting properly sorted by match-sorter. It's just that as soon as you type anything, react-select stops rendering any options until you click out and back in again. Does it have something to do with using JSX as the label value? I'm doing that in my project in order to display an image along with the options.

Body:
I had to do two things to make your code work:

Replaced label: <div>{obj.name}</div> with label: obj.name in your mapper function.

I am not sure if react-select allows html nodes as labels. Their documentation just defines it as type OptionType = { [string]: any } which is way too generic for anything.

The list supplied to matchSorter for matching must be the full list (with all options). You were supplying the filtered list of previous match (from component's state).

const objs = [
  { name: "hello", id: 1 },
  { name: "world", id: 2 },
  { name: "stack", id: 3 },
  { name: "other", id: 4 },
  { name: "name", id: 5 }
];

const myMapper = (obj) => {
  return {
    value: obj.id,
    label: obj.name, // -------------------- (1)
    name: obj.name
  };
};

const allOptions = objs.map((obj) => myMapper(obj));

export default function App() {
  const [options, setOptions] = useState(allOptions);
  return (
    <Select
      options={options}
      onInputChange={(val) => {
        setOptions(
          matchSorter(
            allOptions, // ----------------> (2)
            val,
            { keys: ["name", "value"]
          }
        ));
      }}
    />
  );
}


问:
Run model that need gensim older vesion
I need to run a model but it needs older version of gensim with DocvecsArray attribute.How can i run it?

AttributeError: Can't get attribute 'DocvecsArray' on <module 'gensim.models.doc2vec'...

答:
The DocvecsArray class was removed by Gensim-3.3.0, released in February 2018. So your model, or the code-installation that created it, used a version of Gensim more than 3 years old.

However, it's possible your model will still load in Gensim-3.8.3 – I'm not sure, you'd have to try it.

You can always choose to install an older version of Gensim, or any other library, instead of the latest, when setting up your environment from public package repositories.

If you've been installing Gensim using pip at your command-line in your working environment, you could try uninstalling the current Gensim & then installing a specific exact earlier version:

pip uninstall gensim

pip install gensim==3.8.3

But, some caveats:

you might need to roll-back to gensim==3.2.0

because of all the other potential libraries involved, which might also need to be rolled-back to compatible versions, it may make sense to start a fresh virtual environment, building it up with each requirement (starting with the most-important ones or the ones with the strongest version limitations)

if using some other Python distribution or environment-manager (like conda), the installation commands will change a bit

Also note, the later versions of Gensim have many bug fixes & performance improvements, so if at all possible you should try to either migrate your model forward to be used with the latest library, or re-train a fresh model for the same purposes with either the original or updated data.

Once you manage to load it into a working version, you can re-save it, and another version close should be able to re-load it. For example, if 3.8.3 manages to load your model, then you re-saved it, then current 4.x Gensim should be able to load that save.

Title: Run model that need gensim older vesion


问:
How solve Codility equiLeader challenge
After finding the "leader" I tried finding the possible equiLeaders in the given array but couldn't. Tried to find a solution of someone else but can't wrap my head around what he did.

I left a comment on the part I am lost in his code. can someone who gets it kindly walk me through that part. especially with those calculations

this is his solution

```<code>function solution(A) {
    // I understand this part as he was trying to find the leader
    if (A.length === 1) return 0
    let maxRepetition = 1;
    let maxIndex = -1
    let occurance = new Object()
    for (let i = 0; i < A.length; i++) {
        if (occurance.hasOwnProperty(A[i])) {
            occurance[A[i]][0]++
            if (occurance[A[i]][0] > maxRepetition) {
                if (occurance[A[i]][0] > A.length / 2) {
                    maxRepetition = occurance[A[i]][0]
                    maxIndex = occurance[A[i]][1]
                }
            }
        }
        else {
            occurance[A[i]] = new Array()

            occurance[A[i]][0] = 1
            occurance[A[i]][1] = i
        }
    }

    leader = A[maxIndex]

    // THis is the part I am not getting where he was trying to get the possible equiLeaders

    let equiLeader = 0
    let stack = []
    let stackIndex = -1
    for (let i = 0; i < A.length; i++) {

        if (stack.length > (Math.floor(i / 2)) && (maxRepetition - stack.length > Math.floor((A.length - i) / 2))) {
            equiLeader++
        }
        if (A[i] === leader) stack.push(i)

    }

    return equiLeader

}
</code>```

this is the full question

A non-empty array A consisting of N integers is given.

The leader of this array is the value that occurs in more than half of
the elements of A.

An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences
A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have
leaders of the same value.

For example, given array A such that:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2

we can find two equi leaders:

```<code>    0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
    2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
</code>```

The goal is to count the number of equi leaders.

Write a function:

```<code>function solution(A);
</code>```

that, given a non-empty array A consisting of N integers, returns the
number of equi leaders.

For example, given:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2

the function should return 2, as explained above.

Write an efficient algorithm for the following assumptions:

```<code>    N is an integer within the range [1..100,000];
    each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
</code>```

答:
I found a solution, it's very simple, if we can find a max occurs of any element and by the second loop just divide into two can produce the right result.

This is the code using Javascript, please have look.

```<code>function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
 let totalEleFound = {};
for(let i=0;i<A.length;i++){
    if(!totalEleFound[ A[i] ]){
        totalEleFound[ A[i] ] = 1;
    }
    else{
        totalEleFound[ A[i] ]++;
    }

}

//console.log("totalEleFound",totalEleFound);
let maxOccures = 0;
for(const [key,value] of Object.entries(totalEleFound) ){
    maxOccures = Math.max(maxOccures,Math.floor(value/2))
}

return maxOccures;
}
</code>```

Have a happy coding,
Cheers.

Title: How solve Codility equiLeader challenge

Body:
After finding the "leader" I tried finding the possible equiLeaders in the given array but couldn't. Tried to find a solution of someone else but can't wrap my head around what he did.

I left a comment on the part I am lost in his code. can someone who gets it kindly walk me through that part. especially with those calculations

this is his solution

function solution(A) {
    // I understand this part as he was trying to find the leader
    if (A.length === 1) return 0
    let maxRepetition = 1;
    let maxIndex = -1
    let occurance = new Object()
    for (let i = 0; i  maxRepetition) {
                if (occurance[A[i]][0] > A.length / 2) {
                    maxRepetition = occurance[A[i]][0]
                    maxIndex = occurance[A[i]][1]
                }
            }
        }
        else {
            occurance[A[i]] = new Array()

            occurance[A[i]][0] = 1
            occurance[A[i]][1] = i
        }
    }

    leader = A[maxIndex]

    // THis is the part I am not getting where he was trying to get the possible equiLeaders

    let equiLeader = 0
    let stack = []
    let stackIndex = -1
    for (let i = 0; i  (Math.floor(i / 2)) && (maxRepetition - stack.length > Math.floor((A.length - i) / 2))) {
            equiLeader++
        }
        if (A[i] === leader) stack.push(i)

    }

    return equiLeader

}

this is the full question

A non-empty array A consisting of N integers is given.

The leader of this array is the value that occurs in more than half of
the elements of A.

An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences
A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have
leaders of the same value.

For example, given array A such that:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2

we can find two equi leaders:

    0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
    2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.

The goal is to count the number of equi leaders.

Write a function:

function solution(A);

that, given a non-empty array A consisting of N integers, returns the
number of equi leaders.

For example, given:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2

the function should return 2, as explained above.

Write an efficient algorithm for the following assumptions:

    N is an integer within the range [1..100,000];
    each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].

Body:
I found a solution, it's very simple, if we can find a max occurs of any element and by the second loop just divide into two can produce the right result.

This is the code using Javascript, please have look.

function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
 let totalEleFound = {};
for(let i=0;i<A.length;i++){
    if(!totalEleFound[ A[i] ]){
        totalEleFound[ A[i] ] = 1;
    }
    else{
        totalEleFound[ A[i] ]++;
    }

}

//console.log("totalEleFound",totalEleFound);
let maxOccures = 0;
for(const [key,value] of Object.entries(totalEleFound) ){
    maxOccures = Math.max(maxOccures,Math.floor(value/2))
}

return maxOccures;
}

Have a happy coding,
Cheers.


问:
Trouble adding 2d array contents on an HTML table
I'm making a battleship game implementation with HTML/JavaScript. This function is supposed to add the positions of the ships on an HTML table by copying the elements from a 2d array(p1Board) with the positions of the ships.

```<code>let displayTable = () => {
        document.getElementById("player1turn").hidden = true;
        let table = document.getElementById("player1board");
        for(var i = 1; i < table.rows.length; i++){
          for(var j = 1; j < table.rows.cells; j++){
            table.rows[i].cells[j].innerHTML = p1Board[i - 1][j - 1];
          }
        }
        document.getElementById("player1table").hidden = false;
      }
document.getElementById("p1start").addEventListener("click", displayTable);
</code>```

Then, when I open the program on my browser, the table appears but without the positions of the ships:
[Battleship Board][1]
[1]: https://i.stack.imgur.com/Nv1kA.png

答:
The problem is that you are not specifying the row from which you want to get the cells. Also, once you get the cells, you need to access their .length property.

Change this line

```<code>for(var j = 1; j < table.rows.cells; j++)
</code>```

for this

```<code>for(var j = 1; j < table.rows[i].cells.length; j++)
</code>```

Body:
I'm making a battleship game implementation with HTML/JavaScript. This function is supposed to add the positions of the ships on an HTML table by copying the elements from a 2d array(p1Board) with the positions of the ships.

let displayTable = () => {
        document.getElementById("player1turn").hidden = true;
        let table = document.getElementById("player1board");
        for(var i = 1; i < table.rows.length; i++){
          for(var j = 1; j < table.rows.cells; j++){
            table.rows[i].cells[j].innerHTML = p1Board[i - 1][j - 1];
          }
        }
        document.getElementById("player1table").hidden = false;
      }
document.getElementById("p1start").addEventListener("click", displayTable);

Then, when I open the program on my browser, the table appears but without the positions of the ships:
[Battleship Board][1]
[1]: https://i.stack.imgur.com/Nv1kA.png

Body:
The problem is that you are not specifying the row from which you want to get the cells. Also, once you get the cells, you need to access their .length property.

Change this line

for(var j = 1; j < table.rows.cells; j++)

for this

for(var j = 1; j < table.rows[i].cells.length; j++)