问:
How to animate line clamp
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span class="title">Title</span>
  <div class="text">
  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div></code>```

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

答:
As you can't animate line-clamp (or display) we have to find something animatable but which will nonetheless show exactly two lines in the non-hovered state.

max-height is animatable.

This snippet takes a 'guess' at a suitable max-height for when line-clamp is in use - it needs to be larger than 2 lines high so that the line-clamp can work but it needs to be not so large that there is too discernible a jump when we start the hover transform.

.box {
  transition: all 0.3s ease-in-out;
}

.title {
  color: green;
  font-weight: bold;
}

.text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  transition: all 0.3s ease-in-out;
  /* ADDED */
  max-height: 3em;
}

.box:hover .text {
  -webkit-line-clamp: 40;
  max-height: 40em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span class="title">Title</span>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div></code>```

This is of course only a partial method as when hovering is stopped the transition back to line-clamp: 2 is not smooth. I can't at the moment see a way around that other than to invoke JS on animationend and put the line clamp back at that point.

Title: How to animate line clamp

Body:
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}

  Title

  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

Body:
As you can't animate line-clamp (or display) we have to find something animatable but which will nonetheless show exactly two lines in the non-hovered state.

max-height is animatable.

This snippet takes a 'guess' at a suitable max-height for when line-clamp is in use - it needs to be larger than 2 lines high so that the line-clamp can work but it needs to be not so large that there is too discernible a jump when we start the hover transform.

.box {
  transition: all 0.3s ease-in-out;
}

.title {
  color: green;
  font-weight: bold;
}

.text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  transition: all 0.3s ease-in-out;
  /* ADDED */
  max-height: 3em;
}

.box:hover .text {
  -webkit-line-clamp: 40;
  max-height: 40em;
}

<div class="box">
  <span class="title">Title</span>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div>

This is of course only a partial method as when hovering is stopped the transition back to line-clamp: 2 is not smooth. I can't at the moment see a way around that other than to invoke JS on animationend and put the line clamp back at that point.


来源: stackexchange

问:
How to create custom sql query on category listing page in Prestashop 1.7
In Prestashop 1.7 i want to modify the default SQL query of the listing products on the category page.
I cant found which SQL query returning products on category page.

there is custom fields added to product table priority(1,2,3) and state (0,1)

so need to display products above matching columns using custom SQL query

答:
check classes/Category.php

the getProducts() method is the one responsible of returning products result. You could override it to suit your needs.

Beware that there are two main queries inside the method , first one is for product count pagination, other is for actual getting products data.

ContentLicense: CC BY-SA 4.0


问:
 tags showing different behaviour
When I'm using
 tags to create horizontal rows then the behavior is not uniform i.e. all the
s (in my case) are displaying alternate background color.

Also, I've tested in Chrome and opera and the zoom level was 100% at the time of testing.

For reference, below is the image:-

hr{
    border-style: none;
    width: 10%;
    height: 2px;
    background-color: rgba(0, 0, 0, 0.253) ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

答:
hr{
        width: 80px;
        height: 10px;
        background-color: rgba(0, 0, 0, 0.253) ;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

Don't Use height in percentage it is kind of giving relative values.

Maybe Your HTML hr tags are inheriting styles from somewhere else from your style sheet. That's the reason maybe they are Loading like this.
Try to inspect those hr from chromedev tools.

Title: <hr> tags showing different behaviour

Body:
hr{
        width: 80px;
        height: 10px;
        background-color: rgba(0, 0, 0, 0.253) ;
    }

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>

Don't Use height in percentage it is kind of giving relative values.

Maybe Your HTML hr tags are inheriting styles from somewhere else from your style sheet. That's the reason maybe they are Loading like this.
Try to inspect those hr from chromedev tools.


问:
I need to web scrap a particular value from a page which is contained in a table
I want to scrap net sales value for Dec 2021 that is contained in a table from a webpage. I am using simple beautifulsoup module.I have included the python code I am using for extracting some of the other values.I want to extract the value 9644.8. The code for the webpage is give below

        PARTICULARS
        Dec 2020
        Mar 2021
        Jun 2021
        Sep 2021
        Dec 2021

        Net Sales <svg
                class="svg-inline--fa fa-info-circle fa-w-16" aria-hidden="true" focusable="false" data-prefix="fas"
                data-icon="info-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
                data-fa-i2svg=""><path fill="currentColor"
                                       d="M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z"></path></svg>

            10,824.40

            9,530.90

            9,088.20

            9,321.50

            9,644.80

```
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from bs4 import BeautifulSoup
import requests
a=input("Enter symbol of the company\n")
url="https://ticker.finology.in/company/"+a
print(url)
response=requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
CP = soup.find("div", {"id":"mainContent_clsprice"}).find("span", {"class": "Number"}).getText()
</code>```

The ticker I am using is IDEA

答:
Provided you have located the correct table you can use select_one and the css selector tbody td:last-child > .Number.  tbody will restrict to the table body rows, select_one with td:last-child will grab the first last column, then the > .Number will grab the direct child span. You could of course, combine and shorten the selector list rather than separately grabbing table, however, I was unsure if you would do other things with the table.

```<code>from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://ticker.finology.in/company/idea', headers = {'User-Agent':'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
table = soup.select_one('.card:has(> #mainContent_hfSizeForQuarter) table')
table.select_one('tbody td:last-child > .Number').text.strip()
</code>```

Body:
I want to scrap net sales value for Dec 2021 that is contained in a table from a webpage. I am using simple beautifulsoup module.I have included the python code I am using for extracting some of the other values.I want to extract the value 9644.8. The code for the webpage is give below

        PARTICULARS
        Dec 2020
        Mar 2021
        Jun 2021
        Sep 2021
        Dec 2021

        Net Sales <svg
                class="svg-inline--fa fa-info-circle fa-w-16" aria-hidden="true" focusable="false" data-prefix="fas"
                data-icon="info-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
                data-fa-i2svg=""><path fill="currentColor"
                                       d="M256 8C119.043 8 8 119.083 8 256c0 136.997 111.043 248 248 248s248-111.003 248-248C504 119.083 392.957 8 256 8zm0 110c23.196 0 42 18.804 42 42s-18.804 42-42 42-42-18.804-42-42 18.804-42 42-42zm56 254c0 6.627-5.373 12-12 12h-88c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h12v-64h-12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h64c6.627 0 12 5.373 12 12v100h12c6.627 0 12 5.373 12 12v24z"></path></svg>

            10,824.40

            9,530.90

            9,088.20

            9,321.50

            9,644.80

import pandas as pd
from bs4 import BeautifulSoup
import requests
a=input("Enter symbol of the company\n")
url="https://ticker.finology.in/company/"+a
print(url)
response=requests.get(url)
soup=BeautifulSoup(response.text,'html.parser')
CP = soup.find("div", {"id":"mainContent_clsprice"}).find("span", {"class": "Number"}).getText()

The ticker I am using is IDEA

Body:
Provided you have located the correct table you can use select_one and the css selector tbody td:last-child > .Number.  tbody will restrict to the table body rows, select_one with td:last-child will grab the first last column, then the > .Number will grab the direct child span. You could of course, combine and shorten the selector list rather than separately grabbing table, however, I was unsure if you would do other things with the table.

from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://ticker.finology.in/company/idea', headers = {'User-Agent':'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
table = soup.select_one('.card:has(> #mainContent_hfSizeForQuarter) table')
table.select_one('tbody td:last-child > .Number').text.strip()


问:
Objects created in a thread can only be used in that same thread
I can't find the problem:

```<code>@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method=='POST' and form.validate():
        name =  form.name.data
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        c.execute("INSERT INTO users(name,email,username,password)
        VALUES(?,?,?,?)", (name, email, username, password))

        conn.commit

        conn.close()
</code>```

Error:

File "C:\Users\app.py", line 59, in register c.execute("INSERT INTO
users(name,email,username,password) VALUES(?,?,?,?)", (name, email,
username, password))  ProgrammingError: SQLite objects created in a
thread can only be used in that   same thread.The object was created
in thread id 23508 and this is thread id   22640

Does this mean I can't use the name, email username & password in an HTML file? How do I solve this?

答:
The error doesn't lie on the variables called in your .execute(), but rather the object instances that SQLite uses to access the DB.

I assume that you have:

```<code>conn = sqlite3.connect('your_database.db')
c = conn.cursor()
</code>```

somewhere at the top of the Flask script, & this would be initialized when you first run the script.
 When the register function is called, a new thread, different from the initial script run handles the process. Thus, in this new thread, you're utilizing object instances that are from a different thread, which SQLite captures as an error: rightfully so, because this may lead to data corruption if you anticipate for your DB to be accessed by different threads during the app run.

So a different method, instead of disabling the check-same-thread SQLite functionality, you could try initializing your DB connection & cursor within the HTTP Methods that are being called.

With this, the SQLite objects & utilization will be on the same thread at runtime.

The code would be redundant, but it might save you in situations where the data is being accessed asynchronously, & will also prevent data corruption.

Body:
I can't find the problem:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method=='POST' and form.validate():
        name =  form.name.data
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        c.execute("INSERT INTO users(name,email,username,password)
        VALUES(?,?,?,?)", (name, email, username, password))

        conn.commit

        conn.close()

Error:

File "C:\Users\app.py", line 59, in register c.execute("INSERT INTO
users(name,email,username,password) VALUES(?,?,?,?)", (name, email,
username, password))  ProgrammingError: SQLite objects created in a
thread can only be used in that   same thread.The object was created
in thread id 23508 and this is thread id   22640

Does this mean I can't use the name, email username & password in an HTML file? How do I solve this?

Body:
The error doesn't lie on the variables called in your .execute(), but rather the object instances that SQLite uses to access the DB.

I assume that you have:

conn = sqlite3.connect('your_database.db')
c = conn.cursor()

somewhere at the top of the Flask script, & this would be initialized when you first run the script.
 When the register function is called, a new thread, different from the initial script run handles the process. Thus, in this new thread, you're utilizing object instances that are from a different thread, which SQLite captures as an error: rightfully so, because this may lead to data corruption if you anticipate for your DB to be accessed by different threads during the app run.

So a different method, instead of disabling the check-same-thread SQLite functionality, you could try initializing your DB connection & cursor within the HTTP Methods that are being called.

With this, the SQLite objects & utilization will be on the same thread at runtime.

The code would be redundant, but it might save you in situations where the data is being accessed asynchronously, & will also prevent data corruption.


问:
Data is not getting added to Firebase Realtime Database
I've been following this Tutorial for the Realtime Database, this tutorial was last Updated 31 Dec 2020, from GeeksForGeeks-how-to-save-data-to-the-firebase-realtime-database-in-android
but for me the Data is not getting Added in the Database

I've used the Firebase Assistant in Android Studio

This is the MainActivity, It has only 2 buttons which go to the activities for adding Data and Viewing them

Java File for MainActivity:

```<code>
package com.anurag.newemsapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button btnAdd, btnView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = findViewById(R.id.btnAdd);
        btnView = findViewById(R.id.btnView);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent a = new Intent(MainActivity.this, AddActivity.class);
                startActivity(a);
            }
        });

      // the View button is disabled for time-being

    }
}

</code>```

The Add Activity, This is where, I take user input and try to save the data in Firebase

Java File for AddActivity

```<code>package com.anurag.newemsapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class AddActivity extends AppCompatActivity {

    private EditText etAddEid, etAddEname;
    private Button btnAddSave;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    Employee employee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        etAddEid = findViewById(R.id.etAddEid);
        etAddEname = findViewById(R.id.etAddEname);

        firebaseDatabase = FirebaseDatabase.getInstance();

        databaseReference = firebaseDatabase.getReference("Employee");

        employee = new Employee();

        btnAddSave = findViewById(R.id.btnAddSave);

        btnAddSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String id = etAddEid.getText().toString();
                String name = etAddEname.getText().toString();

                if (id.length() == 0 && name.length() == 0) {
                    Toast.makeText(AddActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
                } else {
                    addDataToFirebase(id, name);
                }
            }
        });
    }

    private void addDataToFirebase(String id, String name) {
        employee.setEmployeeId(id);
        employee.setEmployeeName(name);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                databaseReference.push().setValue(employee);
                Toast.makeText(AddActivity.this, "data added", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(AddActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

</code>```

Now When I press the Save Button, it does the validation part but, addDataToFirebase doesn't seem to work.
I doesn't throw an error, the app runs perfectly fine. it's just the data that is not being added to Firebase Realtime Database

I have added the google-services.json file in the project level, after manually downloading it from the firebase console

答:
So, The solution to this was,

Pass the Database URL to the FirebaseDatabase.getInstance() function. Which you can find on your Firebase Console. You are suppoused to do it only if the Database location is set anything other than US-Central.

I had My database setup on asia-southeast1, as instructed on the Android Studio Firebase Assistant

I just had to add the Database URL to the FirebaseDatabase.getInstance() function, like so,
FirebaseDatabase.getInstance(URL)

Body:
I've been following this Tutorial for the Realtime Database, this tutorial was last Updated 31 Dec 2020, from GeeksForGeeks-how-to-save-data-to-the-firebase-realtime-database-in-android
but for me the Data is not getting Added in the Database

I've used the Firebase Assistant in Android Studio

This is the MainActivity, It has only 2 buttons which go to the activities for adding Data and Viewing them

Java File for MainActivity:

package com.anurag.newemsapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button btnAdd, btnView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = findViewById(R.id.btnAdd);
        btnView = findViewById(R.id.btnView);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent a = new Intent(MainActivity.this, AddActivity.class);
                startActivity(a);
            }
        });

      // the View button is disabled for time-being

    }
}

The Add Activity, This is where, I take user input and try to save the data in Firebase

Java File for AddActivity

package com.anurag.newemsapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class AddActivity extends AppCompatActivity {

    private EditText etAddEid, etAddEname;
    private Button btnAddSave;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    Employee employee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        etAddEid = findViewById(R.id.etAddEid);
        etAddEname = findViewById(R.id.etAddEname);

        firebaseDatabase = FirebaseDatabase.getInstance();

        databaseReference = firebaseDatabase.getReference("Employee");

        employee = new Employee();

        btnAddSave = findViewById(R.id.btnAddSave);

        btnAddSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String id = etAddEid.getText().toString();
                String name = etAddEname.getText().toString();

                if (id.length() == 0 && name.length() == 0) {
                    Toast.makeText(AddActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
                } else {
                    addDataToFirebase(id, name);
                }
            }
        });
    }

    private void addDataToFirebase(String id, String name) {
        employee.setEmployeeId(id);
        employee.setEmployeeName(name);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                databaseReference.push().setValue(employee);
                Toast.makeText(AddActivity.this, "data added", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(AddActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Now When I press the Save Button, it does the validation part but, addDataToFirebase doesn't seem to work.
I doesn't throw an error, the app runs perfectly fine. it's just the data that is not being added to Firebase Realtime Database

I have added the google-services.json file in the project level, after manually downloading it from the firebase console


问:
Invalid hook call, from Reactjs to Nextjs
I have been a while outside the ReactJS world, and I decided to come back and give a try with NextJS. However I am getting a Invalid Hook Call issue.

I'm trying to convert my ReactJS project to a NextJS project. I'll show the code in a shorter format, just for the example.

Here is my Reactjs:

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

App.js

```<code>import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';

class App extends Component {
  render() {
    return (
        <Router>
          <main>
            <Switch>
              <Route exact path='/' component={MainPage}/>
            </Switch>
          </main>
        </Router>
    );
  }
}

export default App;
</code>```

MainPage.js

```<code>import React, { Fragment } from 'react';

import './MainPage.css';

const MainPage = () => {
    return (
        <Fragment>
            <div>
                  Hello There :-)
            </div>
       <Fragment>
    );
};

export default MainPage;
</code>```

Here is my Nextjs:

_app.js

```<code>import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp
</code>```

index.js

```<code>import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';

class App extends Component {
  render() { **// not sure about the render**
    return (
        <Router>
          <main>
            <Switch> **// I think was switched to Routes**
              <Route exact path='/' component={MainPage}/> **// I think was switched to element**
            </Switch>
          </main>
        </Router>
    );
  }
}

export default App;
</code>```

MainPage.js

```<code>import styles from '../styles/Home.module.css'

export default function Home() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
      </main>
    </div>
  )
}
</code>```

答:
you don't need react router inside next js because it has a pages folder that whatever folder you create there will be your route for example if you create an
about folder and an index.js inside of it the index.js file will be shown to you on /about route;

for homepage you can create a components folder near pages folder and move your MainPage.js there and then import it in your index.js inside your pages folder;

Body:
I have been a while outside the ReactJS world, and I decided to come back and give a try with NextJS. However I am getting a Invalid Hook Call issue.

I'm trying to convert my ReactJS project to a NextJS project. I'll show the code in a shorter format, just for the example.

Here is my Reactjs:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';

class App extends Component {
  render() {
    return (
        <Router>

            <Switch>
              <Route exact path='/' component={MainPage}/>
            </Switch>

        </Router>
    );
  }
}

export default App;

MainPage.js

import React, { Fragment } from 'react';

import './MainPage.css';

const MainPage = () => {
    return (
        <Fragment>

                  Hello There :-)

       <Fragment>
    );
};

export default MainPage;

Here is my Nextjs:

_app.js

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

index.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';

class App extends Component {
  render() { **// not sure about the render**
    return (
        <Router>

            <Switch> **// I think was switched to Routes**
              <Route exact path='/' component={MainPage}/> **// I think was switched to element**
            </Switch>

        </Router>
    );
  }
}

export default App;

MainPage.js

import styles from '../styles/Home.module.css'

export default function Home() {
  return (

          Welcome to Next.js!

  )
}


问:
yii2 advanced login function always returns invalid username and password
I made no changes in yii login function but it returns error while giving correct username and password</p>

```<code>public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->render('index');
    } else {
        return $this->render('login', [
            'model' => $model,
        ]);
    }
}
</code>```

答:
I've faced the same problem. For advanced template default signup scenario you need to activate your account by email confirmation (the email you provided at the time of signup). Until that moment your status is inactive. This status is used for login - only active users can log in.

If you're using this project for local purposes, you may change the status of your record in db table 'user' from 9(inactive) to 10(active). Then you will be able to login.

ContentLicense: CC BY-SA 3.0

Body:
I made no changes in yii login function but it returns error while giving correct username and password

public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->render('index');
    } else {
        return $this->render('login', [
            'model' => $model,
        ]);
    }
}


问:
Python function arguments with default arguments
I am new to python. I want to define a function with from and to date. If I call the function with one argument, It should take that argument as to date. If I pass two arguments, It should assign from and to date.

I defined as follows,

```<code>def __init__(self,fdate="",edate):
        self.fdate = fdate
        self.edate = edate
</code>```

I get the below error,

```<code>    def __init__(self,fdate="",edate):
                ^
SyntaxError: non-default argument follows default argument
</code>```

I understand the error. But How can I define a function for my requirment in Python?

答:
When you are passing a value default argument, all arguments to the right of it should also have default values.

This holds true for any other programming language as well. The reason for this restriction is that otherwise, it would be impossible to determine which arguments you are trying to pass. Let's assume the following function:

```<code>def foo(first = 'default', second = 'default', third)
    pass

</code>```

And now we're calling it with

```<code>foo('custom_value', 'another_value')
</code>```

another_value in parameters is obviously the value for the third parameter, but what parameter does the custom_value stand for? first or second? You can only guess and guessing is a really bad thing for a programming language to do, as it limits predictability for the programmer.

A way to fix that would be named parameter passes. In any other programming language like PHP, this could look like

```<code>foo($first='custom_value', 'another_value');
</code>```

Now it's clear which default value you're trying to overwrite.

Python supports this syntax like that

```<code>foo(first='custom_value', third='another_value')
</code>```

but for example, PHP does not (yet). So, while calling the function you need to take care of this step every time which creates unnecessary overhead to the programmer. That's why it's a good practice to have all default arguments to the right side.

Some examples of valid and invalid parameters.

Valid

```<code>def example(a = 1, b = 2):
    pass
</code>```

Valid

```<code>def example(a , b = 2):
    pass
</code>```

Invalid

```<code>def example(a = 1, b):
    pass
</code>```

For more information on the order of parameters in c++ look at here.

For more information on the order of parameters in python look at here.

Body:
I am new to python. I want to define a function with from and to date. If I call the function with one argument, It should take that argument as to date. If I pass two arguments, It should assign from and to date.

I defined as follows,

def __init__(self,fdate="",edate):
        self.fdate = fdate
        self.edate = edate

I get the below error,

    def __init__(self,fdate="",edate):
                ^
SyntaxError: non-default argument follows default argument

I understand the error. But How can I define a function for my requirment in Python?

Body:
When you are passing a value default argument, all arguments to the right of it should also have default values.

This holds true for any other programming language as well. The reason for this restriction is that otherwise, it would be impossible to determine which arguments you are trying to pass. Let's assume the following function:

def foo(first = 'default', second = 'default', third)
    pass

And now we're calling it with

foo('custom_value', 'another_value')

another_value in parameters is obviously the value for the third parameter, but what parameter does the custom_value stand for? first or second? You can only guess and guessing is a really bad thing for a programming language to do, as it limits predictability for the programmer.

A way to fix that would be named parameter passes. In any other programming language like PHP, this could look like

foo($first='custom_value', 'another_value');

Now it's clear which default value you're trying to overwrite.

Python supports this syntax like that

foo(first='custom_value', third='another_value')

but for example, PHP does not (yet). So, while calling the function you need to take care of this step every time which creates unnecessary overhead to the programmer. That's why it's a good practice to have all default arguments to the right side.

Some examples of valid and invalid parameters.

Valid

def example(a = 1, b = 2):
    pass

Valid

def example(a , b = 2):
    pass

Invalid

def example(a = 1, b):
    pass

For more information on the order of parameters in c++ look at here.

For more information on the order of parameters in python look at here.


问:
How to check if a given column is a primary key or an index in sqlite3?
I know that PRAGMA table_info('table_name'); will describe my table and if the column pk is 1 then that column is the primary key of my table.

Similarly, if I write PRAGMA index_list('table_name'); it will give me the name of the indexes on the table.

How do I check if a given column is a primary key of the table? Also I want to check if given an index_name, this index_name is an index of the table.

Edit:

How can I do this in python?

答:
if you can read the data into pandas you can do:</p>
```<code># read to pandas
df = pd.read_sql("SELECT A, B FROM ...")

# test whether A and B are primary keys
df.set_index(['A','B']).index.is_unique
</code>```

Body:
if you can read the data into pandas you can do:

# read to pandas
df = pd.read_sql("SELECT A, B FROM ...")

# test whether A and B are primary keys
df.set_index(['A','B']).index.is_unique


问:
What part (success/error) of jquery's ajax receives a redirect status code?
I'm having a redirect sent by my server but jquery's ajax error: callback seems to get xhr.status=200 and status="parseerror"

Anywork around?? I don't want to overload other codes since I use the for the things that they were intended for? Is this just not possible with jquery?

The callback is like this:
error: function(xhr, status){...}

答:
The redirect codes 301, 302, 303, and 307 are handled by the user agent, so you can't access the redirect code from the callback.

Reference: XMLHttpRequest Level 2 spec


问:
duplicate key value violates unique constraint "auth_user_username_key"DETAIL: Key (username)=(None) already exists
I want to register a user using a custom register model but I keep getting the following error :

duplicate key value violates unique constraint "auth_user_username_key" DETAIL:  Key (username)=(None) already exists

How do I fix this error.

This is the code I have created thus far:

In urls.py I create url configurations for the various pages.

```<code>from django.conf.urls import url
from django.contrib.auth.views import login

from . import views

urlpatterns = [

    url(r'^$', views.nest, name = 'nest'),

    url(r'^login/$', login, {'template_name' : 'Identities/login.html'}, name = 'login'),

    url(r'^register/$', views.register, name = 'register'),
]
</code>```

In forms.py I create the custom registration form.

```<code>from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

# Create custom user registration

class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required = True)

    class Meta:

        model = User

        fields = (

            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.email = self.cleaned_data['email']

            if commit:

                user.save()

            return user
</code>```

In views.py I created the register view function.

```<code>from django.shortcuts import render, redirect
from Identities.forms import CreateAccountForm

# Create your views here.

def nest(request):
    return render(request, 'Identities/nest.html')

def register(request):

    if request.method == 'POST':

        form = CreateAccountForm(request.POST)

        if form.is_valid():
            form.save()

        else:
            return redirect(reverse('Identities:logout'))

    else:

        form = CreateAccountForm()
        var = {'form' : form}
        return render(request, 'Identities/create_account.html', var)
</code>```

答:
You should really try something like below. Here, I have included username to your form fields. Since username is unique, it should be included in form fields. In the save method, self.cleaned_data.get("username", None) takes None to username field if nothing posted in the request. Your db expects None if no value given, but if you don't specify it in the save method, it receives empty strings, which causes duplicate key error. Note that Django does not store empty values as None, but uses empty string instead.

```<code>from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

# Create custom user registration

class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required = True)

    class Meta:

        model = User

        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.username = self.cleaned_data.get("username", None)
            user.first_name = self.cleaned_data.get("first_name", None)
            user.last_name = self.cleaned_data.get("last_name", None)
            user.email = self.cleaned_data.get("email", None)

            if commit:

                user.save()

            return user
</code>```

Body:
I want to register a user using a custom register model but I keep getting the following error :

duplicate key value violates unique constraint "auth_user_username_key" DETAIL:  Key (username)=(None) already exists

How do I fix this error.

This is the code I have created thus far:

In urls.py I create url configurations for the various pages.

from django.conf.urls import url
from django.contrib.auth.views import login

from . import views

urlpatterns = [

    url(r'^$', views.nest, name = 'nest'),

    url(r'^login/$', login, {'template_name' : 'Identities/login.html'}, name = 'login'),

    url(r'^register/$', views.register, name = 'register'),
]

In forms.py I create the custom registration form.

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

# Create custom user registration

class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required = True)

    class Meta:

        model = User

        fields = (

            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.email = self.cleaned_data['email']

            if commit:

                user.save()

            return user

In views.py I created the register view function.

from django.shortcuts import render, redirect
from Identities.forms import CreateAccountForm

# Create your views here.

def nest(request):
    return render(request, 'Identities/nest.html')

def register(request):

    if request.method == 'POST':

        form = CreateAccountForm(request.POST)

        if form.is_valid():
            form.save()

        else:
            return redirect(reverse('Identities:logout'))

    else:

        form = CreateAccountForm()
        var = {'form' : form}
        return render(request, 'Identities/create_account.html', var)

Body:
You should really try something like below. Here, I have included username to your form fields. Since username is unique, it should be included in form fields. In the save method, self.cleaned_data.get("username", None) takes None to username field if nothing posted in the request. Your db expects None if no value given, but if you don't specify it in the save method, it receives empty strings, which causes duplicate key error. Note that Django does not store empty values as None, but uses empty string instead.

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

# Create custom user registration

class CreateAccountForm(UserCreationForm):

    email = forms.EmailField(required = True)

    class Meta:

        model = User

        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )

        def save(self, commit = True):
            user = super(CreateAccountForm, self).save(commit = False)
            user.username = self.cleaned_data.get("username", None)
            user.first_name = self.cleaned_data.get("first_name", None)
            user.last_name = self.cleaned_data.get("last_name", None)
            user.email = self.cleaned_data.get("email", None)

            if commit:

                user.save()

            return user


问:
getline() skipping over string line from text file
My project is supposed to basically sum up the value of all ints on a line and print the word in the next line that amount of times. However, something is causing it to skip over the string line where the word but I am getting the summed value right.

Input file:

1,2,3
word
2,3,4
word2
```
<p>Here is my code:</p>
```int main() {

  std::ifstream in;
  std::ofstream out;
  std::string line;
  in.open("input.txt");
  out.open("output.txt");

  while(std::getline(in, line)){
    std::stringstream ss(line);
    while(ss){
      std::string word;
      std::string number;
      int a = 0;
      while(std::getline(ss, number, ',')){
        a = a + atoi(number.c_str());}
      std::getline(ss, word);
      for (int z = 0; z < a; z++){
        out << word << ",";}
      out << "\n";
    }
  }
  return(0);
}
```
<p>Output I'm getting:</p>
<pre class="lang-none prettyprint-override"><code>,,,,,,
,,,,,,,,,

</code>```

What I should be getting:

word,word,word,word,word,word

word2,word2,word2,word2,word2,word2,word2,word2
```

答:
Change:

```<code>std::getline(ss, word);
</code>```

To this:

```<code>// Gets the next line in input.txt and stores it in the variable 'word'
std::getline(in, word);
</code>```

This is because during the while loop, ss is emptied (exhausted) by the nested while loop (the 2nd while loop) and has no words when it's contents are inserted into the variable 'word'.

Final code:

```<code>#include <iostream>
#include <fstream>
#include <sstream>

int main() {

    std::ifstream in;
    std::ofstream out;
    std::string line;
    in.open("input.txt");
    out.open("output.txt");

    while (std::getline(in, line)) {
        std::stringstream ss(line);
        while (ss) {
            std::string word;
            std::string number;
            int a = 0;
            while (std::getline(ss, number, ',')) {
                a = a + atoi(number.c_str());
            }
            std::getline(in, word); // Changed line
            for (int z = 0; z < a; z++) {
                out << word << ",";
            }
            out << "\n";
        }
    }
    return(0);
}
</code>```

Body:
My project is supposed to basically sum up the value of all ints on a line and print the word in the next line that amount of times. However, something is causing it to skip over the string line where the word but I am getting the summed value right.

Input file:

1,2,3
word
2,3,4
word2

Here is my code:

int main() {

  std::ifstream in;
  std::ofstream out;
  std::string line;
  in.open("input.txt");
  out.open("output.txt");

  while(std::getline(in, line)){
    std::stringstream ss(line);
    while(ss){
      std::string word;
      std::string number;
      int a = 0;
      while(std::getline(ss, number, ',')){
        a = a + atoi(number.c_str());}
      std::getline(ss, word);
      for (int z = 0; z < a; z++){
        out << word << ",";}
      out << "\n";
    }
  }
  return(0);
}

Output I'm getting:

,,,,,,
,,,,,,,,,

What I should be getting:

word,word,word,word,word,word

word2,word2,word2,word2,word2,word2,word2,word2

Body:
Change:

std::getline(ss, word);

To this:

// Gets the next line in input.txt and stores it in the variable 'word'
std::getline(in, word);

This is because during the while loop, ss is emptied (exhausted) by the nested while loop (the 2nd while loop) and has no words when it's contents are inserted into the variable 'word'.

Final code:

#include <iostream>
#include <fstream>
#include <sstream>

int main() {

    std::ifstream in;
    std::ofstream out;
    std::string line;
    in.open("input.txt");
    out.open("output.txt");

    while (std::getline(in, line)) {
        std::stringstream ss(line);
        while (ss) {
            std::string word;
            std::string number;
            int a = 0;
            while (std::getline(ss, number, ',')) {
                a = a + atoi(number.c_str());
            }
            std::getline(in, word); // Changed line
            for (int z = 0; z < a; z++) {
                out << word << ",";
            }
            out << "\n";
        }
    }
    return(0);
}


问:
.NET Core changing the location where my default index.html file is
I am building an Angular 2 app and using .NET Core and Webpack to compile my static resources into a dist folder.  I am using a plugin that builds my index.html file and puts it in my wwwroot/dist folder but am struggling on how to configure my Startup.cs file to look for the default file in the dist folder.

Currently I have...

```<code>        app.UseDefaultFiles();
        app.UseStaticFiles();
</code>```

In my startup.cs file but it will not use the index.html that is generated in my dist folder.  Any ideas on what I need to change?  The docs do not give much reference from what I could find on how to do this.

Thanks.

答:
In net core 6 you have to configure it in WebApplication.CreateBuilder via WebApplicationOptions

```<code>var builder = WebApplication.CreateBuilder(new WebApplicationOptions {
Args = args,
WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist")});
</code>```

That's it. Also there you can change ContentRootPath. Only this thing works for me. So, my empty core project Program.cs look like this:

```<code>var builder = WebApplication.CreateBuilder(new WebApplicationOptions {
    Args = args,
    WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist")
});

var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();

app.Run();
</code>```

Body:
I am building an Angular 2 app and using .NET Core and Webpack to compile my static resources into a dist folder.  I am using a plugin that builds my index.html file and puts it in my wwwroot/dist folder but am struggling on how to configure my Startup.cs file to look for the default file in the dist folder.

Currently I have...

        app.UseDefaultFiles();
        app.UseStaticFiles();

In my startup.cs file but it will not use the index.html that is generated in my dist folder.  Any ideas on what I need to change?  The docs do not give much reference from what I could find on how to do this.

Thanks.

Body:
In net core 6 you have to configure it in WebApplication.CreateBuilder via WebApplicationOptions

var builder = WebApplication.CreateBuilder(new WebApplicationOptions {
Args = args,
WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist")});

That's it. Also there you can change ContentRootPath. Only this thing works for me. So, my empty core project Program.cs look like this:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions {
    Args = args,
    WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist")
});

var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();

app.Run();


问:
How do i split list using 2 different method in for LOOP?
I am sorry if I am unable to put out the question properly. But here is my CODE

```<code>data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

</code>```

Output result

```<code>data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

What I want to do?

if

```<code>data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']
</code>```

I want to be able to loop and split data list using the 2 method

```<code>re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]
</code>```

P.S: Output result can be in same or similar format

I tried this Code

```<code>data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)
</code>```

Result

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

Result I want

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']
</code>```

Thank you for taking your time to answer my question..
really appreciate it.

答:
You can remove all the None values in your code:</p>
```<code>data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  dk = list(filter(lambda a: a != None, dk)) #This removes all the None values from your list
  print(dk)
</code>```

Body:
I am sorry if I am unable to put out the question properly. But here is my CODE

data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

Output result

data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']

What I want to do?

if

data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']

I want to be able to loop and split data list using the 2 method

re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]

P.S: Output result can be in same or similar format

I tried this Code

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)

Result

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']

Result I want

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']

Thank you for taking your time to answer my question..
really appreciate it.

Body:
You can remove all the None values in your code:

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  dk = list(filter(lambda a: a != None, dk)) #This removes all the None values from your list
  print(dk)


问:
Vue.js component click event not finding method
I'm fairly new to VUE.JS and I'm trying to integrate it into an MVC project.

In my MVC view I have my app div.

```<code>@RenderPage("~/Views/Product/Templates/product-details-template.cshtml")

<div id="app">
      <product-details-component></product-details-component>
</div>
</code>```

The component is rendering fine and fetching the database for data which also works fine.

```<code><template id="product-details-container">
        <div class="wrapper">
            <div class="container-body">
                <div class="container-header">
                    <h1>3 Year Discount</h1>
                    <span class="details"><i   class="fa fa-long-arrow-left"></i> Back to Product Details</span>
                </div>
                <div class="container-table">
                    <table class="table-product-details">
                        <tr>
                            <td on:click="UpdateProduct" class="table-title spaceUnder">Description: </td>
                            <td class="table-value spaceUnder">{{ description }}</td>
                            <td class="table-title spaceUnder">Product Code: </td>
                            <td class="table-value spaceUnder">{{ code }}</td>
                            <td class="table-title spaceUnder">Scheme Code: </td>
                            <td class="table-value spaceUnder">{{ schemecode }}</td>
                        </tr>
</code>```

But when I'm trying to fire an event / change the data of vm from the component it simply doesn't work.

Here is the actual js I removed the props from the component and a lot of data from the vm for better readability.

```<code> Vue.component('product-details-component', {
        template: '#product-details-container'
    });

    var vm = new Vue({
        el: '#app',
        data: {
            show: true
        },

        beforeMount() {

    this.UpdateProduct();

    },
    methods: {
        UpdateProduct: function() {
            axios.get('myapiurl' + this.productId)
                 .then(function(response) {

             var data = response.data;
             // assigning data to the vm

         });
    },
</code>```

When i try to run the application it just crashes and in the console it says "UpdateProduct is not defined".
Right Im not sure maybe the problem is because @RenderPage is running before the javascript and trying to attach the event to a method that doesn't exist at that time, but then why would my attribute bindig work? {{ description }} is working fine. I removed the code when I assign value to description and etc but it doesn't matter in this case. Any suggestions?

答:
change @click to @@click</p>
```<code>    <div id="app">
        <button @@click="count++">{{ count }}</button>
    </div>

    <script type="module">

            import { createApp } from 'vue'

            const app = createApp({
                data() {
                    return {
                        count: 0
                    }
                }
            })

            app.mount('#app')

   </script>
</code>```

Body:
I'm fairly new to VUE.JS and I'm trying to integrate it into an MVC project.

In my MVC view I have my app div.

@RenderPage("~/Views/Product/Templates/product-details-template.cshtml")

      <product-details-component></product-details-component>

The component is rendering fine and fetching the database for data which also works fine.

<template id="product-details-container">

3 Year Discount

                     Back to Product Details

                            Description:
                            {{ description }}
                            Product Code:
                            {{ code }}
                            Scheme Code:
                            {{ schemecode }}

But when I'm trying to fire an event / change the data of vm from the component it simply doesn't work.

Here is the actual js I removed the props from the component and a lot of data from the vm for better readability.

 Vue.component('product-details-component', {
        template: '#product-details-container'
    });

    var vm = new Vue({
        el: '#app',
        data: {
            show: true
        },

        beforeMount() {

    this.UpdateProduct();

    },
    methods: {
        UpdateProduct: function() {
            axios.get('myapiurl' + this.productId)
                 .then(function(response) {

             var data = response.data;
             // assigning data to the vm

         });
    },

When i try to run the application it just crashes and in the console it says "UpdateProduct is not defined".
Right Im not sure maybe the problem is because @RenderPage is running before the javascript and trying to attach the event to a method that doesn't exist at that time, but then why would my attribute bindig work? {{ description }} is working fine. I removed the code when I assign value to description and etc but it doesn't matter in this case. Any suggestions?

Body:
change @click to @@click

    <div id="app">
        <button @@click="count++">{{ count }}</button>
    </div>

    <script type="module">

            import { createApp } from 'vue'

            const app = createApp({
                data() {
                    return {
                        count: 0
                    }
                }
            })

            app.mount('#app')

   </script>


问:
CSS Menu not display sub UL in IE6
Im having trouble getting the following to display in ie6, everything works find in all browsers yet ie6 it seems to fall over on.

Instead of display:none ive also tried left:-9999999px yet it still doesnt seem to show/

http://jsfiddle.net/FVkzc/

答:
You'll need csshover.htc for IE6 to work properly.

Use it like so:

```<code>body {
    behavior: url('csshover.htc');
}
</code>```

The reason: IE6 doesn't do hover right on non-anchor elements.

Title: CSS Menu not display sub UL in IE6

Body:
You'll need csshover.htc for IE6 to work properly.

Use it like so:

body {
    behavior: url('csshover.htc');
}

The reason: IE6 doesn't do hover right on non-anchor elements.


答:
I've got two ideas for you:</p>
```<code>import re

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

# first approach (ugly): keep the current, simple code, then get rid of Nones
for i in data5:
    dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
    dk = list([s for s in dk if s != None])
    print(dk)

# second approach: condition to find out which case holds
for i in data5:
    dk = None
    if re.search(r'JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC', i):
        dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
    else:
        dk = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
    print(dk)
</code>```

Title: How do i split list using 2 different method in for LOOP?

Body:
I've got two ideas for you:

import re

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

# first approach (ugly): keep the current, simple code, then get rid of Nones
for i in data5:
    dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
    dk = list([s for s in dk if s != None])
    print(dk)

# second approach: condition to find out which case holds
for i in data5:
    dk = None
    if re.search(r'JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC', i):
        dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
    else:
        dk = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
    print(dk)


问:
getElementsByClassName not showing data in an element
I know there are a lot of questions regarding the getElementsByClassName not working, however I browsed through many and coudldnt find an answer for my situation.

Basically I have the following code:

```<code><script>

var res = localStorage.getItem('img');
    if(res == null){
            const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
            res  = myList[Math.floor(Math.random() * myList.length)];
            localStorage.setItem('img', res);
        }
console.log(res);

document.getElementsByClassName("emoji").innerHTML = res
</code>```

And several spans with same class:

```<code><span class="emoji" style="font-size: 40px !important;"></span>
</code>```

The problem is that the "res" doesn't print anything in span.

The console log prints everything fine and LS stores the information perfectly .

I have tried with ID's:

```<code>document.getElementsById("emoji").innerHTML = res
</code>```

And it works perfectly, however only with the first div (as it should i suppose).

What could I be doing wrong in this situation?

Maybe I am not able to see a very simple mistake in my code.

答: Multiple elements can have the same class name. getElementsByClassName returns an array of elements that have the class name (it's Elements not Element). So if you have only 1 element with that class name, you can do document.getElementsByClassName("emoji")[0].innerHTML = res.


问:
pgadmin 4, cannot find "edit data"
I read the Q/A "How to insert a row in postgreSQL pgAdmin?" from enter link description here
, but it's for pgAdmin 3.

I just installed postgreSQL 9.6.2 with pgAdmin 4, but could not find the option shown in pgAdmin 3, which you can click to have an excel-like window where you can add and update data in a table without using SQL language (as per @KarelG). Does anyone know whether it stills exist in postgreSQL 9.6.2 with pgAdmin 4? Thanks.

答:
I had the same trouble. Trying to find out some short keys, I found using F6 key pretty useful.

Query tool -> F5

It will run the current query in the query editor.

Query tool -> Edit some cells -> F6

It will save the current changes to the database.

Check the query history to confirm what happend exactly.

Title: pgadmin 4, cannot find "edit data"


问:
Terraform Include parent uri with dynamic parameter in child uri for AWS API Gateway
I want to create a endpoint like user/<user_id>/info through aws_api_gateway using terraform

I am able to create endpoint till /user/<user_id>

But how to include <user_id> in the resource for "info"

Here is the code for "info" part:

```<code>resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"

</code>```

When I try this, the url for info resolves to http://root_api/user/<user_id>/info.
Any help on how to inject <user_id> in this url ??

Thanks

答:
Figured Out the answer. This makes you accept any dynamic parameter into your integation uri no matter from where they appear in the ancestor chain</p>
```<code>resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
  request_parameters   =
  {
   "method.request.path.user_id" = true
  }
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"
  request_parameters   =
  {
   "integration.request.path.user_id" = "method.request.path.user_id"
  }
}
</code>```

Body:
I want to create a endpoint like user/<user_id>/info through aws_api_gateway using terraform

I am able to create endpoint till /user/<user_id>

But how to include <user_id> in the resource for "info"

Here is the code for "info" part:

resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"

When I try this, the url for info resolves to http://root_api/user/<user_id>/info.
Any help on how to inject <user_id> in this url ??

Thanks

Body:
Figured Out the answer. This makes you accept any dynamic parameter into your integation uri no matter from where they appear in the ancestor chain

resource "aws_api_gateway_resource" "info" {
  rest_api_id = aws_api_gateway_rest_api.app.id
  parent_id   = aws_api_gateway_resource.user.id
  path_part   = "info"
}

resource "aws_api_gateway_method" "info" {
  rest_api_id   = aws_api_gateway_rest_api.app.id
  resource_id   = aws_api_gateway_resource.info.id
  http_method   = "GET"
  authorization = "NONE"
  request_parameters   =
  {
   "method.request.path.user_id" = true
  }
}

resource "aws_api_gateway_integration" "info" {
  rest_api_id          = aws_api_gateway_rest_api.app.id
  resource_id          = aws_api_gateway_resource.info.id
  http_method          = aws_api_gateway_method.info.http_method
  type                 = "HTTP_PROXY"
  uri                  = "http://root_api/user/<user_id>/info"
  request_parameters   =
  {
   "integration.request.path.user_id" = "method.request.path.user_id"
  }
}


答:
If you specify classname so you have to give index to the class as it puts response only in the first element in the case of id, it is unique but in case of class you have to specify.

```<code>document.getElementsByClassName("emoji")[0].innerHTML = res;
</code>```

Title: getElementsByClassName not showing data in an element

Body:
I know there are a lot of questions regarding the getElementsByClassName not working, however I browsed through many and coudldnt find an answer for my situation.

Basically I have the following code:

Body:
If you specify classname so you have to give index to the class as it puts response only in the first element in the case of id, it is unique but in case of class you have to specify.

document.getElementsByClassName("emoji")[0].innerHTML = res;


问:
page permission check with react router v6
I'm using useRoutes of React Router v6 to render routes, and I want to check permissions every time user access the page .

I found below example,but is there any other way to use a wrapper for each page?
like next middleware.

https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx

about useRoutes : https://reactrouter.com/docs/en/v6/examples/route-objects

this is my code. it works but the problem is that NavBar is also invisible when an unauthorized user approaches.

```<code>function App() {
...
  const routes: RouteObject[] = [
    {
      path: "/",
      element: <RequireAuth role={"role test"} component={<NavBar />}></RequireAuth>,
      children: [
        { index: true, element: <Home /> },
        {
          path: "/pricing",
          element: <Pricing />,
        },
        {
          path: "/guide",
          element: <Guide />,
        },
        {
          path: "/consult",
          element: <Consult />,
        },
        { path: "*", element:  <Error /> }
      ]
    }
  ];
  let element = useRoutes(routes);

  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        {element}
      </ThemeProvider>
    </Fragment>
  );

</code>```

答:
...the problem is that NavBar is also invisible when an unauthorized user
approaches.

Move the Navbar component outside the routes configuration so it is always rendered regardless of route or auth status.

```<code>const routes: RouteObject[] = [
  {
    path: "/",
    element: <RequireAuth role={"role test"} />,
    children: [
      { index: true, element: <Home /> },
      {
        path: "/pricing",
        element: <Pricing />,
      },
      {
        path: "/guide",
        element: <Guide />,
      },
      {
        path: "/consult",
        element: <Consult />,
      },
      { path: "*", element:  <Error /> }
    ]
  }
];

function App() {
  ...

  const element = useRoutes(routes);

  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <NavBar /> // <-- render NavBar outside routes
        {element}
      </ThemeProvider>
    </Fragment>
  );
}
</code>```

Body:
I'm using useRoutes of React Router v6 to render routes, and I want to check permissions every time user access the page .

I found below example,but is there any other way to use a wrapper for each page?
like next middleware.

https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx

about useRoutes : https://reactrouter.com/docs/en/v6/examples/route-objects

this is my code. it works but the problem is that NavBar is also invisible when an unauthorized user approaches.

function App() {
...
  const routes: RouteObject[] = [
    {
      path: "/",
      element: <RequireAuth role={"role test"} component={<NavBar />}></RequireAuth>,
      children: [
        { index: true, element: <Home /> },
        {
          path: "/pricing",
          element: <Pricing />,
        },
        {
          path: "/guide",
          element: <Guide />,
        },
        {
          path: "/consult",
          element: <Consult />,
        },
        { path: "*", element:  <Error /> }
      ]
    }
  ];
  let element = useRoutes(routes);

  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        {element}
      </ThemeProvider>
    </Fragment>
  );

Body:
...the problem is that NavBar is also invisible when an unauthorized user
approaches.

Move the Navbar component outside the routes configuration so it is always rendered regardless of route or auth status.

const routes: RouteObject[] = [
  {
    path: "/",
    element: <RequireAuth role={"role test"} />,
    children: [
      { index: true, element: <Home /> },
      {
        path: "/pricing",
        element: <Pricing />,
      },
      {
        path: "/guide",
        element: <Guide />,
      },
      {
        path: "/consult",
        element: <Consult />,
      },
      { path: "*", element:  <Error /> }
    ]
  }
];

function App() {
  ...

  const element = useRoutes(routes);

  return (
    <Fragment>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <NavBar /> // <-- render NavBar outside routes
        {element}
      </ThemeProvider>
    </Fragment>
  );
}


问:
Trouble understanding veganCovEllipse covariance ellipse calculation
I'm having issues understanding how the veganCovEllipse() function from the vegan package v 2.5-7 calculates an ellipse.

```<code>veganCovEllipse <- function (cov, center = c(0, 0), scale = 1, npoints = 100)
{
  theta <- (0:npoints) * 2 * pi/npoints
  Circle <- cbind(cos(theta), sin(theta))
  t(center + scale * t(Circle %*% chol(cov)))
}
</code>```

Specifically, what is occurring in the last line within the function. This function calculates an ellipse based off of a covariance matrix, but I'm not sure what type of ellipse is calculated. Would this be an error ellipse? If so, what does the scale argument represent?
Here's an example creating ellipses from PCA scores:

```<code>library(stats)

# fit pca on mtcars dataset
mtcars_pca <- prcomp(mtcars[,c(1:7,10,11)], center = TRUE,scale. = TRUE)

# dataframe of pc1 and pc2 scores
pcs <- data.frame(PC1 = mtcars_pca$x[,1],
                  PC2 = mtcars_pca$x[,2])

# calculate weighted covariance of PC1 and PC2
weight_cov <- cov.wt(cbind(pcs$PC1, pcs$PC2), wt=rep(1/length(pcs$PC1), length(pcs$PC1)))$cov

# calculate mean of PC1 and PC2, used as the center of the ellipse
center <- c(mean(pcs$PC1),
            mean(pcs$PC2))

# fit ellipse given weighted covariance and center
ellipse <- veganCovEllipse(weight_cov, center)
</code>```

答:
veganCovEllipse is not an exported function. This means that it is not intended for interactive use, but it is a support function only to be called from other functions in vegan. Therefore it is not documented. However, the answer is simple: it can calculate any kind of ellipse depending on the input. In vegan the function is called for instance from ordiellipse and there it can draw standard error ellipses, "confidence" ellipses (standard error multiplied by some value picked from statistical distribution), standard deviation ellipses, standard deviation ellipses multiplied by similar constants as standard errors, or enclosing ellipses that contain all points of a group, depending on the input to the function. In showvarparts function it is just re-used to draw circles. Actually veganCovEllipse does not fit anything: it just calculates the coordinates to draw what you asked it to draw, and your input defines the shape, size, orientation and location of the ellipse coordinates.

There are other functions in other packages that do the same: return you the points needed to plot an ellipse from your input data. For instance, the standard (recommended) package cluster makes similar calculations in non-exported functions cluster:::ellipsoidPoints with effectively the same mathematics, but in completely different way. This function is non-exported as well, and it is intended to be called from user function cluster::predict.ellipsoid. The vegan implementation is similar as in the ellipse function in the car package, where these calculations are embedded in that function and cannot be called separately from car::ellipse.

Body:
I'm having issues understanding how the veganCovEllipse() function from the vegan package v 2.5-7 calculates an ellipse.

veganCovEllipse <- function (cov, center = c(0, 0), scale = 1, npoints = 100)
{
  theta <- (0:npoints) * 2 * pi/npoints
  Circle <- cbind(cos(theta), sin(theta))
  t(center + scale * t(Circle %*% chol(cov)))
}

Specifically, what is occurring in the last line within the function. This function calculates an ellipse based off of a covariance matrix, but I'm not sure what type of ellipse is calculated. Would this be an error ellipse? If so, what does the scale argument represent?
Here's an example creating ellipses from PCA scores:

library(stats)

# fit pca on mtcars dataset
mtcars_pca <- prcomp(mtcars[,c(1:7,10,11)], center = TRUE,scale. = TRUE)

# dataframe of pc1 and pc2 scores
pcs <- data.frame(PC1 = mtcars_pca$x[,1],
                  PC2 = mtcars_pca$x[,2])

# calculate weighted covariance of PC1 and PC2
weight_cov <- cov.wt(cbind(pcs$PC1, pcs$PC2), wt=rep(1/length(pcs$PC1), length(pcs$PC1)))$cov

# calculate mean of PC1 and PC2, used as the center of the ellipse
center <- c(mean(pcs$PC1),
            mean(pcs$PC2))

# fit ellipse given weighted covariance and center
ellipse <- veganCovEllipse(weight_cov, center)


问:
When do custom table view cells dealloc?
I was under the impression that table view cells never got dealloced until the app crash because you are able to resuse them. But when I was profiling my table view, I realized that something was calling dealloc on my custom cell. What exactly dealloc's custom cells and can I stop it?</p>

答: The semantics of the dequeueReusableCellWithIdentifier: selector are opaque (as far as I know). If you want complete control of your table view cells, don't use that selector to get a cell: just construct a new one or use your own pool for reuse.


问:
Why special behavior of spilling background-color to all its parents only provided to Body-tag and NOT to any other tag?
Based on: Setting background color for  element (without height set to 100%) apply to the whole viewport

The question will only rise, when  tag is not touching the browser-inside-boundries, ie, we try giving margin to  element (so that it also doesn't touch) the browser window. To extend this example, again, we'll give margin to  tag, so that there is a 20px gap between html element and browser-inside-area.

Now, lets see what happens?

Case-I:

html {margin:20px; border:2px solid blue;}
body {margin:20px; border:2px solid brown;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Case-II:

html {margin:20px; border:2px solid blue;}
body {margin:20px; border:2px solid brown; background:pink;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Now, how stupid is it - to spill the 'background of body' to  element, and to the area of viewport/browser-inside-window? Though, this is intended behavior, no-doubt? but doesn't this create anomaly or wrong-implementation of background and element integrity?

Note: We may provide background of html-tag also, which would take place as follows? But, then - in earlier example if spilling is happening ...should'nt it be consistant? And, the spill of div's background, should go ... and even body & html - should have been painted yellow? (in case-I), Why the inconsistency?

Case-III:

html {margin:20px; border:2px solid blue; background:gray;}
body {margin:20px; border:2px solid brown; background:pink;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Though :root cannot have its own background, but  can, so again in Case-II, body's pink color should have stopped and NOT painted  background, as this is a legal element and can have its own background. Am I wrong?

答:
Because the spec says so:

For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element. Such backgrounds must also be anchored at the same point as they would be if they were painted only for the root element.

Body:
Based on: Setting background color for  element (without height set to 100%) apply to the whole viewport

The question will only rise, when  tag is not touching the browser-inside-boundries, ie, we try giving margin to  element (so that it also doesn't touch) the browser window. To extend this example, again, we'll give margin to  tag, so that there is a 20px gap between html element and browser-inside-area.

Now, lets see what happens?

Case-I:

html {margin:20px; border:2px solid blue;}
body {margin:20px; border:2px solid brown;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}

Case-II:

html {margin:20px; border:2px solid blue;}
body {margin:20px; border:2px solid brown; background:pink;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}

Now, how stupid is it - to spill the 'background of body' to  element, and to the area of viewport/browser-inside-window? Though, this is intended behavior, no-doubt? but doesn't this create anomaly or wrong-implementation of background and element integrity?

Note: We may provide background of html-tag also, which would take place as follows? But, then - in earlier example if spilling is happening ...should'nt it be consistant? And, the spill of div's background, should go ... and even body & html - should have been painted yellow? (in case-I), Why the inconsistency?

Case-III:

html {margin:20px; border:2px solid blue; background:gray;}
body {margin:20px; border:2px solid brown; background:pink;}
div {margin:20px; border:2px solid red; background:yellow; height:200px; width:200px;}

Though :root cannot have its own background, but  can, so again in Case-II, body's pink color should have stopped and NOT painted  background, as this is a legal element and can have its own background. Am I wrong?


问:
Paypal with Braintree saying "Merchant account not found"
I tried integrating PayPal using braintree and following this tutorial. I end up getting an error: Merchant account not found - screenshot.

I am using Swift 3 and Xcode 8.1.

here is my viewDidLoad

These are all required updates in my app:

ScreenShot 1

ScreenShot 2

ScreenShot 3

ScreenShot 4

ScreenShot 5

Any help will be appreciated!

答: In my case, it was not working due to the selection of country during account creation where Paypal does not operate. I just create a new account with the country where Paypal operates and it solved this issue.</p>


问:
How to convert dataframe with datetimes to daily time series in + mean aggregation R
I have a dataframe that looks like this:

```<code>Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00", "2009-01-01 10:25:00",
                     "2009-01-02 07:45:00", "2009-01-02 15:32:00", "2009-01-02 11:15:00",
                     "2009-01-02 12:35:00")
Cust_ID = c("1214", "2643", "31231", "41244", "1214", "15317", "51591")
Wait_Time_Mins = c("54","43","88","94","12","130", "170")
df_have = data.frame(Arrival_DateTime, Cust_ID, Wait_Time_Mins)
</code>```

and want to convert it so I get the number of customer visits per day, and also their average wait time per day, so it looks something like this:

```<code>dates = c("2009-01-01", "2009-01-02")
num_visits = c("3", "4")
avg_wait_time = c("61.7","101.5")
df_want = data.frame(dates, num_visits, avg_wait_time)
</code>```

How would I go about doing this?

Similarly, is there a way to do monthly aggregations as well?

Body:
I have a dataframe that looks like this:

Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00", "2009-01-01 10:25:00",
                     "2009-01-02 07:45:00", "2009-01-02 15:32:00", "2009-01-02 11:15:00",
                     "2009-01-02 12:35:00")
Cust_ID = c("1214", "2643", "31231", "41244", "1214", "15317", "51591")
Wait_Time_Mins = c("54","43","88","94","12","130", "170")
df_have = data.frame(Arrival_DateTime, Cust_ID, Wait_Time_Mins)

and want to convert it so I get the number of customer visits per day, and also their average wait time per day, so it looks something like this:

dates = c("2009-01-01", "2009-01-02")
num_visits = c("3", "4")
avg_wait_time = c("61.7","101.5")
df_want = data.frame(dates, num_visits, avg_wait_time)

How would I go about doing this?

Similarly, is there a way to do monthly aggregations as well?

Body:
Using aggregate().

aggregate(as.double(Wait_Time_Mins) ~ as.Date(Arrival_DateTime), df_have,
          \(x) c(length(x), mean(x))) |>
  do.call(what=data.frame) |>
  setNames(c('date', 'num_visits', 'avg_wait_time'))
#         date num_visits avg_wait_time
# 1 2009-01-01          3      61.66667
# 2 2009-01-02          4     101.50000

Note: R >= 4.1 used.

Data:

df_have <- structure(list(Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00",
"2009-01-01 10:25:00", "2009-01-02 07:45:00", "2009-01-02 15:32:00",
"2009-01-02 11:15:00", "2009-01-02 12:35:00"), Cust_ID = c("1214",
"2643", "31231", "41244", "1214", "15317", "51591"), Wait_Time_Mins = c("54",
"43", "88", "94", "12", "130", "170")), class = "data.frame", row.names = c(NA,
-7L))


问:
How to deal with SettingWithCopyWarning in Pandas

Background

I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:

E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
```
<p>I want to know what exactly it means?  Do I need to change something?</p>
<p>How should I suspend the warning if I insist to use <code>quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE</code>?</p>
<h2>The function that gives warnings</h2>
```def _decode_stock_quote(list_of_150_stk_str):
    """decode the webpage and return dataframe"""

    from cStringIO import StringIO

    str_of_all = "".join(list_of_150_stk_str)

    quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
    quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
    quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
    quote_df['TClose'] = quote_df['TPrice']
    quote_df['RT']     = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1)
    quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
    quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
    quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19)
    quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312')
    quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])

    return quote_df
```
<h2>More warning messages</h2>
<pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
</code>```

答:
In my case, I would create a new column based on the index, but I got the same warning as you:

```<code>df_temp["Quarter"] = df_temp.index.quarter
</code>```

I use insert() instead of direct assignment, and it works for me:

```<code>df_temp.insert(loc=0, column='Quarter', value=df_temp.index.quarter)
</code>```

Body:
Background

I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:

E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE

I want to know what exactly it means?  Do I need to change something?

How should I suspend the warning if I insist to use quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE?

The function that gives warnings

def _decode_stock_quote(list_of_150_stk_str):
    """decode the webpage and return dataframe"""

    from cStringIO import StringIO

    str_of_all = "".join(list_of_150_stk_str)

    quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
    quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
    quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
    quote_df['TClose'] = quote_df['TPrice']
    quote_df['RT']     = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1)
    quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
    quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
    quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19)
    quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312')
    quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])

    return quote_df

More warning messages

E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])

Body:
In my case, I would create a new column based on the index, but I got the same warning as you:

df_temp["Quarter"] = df_temp.index.quarter

I use insert() instead of direct assignment, and it works for me:

df_temp.insert(loc=0, column='Quarter', value=df_temp.index.quarter)


问:
Why cannot I set the value attribute of texarea by setAttribute?
```<code><textarea value="hello" id="id1"></textarea>
</code>```

The above textarea does not show "hello" in it.

document.getElementById('id1').setAttribute("value", "hello");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea value="hello" id="id1"></textarea></code>```

This textarea  does not show "hello", either. But the following one does show "hello" in it, why?

document.getElementById('id1').value = "hello";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea value="hello" id="id1"></textarea></code>```

The setAttribute works perfectly for <input> element:

document.getElementById('id1').setAttribute("value", "hello");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value="" id="id1" /></code>```

答:
A textarea does not have a value attribute to set using setAttribute - it has a value property you set directly using the element.value

Compare

```<code><textarea>value</textarea>
</code>```

to

```<code><input value="value"/>
</code>```

where value is an attribute of the input element

Body:
<textarea value="hello" id="id1"></textarea>

The above textarea does not show "hello" in it.

document.getElementById('id1').setAttribute("value", "hello");

<textarea value="hello" id="id1"></textarea>

This textarea  does not show "hello", either. But the following one does show "hello" in it, why?

document.getElementById('id1').value = "hello";

<textarea value="hello" id="id1"></textarea>

The setAttribute works perfectly for <input> element:

document.getElementById('id1').setAttribute("value", "hello");

<input value="" id="id1" />

Body:
A textarea does not have a value attribute to set using setAttribute - it has a value property you set directly using the element.value

Compare

<textarea>value</textarea>

to

<input value="value"/>

where value is an attribute of the input element