问:
how to scrape data individually from  tags using beautifulSoup?
I'm trying to scrape data from elections.in .There are three tables with the same class . below is the HTML from the website

```<code><h3 class="blmap">17th General (Lok Sabha) Election Results 2019 – State Wise</h3>

<table class="tableizer-table">

<thead><tr class="tableizer-firstrow"><th>State</th><th>Party</th><th>Number of Seats</th></tr></thead><tbody>

 <tr><td>Andaman & Nicobar Islands</td><td>Indian National Congress</td><td>1</td></tr>

 <tr><td>Andhra Pradesh</td><td>Yuvajana Sramika Rythu Congress Party</td><td>22</td></tr>

 <tr><td>Andhra Pradesh</td><td>Telugu Desam</td><td>3</td></tr>

 <tr><td>Arunachal Pradesh</td><td>Bharatiya Janata Party</td><td>2</td></tr>

 <tr><td>Assam</td><td>Bharatiya Janata Party</td><td>9</td></tr>

 <tr><td>Assam</td><td>Indian National Congress</td><td>3</td></tr>

 <tr><td>Assam</td><td>All India United Democratic Front</td><td>1</td></tr>
</code>```

I was able to get data and that appears like this,

```<code>    StatePartyNumber of Seats
    Andaman & Nicobar IslandsIndian National Congress1
    Andhra PradeshYuvajana Sramika Rythu Congress Party22
    Andhra PradeshTelugu Desam3
    Arunachal PradeshBharatiya Janata Party2
    AssamBharatiya Janata Party9
    AssamIndian National Congress3
    AssamAll India United Democratic Front1
    AssamIndependent1
    BiharBharatiya Janata Party17
</code>```

I wanted the output like below ,

```<code>    State,Party,Number of Seats
    Andaman & Nicobar Islands, Indian National Congress,1
    Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22
</code>```

or as a list .

This line of code is giving me the above output

```<code>soup.find_all('table')[1].get_text()
</code>```

This is my code , Github

Please suggest how to achieve that

thanks.

答:
If you're trying to parse
 tags, go for pandas .read_html(). It does most of the heavy lifting for you. It'll return a list of dataframes. The table you are referencing is the 3rd table (so index position 2)

```<code>import pandas as pd

url="http://www.elections.in/"
tables = pd.read_html(url)
</code>```

Output:

```<code>print (tables[2].to_string())
                        State                                     Party  Number of Seats
0   Andaman & Nicobar Islands                  Indian National Congress                1
1              Andhra Pradesh     Yuvajana Sramika Rythu Congress Party               22
2              Andhra Pradesh                              Telugu Desam                3
3           Arunachal Pradesh                    Bharatiya Janata Party                2
4                       Assam                    Bharatiya Janata Party                9
5                       Assam                  Indian National Congress                3
6                       Assam         All India United Democratic Front                1
7                       Assam                               Independent                1
8                       Bihar                    Bharatiya Janata Party               17
9                       Bihar                       Janata Dal (United)               16
10                      Bihar                      Lok Jan Shakti Party                6
11                      Bihar                  Indian National Congress                1
12                 Chandigarh                    Bharatiya Janata Party                1
13               Chhattisgarh                    Bharatiya Janata Party                9
14               Chhattisgarh                  Indian National Congress                2
15       Dadra & Nagar Haveli                               Independent                1
16                Daman & Diu                    Bharatiya Janata Party                1
17                        Goa                    Bharatiya Janata Party                1
18                        Goa                  Indian National Congress                1
19                    Gujarat                    Bharatiya Janata Party               26
20                    Haryana                    Bharatiya Janata Party               10
21           Himachal Pradesh                    Bharatiya Janata Party                4
22            Jammu & Kashmir                    Bharatiya Janata Party                3
23            Jammu & Kashmir       Jammu & Kashmir National Conference                3
24                  Jharkhand                    Bharatiya Janata Party               11
25                  Jharkhand                                Ajsu Party                1
26                  Jharkhand                  Indian National Congress                1
27                  Jharkhand                    Jharkhand Mukti Morcha                1
28                  Karnataka                    Bharatiya Janata Party               25
29                  Karnataka                               Independent                1
30                  Karnataka                  Indian National Congress                1
31                  Karnataka                      Janata Dal (Secular)                1
32                     Kerala                  Indian National Congress               15
33                     Kerala                Indian Union Muslim League                2
34                     Kerala        Communist Party Of India (Marxist)                1
35                     Kerala                       Kerala Congress (M)                1
36                     Kerala             Revolutionary Socialist Party                1
37                Lakshadweep                Nationalist Congress Party                1
38             Madhya Pradesh                    Bharatiya Janata Party               28
39             Madhya Pradesh                  Indian National Congress                1
40                Maharashtra                    Bharatiya Janata Party               23
41                Maharashtra                                  Shivsena               18
42                Maharashtra                Nationalist Congress Party                4
43                Maharashtra    All India Majlis-E-Ittehadul Muslimeen                1
44                Maharashtra                               Independent                1
45                Maharashtra                  Indian National Congress                1
46                    Manipur                    Bharatiya Janata Party                1
47                    Manipur                        Naga Peoples Front                1
48                  Meghalaya                  Indian National Congress                1
49                  Meghalaya                   National People'S Party                1
50                    Mizoram                       Mizo National Front                1
51                   Nagaland  Nationalist Democratic Progressive Party                1
52               NCT OF Delhi                    Bharatiya Janata Party                7
53                     Odisha                           Biju Janata Dal               12
54                     Odisha                    Bharatiya Janata Party                8
55                     Odisha                  Indian National Congress                1
56                 Puducherry                  Indian National Congress                1
57                     Punjab                  Indian National Congress                8
58                     Punjab                    Bharatiya Janata Party                2
59                     Punjab                       Shiromani Akali Dal                2
60                     Punjab                           Aam Aadmi Party                1
61                  Rajasthan                    Bharatiya Janata Party               24
62                  Rajasthan                Rashtriya Loktantrik Party                1
63                     Sikkim                  Sikkim Krantikari Morcha                1
64                 Tamil Nadu                 Dravida Munnetra Kazhagam               23
65                 Tamil Nadu                  Indian National Congress                8
66                 Tamil Nadu                  Communist Party Of India                2
67                 Tamil Nadu        Communist Party Of India (Marxist)                2
68                 Tamil Nadu  All India Anna Dravida Munnetra Kazhagam                1
69                 Tamil Nadu                Indian Union Muslim League                1
70                 Tamil Nadu            Viduthalai Chiruthaigal Katchi                1
71                  Telangana                 Telangana Rashtra Samithi                9
72                  Telangana                    Bharatiya Janata Party                4
73                  Telangana                  Indian National Congress                3
74                  Telangana    All India Majlis-E-Ittehadul Muslimeen                1
75                    Tripura                    Bharatiya Janata Party                2
76              Uttar Pradesh                    Bharatiya Janata Party               62
77              Uttar Pradesh                       Bahujan Samaj Party               10
78              Uttar Pradesh                           Samajwadi Party                5
79              Uttar Pradesh                       Apna Dal (Soneylal)                2
80              Uttar Pradesh                  Indian National Congress                1
81                Uttarakhand                    Bharatiya Janata Party                5
82                West Bengal              All India Trinamool Congress               22
83                West Bengal                    Bharatiya Janata Party               18
84                West Bengal                  Indian National Congress

2
</code>```

To acheive this using BeautifulSoup, you'd have to iterate through each row (tag
), then each data cell tag of each row () and then append that into a list or dataframe, or how ever you want to store it.

So something like this:

```<code>import requests
import os
from bs4 import BeautifulSoup

url="http://www.elections.in/"

r=requests.get(url).content
htmlDoc=r.decode("utf-8")

soup = BeautifulSoup(htmlDoc, 'html.parser')

table = soup.find_all('table')[2]
rows = table.find_all('tr')

headers = table.find_all('th')
headers = [ each.text for each in headers ]

list_of_rows = []
for row in rows:
    data = row.find_all('td')
    if data != []:
        data = [ each.text for each in data ]
        list_of_rows.append(data)
</code>```

Output:

```<code>print (headers)
['State', 'Party', 'Number of Seats']

print (list_of_rows)
[['Andaman & Nicobar Islands', 'Indian National Congress', '1'], ['Andhra Pradesh', 'Yuvajana Sramika Rythu Congress Party', '22'], ['Andhra Pradesh', 'Telugu Desam', '3'], ['Arunachal Pradesh', 'Bharatiya Janata Party', '2'], ['Assam', 'Bharatiya Janata Party', '9'], ['Assam', 'Indian National Congress', '3'], ['Assam', 'All India United Democratic Front', '1'], ['Assam', 'Independent', '1'], ['Bihar', 'Bharatiya Janata Party', '17'], ['Bihar', 'Janata Dal (United)', '16'], ['Bihar', 'Lok Jan Shakti Party', '6'], ['Bihar', 'Indian National Congress', '1'], ['Chandigarh', 'Bharatiya Janata Party', '1'], ['Chhattisgarh', 'Bharatiya Janata Party', '9'], ['Chhattisgarh', 'Indian National Congress', '2'], ['Dadra & Nagar Haveli', 'Independent', '1'], ['Daman & Diu', 'Bharatiya Janata Party', '1'], ['Goa', 'Bharatiya Janata Party', '1'], ['Goa', 'Indian National Congress', '1'], ['Gujarat', 'Bharatiya Janata Party', '26'], ['Haryana', 'Bharatiya Janata Party', '10'], ['Himachal Pradesh', 'Bharatiya Janata Party', '4'], ['Jammu & Kashmir', 'Bharatiya Janata Party', '3'], ['Jammu & Kashmir', 'Jammu & Kashmir National Conference', '3'], ['Jharkhand', 'Bharatiya Janata Party', '11'], ['Jharkhand', 'Ajsu Party', '1'], ['Jharkhand', 'Indian National Congress', '1'], ['Jharkhand', 'Jharkhand Mukti Morcha', '1'], ['Karnataka', 'Bharatiya Janata Party', '25'], ['Karnataka', 'Independent', '1'], ['Karnataka', 'Indian National Congress', '1'], ['Karnataka', 'Janata Dal (Secular)', '1'], ['Kerala', 'Indian National Congress', '15'], ['Kerala', 'Indian Union Muslim League', '2'], ['Kerala', 'Communist Party Of India (Marxist)', '1'], ['Kerala', 'Kerala Congress (M)', '1'], ['Kerala', 'Revolutionary Socialist Party', '1'], ['Lakshadweep', 'Nationalist Congress Party', '1'], ['Madhya Pradesh', 'Bharatiya Janata Party', '28'], ['Madhya Pradesh', 'Indian National Congress', '1'], ['Maharashtra', 'Bharatiya Janata Party', '23'], ['Maharashtra', 'Shivsena', '18'], ['Maharashtra', 'Nationalist Congress Party', '4'], ['Maharashtra', 'All India Majlis-E-Ittehadul Muslimeen', '1'], ['Maharashtra', 'Independent', '1'], ['Maharashtra', 'Indian National Congress', '1'], ['Manipur', 'Bharatiya Janata Party', '1'], ['Manipur', 'Naga Peoples Front', '1'], ['Meghalaya', 'Indian National Congress', '1'], ['Meghalaya', "National People'S Party", '1'], ['Mizoram', 'Mizo National Front', '1'], ['Nagaland', 'Nationalist Democratic Progressive Party', '1'], ['NCT OF Delhi', 'Bharatiya Janata Party', '7'], ['Odisha', 'Biju Janata Dal', '12'], ['Odisha', 'Bharatiya Janata Party', '8'], ['Odisha', 'Indian National Congress', '1'], ['Puducherry', 'Indian National Congress', '1'], ['Punjab', 'Indian National Congress', '8'], ['Punjab', 'Bharatiya Janata Party', '2'], ['Punjab', 'Shiromani Akali Dal', '2'], ['Punjab', 'Aam Aadmi Party', '1'], ['Rajasthan', 'Bharatiya Janata Party', '24'], ['Rajasthan', 'Rashtriya Loktantrik Party', '1'], ['Sikkim', 'Sikkim Krantikari Morcha', '1'], ['Tamil Nadu', 'Dravida Munnetra Kazhagam', '23'], ['Tamil Nadu', 'Indian National Congress', '8'], ['Tamil Nadu', 'Communist Party Of India', '2'], ['Tamil Nadu', 'Communist Party Of India (Marxist)', '2'], ['Tamil Nadu', 'All India Anna Dravida Munnetra Kazhagam', '1'], ['Tamil Nadu', 'Indian Union Muslim League', '1'], ['Tamil Nadu', 'Viduthalai Chiruthaigal Katchi', '1'], ['Telangana', 'Telangana Rashtra Samithi', '9'], ['Telangana', 'Bharatiya Janata Party', '4'], ['Telangana', 'Indian National Congress', '3'], ['Telangana', 'All India Majlis-E-Ittehadul Muslimeen', '1'], ['Tripura', 'Bharatiya Janata Party', '2'], ['Uttar Pradesh', 'Bharatiya Janata Party', '62'], ['Uttar Pradesh', 'Bahujan Samaj Party', '10'], ['Uttar Pradesh', 'Samajwadi Party', '5'], ['Uttar Pradesh', 'Apna Dal (Soneylal)', '2'], ['Uttar Pradesh', 'Indian National Congress', '1'], ['Uttarakhand', 'Bharatiya Janata Party', '5'], ['West Bengal', 'All India Trinamool Congress', '22'], ['West Bengal', 'Bharatiya Janata Party', '18'], ['West Bengal', 'Indian National Congress', '2']]
</code>```

But like I said, pandas will do that for you with .read_html()

Title: how to scrape data individually from <td> tags using beautifulSoup?

Body:
I'm trying to scrape data from elections.in .There are three tables with the same class . below is the HTML from the website

17th General (Lok Sabha) Election Results 2019 – State Wise

State	Party	Number of Seats

Andaman & Nicobar Islands	Indian National Congress	1

Andhra Pradesh	Yuvajana Sramika Rythu Congress Party	22

Andhra Pradesh	Telugu Desam	3

Arunachal Pradesh	Bharatiya Janata Party	2

Assam	Bharatiya Janata Party	9

Assam	Indian National Congress	3

Assam	All India United Democratic Front	1

I was able to get data and that appears like this,

    StatePartyNumber of Seats
    Andaman & Nicobar IslandsIndian National Congress1
    Andhra PradeshYuvajana Sramika Rythu Congress Party22
    Andhra PradeshTelugu Desam3
    Arunachal PradeshBharatiya Janata Party2
    AssamBharatiya Janata Party9
    AssamIndian National Congress3
    AssamAll India United Democratic Front1
    AssamIndependent1
    BiharBharatiya Janata Party17

I wanted the output like below ,

    State,Party,Number of Seats
    Andaman & Nicobar Islands, Indian National Congress,1
    Andhra Pradesh,Yuvajana Sramika Rythu Congress Party,22

or as a list .

This line of code is giving me the above output

soup.find_all('table')[1].get_text()

This is my code , Github

Please suggest how to achieve that

thanks.

Body:
If you're trying to parse <table> tags, go for pandas .read_html(). It does most of the heavy lifting for you. It'll return a list of dataframes. The table you are referencing is the 3rd table (so index position 2)

import pandas as pd

url="http://www.elections.in/"
tables = pd.read_html(url)

Output:

print (tables[2].to_string())
                        State                                     Party  Number of Seats
0   Andaman & Nicobar Islands                  Indian National Congress                1
1              Andhra Pradesh     Yuvajana Sramika Rythu Congress Party               22
2              Andhra Pradesh                              Telugu Desam                3
3           Arunachal Pradesh                    Bharatiya Janata Party                2
4                       Assam                    Bharatiya Janata Party                9
5                       Assam                  Indian National Congress                3
6                       Assam         All India United Democratic Front                1
7                       Assam                               Independent                1
8                       Bihar                    Bharatiya Janata Party               17
9                       Bihar                       Janata Dal (United)               16
10                      Bihar                      Lok Jan Shakti Party                6
11                      Bihar                  Indian National Congress                1
12                 Chandigarh                    Bharatiya Janata Party                1
13               Chhattisgarh                    Bharatiya Janata Party                9
14               Chhattisgarh                  Indian National Congress                2
15       Dadra & Nagar Haveli                               Independent                1
16                Daman & Diu                    Bharatiya Janata Party                1
17                        Goa                    Bharatiya Janata Party                1
18                        Goa                  Indian National Congress                1
19                    Gujarat                    Bharatiya Janata Party               26
20                    Haryana                    Bharatiya Janata Party               10
21           Himachal Pradesh                    Bharatiya Janata Party                4
22            Jammu & Kashmir                    Bharatiya Janata Party                3
23            Jammu & Kashmir       Jammu & Kashmir National Conference                3
24                  Jharkhand                    Bharatiya Janata Party               11
25                  Jharkhand                                Ajsu Party                1
26                  Jharkhand                  Indian National Congress                1
27                  Jharkhand                    Jharkhand Mukti Morcha                1
28                  Karnataka                    Bharatiya Janata Party               25
29                  Karnataka                               Independent                1
30                  Karnataka                  Indian National Congress                1
31                  Karnataka                      Janata Dal (Secular)                1
32                     Kerala                  Indian National Congress               15
33                     Kerala                Indian Union Muslim League                2
34                     Kerala        Communist Party Of India (Marxist)                1
35                     Kerala                       Kerala Congress (M)                1
36                     Kerala             Revolutionary Socialist Party                1
37                Lakshadweep                Nationalist Congress Party                1
38             Madhya Pradesh                    Bharatiya Janata Party               28
39             Madhya Pradesh                  Indian National Congress                1
40                Maharashtra                    Bharatiya Janata Party               23
41                Maharashtra                                  Shivsena               18
42                Maharashtra                Nationalist Congress Party                4
43                Maharashtra    All India Majlis-E-Ittehadul Muslimeen                1
44                Maharashtra                               Independent                1
45                Maharashtra                  Indian National Congress                1
46                    Manipur                    Bharatiya Janata Party                1
47                    Manipur                        Naga Peoples Front                1
48                  Meghalaya                  Indian National Congress                1
49                  Meghalaya                   National People'S Party                1
50                    Mizoram                       Mizo National Front                1
51                   Nagaland  Nationalist Democratic Progressive Party                1
52               NCT OF Delhi                    Bharatiya Janata Party                7
53                     Odisha                           Biju Janata Dal               12
54                     Odisha                    Bharatiya Janata Party                8
55                     Odisha                  Indian National Congress                1
56                 Puducherry                  Indian National Congress                1
57                     Punjab                  Indian National Congress                8
58                     Punjab                    Bharatiya Janata Party                2
59                     Punjab                       Shiromani Akali Dal                2
60                     Punjab                           Aam Aadmi Party                1
61                  Rajasthan                    Bharatiya Janata Party               24
62                  Rajasthan                Rashtriya Loktantrik Party                1
63                     Sikkim                  Sikkim Krantikari Morcha                1
64                 Tamil Nadu                 Dravida Munnetra Kazhagam               23
65                 Tamil Nadu                  Indian National Congress                8
66                 Tamil Nadu                  Communist Party Of India                2
67                 Tamil Nadu        Communist Party Of India (Marxist)                2
68                 Tamil Nadu  All India Anna Dravida Munnetra Kazhagam                1
69                 Tamil Nadu                Indian Union Muslim League                1
70                 Tamil Nadu            Viduthalai Chiruthaigal Katchi                1
71                  Telangana                 Telangana Rashtra Samithi                9
72                  Telangana                    Bharatiya Janata Party                4
73                  Telangana                  Indian National Congress                3
74                  Telangana    All India Majlis-E-Ittehadul Muslimeen                1
75                    Tripura                    Bharatiya Janata Party                2
76              Uttar Pradesh                    Bharatiya Janata Party               62
77              Uttar Pradesh                       Bahujan Samaj Party               10
78              Uttar Pradesh                           Samajwadi Party                5
79              Uttar Pradesh                       Apna Dal (Soneylal)                2
80              Uttar Pradesh                  Indian National Congress                1
81                Uttarakhand                    Bharatiya Janata Party                5
82                West Bengal              All India Trinamool Congress               22
83                West Bengal                    Bharatiya Janata Party               18
84                West Bengal                  Indian National Congress

2

To acheive this using BeautifulSoup, you'd have to iterate through each row (tag <tr>), then each data cell tag of each row (<td>) and then append that into a list or dataframe, or how ever you want to store it.

So something like this:

import requests
import os
from bs4 import BeautifulSoup

url="http://www.elections.in/"

r=requests.get(url).content
htmlDoc=r.decode("utf-8")

soup = BeautifulSoup(htmlDoc, 'html.parser')

table = soup.find_all('table')[2]
rows = table.find_all('tr')

headers = table.find_all('th')
headers = [ each.text for each in headers ]

list_of_rows = []
for row in rows:
    data = row.find_all('td')
    if data != []:
        data = [ each.text for each in data ]
        list_of_rows.append(data)

Output:

print (headers)
['State', 'Party', 'Number of Seats']

print (list_of_rows)
[['Andaman & Nicobar Islands', 'Indian National Congress', '1'], ['Andhra Pradesh', 'Yuvajana Sramika Rythu Congress Party', '22'], ['Andhra Pradesh', 'Telugu Desam', '3'], ['Arunachal Pradesh', 'Bharatiya Janata Party', '2'], ['Assam', 'Bharatiya Janata Party', '9'], ['Assam', 'Indian National Congress', '3'], ['Assam', 'All India United Democratic Front', '1'], ['Assam', 'Independent', '1'], ['Bihar', 'Bharatiya Janata Party', '17'], ['Bihar', 'Janata Dal (United)', '16'], ['Bihar', 'Lok Jan Shakti Party', '6'], ['Bihar', 'Indian National Congress', '1'], ['Chandigarh', 'Bharatiya Janata Party', '1'], ['Chhattisgarh', 'Bharatiya Janata Party', '9'], ['Chhattisgarh', 'Indian National Congress', '2'], ['Dadra & Nagar Haveli', 'Independent', '1'], ['Daman & Diu', 'Bharatiya Janata Party', '1'], ['Goa', 'Bharatiya Janata Party', '1'], ['Goa', 'Indian National Congress', '1'], ['Gujarat', 'Bharatiya Janata Party', '26'], ['Haryana', 'Bharatiya Janata Party', '10'], ['Himachal Pradesh', 'Bharatiya Janata Party', '4'], ['Jammu & Kashmir', 'Bharatiya Janata Party', '3'], ['Jammu & Kashmir', 'Jammu & Kashmir National Conference', '3'], ['Jharkhand', 'Bharatiya Janata Party', '11'], ['Jharkhand', 'Ajsu Party', '1'], ['Jharkhand', 'Indian National Congress', '1'], ['Jharkhand', 'Jharkhand Mukti Morcha', '1'], ['Karnataka', 'Bharatiya Janata Party', '25'], ['Karnataka', 'Independent', '1'], ['Karnataka', 'Indian National Congress', '1'], ['Karnataka', 'Janata Dal (Secular)', '1'], ['Kerala', 'Indian National Congress', '15'], ['Kerala', 'Indian Union Muslim League', '2'], ['Kerala', 'Communist Party Of India (Marxist)', '1'], ['Kerala', 'Kerala Congress (M)', '1'], ['Kerala', 'Revolutionary Socialist Party', '1'], ['Lakshadweep', 'Nationalist Congress Party', '1'], ['Madhya Pradesh', 'Bharatiya Janata Party', '28'], ['Madhya Pradesh', 'Indian National Congress', '1'], ['Maharashtra', 'Bharatiya Janata Party', '23'], ['Maharashtra', 'Shivsena', '18'], ['Maharashtra', 'Nationalist Congress Party', '4'], ['Maharashtra', 'All India Majlis-E-Ittehadul Muslimeen', '1'], ['Maharashtra', 'Independent', '1'], ['Maharashtra', 'Indian National Congress', '1'], ['Manipur', 'Bharatiya Janata Party', '1'], ['Manipur', 'Naga Peoples Front', '1'], ['Meghalaya', 'Indian National Congress', '1'], ['Meghalaya', "National People'S Party", '1'], ['Mizoram', 'Mizo National Front', '1'], ['Nagaland', 'Nationalist Democratic Progressive Party', '1'], ['NCT OF Delhi', 'Bharatiya Janata Party', '7'], ['Odisha', 'Biju Janata Dal', '12'], ['Odisha', 'Bharatiya Janata Party', '8'], ['Odisha', 'Indian National Congress', '1'], ['Puducherry', 'Indian National Congress', '1'], ['Punjab', 'Indian National Congress', '8'], ['Punjab', 'Bharatiya Janata Party', '2'], ['Punjab', 'Shiromani Akali Dal', '2'], ['Punjab', 'Aam Aadmi Party', '1'], ['Rajasthan', 'Bharatiya Janata Party', '24'], ['Rajasthan', 'Rashtriya Loktantrik Party', '1'], ['Sikkim', 'Sikkim Krantikari Morcha', '1'], ['Tamil Nadu', 'Dravida Munnetra Kazhagam', '23'], ['Tamil Nadu', 'Indian National Congress', '8'], ['Tamil Nadu', 'Communist Party Of India', '2'], ['Tamil Nadu', 'Communist Party Of India (Marxist)', '2'], ['Tamil Nadu', 'All India Anna Dravida Munnetra Kazhagam', '1'], ['Tamil Nadu', 'Indian Union Muslim League', '1'], ['Tamil Nadu', 'Viduthalai Chiruthaigal Katchi', '1'], ['Telangana', 'Telangana Rashtra Samithi', '9'], ['Telangana', 'Bharatiya Janata Party', '4'], ['Telangana', 'Indian National Congress', '3'], ['Telangana', 'All India Majlis-E-Ittehadul Muslimeen', '1'], ['Tripura', 'Bharatiya Janata Party', '2'], ['Uttar Pradesh', 'Bharatiya Janata Party', '62'], ['Uttar Pradesh', 'Bahujan Samaj Party', '10'], ['Uttar Pradesh', 'Samajwadi Party', '5'], ['Uttar Pradesh', 'Apna Dal (Soneylal)', '2'], ['Uttar Pradesh', 'Indian National Congress', '1'], ['Uttarakhand', 'Bharatiya Janata Party', '5'], ['West Bengal', 'All India Trinamool Congress', '22'], ['West Bengal', 'Bharatiya Janata Party', '18'], ['West Bengal', 'Indian National Congress', '2']]

But like I said, pandas will do that for you with .read_html()


来源: stackexchange

问:
Problem with textbox inside updatepanel - not causing OnTextChanged event
I have the following situation: I have a textbox inside an ajax updatepanel. Wherever the user types in the textbox I must display a message (different message that depends on the user typed data).

```<code>     <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
        <ContentTemplate>
            <asp:TextBox ID="txtMyTexbox" runat="server" Width="500px" OnTextChanged="txtMyTexbox_TextChanged" AutoPostBack="true"></asp:TextBox>
            <br />
            <asp:Label ID="lblMessage" runat="server" CssClass="errorMessage" Visible="false">Hello World</asp:Label>
         </ContentTemplate>
            <Triggers>
             <asp:AsyncPostBackTrigger ControlID="txtMyTexbox" />
            </Triggers>
      </asp:UpdatePanel>
</code>```

In server side I have written the following at page load

```<code>ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtMyTexbox);
</code>```

and the method like this

```<code>protected void txtMyTexbox_TextChanged(object sender, EventArgs e)
    {
            if (.....)
            {
                lblMessage.Visible = false;
            }
            else
            {
                lblMessage.Visible = true;
            }
    }
</code>```

My problem now is that: when the user types in the textbox it doesn't cause OnTextChanged event.

Am I missing something?

答:
The Control which id is used in AsyncPostBackTrigger must be outside the update Panel(that cause to fire the Async call) like this:</p>

```<code><tr>
    <td colspan="4"><asp:Label ID="lblEnter_Successfully"  Text="Enter Record SuccessFully" runat="server" Visible ="false" ForeColor ="Blue" Font-Size ="Larger" Font-Bold ="true"></asp:Label>
    </td>
</tr>
</table>
</ContentTemplate>

  <Triggers>
     <asp:AsyncPostBackTrigger ControlID = "Button_Save" EventName ="Click"/>
  </Triggers>

</asp:UpdatePanel>
            <table>
              <tr>
                <td width = "472px" align ="right">
                    <asp:Button ID="Button_Save" runat="server" Text="Save"  OnClientClick ="return URLValidation();"/>
                    <asp:Button ID="Button_Clear" runat="server" Text="Clear"/>
                </td>
              </tr>
            </table>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following situation: I have a textbox inside an ajax updatepanel. Wherever the user types in the textbox I must display a message (different message that depends on the user typed data).

     <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
        <ContentTemplate>
            <asp:TextBox ID="txtMyTexbox" runat="server" Width="500px" OnTextChanged="txtMyTexbox_TextChanged" AutoPostBack="true"></asp:TextBox>

            <asp:Label ID="lblMessage" runat="server" CssClass="errorMessage" Visible="false">Hello World</asp:Label>
         </ContentTemplate>
            <Triggers>
             <asp:AsyncPostBackTrigger ControlID="txtMyTexbox" />
            </Triggers>
      </asp:UpdatePanel>

In server side I have written the following at page load

ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtMyTexbox);

and the method like this

protected void txtMyTexbox_TextChanged(object sender, EventArgs e)
    {
            if (.....)
            {
                lblMessage.Visible = false;
            }
            else
            {
                lblMessage.Visible = true;
            }
    }

My problem now is that: when the user types in the textbox it doesn't cause OnTextChanged event.

Am I missing something?

Body:
The Control which id is used in AsyncPostBackTrigger must be outside the update Panel(that cause to fire the Async call) like this:

<tr>
    <td colspan="4"><asp:Label ID="lblEnter_Successfully"  Text="Enter Record SuccessFully" runat="server" Visible ="false" ForeColor ="Blue" Font-Size ="Larger" Font-Bold ="true"></asp:Label>
    </td>
</tr>
</table>
</ContentTemplate>

  <Triggers>
     <asp:AsyncPostBackTrigger ControlID = "Button_Save" EventName ="Click"/>
  </Triggers>

</asp:UpdatePanel>
            <table>
              <tr>
                <td width = "472px" align ="right">
                    <asp:Button ID="Button_Save" runat="server" Text="Save"  OnClientClick ="return URLValidation();"/>
                    <asp:Button ID="Button_Clear" runat="server" Text="Clear"/>
                </td>
              </tr>
            </table>

ContentLicense: CC BY-SA 3.0


问:
Change cube rotation speed through input (threejs)
I am using the Threejs tutorial to make a javascript cube. This worked.
Now I want a number input on my page to change the speed at which the cube rotates (X and Y axis) but I can't figure out how. Anyone able to help me with this?

I have tried using number and text inputs but I'm sure it has to do with my javascript (I'm not that great)

HTML

```<code><ul>
        <li>Color cube: <input type="text" id="colorCube" placeholder=""></li><br>
        <li>Rotation X: <input type="number" id="rotationCubeX" placeholder=""></li><br>
        <li>Rotation Y: <input type="number" id="rotationCubeY" placeholder=""></li><br>
        <li>Change: <input id="submitColor" value="Submit" type="button"></li>
</ul>
</code>```

This is where I want to change the rotation in (the color works)

JS

```<code>var cube = (function(){
  my = {};

  var cube;
  var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);

  // Function to change color
  my.color = function(value){
    cube.material.color.set(value);
  }

  // Generate Cube

  my.generate = function(colorCube, rotationCubeX, rotationCubeY) {
    var scene = new THREE.Scene();
    var width = 1280;
    var height = 505;
    var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
    var renderer = new THREE.WebGLRenderer();

    renderer.setSize(width, height);
    renderer.shadowMapEnabled = true; //Shadow
    renderer.shadowMapSoft = true; // Shadow
    renderer.shadowMapType = THREE.PCFShadowMap; //Shadow

    document.getElementById('projects').appendChild( renderer.domElement );

    // Define Shape Object
    geometry = new THREE.BoxGeometry(1, 1, 1);
    material = new THREE.MeshPhongMaterial({ // Required For Shadows
      color: colorCube,
      specular: 0x000000,
      shininess: 100
    });

    //Cube
    cube = new THREE.Mesh(geometry, material);
    cube.position.y = 0.8;
    cube.castShadow = true;
    cube.receiveShadow = true;
    scene.add(cube);
    camera.position.z = 3;
    camera.position.y = 1.8;
    camera.position.x = 0;

    // Floor
    var floorGeometry = new THREE.PlaneGeometry(100, 100, 20, 20);
    var floorMaterial = new THREE.MeshPhongMaterial({
      color: 0xecebec,
      specular: 0x000000,
      shininess: 0
    });

    var floor = new THREE.Mesh(floorGeometry, floorMaterial);
    floor.rotation.x = -0.5 * Math.PI;
    floor.receiveShadow = true;
    scene.add(floor);

    // Lights
    // Ambient light for general illumination
    var ambientLight = new THREE.AmbientLight(0x090909);
    scene.add(ambientLight);

    // Spotlight for specific illumination
    var spotLight = new THREE.SpotLight(0xAAAAAA);
    spotLight.position.set(2, 3, 3);
    spotLight.castShadow = true;
    spotLight.shadowBias = 0.0001;
    spotLight.shadowDarkness = 0.2;
    spotLight.shadowMapWidth = 2048; // Shadow Quality
    spotLight.shadowMapHeight = 2048; // Shadow Quality
    scene.add(spotLight);

    // Render Loop
    function render() {
      requestAnimationFrame(render);
      cube.rotation.x += xSpeed; // spin cube
      cube.rotation.y += ySpeed; //spin cube
      renderer.render(scene, camera);
    }
    //window.addEventListener('click', onDocumentMouseDown, false);
    render();
  }

//function onDocumentMouseDown(event) {

  // Welcome to the exciting world of raycasting !
  // First let's get some mouse coordinates:
  //mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  //mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  // This is basically converting 2d coordinates to 3d Space:
  //raycaster.setFromCamera(mouse, camera);
  // And checking if it intersects with an array object
  //var intersects = raycaster.intersectObjects([cube]);

  // And finally change the color:
  // if (intersects.length > 0) {
  //   intersects[0].object.material.color.setHex(Math.random() * 0xffffff);
  // }
//}

return my;
}());

</code>```

This is where the starting rotation is added to the cube (if I were to change the 0.001 to rotationCubeX the cube doesnt spawn)

Main.JS

```<code>document.addEventListener("DOMContentLoaded", function () {
  cube.generate('blue', 0.001, 0.005);

  document.getElementById("submitColor").onclick = function() {
    cube.color(document.getElementById('colorCube').value);
    // cube.color(document.getElementById('rotationCube').value);
    xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
    ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
  };

});

</code>```

This is my main.js where I call the functions

I made this with great help of the provided Threejs code but I am stuck now.

答:
At the moment your cube spins using the hardcoded values 0.001 and 0.005 inside the render() function.
To be able to change those values you need two global variables instead.

First determine the initial speed directly using the input element's value property:

```<code><ul>
  <li>Color cube: <input type="text" id="colorCube" placeholder=""></li><br>
  <li>Rotation X: <input type="number" id="rotationCubeX" placeholder="" value="0.001"></li><br>
  <li>Rotation Y: <input type="number" id="rotationCubeY" placeholder="" value="0.005"></li><br>
  <li>Change: <input id="submitColor" value="Submit" type="button"></li>
</ul>
</code>```

Create two global variables and get the values from the input element:

```<code>var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
</code>```

parseFloat() is used because the value returned from the property is a string.

Update the variables as soon as the submit button is clicked:

```<code>document.getElementById("submitColor").onclick = function() {
  cube.color(document.getElementById('colorCube').value);
  cube.color(document.getElementById('rotationCube').value);
  xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
};
</code>```

Finally use the value of the global variabels inside the render function:

```<code>function render() {
  requestAnimationFrame(render);
  cube.rotation.x += xSpeed; // spin cube
  cube.rotation.y += ySpeed; //spin cube
  renderer.render(scene, camera);
}
</code>```

Here's a live example. Please make sure to click Submit after chaning values using the up/down arrows.

var camera, scene, renderer;
var cube;
var width = 400;
var height = 300;
var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);

function init() {
  camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
  camera.position.z = 400;
  scene = new THREE.Scene();

  var geometry = new THREE.BoxBufferGeometry(200, 200, 200);

  cube = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
  scene.add(cube);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);
  document.body.appendChild(renderer.domElement);
}

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += xSpeed;
  cube.rotation.y += ySpeed;

  renderer.render(scene, camera);
}

init();
animate();

document.getElementById("submitColor").onclick = function() {
  xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://threejs.org/build/three.js"></script>
<ul>
  <li>Color cube: <input type="text" id="colorCube" placeholder=""></li><br>
  <li>Rotation X: <input type="number" id="rotationCubeX" placeholder="" value="0.001" step="0.01"></li><br>
  <li>Rotation Y: <input type="number" id="rotationCubeY" placeholder="" value="0.005" step="0.01"></li><br>
  <li>Change: <input id="submitColor" value="Submit" type="button"></li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the Threejs tutorial to make a javascript cube. This worked.
Now I want a number input on my page to change the speed at which the cube rotates (X and Y axis) but I can't figure out how. Anyone able to help me with this?

I have tried using number and text inputs but I'm sure it has to do with my javascript (I'm not that great)

HTML

Color cube: <input type="text" id="colorCube" placeholder="">

Rotation X: <input type="number" id="rotationCubeX" placeholder="">

Rotation Y: <input type="number" id="rotationCubeY" placeholder="">

Change: <input id="submitColor" value="Submit" type="button">

This is where I want to change the rotation in (the color works)

JS

var cube = (function(){
  my = {};

  var cube;
  var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);

  // Function to change color
  my.color = function(value){
    cube.material.color.set(value);
  }

  // Generate Cube

  my.generate = function(colorCube, rotationCubeX, rotationCubeY) {
    var scene = new THREE.Scene();
    var width = 1280;
    var height = 505;
    var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
    var renderer = new THREE.WebGLRenderer();

    renderer.setSize(width, height);
    renderer.shadowMapEnabled = true; //Shadow
    renderer.shadowMapSoft = true; // Shadow
    renderer.shadowMapType = THREE.PCFShadowMap; //Shadow

    document.getElementById('projects').appendChild( renderer.domElement );

    // Define Shape Object
    geometry = new THREE.BoxGeometry(1, 1, 1);
    material = new THREE.MeshPhongMaterial({ // Required For Shadows
      color: colorCube,
      specular: 0x000000,
      shininess: 100
    });

    //Cube
    cube = new THREE.Mesh(geometry, material);
    cube.position.y = 0.8;
    cube.castShadow = true;
    cube.receiveShadow = true;
    scene.add(cube);
    camera.position.z = 3;
    camera.position.y = 1.8;
    camera.position.x = 0;

    // Floor
    var floorGeometry = new THREE.PlaneGeometry(100, 100, 20, 20);
    var floorMaterial = new THREE.MeshPhongMaterial({
      color: 0xecebec,
      specular: 0x000000,
      shininess: 0
    });

    var floor = new THREE.Mesh(floorGeometry, floorMaterial);
    floor.rotation.x = -0.5 * Math.PI;
    floor.receiveShadow = true;
    scene.add(floor);

    // Lights
    // Ambient light for general illumination
    var ambientLight = new THREE.AmbientLight(0x090909);
    scene.add(ambientLight);

    // Spotlight for specific illumination
    var spotLight = new THREE.SpotLight(0xAAAAAA);
    spotLight.position.set(2, 3, 3);
    spotLight.castShadow = true;
    spotLight.shadowBias = 0.0001;
    spotLight.shadowDarkness = 0.2;
    spotLight.shadowMapWidth = 2048; // Shadow Quality
    spotLight.shadowMapHeight = 2048; // Shadow Quality
    scene.add(spotLight);

    // Render Loop
    function render() {
      requestAnimationFrame(render);
      cube.rotation.x += xSpeed; // spin cube
      cube.rotation.y += ySpeed; //spin cube
      renderer.render(scene, camera);
    }
    //window.addEventListener('click', onDocumentMouseDown, false);
    render();
  }

//function onDocumentMouseDown(event) {

  // Welcome to the exciting world of raycasting !
  // First let's get some mouse coordinates:
  //mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  //mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  // This is basically converting 2d coordinates to 3d Space:
  //raycaster.setFromCamera(mouse, camera);
  // And checking if it intersects with an array object
  //var intersects = raycaster.intersectObjects([cube]);

  // And finally change the color:
  // if (intersects.length > 0) {
  //   intersects[0].object.material.color.setHex(Math.random() * 0xffffff);
  // }
//}

return my;
}());

This is where the starting rotation is added to the cube (if I were to change the 0.001 to rotationCubeX the cube doesnt spawn)

Main.JS

document.addEventListener("DOMContentLoaded", function () {
  cube.generate('blue', 0.001, 0.005);

  document.getElementById("submitColor").onclick = function() {
    cube.color(document.getElementById('colorCube').value);
    // cube.color(document.getElementById('rotationCube').value);
    xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
    ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
  };

});

This is my main.js where I call the functions

I made this with great help of the provided Threejs code but I am stuck now.

Body:
At the moment your cube spins using the hardcoded values 0.001 and 0.005 inside the render() function.
To be able to change those values you need two global variables instead.

First determine the initial speed directly using the input element's value property:

<ul>
  <li>Color cube: <input type="text" id="colorCube" placeholder=""></li><br>
  <li>Rotation X: <input type="number" id="rotationCubeX" placeholder="" value="0.001"></li><br>
  <li>Rotation Y: <input type="number" id="rotationCubeY" placeholder="" value="0.005"></li><br>
  <li>Change: <input id="submitColor" value="Submit" type="button"></li>
</ul>

Create two global variables and get the values from the input element:

var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);

parseFloat() is used because the value returned from the property is a string.

Update the variables as soon as the submit button is clicked:

document.getElementById("submitColor").onclick = function() {
  cube.color(document.getElementById('colorCube').value);
  cube.color(document.getElementById('rotationCube').value);
  xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
};

Finally use the value of the global variabels inside the render function:

function render() {
  requestAnimationFrame(render);
  cube.rotation.x += xSpeed; // spin cube
  cube.rotation.y += ySpeed; //spin cube
  renderer.render(scene, camera);
}

Here's a live example. Please make sure to click Submit after chaning values using the up/down arrows.

var camera, scene, renderer;
var cube;
var width = 400;
var height = 300;
var xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
var ySpeed = parseFloat(document.getElementById('rotationCubeY').value);

function init() {
  camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
  camera.position.z = 400;
  scene = new THREE.Scene();

  var geometry = new THREE.BoxBufferGeometry(200, 200, 200);

  cube = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
  scene.add(cube);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);
  document.body.appendChild(renderer.domElement);
}

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += xSpeed;
  cube.rotation.y += ySpeed;

  renderer.render(scene, camera);
}

init();
animate();

document.getElementById("submitColor").onclick = function() {
  xSpeed = parseFloat(document.getElementById('rotationCubeX').value);
  ySpeed = parseFloat(document.getElementById('rotationCubeY').value);
};

<script src="https://threejs.org/build/three.js"></script>
<ul>
  <li>Color cube: <input type="text" id="colorCube" placeholder=""></li><br>
  <li>Rotation X: <input type="number" id="rotationCubeX" placeholder="" value="0.001" step="0.01"></li><br>
  <li>Rotation Y: <input type="number" id="rotationCubeY" placeholder="" value="0.005" step="0.01"></li><br>
  <li>Change: <input id="submitColor" value="Submit" type="button"></li>
</ul>


问:
Attempted to dequeue multiple cells for the same index path, which is not allowed Swift
In my app I have aTabBarnavigation system. When app loads the view controller for the first tab the calendarTableView in it loads normally, but if I switch to another tab and then return to the first I get the NSInternalInconsistencyException Attempted to dequeue multiple cells for the same index path error. Declaring the cell as : let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell gives me the error. For now, I solved it as advised in other posts by not specifying an indexPath in the cell declaration in cellForRowAt method and declaring it as : let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell but does that mean that I'm managing the data source wrongly or what's the cause of having that error? Shouldn't be indexPath always be specified? I did a test as I didn't have the problem until now and I changed the system date to an earlier date say the 10th of the month, and I don't get the error. So does it mean that tableview is trying to dequeue too many cells? Can you see what's happening? I would really appreciate some explanation of this.
As always thank you very much for your time.
Here is the code I'm using:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell
//        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell
        cell.configureUi()
        let date = datesArray[indexPath.row]
        cell.cellDate = String( describing: date)
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let dayInWeek = dateFormatter.string(from: date)
//        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + "\(dayNamesArray[components.weekday! - 1])"
        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + dayInWeek
        cell.cellWeekday = components.weekday!
        //        print("cell weekday is: \(cell.cellWeekday!)") // prints correct weekday
        cell.cellId = "\(String(format:"%04d", components.year!))" + "\(String(format:"%02d", components.month!))" + "\(String(format:"%02d", components.day!))"
        self.selectedDate = cell.cellId // used for time slots cellId
        //        print("##################### selectedDate in tableview is :\(self.selectedDate) ")
        // highlighting current day cell
        if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.calendarCellToday?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                }
            }
            //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
            self.selectedDate = cell.cellId
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.configureUi()
            // highlighting current day cell
            if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
                cell.layer.borderWidth = 4
                if Theme.selectedTheme == 1 {
                    if #available(iOS 11.0, *) {
                        cell.layer.borderColor = Theme.calendarCellToday?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
                    }
                } else if Theme.selectedTheme == 2 {
                    if #available(iOS 11.0, *) {
                        cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                    }
                }
                //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")

                self.selectedDate = cell.cellId
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.firstTintColor?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.firstTintColorRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {

                    cell.layer.borderColor = Theme.firstTintColor2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.firstTintColorRgb2.cgColor
                }
            }
            self.updateTimeSlots(selectedCell: cell)
        }
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let cell: CalendarTableViewCell = tableView(self.calendarTableview, cellForRowAt: IndexPath.init(row: self.actualDay - 1, section: 0)) as! CalendarTableViewCell
        self.updateTimeSlots(selectedCell: cell)

    }
</code>```

答:
Most likely the actual reason is in scrollViewDidEndScrollingAnimation.

Never ever call the datasource method tableView(_:cellForRowAt:) (unlike cellForRow(at:) yourself. It's exclusively called by the framework.

And you are strongly discouraged from manipulating the cells outside of cellForRow. Modify the model and reload the row.

Body:
In my app I have aTabBarnavigation system. When app loads the view controller for the first tab the calendarTableView in it loads normally, but if I switch to another tab and then return to the first I get the NSInternalInconsistencyException Attempted to dequeue multiple cells for the same index path error. Declaring the cell as : let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell gives me the error. For now, I solved it as advised in other posts by not specifying an indexPath in the cell declaration in cellForRowAt method and declaring it as : let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell but does that mean that I'm managing the data source wrongly or what's the cause of having that error? Shouldn't be indexPath always be specified? I did a test as I didn't have the problem until now and I changed the system date to an earlier date say the 10th of the month, and I don't get the error. So does it mean that tableview is trying to dequeue too many cells? Can you see what's happening? I would really appreciate some explanation of this.
As always thank you very much for your time.
Here is the code I'm using:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell
//        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell
        cell.configureUi()
        let date = datesArray[indexPath.row]
        cell.cellDate = String( describing: date)
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let dayInWeek = dateFormatter.string(from: date)
//        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + "\(dayNamesArray[components.weekday! - 1])"
        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + dayInWeek
        cell.cellWeekday = components.weekday!
        //        print("cell weekday is: \(cell.cellWeekday!)") // prints correct weekday
        cell.cellId = "\(String(format:"%04d", components.year!))" + "\(String(format:"%02d", components.month!))" + "\(String(format:"%02d", components.day!))"
        self.selectedDate = cell.cellId // used for time slots cellId
        //        print("##################### selectedDate in tableview is :\(self.selectedDate) ")
        // highlighting current day cell
        if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.calendarCellToday?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                }
            }
            //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
            self.selectedDate = cell.cellId
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.configureUi()
            // highlighting current day cell
            if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
                cell.layer.borderWidth = 4
                if Theme.selectedTheme == 1 {
                    if #available(iOS 11.0, *) {
                        cell.layer.borderColor = Theme.calendarCellToday?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
                    }
                } else if Theme.selectedTheme == 2 {
                    if #available(iOS 11.0, *) {
                        cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                    }
                }
                //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")

                self.selectedDate = cell.cellId
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.firstTintColor?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.firstTintColorRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {

                    cell.layer.borderColor = Theme.firstTintColor2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.firstTintColorRgb2.cgColor
                }
            }
            self.updateTimeSlots(selectedCell: cell)
        }
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let cell: CalendarTableViewCell = tableView(self.calendarTableview, cellForRowAt: IndexPath.init(row: self.actualDay - 1, section: 0)) as! CalendarTableViewCell
        self.updateTimeSlots(selectedCell: cell)

    }


问:
How to write from loop to dataframe
I'am trying to calculate 33 stock betas and write them to dataframe.

Unfortunately, I have an error in my code:
cannot concatenate object of type ""; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are vali

```<code>import pandas as pd
import numpy as np
stock1=pd.read_excel(r"C:\Users\Кир\Desktop\Uni\Master\Nasdaq\Financials 11.05\Nasdaq last\clean data\01.xlsx", '1') #read second sheet of excel file
stock2=pd.read_excel(r"C:\Users\Кир\Desktop\Uni\Master\Nasdaq\Financials 11.05\Nasdaq last\clean data\01.xlsx", '2') #read second sheet of excel file
stock2['stockreturn']=np.log(stock2.AdjCloseStock / stock2.AdjCloseStock.shift(1)) #stock ln return
stock2['SP500return']=np.log(stock2.AdjCloseSP500 / stock2.AdjCloseSP500.shift(1)) #SP500 ln return
stock2 = stock2.iloc[1:] #delete first row in dataframe
betas = pd.DataFrame()
for i in range(0,(len(stock2.AdjCloseStock)//52)-1):
    betas = betas.append(stock2.stockreturn.iloc[i*52:(i+1)*52].cov(stock2.SP500return.iloc[i*52:(i+1)*52])/stock2.SP500return.iloc[i*52:(i+1)*52].cov(stock2.SP500return.iloc[i*52:(i+1)*52]))
</code>```

My data looks like weekly stock and S&P index return for 33 years. So the output should have 33 betas.

答:
I tried simplifying your code and creating an example. I think the problem is that your calculation returns a float. You want to make it a pd.Series. DataFrame.append takes:

DataFrame or Series/dict-like object, or list of these

```<code>np.random.seed(20)
df = pd.DataFrame(np.random.randn(33*53, 2),
                  columns=['a', 'b'])
betas = pd.DataFrame()
for year in range(len(df['a'])//52 -1):
    # Take some data
    in_slice = pd.IndexSlice[year*52:(year+1)*52]
    numerator = df['a'].iloc[in_slice].cov(df['b'].iloc[in_slice])
    denominator = df['b'].iloc[in_slice].cov(df['b'].iloc[in_slice])
    # Do some calculations and create a pd.Series from the result
    data = pd.Series(numerator / denominator, name = year)
    # Append to the DataFrame
    betas = betas.append(data)

betas.index.name = 'years'
betas.columns = ['beta']
</code>```

betas.head():

```<code>           beta
years
0      0.107669
1     -0.009302
2     -0.063200
3      0.025681
4     -0.000813
</code>```

Title: How to write from loop to dataframe

Body:
I'am trying to calculate 33 stock betas and write them to dataframe.

Unfortunately, I have an error in my code:
cannot concatenate object of type ""; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are vali

import pandas as pd
import numpy as np
stock1=pd.read_excel(r"C:\Users\Кир\Desktop\Uni\Master\Nasdaq\Financials 11.05\Nasdaq last\clean data\01.xlsx", '1') #read second sheet of excel file
stock2=pd.read_excel(r"C:\Users\Кир\Desktop\Uni\Master\Nasdaq\Financials 11.05\Nasdaq last\clean data\01.xlsx", '2') #read second sheet of excel file
stock2['stockreturn']=np.log(stock2.AdjCloseStock / stock2.AdjCloseStock.shift(1)) #stock ln return
stock2['SP500return']=np.log(stock2.AdjCloseSP500 / stock2.AdjCloseSP500.shift(1)) #SP500 ln return
stock2 = stock2.iloc[1:] #delete first row in dataframe
betas = pd.DataFrame()
for i in range(0,(len(stock2.AdjCloseStock)//52)-1):
    betas = betas.append(stock2.stockreturn.iloc[i*52:(i+1)*52].cov(stock2.SP500return.iloc[i*52:(i+1)*52])/stock2.SP500return.iloc[i*52:(i+1)*52].cov(stock2.SP500return.iloc[i*52:(i+1)*52]))

My data looks like weekly stock and S&P index return for 33 years. So the output should have 33 betas.

Body:
I tried simplifying your code and creating an example. I think the problem is that your calculation returns a float. You want to make it a pd.Series. DataFrame.append takes:

DataFrame or Series/dict-like object, or list of these

np.random.seed(20)
df = pd.DataFrame(np.random.randn(33*53, 2),
                  columns=['a', 'b'])
betas = pd.DataFrame()
for year in range(len(df['a'])//52 -1):
    # Take some data
    in_slice = pd.IndexSlice[year*52:(year+1)*52]
    numerator = df['a'].iloc[in_slice].cov(df['b'].iloc[in_slice])
    denominator = df['b'].iloc[in_slice].cov(df['b'].iloc[in_slice])
    # Do some calculations and create a pd.Series from the result
    data = pd.Series(numerator / denominator, name = year)
    # Append to the DataFrame
    betas = betas.append(data)

betas.index.name = 'years'
betas.columns = ['beta']

betas.head():

           beta
years
0      0.107669
1     -0.009302
2     -0.063200
3      0.025681
4     -0.000813


问:
Problem when sorting rows of data frame and changing the values of every other row
I have been working on a dataframe, trying to first sort it by values of a column. Then change the value of every other row of certain columns. To sort the columns I am doing:

```<code>df['key'] = df['Direction'].apply(lambda x: x.split()[0])
# Take the second number to ensure the order is kept
df['key2'] = df['Direction'].apply(lambda x: x.split()[2])

class_determiner_df = df.sort_values(['key', 'key2'])
</code>```

This works in sorting the columns as expected, from my previous question here Sort the rows of a data frame.

I then have the following dataframe:

```<code>         Node               Feature Indicator  Scaled     Class    Direction
    0       0                    km        <=   0.181   class_4      0 -> 1
    201   201                  gini         =   0.000   class_5    0 -> 202
    1       1                   WPS        <=   0.074   class_5      1 -> 2
    64     64                  gini         =   0.000   class_4     1 -> 65
    10     10              funktion        <=   0.500   class_2    10 -> 11
    17     17                  gini         =   0.000   class_5    10 -> 18
    100   100                   SPW        <=   0.282   class_5  100 -> 101
    101   101                  gini         =   0.000   class_5  100 -> 102
    102   102              words_nb        <=   0.322   class_3  102 -> 103
    123   123                  gini         =   0.496   class_2  102 -> 124
    103   103              words_nb        <=   0.125   class_2  103 -> 104
    104   104                  gini         =   0.000   class_2  103 -> 105
    105   105                   SPW        <=   0.290   class_4  105 -> 106
    106   106                  gini         =   0.000   class_4  105 -> 107
    107   107              words_nb        <=   0.197   class_3  107 -> 108
    116   116                  gini         =   0.000   class_4  107 -> 117
    108   108                   SPW        <=   0.330   class_3  108 -> 109
    109   109                  gini         =   0.000   class_3  108 -> 110
    11     11           auftragnehm        <=   0.500   class_2    11 -> 12
    16     16                  gini         =   0.000   class_2    11 -> 17
    110   110             Comp_conj        <=   0.125   class_3  110 -> 111
    115   115                  gini         =   0.000   class_4  110 -> 116
    111   111              words_nb        <=   0.138   class_3  111 -> 112
    112   112                  gini         =   0.000   class_3  111 -> 113
    113   113           weird_words        <=   0.167   class_3  113 -> 114
    114   114                  gini         =   0.000   class_3  113 -> 115
    117   117              polarity        <=   0.175   class_2  117 -> 118
    118   118                  gini         =   0.000   class_2  117 -> 119
    119   119          Aux_Start_no        <=   0.500   class_3  119 -> 120
    120   120                  gini         =   0.000   class_3  119 -> 121
    ..    ...                   ...       ...     ...       ...          ...

</code>```

I then try to make every second row for df['feature'] and df['value'] equal to the row above, and df['indicator'] to equal '>'

I use the following to do this, taken from this answer: Adjust every other row of a data frame

```<code> # Adjust every other row
class_determiner_df.loc[1::2, 'Feature'] = None
class_determiner_df.loc[1::2, 'Scaled'] = None
class_determiner_df.loc[1::2, 'Indicator'] = '>'
# fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
# it replaces the None value with the last significant value from the same column
class_determiner_df.fillna(method='ffill', inplace=True)
</code>```

This is producing the following incorrect dataframe:

```<code>
         Node             Feature Indicator  Scaled     Class    Direction
    0       0                  km        <=   0.181   class_4      0 -> 1
    201   201                gini         =   0.000   class_5    0 -> 202
    1       1                gini         >   0.000   class_5      1 -> 2
    64     64                gini         =   0.000   class_4     1 -> 65
    10     10                gini         >   0.000   class_2    10 -> 11
    17     17                gini         =   0.000   class_5    10 -> 18
    100   100                gini         >   0.000   class_5  100 -> 101
    101   101                gini         =   0.000   class_5  100 -> 102
    102   102                gini         >   0.000   class_3  102 -> 103
    123   123                gini         =   0.496   class_2  102 -> 124
    103   103                gini         >   0.496   class_2  103 -> 104
    104   104                gini         =   0.000   class_2  103 -> 105
    105   105                gini         >   0.000   class_4  105 -> 106
    106   106                gini         =   0.000   class_4  105 -> 107
    107   107                gini         >   0.000   class_3  107 -> 108
    116   116                gini         =   0.000   class_4  107 -> 117
    108   108                gini         >   0.000   class_3  108 -> 109
    109   109                gini         =   0.000   class_3  108 -> 110
    11     11                gini         >   0.000   class_2    11 -> 12
    16     16                gini         =   0.000   class_2    11 -> 17
    110   110                gini         >   0.000   class_3  110 -> 111
    115   115                gini         =   0.000   class_4  110 -> 116
    111   111                gini         >   0.000   class_3  111 -> 112
    112   112                gini         =   0.000   class_3  111 -> 113
    113   113                gini         >   0.000   class_3  113 -> 114
    114   114                gini         =   0.000   class_3  113 -> 115
    117   117                gini         >   0.000   class_2  117 -> 118
    118   118                gini         =   0.000   class_2  117 -> 119
    119   119                gini         >   0.000   class_3  119 -> 120
    120   120                gini         =   0.000   class_3  119 -> 121
    ..    ...                 ...       ...     ...       ...          ...
</code>```

The second row 'gini' has replaced every row after it, is there a better way to ensure that the dataframe would look something like:

```<code>        Node               Feature Indicator  Scaled     Class    Direction
    0       0                    km        <=   0.181   class_4      0 -> 1
    201   201                    km         >   0.181   class_5    0 -> 202
    1       1                   WPS        <=   0.074   class_5      1 -> 2
    64     64                   WPS         >   0.074   class_4     1 -> 65
    10     10              funktion        <=   0.500   class_2    10 -> 11
    17     17              function         >   0.500   class_5    10 -> 18
    100   100                   SPW        <=   0.282   class_5  100 -> 101
    101   101                   SPW         >   0.282   class_5  100 -> 102
    102   102              words_nb        <=   0.322   class_3  102 -> 103
    123   123              words_nb         >   0.322   class_2  102 -> 124
    105   105                   SPW        <=   0.290   class_4  105 -> 106
    106   106                   SPW         >   0.290   class_4  105 -> 107
    ...

</code>```

I'm not really sure why the following doesn't work as it seems to be what I need

```<code>    class_determiner_df.loc[1::2, 'Feature'] = None
    class_determiner_df.loc[1::2, 'Scaled'] = None
    class_determiner_df.loc[1::2, 'Indicator'] = '>'
    # fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
    # it replaces the None value with the last significant value from the same column
    class_determiner_df.fillna(method='ffill', inplace=True)
</code>```

答:
It's because loc is using index label rather than position. You can use DataFrame.reset_index to fix this easily:

```<code>class_determiner_df.reset_index(inplace=True, drop=True)

# Adjust every other row
class_determiner_df.loc[1::2, 'Feature'] = None
class_determiner_df.loc[1::2, 'Scaled'] = None
class_determiner_df.loc[1::2, 'Indicator'] = '>'
# fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
# it replaces the None value with the last significant value from the same column
class_determiner_df.fillna(method='ffill', inplace=True)
</code>```

Body:
I have been working on a dataframe, trying to first sort it by values of a column. Then change the value of every other row of certain columns. To sort the columns I am doing:

df['key'] = df['Direction'].apply(lambda x: x.split()[0])
# Take the second number to ensure the order is kept
df['key2'] = df['Direction'].apply(lambda x: x.split()[2])

class_determiner_df = df.sort_values(['key', 'key2'])

This works in sorting the columns as expected, from my previous question here Sort the rows of a data frame.

I then have the following dataframe:

         Node               Feature Indicator  Scaled     Class    Direction
    0       0                    km        <=   0.181   class_4      0 -> 1
    201   201                  gini         =   0.000   class_5    0 -> 202
    1       1                   WPS        <=   0.074   class_5      1 -> 2
    64     64                  gini         =   0.000   class_4     1 -> 65
    10     10              funktion        <=   0.500   class_2    10 -> 11
    17     17                  gini         =   0.000   class_5    10 -> 18
    100   100                   SPW        <=   0.282   class_5  100 -> 101
    101   101                  gini         =   0.000   class_5  100 -> 102
    102   102              words_nb        <=   0.322   class_3  102 -> 103
    123   123                  gini         =   0.496   class_2  102 -> 124
    103   103              words_nb        <=   0.125   class_2  103 -> 104
    104   104                  gini         =   0.000   class_2  103 -> 105
    105   105                   SPW        <=   0.290   class_4  105 -> 106
    106   106                  gini         =   0.000   class_4  105 -> 107
    107   107              words_nb        <=   0.197   class_3  107 -> 108
    116   116                  gini         =   0.000   class_4  107 -> 117
    108   108                   SPW        <=   0.330   class_3  108 -> 109
    109   109                  gini         =   0.000   class_3  108 -> 110
    11     11           auftragnehm        <=   0.500   class_2    11 -> 12
    16     16                  gini         =   0.000   class_2    11 -> 17
    110   110             Comp_conj        <=   0.125   class_3  110 -> 111
    115   115                  gini         =   0.000   class_4  110 -> 116
    111   111              words_nb        <=   0.138   class_3  111 -> 112
    112   112                  gini         =   0.000   class_3  111 -> 113
    113   113           weird_words        <=   0.167   class_3  113 -> 114
    114   114                  gini         =   0.000   class_3  113 -> 115
    117   117              polarity        <=   0.175   class_2  117 -> 118
    118   118                  gini         =   0.000   class_2  117 -> 119
    119   119          Aux_Start_no        <=   0.500   class_3  119 -> 120
    120   120                  gini         =   0.000   class_3  119 -> 121
    ..    ...                   ...       ...     ...       ...          ...

I then try to make every second row for df['feature'] and df['value'] equal to the row above, and df['indicator'] to equal '>'

I use the following to do this, taken from this answer: Adjust every other row of a data frame

 # Adjust every other row
class_determiner_df.loc[1::2, 'Feature'] = None
class_determiner_df.loc[1::2, 'Scaled'] = None
class_determiner_df.loc[1::2, 'Indicator'] = '>'
# fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
# it replaces the None value with the last significant value from the same column
class_determiner_df.fillna(method='ffill', inplace=True)

This is producing the following incorrect dataframe:

         Node             Feature Indicator  Scaled     Class    Direction
    0       0                  km        <=   0.181   class_4      0 -> 1
    201   201                gini         =   0.000   class_5    0 -> 202
    1       1                gini         >   0.000   class_5      1 -> 2
    64     64                gini         =   0.000   class_4     1 -> 65
    10     10                gini         >   0.000   class_2    10 -> 11
    17     17                gini         =   0.000   class_5    10 -> 18
    100   100                gini         >   0.000   class_5  100 -> 101
    101   101                gini         =   0.000   class_5  100 -> 102
    102   102                gini         >   0.000   class_3  102 -> 103
    123   123                gini         =   0.496   class_2  102 -> 124
    103   103                gini         >   0.496   class_2  103 -> 104
    104   104                gini         =   0.000   class_2  103 -> 105
    105   105                gini         >   0.000   class_4  105 -> 106
    106   106                gini         =   0.000   class_4  105 -> 107
    107   107                gini         >   0.000   class_3  107 -> 108
    116   116                gini         =   0.000   class_4  107 -> 117
    108   108                gini         >   0.000   class_3  108 -> 109
    109   109                gini         =   0.000   class_3  108 -> 110
    11     11                gini         >   0.000   class_2    11 -> 12
    16     16                gini         =   0.000   class_2    11 -> 17
    110   110                gini         >   0.000   class_3  110 -> 111
    115   115                gini         =   0.000   class_4  110 -> 116
    111   111                gini         >   0.000   class_3  111 -> 112
    112   112                gini         =   0.000   class_3  111 -> 113
    113   113                gini         >   0.000   class_3  113 -> 114
    114   114                gini         =   0.000   class_3  113 -> 115
    117   117                gini         >   0.000   class_2  117 -> 118
    118   118                gini         =   0.000   class_2  117 -> 119
    119   119                gini         >   0.000   class_3  119 -> 120
    120   120                gini         =   0.000   class_3  119 -> 121
    ..    ...                 ...       ...     ...       ...          ...

The second row 'gini' has replaced every row after it, is there a better way to ensure that the dataframe would look something like:

        Node               Feature Indicator  Scaled     Class    Direction
    0       0                    km        <=   0.181   class_4      0 -> 1
    201   201                    km         >   0.181   class_5    0 -> 202
    1       1                   WPS        <=   0.074   class_5      1 -> 2
    64     64                   WPS         >   0.074   class_4     1 -> 65
    10     10              funktion        <=   0.500   class_2    10 -> 11
    17     17              function         >   0.500   class_5    10 -> 18
    100   100                   SPW        <=   0.282   class_5  100 -> 101
    101   101                   SPW         >   0.282   class_5  100 -> 102
    102   102              words_nb        <=   0.322   class_3  102 -> 103
    123   123              words_nb         >   0.322   class_2  102 -> 124
    105   105                   SPW        <=   0.290   class_4  105 -> 106
    106   106                   SPW         >   0.290   class_4  105 -> 107
    ...

I'm not really sure why the following doesn't work as it seems to be what I need

    class_determiner_df.loc[1::2, 'Feature'] = None
    class_determiner_df.loc[1::2, 'Scaled'] = None
    class_determiner_df.loc[1::2, 'Indicator'] = '>'
    # fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
    # it replaces the None value with the last significant value from the same column
    class_determiner_df.fillna(method='ffill', inplace=True)

Body:
It's because loc is using index label rather than position. You can use DataFrame.reset_index to fix this easily:

class_determiner_df.reset_index(inplace=True, drop=True)

# Adjust every other row
class_determiner_df.loc[1::2, 'Feature'] = None
class_determiner_df.loc[1::2, 'Scaled'] = None
class_determiner_df.loc[1::2, 'Indicator'] = '>'
# fillna() method of DataFrame scans rows from top, and when it finds a python None value (equivalent to numpy.NaN)
# it replaces the None value with the last significant value from the same column
class_determiner_df.fillna(method='ffill', inplace=True)


问:
Booking system remove all saved bookings during a period
I have multiple bookings in pending status. But 1 of them is paid and the status is now confirmed.

Here is an example of what I have :

```<code>id |       start_date       |        end_date       |  status
   |                        |                       |
1  |   2019-06-10 08:00:00  |  2019-06-10 20:00:00  |  pending    <-- To delete
2  |   2019-06-10 10:00:00  |  2019-06-10 13:00:00  |  confirmed
3  |   2019-06-09 06:00:00  |  2019-06-11 11:00:00  |  pending    <-- To delete
4  |   2019-06-10 21:00:00  |  2019-06-10 22:00:00  |  pending    <-- Keep it
5  |   2019-06-10 11:00:00  |  2019-06-10 12:00:00  |  pending    <-- To delete
</code>```

The id 2 is confirmed and I need to delete all other bookings in pending status who are in the same period of the confirmed status.

So I need to delete ids 1, 3 and 5

How can I do that with SQL query ?

I thought about but I'm not sure it will cover all possible cases:

```<code>DELETE FROM booking
WHERE status = 'pending'
AND start_date <= '2019-06-10 10:00:00'
AND end_date >= '2019-06-10 13:00:00'
</code>```

Body:
I have multiple bookings in pending status. But 1 of them is paid and the status is now confirmed.

Here is an example of what I have :

id |       start_date       |        end_date       |  status
   |                        |                       |
1  |   2019-06-10 08:00:00  |  2019-06-10 20:00:00  |  pending    <-- To delete
2  |   2019-06-10 10:00:00  |  2019-06-10 13:00:00  |  confirmed
3  |   2019-06-09 06:00:00  |  2019-06-11 11:00:00  |  pending    <-- To delete
4  |   2019-06-10 21:00:00  |  2019-06-10 22:00:00  |  pending    <-- Keep it
5  |   2019-06-10 11:00:00  |  2019-06-10 12:00:00  |  pending    <-- To delete

The id 2 is confirmed and I need to delete all other bookings in pending status who are in the same period of the confirmed status.

So I need to delete ids 1, 3 and 5

How can I do that with SQL query ?

I thought about but I'm not sure it will cover all possible cases:

DELETE FROM booking
WHERE status = 'pending'
AND start_date <= '2019-06-10 10:00:00'
AND end_date >= '2019-06-10 13:00:00'

Body:
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,start_date DATETIME NOT NULL
,end_date DATETIME NOT NULL
,status VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,'2019-06-10 08:00:00','2019-06-10 20:00:00','pending'),
(2,'2019-06-10 10:00:00','2019-06-10 13:00:00','confirmed'),
(3,'2019-06-09 06:00:00','2019-06-11 11:00:00','pending'),
(4,'2019-06-10 21:00:00','2019-06-10 22:00:00','pending'),
(5,'2019-06-10 11:00:00','2019-06-10 12:00:00','pending');

DELETE y
  FROM my_table x
  JOIN my_table y
    ON y.start_date <= x.end_date
   AND y.end_date > x.start_date
 WHERE x.status = 'confirmed'
   AND y.id <> x.id;

Query OK, 3 rows affected (0.00 sec)

SELECT * FROM my_table;
+----+---------------------+---------------------+-----------+
| id | start_date          | end_date            | status    |
+----+---------------------+---------------------+-----------+
|  2 | 2019-06-10 10:00:00 | 2019-06-10 13:00:00 | confirmed |
|  4 | 2019-06-10 21:00:00 | 2019-06-10 22:00:00 | pending   |
+----+---------------------+---------------------+-----------+
2 rows in set (0.00 sec)


问:
What's the RIGHT Way to do Multi-Threading in Azure
I've got an Azure app that needs 3 distinctly unique tasks to run as long-running processes.  I could easily spin up 3 Worker Roles, but that would cost 3x more than I need to spend given how simple the tasks are.  I'd like to run each task in its own thread since each task is very different in the amount of time they take to complete, and how frequently the need to run.

Given that scenario, or even a general multi-threading Azure scenario, what's the best way you know of to have each task run independently?

A few considerations I'd like to propose are:

Keep the CPU utilization low (not always possible with EventWaitHandles..?).

Uses the most current framework utilities (i.e. TPL or PLINQ).

Graceful shutdown and restart in case of an unrecoverable exception.

Thanks for the suggestions, links, or code samples.

EDIT

Here's what I've settled on - Given the code is bound for the Azure cloud, a self-healing option seems the most appropriate.  This approach aims to take a collection of threads and delegate their work to a diversity of "units of work."

Here's how it's glued together.  First, a simple class to wrap a diversity of workers.

```<code>public class ThreadWorker
{
    internal void RunInternal()
    {
        try
        {
            Run();
        }
        catch (SystemException)
        {
            throw;
        }
        catch (Exception)
        {
        }
    }

    public virtual void Run()
    {
    }

    public virtual void OnStop()
    {
    }
}
</code>```

Next, the code to keep a series of threads alive indefinitely.  This involves a list of threads, a list of "workers" (one per thread), and an infinite loop that checks the status of each thread on a given interval.

Note that an exception that terminates a thread won't tear down the other threads.  If an unhandled exception is encountered, the thread will be restarted the next time the event wait handle responds.

```<code>private readonly List<Thread> _threads = new List<Thread>();
private readonly List<ThreadWorker> _workers = new List<ThreadWorker>();
private EventWaitHandle EventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

public override void Run()
{
    foreach (var worker in _workers)
    {
        _threads.Add(new Thread(worker.RunInternal));
    }

    foreach (var thread in _threads)
    {
         thread.Start();
    }

    while (!EventWaitHandle.WaitOne(500))
    {
         // Restart any threads that have stopped running
         for (var i = 0; i < _threads.Count; i++)
         {
               if (_threads[i].IsAlive)
               {
                   continue;
               }

                _threads[i] = new Thread(_workers[i].RunInternal);
                _threads[i].Start();
          }

          EventWaitHandle.WaitOne(2000);
    }
}
</code>```

Simple enough - the main thread (in this case an Azure worker role's Run method) blocks for half a second between checks to the active list of threads.  Terminated threads are re-started and the host thread then blocks for 2 seconds before checking the worker threads' health again.

Adding workers is as simple as adding a list of classes that inherit from the ThreadWorker base class

```<code>_workers.Add(new SomeWorker());
_workers.Add(new AnotherWorker());
</code>```

And, finally, the concrete workers:

```<code>public class SomeWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.

            Thread.Sleep(2000); // Take a breather - not necessary.
        }
    }
}

public class AnotherWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.
        }
    }
}
</code>```

答:
I think this is quite a common scenario - in an ideal world one job per role, but for cash reasons (and environmental reasons too!) its better to merge them into one role.

I personally don't think there is a RIGHT way - there are several options available, and you need to choose the one that best suits your app's current requirements:

use the Task Processing library

use Quartz.net for scheduled tasks - http://quartznet.sourceforge.net/

Lokad.Cloud provides a couple of frameworks for servicing multiple queues and for doing regular scheduled tasks - http://lokadcloud.codeplex.com/

roll-your-own

Body:
I've got an Azure app that needs 3 distinctly unique tasks to run as long-running processes.  I could easily spin up 3 Worker Roles, but that would cost 3x more than I need to spend given how simple the tasks are.  I'd like to run each task in its own thread since each task is very different in the amount of time they take to complete, and how frequently the need to run.

Given that scenario, or even a general multi-threading Azure scenario, what's the best way you know of to have each task run independently?

A few considerations I'd like to propose are:

Keep the CPU utilization low (not always possible with EventWaitHandles..?).

Uses the most current framework utilities (i.e. TPL or PLINQ).

Graceful shutdown and restart in case of an unrecoverable exception.

Thanks for the suggestions, links, or code samples.

EDIT

Here's what I've settled on - Given the code is bound for the Azure cloud, a self-healing option seems the most appropriate.  This approach aims to take a collection of threads and delegate their work to a diversity of "units of work."

Here's how it's glued together.  First, a simple class to wrap a diversity of workers.

public class ThreadWorker
{
    internal void RunInternal()
    {
        try
        {
            Run();
        }
        catch (SystemException)
        {
            throw;
        }
        catch (Exception)
        {
        }
    }

    public virtual void Run()
    {
    }

    public virtual void OnStop()
    {
    }
}

Next, the code to keep a series of threads alive indefinitely.  This involves a list of threads, a list of "workers" (one per thread), and an infinite loop that checks the status of each thread on a given interval.

Note that an exception that terminates a thread won't tear down the other threads.  If an unhandled exception is encountered, the thread will be restarted the next time the event wait handle responds.

private readonly List<Thread> _threads = new List<Thread>();
private readonly List<ThreadWorker> _workers = new List<ThreadWorker>();
private EventWaitHandle EventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

public override void Run()
{
    foreach (var worker in _workers)
    {
        _threads.Add(new Thread(worker.RunInternal));
    }

    foreach (var thread in _threads)
    {
         thread.Start();
    }

    while (!EventWaitHandle.WaitOne(500))
    {
         // Restart any threads that have stopped running
         for (var i = 0; i < _threads.Count; i++)
         {
               if (_threads[i].IsAlive)
               {
                   continue;
               }

                _threads[i] = new Thread(_workers[i].RunInternal);
                _threads[i].Start();
          }

          EventWaitHandle.WaitOne(2000);
    }
}

Simple enough - the main thread (in this case an Azure worker role's Run method) blocks for half a second between checks to the active list of threads.  Terminated threads are re-started and the host thread then blocks for 2 seconds before checking the worker threads' health again.

Adding workers is as simple as adding a list of classes that inherit from the ThreadWorker base class

_workers.Add(new SomeWorker());
_workers.Add(new AnotherWorker());

And, finally, the concrete workers:

public class SomeWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.

            Thread.Sleep(2000); // Take a breather - not necessary.
        }
    }
}

public class AnotherWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.
        }
    }
}


问:
Update Kivy text variable with StringpPoperty and ID
So my problem is how do i update text to label. Should I use id:s in KV file and string property or is there even any other way?

Main.Py

```<code>    print_label = StringProperty()

    print_label = lyrics

class MyApp(App):
    def build(self):
        Window.clearcolor = (.13, .13, .13, 1)
        return MyFloatLayout()```
my.kv
```<Button>:
    font_size: 40
    color: 0.1,0.5,0.6,1
    size_hint: 0.3, 0.1

<FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""

    Button:
        pos_hint:{"bottom":1}
        text: "RE-SEARCH"
        font_size: 10
        on_press: root.btn()

</code>```

答:
You need to decide if you want print_label to be a StringProperty or an ObjectProperty. You are currently using ObjectProperty in kv and StringProperty in python.

If you want to use StringProperty you can set it directly to the text attribute. text = root.print_label.
If you use it as ObjectProperty you bind it to the object. And you can access the objects properties like text, print_label.text = "something".
So you need to choose what you want print_label to be.

Body:
So my problem is how do i update text to label. Should I use id:s in KV file and string property or is there even any other way?

Main.Py

    print_label = StringProperty()

    print_label = lyrics

class MyApp(App):
    def build(self):
        Window.clearcolor = (.13, .13, .13, 1)
        return MyFloatLayout()```
my.kv
```<Button>:
    font_size: 40
    color: 0.1,0.5,0.6,1
    size_hint: 0.3, 0.1

<FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""

    Button:
        pos_hint:{"bottom":1}
        text: "RE-SEARCH"
        font_size: 10
        on_press: root.btn()


问:
Make an ios notifications from ios website
I want to build html5 application using some frontend framework like angular or vue.js and then I want to make a mobile app from it. I don't need this mobile app to be native, so that's okay. </p>

<p>Then I want to put it into webview to make a mobile app from it.
I know this is possible with android. Is this possible with ios?
And will it possible to send push notifications?
ps: I don't want to use react native or cordova cause it will be much more difficult and we will run over the budget for this mvp  </p>

答:
While technically possible, if you're planning on trying to put it on the app store, you're likely going to run afoul of the app store guidelines and will likely get rejected:

4.2 Minimum Functionality

Your app should include features, content, and UI that elevate it
  beyond a repackaged website.

https://developer.apple.com/app-store/review/guidelines/

Technically, all you need for a push notification is to get the mobile id (the one they register to APNS) then send a notification package to apple some way (normally a remote server) to register a new notification. My question is aside from notifications, why not just build a different sort of app like a progressive web app?

Body:
I want to build html5 application using some frontend framework like angular or vue.js and then I want to make a mobile app from it. I don't need this mobile app to be native, so that's okay.

Then I want to put it into webview to make a mobile app from it.
I know this is possible with android. Is this possible with ios?
And will it possible to send push notifications?
ps: I don't want to use react native or cordova cause it will be much more difficult and we will run over the budget for this mvp