问:
List to string with separators
I am trying to pass a command line arguments to AWS lambda as a event json.
I have a list out of the command line args like:

```<code>['engine', '-e', '100', '-w', '4']
</code>```

When I pass this list I want to it get passed as:

```<code>'engine', '-e', '100', '-w', '4'
</code>```

I am trying to use it like this:

listcommd = ['engine', '-e', '100', '-w', '4']
command = ["--bucket", "mybucket", f"{listcommand}"]
```
<p>I want the end result to look like:</p>
<pre class="lang-py prettyprint-override"><code>command = ["--bucket", "mybucket", 'engine', '-e', '100', '-w', '4']
</code>```

but it is looking like:

command = ["--bucket", "mybucket", "['engine', '-e', '100', '-w', '4']"]
```

答:
Lists support concatenation. Just do this:

command = ["--bucket", "mybucket"] + listcommand
```

Title: List to string with separators

Body:
I am trying to pass a command line arguments to AWS lambda as a event json.
I have a list out of the command line args like:

['engine', '-e', '100', '-w', '4']

When I pass this list I want to it get passed as:

'engine', '-e', '100', '-w', '4'

I am trying to use it like this:

listcommd = ['engine', '-e', '100', '-w', '4']
command = ["--bucket", "mybucket", f"{listcommand}"]

I want the end result to look like:

command = ["--bucket", "mybucket", 'engine', '-e', '100', '-w', '4']

but it is looking like:

command = ["--bucket", "mybucket", "['engine', '-e', '100', '-w', '4']"]


来源: stackexchange

问:
enum class as array index
I made an enum as:

```<code>enum class KeyPressSurfaces {
    KEY_PRESS_SURFACE_DEFAULT,
    KEY_PRESS_SURFACE_UP,
    KEY_PRESS_SURFACE_DOWN,
    KEY_PRESS_SURFACE_LEFT,
    KEY_PRESS_SURFACE_RIGHT,
    KEY_PRESS_SURFACE_TOTAL
};
</code>```

and later on I attempt to define an array as I typed below, but I received the error, size of array 'KEY_PRESS_SURFACES' has non-integral type 'KeyPressSurfaces'

```<code>SDL_Surface*KEY_PRESS_SURFACES[KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL];
</code>```

I understand the error fine, but I don't know where to move the KeyPressSurfaces to qualify the constant in the enum.

I also realize I could just use an enum and not an enum class, but I feel like this should work, and I want to learn how to do this.

Any response/advice?

答:
You can use a namespace and anonymous enum. So you can get rid of these ugly prefixes and use enum items as index.</p>
```<code>namespace KeyPressSurfaces
{
    enum
    {
        DEFAULT = 0,
        UP,
        DOWN,
        LEFT,
        RIGHT,
        TOTAL
    };
}

SDL_Surface* KEY_PRESS_SURFACES[KeyPressSurfaces::TOTAL];
</code>```

ContentLicense: CC BY-SA 4.0

Title: enum class as array index

Body:
I made an enum as:

enum class KeyPressSurfaces {
    KEY_PRESS_SURFACE_DEFAULT,
    KEY_PRESS_SURFACE_UP,
    KEY_PRESS_SURFACE_DOWN,
    KEY_PRESS_SURFACE_LEFT,
    KEY_PRESS_SURFACE_RIGHT,
    KEY_PRESS_SURFACE_TOTAL
};

and later on I attempt to define an array as I typed below, but I received the error, size of array 'KEY_PRESS_SURFACES' has non-integral type 'KeyPressSurfaces'

SDL_Surface*KEY_PRESS_SURFACES[KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL];

I understand the error fine, but I don't know where to move the KeyPressSurfaces to qualify the constant in the enum.

I also realize I could just use an enum and not an enum class, but I feel like this should work, and I want to learn how to do this.

Any response/advice?

Body:
You can use a namespace and anonymous enum. So you can get rid of these ugly prefixes and use enum items as index.

namespace KeyPressSurfaces
{
    enum
    {
        DEFAULT = 0,
        UP,
        DOWN,
        LEFT,
        RIGHT,
        TOTAL
    };
}

SDL_Surface* KEY_PRESS_SURFACES[KeyPressSurfaces::TOTAL];


问:
Any Python Library Produces Publication Style Regression Tables
I've been using Python for regression analysis. After getting the regression results, I need to summarize all the results into one single table and convert them to LaTex (for publication). Is there any package that does this in Python? Something like estout in Stata that gives the following table:

答:
In addition to @Karl D. 's great answer with Statsmodels as_latex method, you can also check out the pystout package.

```<code>!pip install pystout
</code>```
```<code>import pandas as pd
from sklearn.datasets import load_iris
import statsmodels.api as sm
from pystout import pystout
</code>```
```<code>data = load_iris()
df = pd.DataFrame(data = data.data, columns = data.feature_names)
df.columns = ['s_len', 's_w', 'p_len', 'p_w']

y = df['p_w']

X = df[['s_len', 's_w', 'p_len']]
m1 = sm.OLS(y, X).fit()

X = df[['s_len', 's_w']]
m2 =  sm.OLS(y, X).fit()

X = df[['s_len']]
m3 =  sm.OLS(y, X).fit()

pystout(models=[m1, m2, m3],
        file='test_table.tex',
        addnotes=['Note above','Note below'],
        digits=2,
        endog_names=['petal width', 'petal width', 'petal width'],
        varlabels={'const':'Constant',
                   'displacement':'Disp','mpg':'MPG'},
        mgroups={'First Group':[1,2],'Second Group':3},
        modstat={'nobs':'Obs','rsquared_adj':'Adj. R\sym{2}','fvalue':'F-stat'}
        )

</code>```

Don't spend hours like me trying to print out pystout, the LateX output is directly written on the .tex document you pass for file.

When compiled, the output looks like this:

ContentLicense: CC BY-SA 3.0

Body:
In addition to @Karl D. 's great answer with Statsmodels as_latex method, you can also check out the pystout package.

!pip install pystout

import pandas as pd
from sklearn.datasets import load_iris
import statsmodels.api as sm
from pystout import pystout

data = load_iris()
df = pd.DataFrame(data = data.data, columns = data.feature_names)
df.columns = ['s_len', 's_w', 'p_len', 'p_w']

y = df['p_w']

X = df[['s_len', 's_w', 'p_len']]
m1 = sm.OLS(y, X).fit()

X = df[['s_len', 's_w']]
m2 =  sm.OLS(y, X).fit()

X = df[['s_len']]
m3 =  sm.OLS(y, X).fit()

pystout(models=[m1, m2, m3],
        file='test_table.tex',
        addnotes=['Note above','Note below'],
        digits=2,
        endog_names=['petal width', 'petal width', 'petal width'],
        varlabels={'const':'Constant',
                   'displacement':'Disp','mpg':'MPG'},
        mgroups={'First Group':[1,2],'Second Group':3},
        modstat={'nobs':'Obs','rsquared_adj':'Adj. R\sym{2}','fvalue':'F-stat'}
        )

Don't spend hours like me trying to print out pystout, the LateX output is directly written on the .tex document you pass for file.

When compiled, the output looks like this:


问:
Testing PayPal payouts
I've seen the requirements for the Paypal Payout. It says that accounts should be business type and that the platform account should request a payout access to PayPal. I'm from the Philippines, but my client is in Australia so they can make the business account and request payout access. My question is, once we got access to payouts, can we test the payout on sandbox mode? or the payout only works with real paypal credits/money?

答: Payouts always works for sandbox Business accounts of countries that support payouts. Create such accounts in the developer dashboard, logging in with any live PayPal account.</p>

Title: Testing PayPal payouts


问:
How to check whether a dataframe column value is not present in another column of same dataframe if nan value is present in python
Can anyone help me out to check whether a dataframe column(Code) value is not present in another column(Place) of same dataframe in python

Below is the dataframe (df):

```<code>                Place     Code
0   Mumbai, MH34, IND     MH34
1                 NaN    KOL21
2     Pune, PU341, In    PU125
3       Chennai, CH54     CH54
4  Delhi, DL78, India      NaN
5     Hy, HYD7687, IN  HYD7687
</code>```

I am trying to find the new dataframe if "Code" column value is not present in "Place" column if "Place" column value is non null with the below codes, but not getting the desired output.

```<code>df1 = df[~df["Code"].isin(df["Place"].values)]
</code>```

Expected Output (df1):

```<code>            Place   Code
0  Pune, PU341, In  PU125
</code>```

答:
I'm sure this can be done in a quicker way, but this is an approach I'd take which answers your question. In short, it may be best to create a validation column that enables you to filter where your condition is equal to "False."

```<code>import pandas as pd, numpy as np

# sample df
d = {'Place': ['Mumbai, MH34, IND', np.NaN, 'Pune, PU341, In','Chennai, CH54','Delhi, DL78, India','Hy, HYD7687, IN'],
     'Code': ['MH34', 'KOL21', 'PU125','CH54', np.NaN, 'HYD7687']}
df = pd.DataFrame(data=d)

# convert to string to avoid float errors
df = df.replace(np.NaN,'')

# create a temporary column; also converting to list
df['Place_'] = df['Place'].str.split(',')

# loop each row to test if Code is in Place
lst = []
for row in range(len(df)):
    if df.iloc[row,1] in df.iloc[row,0]:
        lst.append(True)
    else:
        lst.append(False)

# create validation column
df['Test'] = lst

# delete temporary column
del df['Place_']

# filter to see items to check whether a
# dataframe column(Code) value is not present in another column(Place)
df[(df['Place'] != '') & (df['Test'] == False)]
</code>```

Desired Output:

```<code>     Place               Code   Test
2    Pune, PU341, In     PU125  False
</code>```

Body:
Can anyone help me out to check whether a dataframe column(Code) value is not present in another column(Place) of same dataframe in python

Below is the dataframe (df):

                Place     Code
0   Mumbai, MH34, IND     MH34
1                 NaN    KOL21
2     Pune, PU341, In    PU125
3       Chennai, CH54     CH54
4  Delhi, DL78, India      NaN
5     Hy, HYD7687, IN  HYD7687

I am trying to find the new dataframe if "Code" column value is not present in "Place" column if "Place" column value is non null with the below codes, but not getting the desired output.

df1 = df[~df["Code"].isin(df["Place"].values)]

Expected Output (df1):

            Place   Code
0  Pune, PU341, In  PU125

Body:
I'm sure this can be done in a quicker way, but this is an approach I'd take which answers your question. In short, it may be best to create a validation column that enables you to filter where your condition is equal to "False."

import pandas as pd, numpy as np

# sample df
d = {'Place': ['Mumbai, MH34, IND', np.NaN, 'Pune, PU341, In','Chennai, CH54','Delhi, DL78, India','Hy, HYD7687, IN'],
     'Code': ['MH34', 'KOL21', 'PU125','CH54', np.NaN, 'HYD7687']}
df = pd.DataFrame(data=d)

# convert to string to avoid float errors
df = df.replace(np.NaN,'')

# create a temporary column; also converting to list
df['Place_'] = df['Place'].str.split(',')

# loop each row to test if Code is in Place
lst = []
for row in range(len(df)):
    if df.iloc[row,1] in df.iloc[row,0]:
        lst.append(True)
    else:
        lst.append(False)

# create validation column
df['Test'] = lst

# delete temporary column
del df['Place_']

# filter to see items to check whether a
# dataframe column(Code) value is not present in another column(Place)
df[(df['Place'] != '') & (df['Test'] == False)]

Desired Output:

     Place               Code   Test
2    Pune, PU341, In     PU125  False


问:
SQL UNION query with order by giving syntax error on "("
I'm trying to select 2 oldest females and 2 oldest males using 1 query. The union keeps giving me a syntax error near "(". Both queries work independantly but after union I get error.</p>
```<code>-- create a table
CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  gender TEXT NOT NULL,
  age INTEGER NOT NULL
);

-- insert some values
INSERT INTO students VALUES (1, 'Ryan', 'M', 23);
INSERT INTO students VALUES (2, 'Joanna', 'F', 22);
INSERT INTO students VALUES (3, 'Alex', 'F', 25);
INSERT INTO students VALUES (4, 'Ted', 'M', 21);
INSERT INTO students VALUES (5, 'June', 'F', 26);
INSERT INTO students VALUES (6, 'Rose', 'F', 24);
INSERT INTO students VALUES (7, 'Jack', 'M', 25);

-- select * from students;

SELECT * FROM
(SELECT name FROM students WHERE GENDER = 'F' ORDER BY age DESC LIMIT 2)
UNION
(SELECT name FROM students WHERE GENDER = 'M' ORDER BY age DESC LIMIT 2);
</code>```

答:
Your online compliler uses not MySQL but SQLite!

Execute select sqlite_version(); - the output is '3.31.1'.

Use this:

WITH cte AS (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY gender ORDER BY age DESC) rn
     FROM students
     )
SELECT name
FROM cte
WHERE rn <= 2;
```

This code is correct for SQLite.

PS. Add ORDER BY if needed.

Body:
I'm trying to select 2 oldest females and 2 oldest males using 1 query. The union keeps giving me a syntax error near "(". Both queries work independantly but after union I get error.

-- create a table
CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  gender TEXT NOT NULL,
  age INTEGER NOT NULL
);

-- insert some values
INSERT INTO students VALUES (1, 'Ryan', 'M', 23);
INSERT INTO students VALUES (2, 'Joanna', 'F', 22);
INSERT INTO students VALUES (3, 'Alex', 'F', 25);
INSERT INTO students VALUES (4, 'Ted', 'M', 21);
INSERT INTO students VALUES (5, 'June', 'F', 26);
INSERT INTO students VALUES (6, 'Rose', 'F', 24);
INSERT INTO students VALUES (7, 'Jack', 'M', 25);

-- select * from students;

SELECT * FROM
(SELECT name FROM students WHERE GENDER = 'F' ORDER BY age DESC LIMIT 2)
UNION
(SELECT name FROM students WHERE GENDER = 'M' ORDER BY age DESC LIMIT 2);

Body:
Your online compliler uses not MySQL but SQLite!

Execute select sqlite_version(); - the output is '3.31.1'.

Use this:

WITH cte AS (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY gender ORDER BY age DESC) rn
     FROM students
     )
SELECT name
FROM cte
WHERE rn <= 2;

This code is correct for SQLite.

PS. Add ORDER BY if needed.


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

Team(teamID, teamName)

TeamMembers(membersID, teamID, membersStatusID)

Members(membersID, membersName)

Status(membersStatusID, statusName)

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

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

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

答:
```<code>SELECT
teamName,
b.[Number Of Members],
c.membersName AS [Captian]
FROM
Team
LEFT JOIN
(
SELECT
    COUNT(*) AS [Number Of Members],
    teamID
FROM
    TeamMembers
GROUP BY
    teamID
) AS b ON Team.teamID = c.teamID
LEFT JOIN
(
SELECT
    membersName,
    teamID
FROM
    Members
INNER JOIN
    TeamMembers ON Members.membersID = TeamMembers.membersID
INNER JOIN
    Status ON TeamMembers.memberStatusID = Status.memberStatusID AND Status.statusName = 'Captian'
) AS c ON c.teamID = Team.teamID
</code>```

May Work. Might need to tweak it though because of the group by in the b select statement. Also I wrote this in sql only since I dont know oracle syntax

Body:
SELECT
teamName,
b.[Number Of Members],
c.membersName AS [Captian]
FROM
Team
LEFT JOIN
(
SELECT
    COUNT(*) AS [Number Of Members],
    teamID
FROM
    TeamMembers
GROUP BY
    teamID
) AS b ON Team.teamID = c.teamID
LEFT JOIN
(
SELECT
    membersName,
    teamID
FROM
    Members
INNER JOIN
    TeamMembers ON Members.membersID = TeamMembers.membersID
INNER JOIN
    Status ON TeamMembers.memberStatusID = Status.memberStatusID AND Status.statusName = 'Captian'
) AS c ON c.teamID = Team.teamID

May Work. Might need to tweak it though because of the group by in the b select statement. Also I wrote this in sql only since I dont know oracle syntax


问:
How to send an embed with discord.js
I was wondering how to write an embed in discord.js. This is my current code: it is not functional. I get the warning: 'message is not defined' on message.channel.send I do not know how to fix this. I was hoping you guys could tell me how to fix this. js

// Embeding the image in An Embeded message
    const EmbededTweet = new MessageEmbed()
        .setColor('0x00FF00')
        .setTitle(`You made ${account} tweet this:`)
        .setImage(imageUrl)
        .setTimestamp();

    // replying with the Embeded message
    await interaction.reply({embeds: [EmbededTweet]});
```

答:
More code could be appreciated, but this is why I the error is showing up.

Explanation

You probably didn't declare "MessageEmbed" when you declared discord, and in your module.exports.

How to Solve

At the top of your code, you should have something like const Discord = require('discord.js'); change this to const { Discord, MessageEmbed } = require('discord.js');

Feel free to reply if this didn't work, have a good day.

Title: How to send an embed with discord.js


问:
Is there an easy way to custom fill null values in Pandas?
I have the following DataFrame:

```<code>     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  NaN  2.0  2.0  2.0
3  NaN  3.0  3.0  3.0
4  NaN  4.0  4.0  NaN
5  NaN  NaN  5.0  NaN
6  NaN  NaN  6.0  NaN
</code>```

I am working to generate visualizations with this data, and I need to fill the null values in a very specific way. I want to loop the existing values repeatedly for each column until the null values are all filled, so that the DataFrame looks like this:

```<code>     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  0.0  2.0  2.0  2.0
3  1.0  3.0  3.0  3.0
4  0.0  4.0  4.0  0.0
5  1.0  0.0  5.0  1.0
6  0.0  1.0  6.0  2.0
</code>```

Is there any convenient way to do this in Pandas?

答:
One option is with a for loop; the assumption is that the NaNs are at the end of each column, if any. Use np.place to fill the nulls :

 [np.place(df[col].to_numpy(),
           df[col].isna(),
           df[col].dropna().array)
   for col in df
   if df[col].hasnans]

[None, None, None]

df
     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  0.0  2.0  2.0  2.0
3  1.0  3.0  3.0  3.0
4  0.0  4.0  4.0  0.0
5  1.0  0.0  5.0  1.0
6  0.0  1.0  6.0  2.0
```

Note that np.place is an in place operation, no assignment is needed.

Body:
I have the following DataFrame:

     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  NaN  2.0  2.0  2.0
3  NaN  3.0  3.0  3.0
4  NaN  4.0  4.0  NaN
5  NaN  NaN  5.0  NaN
6  NaN  NaN  6.0  NaN

I am working to generate visualizations with this data, and I need to fill the null values in a very specific way. I want to loop the existing values repeatedly for each column until the null values are all filled, so that the DataFrame looks like this:

     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  0.0  2.0  2.0  2.0
3  1.0  3.0  3.0  3.0
4  0.0  4.0  4.0  0.0
5  1.0  0.0  5.0  1.0
6  0.0  1.0  6.0  2.0

Is there any convenient way to do this in Pandas?

Body:
One option is with a for loop; the assumption is that the NaNs are at the end of each column, if any. Use np.place to fill the nulls :

 [np.place(df[col].to_numpy(),
           df[col].isna(),
           df[col].dropna().array)
   for col in df
   if df[col].hasnans]

[None, None, None]

df
     A    B    C    D
0  0.0  0.0  0.0  0.0
1  1.0  1.0  1.0  1.0
2  0.0  2.0  2.0  2.0
3  1.0  3.0  3.0  3.0
4  0.0  4.0  4.0  0.0
5  1.0  0.0  5.0  1.0
6  0.0  1.0  6.0  2.0

Note that np.place is an in place operation, no assignment is needed.


问:
Passing Data from node js to html
I am connecting to an authentication server which is returning the credentials and calling to my call back method. How do I pass the authenticated values back to the html to render?

Here is my code

```<code>function getHomePage()
{
   // alert("here in ajax call")

    $.ajax({
        url: "/calloidcServer",
        headers:{
            'Access-Control-Allow-Methods':'POST, PUT, OPTIONS, DELETE, GET',
        'Access-Control-Allow-Origin':['https://localhost:3000','https://localhost:9031'],
        'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Credentials':true,
        'Content-Type':'application/json',
        },
        type: "GET",

        success: function (resp) {
            console.log(resp)

            $('#testoidc').append(resp);

        },
        error: function (resp, status, error) {

        }

    });

}

app.get("/calloidcServer",function (req, res, next) {
  console.log('-----------------------------');
  console.log('/Start login handler');
  next();

},
passport.authenticate('oidc',{scope:"openid"})
)

app.get('/callback',(req,res,next) =>{

  console.log(" call back from auth server here")
passport.authenticate('oidc',{ successRedirect: '/user',
failureRedirect: '/' })(req, res, next)

  }
)

app.get ("/user",(req,res) =>{
  res.header("Content-Type",'application/json');

  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/public/citizenHome.html'))

  res.redirect("/citizenHome.html")
  //res.send(JSON.stringify({tokenset:req.session.tokenSet,userinfo:req.session.userinfo},null,2));

})
</code>```

When I redirect to citizenHome.html, I want to send back some data to it to show in the html? I have not used any view engine.

答:
I am not sure if you can pass values to the HTML directly, but you can use any view-engine with Node.js that can help you pass values from the routes and render the page as you want.

You can use EJS, JADE or Pug.

Title: Passing Data from node js to html

Body:
I am connecting to an authentication server which is returning the credentials and calling to my call back method. How do I pass the authenticated values back to the html to render?

Here is my code

function getHomePage()
{
   // alert("here in ajax call")

    $.ajax({
        url: "/calloidcServer",
        headers:{
            'Access-Control-Allow-Methods':'POST, PUT, OPTIONS, DELETE, GET',
        'Access-Control-Allow-Origin':['https://localhost:3000','https://localhost:9031'],
        'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Credentials':true,
        'Content-Type':'application/json',
        },
        type: "GET",

        success: function (resp) {
            console.log(resp)

            $('#testoidc').append(resp);

        },
        error: function (resp, status, error) {

        }

    });

}

app.get("/calloidcServer",function (req, res, next) {
  console.log('-----------------------------');
  console.log('/Start login handler');
  next();

},
passport.authenticate('oidc',{scope:"openid"})
)

app.get('/callback',(req,res,next) =>{

  console.log(" call back from auth server here")
passport.authenticate('oidc',{ successRedirect: '/user',
failureRedirect: '/' })(req, res, next)

  }
)

app.get ("/user",(req,res) =>{
  res.header("Content-Type",'application/json');

  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/public/citizenHome.html'))

  res.redirect("/citizenHome.html")
  //res.send(JSON.stringify({tokenset:req.session.tokenSet,userinfo:req.session.userinfo},null,2));

})

When I redirect to citizenHome.html, I want to send back some data to it to show in the html? I have not used any view engine.


问:
how to debug to know what caused IE8 crash?
when visiting certain web pages on one of websites, IE8 Crashes before it can render anything. Works on IE7 and 9 though. Im stuck with this for a couple days.

If I removed all style sheet links in the page then it worked. so looks like probably a css issue. Anyone know how to debug that to know that caused it?

Any help will be much appreciated!

答:
Turned out to be the background image! Brutal!
css is like this:

```<code>body{
    background: url(../images/bg2.png) 50% 0 repeat-y;
    color:#7C7C7C;
    font: normal 12px "Helvetica Neue", Helvetica, Verdana, Arial,sans-serif !important;
    margin: 0px;
    padding: 0px;
}
</code>```

turned out IE8(not 7, not 9) does not like the background image bg2.png.
Why the heck this is happening?

Body:
Turned out to be the background image! Brutal!
css is like this:

body{
    background: url(../images/bg2.png) 50% 0 repeat-y;
    color:#7C7C7C;
    font: normal 12px "Helvetica Neue", Helvetica, Verdana, Arial,sans-serif !important;
    margin: 0px;
    padding: 0px;
}

turned out IE8(not 7, not 9) does not like the background image bg2.png.
Why the heck this is happening?


问:
How can I improve this python code approximating pi?
My way of calculating pi is:

import math
a = 2
n = int(input('number:'))

for i in range(n):
    a = 2 - math.sqrt(4-a)
    print((2**(i+2))*math.sqrt(a))
```

If this worked well, the printout would have become very close to pi. But when I tried this out, it seemed to converge into pi value, but became bigger and bigger than pi, reached 4, and dropped to 0.

How can I solve this problem?

答:
While mathematically the formula you are trying to implement is true, it assumes that all computations are performed with exact precision. Meanwhile, computers represent floating-point numbers only with certain accuracy, and all operations on these numbers involve rounding errors. In some cases, such as in this case, these errors can accumulate and entirely distort the results of computations.

To alleviate this issue, you can use Python decimal library which lets one perform computations with higher precision than the one provided by the standard Python floating-point numbers.
For example, you can try the following:

```<code>from decimal import Decimal, getcontext

# set precision to 30 places
getcontext().prec = 30

n = 10

a = Decimal(2)
for i in range(n):
    a = 2 - Decimal(4 - a).sqrt()
    print((Decimal(2)**Decimal(i + 2)) * a.sqrt())
</code>```

This gives:

```<code>3.06146745892071817382767987224
3.12144515225805228557255789567
3.13654849054593926381425804437
3.14033115695475291231711852416
3.14127725093277286806201976961
3.14151380114430107632851506557
3.14157294036709138413580013914
3.14158772527715970062885414319
3.14159142151119997399797180376
3.14159234557011774234037803153
</code>```

Body:
My way of calculating pi is:

import math
a = 2
n = int(input('number:'))

for i in range(n):
    a = 2 - math.sqrt(4-a)
    print((2**(i+2))*math.sqrt(a))

If this worked well, the printout would have become very close to pi. But when I tried this out, it seemed to converge into pi value, but became bigger and bigger than pi, reached 4, and dropped to 0.

How can I solve this problem?

Body:
While mathematically the formula you are trying to implement is true, it assumes that all computations are performed with exact precision. Meanwhile, computers represent floating-point numbers only with certain accuracy, and all operations on these numbers involve rounding errors. In some cases, such as in this case, these errors can accumulate and entirely distort the results of computations.

To alleviate this issue, you can use Python decimal library which lets one perform computations with higher precision than the one provided by the standard Python floating-point numbers.
For example, you can try the following:

from decimal import Decimal, getcontext

# set precision to 30 places
getcontext().prec = 30

n = 10

a = Decimal(2)
for i in range(n):
    a = 2 - Decimal(4 - a).sqrt()
    print((Decimal(2)**Decimal(i + 2)) * a.sqrt())

This gives:

3.06146745892071817382767987224
3.12144515225805228557255789567
3.13654849054593926381425804437
3.14033115695475291231711852416
3.14127725093277286806201976961
3.14151380114430107632851506557
3.14157294036709138413580013914
3.14158772527715970062885414319
3.14159142151119997399797180376
3.14159234557011774234037803153


问:
SwiftUI retain cycle in view hierarchy
I'm having the following view hierarchy which has a retain cycle, that's the simplest I could make to reproduce the issue. All viewmodels and properties has to stay as they are needed in the original solution:

```<code>import SwiftUI

struct MainView: View {
    @StateObject var viewModel = MainViewModel()

    var body: some View {
        NavigationView { [weak viewModel] in
            VStack {
                Button("StartCooking") {
                    viewModel?.show()
                }

                if viewModel?.isShowingContainerView == true {
                    ContainerView()
                }
                Button("StopCooking") {
                    viewModel?.hide()
                }
            }
        }
        .navigationViewStyle(.stack)
    }
}

final class MainViewModel: ObservableObject {
    @Published var isShowingContainerView = false

    func show() {
        isShowingContainerView = true
    }

    func hide() {
        isShowingContainerView = false
    }
}

struct ContainerView: View {
    @Namespace var namespace

    var body: some View {
        VStack {
            SubView(
                namespace: namespace
            )
        }
    }
}

struct SubView: View {
    @StateObject var viewModel = SubViewModel()
    var namespace: Namespace.ID

    var body: some View {
        Text("5 min")
            .matchedGeometryEffect(id: UUID().uuidString, in: namespace)
            .onTapGesture {
                foo()
            }
    }

    private func foo() {}
}

final class SubViewModel: ObservableObject {}
</code>```

If I run the app, tap on StartCooking, than on StopCooking and check the memory graph, I still see an instance of SubViewModel, which means that there is a leak in this code.
If I remove:

NavigationView OR

The VStack from ContainerView OR

matchedGeometryEffect OR

tapGesture

The retain cycle is resolved. Unfortunately I need all these. Can you see what the issue might be and how could it be solved?

答:
Looks like a SwiftUI bug. A possible workaround (if sub-view is one or limited set) is to use view model factory to provided instances.

Here is an example for one view:

```<code>struct SubView: View {

    @StateObject var viewModel = SubViewModel.shared  // single instance !!

    // .. other code
}

final class SubViewModel: ObservableObject {
    static var shared = SubViewModel()         // << this !!
}
</code>```

Title: SwiftUI retain cycle in view hierarchy

Body:
I'm having the following view hierarchy which has a retain cycle, that's the simplest I could make to reproduce the issue. All viewmodels and properties has to stay as they are needed in the original solution:

import SwiftUI

struct MainView: View {
    @StateObject var viewModel = MainViewModel()

    var body: some View {
        NavigationView { [weak viewModel] in
            VStack {
                Button("StartCooking") {
                    viewModel?.show()
                }

                if viewModel?.isShowingContainerView == true {
                    ContainerView()
                }
                Button("StopCooking") {
                    viewModel?.hide()
                }
            }
        }
        .navigationViewStyle(.stack)
    }
}

final class MainViewModel: ObservableObject {
    @Published var isShowingContainerView = false

    func show() {
        isShowingContainerView = true
    }

    func hide() {
        isShowingContainerView = false
    }
}

struct ContainerView: View {
    @Namespace var namespace

    var body: some View {
        VStack {
            SubView(
                namespace: namespace
            )
        }
    }
}

struct SubView: View {
    @StateObject var viewModel = SubViewModel()
    var namespace: Namespace.ID

    var body: some View {
        Text("5 min")
            .matchedGeometryEffect(id: UUID().uuidString, in: namespace)
            .onTapGesture {
                foo()
            }
    }

    private func foo() {}
}

final class SubViewModel: ObservableObject {}

If I run the app, tap on StartCooking, than on StopCooking and check the memory graph, I still see an instance of SubViewModel, which means that there is a leak in this code.
If I remove:

NavigationView OR

The VStack from ContainerView OR

matchedGeometryEffect OR

tapGesture

The retain cycle is resolved. Unfortunately I need all these. Can you see what the issue might be and how could it be solved?

Body:
Looks like a SwiftUI bug. A possible workaround (if sub-view is one or limited set) is to use view model factory to provided instances.

Here is an example for one view:

struct SubView: View {

    @StateObject var viewModel = SubViewModel.shared  // single instance !!

    // .. other code
}

final class SubViewModel: ObservableObject {
    static var shared = SubViewModel()         // << this !!
}


问:
Applying ImageMagick operators in a specific sequence
I have two images that are 2048x1638 which I want to append together in the following manner:

```<code>save(append(crop(image1.jpg, geometry), image2.jpg), image3.jpg)
</code>```

that is, I want to perform this sequence of operations:

crop image1.jpg to geometry

append the result of the crop to image2.jpg

save the result of the append to image3.jpg

Is there a way to do this?

I've looked at the usage guide and tried

```<code>convert image1.jpg -crop 2048x819+0+105 -append image2.jpg image3.jpg
</code>```

but it doesn't do the crop, and if I rearrange the order

```<code>convert -append -crop 2048x819+0+105 image1.jpg image2.jpg image3.jpg
</code>```

then it crops both images and then appends them.

答:
Haha, I was almost there; this works:

```<code>convert image1.jpg -crop 2048x819+0+105 image2.jpg -append  image3.jpg
</code>```

and it looks like parentheses (escaped at shell) can localize operators if needed:

```<code>convert \( image1.jpg -crop 2048x819+0+105 \) image2.jpg -append  image3.jpg
</code>```

Body:
I have two images that are 2048x1638 which I want to append together in the following manner:

save(append(crop(image1.jpg, geometry), image2.jpg), image3.jpg)

that is, I want to perform this sequence of operations:

crop image1.jpg to geometry

append the result of the crop to image2.jpg

save the result of the append to image3.jpg

Is there a way to do this?

I've looked at the usage guide and tried

convert image1.jpg -crop 2048x819+0+105 -append image2.jpg image3.jpg

but it doesn't do the crop, and if I rearrange the order

convert -append -crop 2048x819+0+105 image1.jpg image2.jpg image3.jpg

then it crops both images and then appends them.

Body:
Haha, I was almost there; this works:

convert image1.jpg -crop 2048x819+0+105 image2.jpg -append  image3.jpg

and it looks like parentheses (escaped at shell) can localize operators if needed:

convert \( image1.jpg -crop 2048x819+0+105 \) image2.jpg -append  image3.jpg


问:
Sql Bigquery - concat two columns into a new column
I want to concat two columns shown below into one new column.

I'm using this query:

```<code>SELECT
CONCAT( A_Bill_ID , ' ', B_BILL_ID ) AS BILL_ID
FROM
`table.tmp_140222`
</code>```

From this query, the result will be like this.

My problem is I want to concat only columns that don't have a similar value so that the new column value will not duplicate two times. From the above result, the ID is duplicated since both of the columns has the same value.

Can anyone help me?

Thanks

答:
```<code>select if (
    a_bill_id = b_bill_id,
    a_bill_id,
    concat(a_bill_id , ' ', b_bill_id )
  ) as bill_id
from your_table
</code>```

... shows null value ....

```<code>select if (
    a_bill_id = b_bill_id or (a_bill_id = b_bill_id) is null,
    coalesce(a_bill_id, b_bill_id),
    concat(a_bill_id , ' ', b_bill_id )
  ) as bill_id
from your_table
</code>```

Body:
I want to concat two columns shown below into one new column.

I'm using this query:

SELECT
CONCAT( A_Bill_ID , ' ', B_BILL_ID ) AS BILL_ID
FROM
`table.tmp_140222`

From this query, the result will be like this.

My problem is I want to concat only columns that don't have a similar value so that the new column value will not duplicate two times. From the above result, the ID is duplicated since both of the columns has the same value.

Can anyone help me?

Thanks

Body:
select if (
    a_bill_id = b_bill_id,
    a_bill_id,
    concat(a_bill_id , ' ', b_bill_id )
  ) as bill_id
from your_table

... shows null value ....

select if (
    a_bill_id = b_bill_id or (a_bill_id = b_bill_id) is null,
    coalesce(a_bill_id, b_bill_id),
    concat(a_bill_id , ' ', b_bill_id )
  ) as bill_id
from your_table


问:
When should I use RequestFactory vs GWT-RPC?
I am trying to figure out if I should migrate my gwt-rpc calls to the new GWT2.1 RequestFactory cals.

Google documentation vaguely mentions that RequestFactory is a better client-server communication method for "data-oriented services"

What I can distill from the documentation is that there is a new Proxy class that simplifies the communication (you don't pass back and forth the actual entity but just the proxy, so it is lighter weight and easier to manage)

Is that the whole point or am I missing something else in the big picture?

答:
We have have a very large implementation of GWT-RPC in our project.
Actually we have 50 Service interfaces with many methods each, and we have problems with the size of TypeSerializers generated by the compiler that turns our JS code huge.
So we are analizing to move towards RequestFactory.
I have been read for a couple of days digging into the web and trying to find what other people are doing.
The most important drawback I saw, and maybe I could be wrong, is that with RequestFactory your are no longer in control of the communication between your Server Domain objects and your client ones.
What we need is apply the load / save pattern in a controlled way. I mean, for example client receive the whole object graph of objects belonging to a specific transaction, do his updates and them send the whole back to the server. The server will be responsible for doing validation, compare old with new values and do persistance. If 2 users from different sites gets the same transaction and do some updates, the resulting transaction shouldn't be the merged one. One of the updates should fail in my scenario.
I don't see that RequestFactory helps supporting this kind of processing.

Regards
Daniel

ContentLicense: CC BY-SA 2.5


问:
node.JS Express passport stuck in infinte loop on auth check
My node.JS passport authentification check is stuck in an infinite loop if I return 400 status for requests which are not authentified:

```<code>  //ensure authentification
  function authorizeApi(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
      else res.status(400).json({
        message : "User Not Authenticated",
       user : null
     })

}

// retrieve logged in user profile
router.post("/login/success",authorizeApi, (req, res) => {
...
   res.json({
      success: true,
      message: "user has successfully been authenticated",
      user: req.user,
      cookies: req.cookies
    });
}
</code>```
```<code>
app.use(bodyParser.json({ limit: "50mb", extended: true }));

app.use(bodyParser.urlencoded({ extended: true }));

app.use("/auth", authRoutes);

</code>```

If I return only the profile for users which are authentificated I get a request from the client which remains in pending...

EDIT: After user is logged in loop ends and back-end returns the user profile info.

My client application is build in React. The function that gets the user profile is a fetch inside:

```<code>   login();
 }, [])

// gets login details
 function login() {
   fetch(config.baseURL + config.baseLOCATION + "/auth/login/success/", {
     method: "POST",
     credentials: "include",
     headers: {
       Accept: "application/json",
       "Content-Type": "application/json",
       "Access-Control-Allow-Credentials": true,

     }
   })
     .then(response => {
       if (response.status === 200) return response.json();
       throw new Error("failed to authenticate user");
     })
     .then(responseJson => {
       sessionStorage.setItem('exp', responseJson.user.exp);
....

       dispatch({
         type: UPDATE_PROFILE,
         payload: {
           role: responseJson.user.roles,
         ....
         }
       });
     }
     )
     .catch(error => {
       setState({
         authenticated: false,
         error: "Failed to authenticate user"
       });
       console.log(error);
       _handleLogoutClick();
     });
 }
</code>```

UPDATE: The issue is being generated from the frontend client.

答:
I have updated the client request:</p>
```<code>  .then(response => {
        if (response.status) return response.json();
    })
      .then(responseJson => {
        if(responseJson.success === true) {
           ...
        }
         else {
           ...
        }
</code>```

Body:
My node.JS passport authentification check is stuck in an infinite loop if I return 400 status for requests which are not authentified:

  //ensure authentification
  function authorizeApi(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
      else res.status(400).json({
        message : "User Not Authenticated",
       user : null
     })

}

// retrieve logged in user profile
router.post("/login/success",authorizeApi, (req, res) => {
...
   res.json({
      success: true,
      message: "user has successfully been authenticated",
      user: req.user,
      cookies: req.cookies
    });
}

app.use(bodyParser.json({ limit: "50mb", extended: true }));

app.use(bodyParser.urlencoded({ extended: true }));

app.use("/auth", authRoutes);

If I return only the profile for users which are authentificated I get a request from the client which remains in pending...

EDIT: After user is logged in loop ends and back-end returns the user profile info.

My client application is build in React. The function that gets the user profile is a fetch inside:

   login();
 }, [])

// gets login details
 function login() {
   fetch(config.baseURL + config.baseLOCATION + "/auth/login/success/", {
     method: "POST",
     credentials: "include",
     headers: {
       Accept: "application/json",
       "Content-Type": "application/json",
       "Access-Control-Allow-Credentials": true,

     }
   })
     .then(response => {
       if (response.status === 200) return response.json();
       throw new Error("failed to authenticate user");
     })
     .then(responseJson => {
       sessionStorage.setItem('exp', responseJson.user.exp);
....

       dispatch({
         type: UPDATE_PROFILE,
         payload: {
           role: responseJson.user.roles,
         ....
         }
       });
     }
     )
     .catch(error => {
       setState({
         authenticated: false,
         error: "Failed to authenticate user"
       });
       console.log(error);
       _handleLogoutClick();
     });
 }

UPDATE: The issue is being generated from the frontend client.

Body:
I have updated the client request:

  .then(response => {
        if (response.status) return response.json();
    })
      .then(responseJson => {
        if(responseJson.success === true) {
           ...
        }
         else {
           ...
        }


问:
Storybook keep in loading status for react native?
I'm following the introduction from the official website here: https://storybook.js.org/tutorials/intro-to-storybook/react-native/en/get-started/

I have repeated the steps for few times, I still can't start the storybook. Anyone success?

Any hint for what I missed?

As Tyler requested, I share the storybook index file as below (I didn't change anything, it is completed autogenerated new app):

```<code>import { AppRegistry } from "react-native";

import {
  getStorybookUI,
  configure,
  addDecorator,
} from "@storybook/react-native";
import { withKnobs } from "@storybook/addon-knobs";

import "./rn-addons";

// enables knobs for all stories
addDecorator(withKnobs);

// import stories
configure(() => {
  require("./stories");
}, module);

// Refer to https://github.com/storybookjs/react-native/tree/master/app/react-native#getstorybookui-options
// To find allowed options for getStorybookUI
const StorybookUIRoot = getStorybookUI({});

// If you are using React Native vanilla and after installation you don't see your app name here, write it manually.
// If you use Expo you should remove this line.
AppRegistry.registerComponent("%APP_NAME%", () => StorybookUIRoot);

export default StorybookUIRoot;

</code>```

Add screenshot of App.tsx.

答:
Thanks @TylerWilliams' hint.

It might due to an unknown bug on storybook, there isn't a complete solution yet, but build an android app could resolve the unlimited loading issue.

Body:
I'm following the introduction from the official website here: https://storybook.js.org/tutorials/intro-to-storybook/react-native/en/get-started/

I have repeated the steps for few times, I still can't start the storybook. Anyone success?

Any hint for what I missed?

As Tyler requested, I share the storybook index file as below (I didn't change anything, it is completed autogenerated new app):

import { AppRegistry } from "react-native";

import {
  getStorybookUI,
  configure,
  addDecorator,
} from "@storybook/react-native";
import { withKnobs } from "@storybook/addon-knobs";

import "./rn-addons";

// enables knobs for all stories
addDecorator(withKnobs);

// import stories
configure(() => {
  require("./stories");
}, module);

// Refer to https://github.com/storybookjs/react-native/tree/master/app/react-native#getstorybookui-options
// To find allowed options for getStorybookUI
const StorybookUIRoot = getStorybookUI({});

// If you are using React Native vanilla and after installation you don't see your app name here, write it manually.
// If you use Expo you should remove this line.
AppRegistry.registerComponent("%APP_NAME%", () => StorybookUIRoot);

export default StorybookUIRoot;

Add screenshot of App.tsx.


问:
NU1101 Unable to find package DevExpress.ExpressApp.Persistent.Base. No packages exist with this id in source(s):
I am trying to set up packages for a WinForms XAF XPO Standard Security Application.
I used the wizard to create the solution.
Then the project updater
Then I edited the project file package references.
However when I try to build the .exe project I get

```<code>NU1101  Unable to find package DevExpress.ExpressApp.Persistent.Base. No packages exist with this id in source(s):
</code>```

Even though the package shows in the references.

I tried checking the installed packages

答:
For some reason DevExpress.ExpressApp.Persistent.Base was showing in Package Manager as installed in the Module.Win project.
I removed it and now I can build the solution.</p>

Body:
I am trying to set up packages for a WinForms XAF XPO Standard Security Application.
I used the wizard to create the solution.
Then the project updater
Then I edited the project file package references.
However when I try to build the .exe project I get

NU1101  Unable to find package DevExpress.ExpressApp.Persistent.Base. No packages exist with this id in source(s):

Even though the package shows in the references.

I tried checking the installed packages


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答:
This is answered well by sqlite itself : Appropriate use of sqlite</p>

```<code>Another way to look at SQLite is this:
SQLite is not designed to replace Oracle. It is designed to replace fopen().
</code>```

OwnerDisplayName: johnny

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

Body:
This is answered well by sqlite itself : Appropriate use of sqlite

Another way to look at SQLite is this:
SQLite is not designed to replace Oracle. It is designed to replace fopen().

OwnerDisplayName: Learning

LastEditorDisplayName: Learning


问:
Why does setInterval works in useEffect but not when inside functional component context (see inside if condition)?
I was building UI for a dictionary that shows a word followed by its meaning. The word switches through a setInterval. In the below code I'm setting up the setInterval initially and then on some events. Here I'm just focused on the initial setInterval.

Although I'm quite experienced in React I am still not able to grab my head around why the setInterval works when inside useEffect hook but not from the if condition.

To replicate just comment out the if condition and uncomment useEffect block.

Can someone please explain?

```<code>import React, { useState, useEffect } from 'react';
import Dictionary from './Dictionary.json';
import './App.css';

const words = Object.keys(Dictionary);
let currentInterval;

function App() {
  const [randomWord, setRandomWord] = useState(words && words[Math.round(Math.random() * words.length)]);
  const [wordGenerationDuration, setWordGenerationDuration] = useState(10000);

  function selectRandomWord() {
    setRandomWord(words[Math.round(Math.random() * (words.length - 1))]);
  }

  if(!currentInterval) {
    currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
  }

  // useEffect(
  //   () => {
  //     currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
  //   }, []
  // )

  return (
    <div className='App'>
      <div className='dictionary-wrapper'>
        <p className='dictionary-word'>
          {randomWord}
        </p>
        <p className='dictionary-meaning'>
          {Dictionary[randomWord]}
        </p>
        <p className='next-button cursor-pointer'>
          <span
            onClick={
              () => {
                clearInterval(currentInterval);
                selectRandomWord();
                currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
              }
            }
          >
            Next Word
          </span>
        </p>
        <p>
          <span>Auto Switch Duration:</span>
          <input
            className='dictionary-input'
            type='number'
            placeholder={wordGenerationDuration / 1000}
            onChange={
              (evt) => {
                const wordGenerationDuration = Math.max(evt.target?.value * 1000, 10000);
                clearInterval(currentInterval);
                setWordGenerationDuration(wordGenerationDuration);
                currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
              }
            }
            min='10'
          />
        </p>
      </div>
    </div>
  );
}

export default App;

</code>```

答:
Your original interval callback is a function defined within your component (selectRandomWord).

When your component re-renders, the currentInterval will be set so your interval will not be redefined. The existing interval will then refer to the previous render's version of selectRandomWord which is no longer updating the state of the current render.

What you should really do is

Store the interval hook in a ref

Register your interval within useEffect(), and

Make sure you clear the interval in the component cleanup

function App() {
  const interval = useRef()
  const [randomWord, setRandomWord] = useState(words && words[Math.round(Math.random() * words.length)]);
  const [wordGenerationDuration, setWordGenerationDuration] = useState(10000);

  function selectRandomWord() {
    setRandomWord(words[Math.round(Math.random() * (words.length - 1))]);
  }

  useEffect(() => {
    if (!interval.current) {
      interval.current = setInterval(selectRandomWord, wordGenerationDuration)
    }

    // cleanup
    return () => {
      clearInterval(interval.current)
    }
  }, [])
```
<p>You can also clear the interval at any time using</p>
<pre class="lang-js prettyprint-override"><code>clearInterval(interval.current)
</code>```

See also https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables

Body:
I was building UI for a dictionary that shows a word followed by its meaning. The word switches through a setInterval. In the below code I'm setting up the setInterval initially and then on some events. Here I'm just focused on the initial setInterval.

Although I'm quite experienced in React I am still not able to grab my head around why the setInterval works when inside useEffect hook but not from the if condition.

To replicate just comment out the if condition and uncomment useEffect block.

Can someone please explain?

import React, { useState, useEffect } from 'react';
import Dictionary from './Dictionary.json';
import './App.css';

const words = Object.keys(Dictionary);
let currentInterval;

function App() {
  const [randomWord, setRandomWord] = useState(words && words[Math.round(Math.random() * words.length)]);
  const [wordGenerationDuration, setWordGenerationDuration] = useState(10000);

  function selectRandomWord() {
    setRandomWord(words[Math.round(Math.random() * (words.length - 1))]);
  }

  if(!currentInterval) {
    currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
  }

  // useEffect(
  //   () => {
  //     currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
  //   }, []
  // )

  return (

          {randomWord}

          {Dictionary[randomWord]}

           {
                clearInterval(currentInterval);
                selectRandomWord();
                currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
              }
            }
          >
            Next Word

          Auto Switch Duration:
          <input
            className='dictionary-input'
            type='number'
            placeholder={wordGenerationDuration / 1000}
            onChange={
              (evt) => {
                const wordGenerationDuration = Math.max(evt.target?.value * 1000, 10000);
                clearInterval(currentInterval);
                setWordGenerationDuration(wordGenerationDuration);
                currentInterval = setInterval(selectRandomWord, wordGenerationDuration);
              }
            }
            min='10'
          />

  );
}

export default App;

Body:
Your original interval callback is a function defined within your component (selectRandomWord).

When your component re-renders, the currentInterval will be set so your interval will not be redefined. The existing interval will then refer to the previous render's version of selectRandomWord which is no longer updating the state of the current render.

What you should really do is

Store the interval hook in a ref

Register your interval within useEffect(), and

Make sure you clear the interval in the component cleanup

function App() {
  const interval = useRef()
  const [randomWord, setRandomWord] = useState(words && words[Math.round(Math.random() * words.length)]);
  const [wordGenerationDuration, setWordGenerationDuration] = useState(10000);

  function selectRandomWord() {
    setRandomWord(words[Math.round(Math.random() * (words.length - 1))]);
  }

  useEffect(() => {
    if (!interval.current) {
      interval.current = setInterval(selectRandomWord, wordGenerationDuration)
    }

    // cleanup
    return () => {
      clearInterval(interval.current)
    }
  }, [])

You can also clear the interval at any time using

clearInterval(interval.current)

See also https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables


问:
AWS EKS, I encountered a tolerations error in all ArgoCD pods
I used the following command to install the Argo CD in the EKS fargate cluster.

$ VERSION=$(curl --silent "https://api.github.com/repos/argoproj/argo-cd/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
$ sudo curl --silent --location -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-linux-amd64
$ sudo chmod +x /usr/local/bin/argocd
```
<pre class="lang-sh prettyprint-override"><code>$ kubectl create namespace argocd
$ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
</code>```

And I look up the namespace resources, the state of the pad is pinging as follows.

NAME                                      READY   STATUS    RESTARTS   AGE
pod/argocd-application-controller-0       0/1     Pending   0          3m47s
pod/argocd-dex-server-65bf5f4fc7-dh4ql    0/1     Pending   0          3m47s
pod/argocd-redis-d486999b7-rn9g8          0/1     Pending   0          3m47s
pod/argocd-repo-server-8465d84869-jwj47   0/1     Pending   0          3m47s
pod/argocd-server-87b47d787-29mcp         0/1     Pending   0          3m47s

NAME                            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
service/argocd-dex-server       ClusterIP   172.20.30.228    <none>        5556/TCP,5557/TCP,5558/TCP   3m47s
service/argocd-metrics          ClusterIP   172.20.229.100   <none>        8082/TCP                     3m47s
service/argocd-redis            ClusterIP   172.20.240.101   <none>        6379/TCP                     3m47s
service/argocd-repo-server      ClusterIP   172.20.133.210   <none>        8081/TCP,8084/TCP            3m47s
service/argocd-server           ClusterIP   172.20.39.79     <none>        80/TCP,443/TCP               3m47s
service/argocd-server-metrics   ClusterIP   172.20.32.2      <none>        8083/TCP                     3m47s

NAME                                 READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/argocd-dex-server    0/1     1            0           3m47s
deployment.apps/argocd-redis         0/1     1            0           3m47s
deployment.apps/argocd-repo-server   0/1     1            0           3m47s
deployment.apps/argocd-server        0/1     1            0           3m47s

NAME                                            DESIRED   CURRENT   READY   AGE
replicaset.apps/argocd-dex-server-65bf5f4fc7    1         1         0       3m47s
replicaset.apps/argocd-redis-d486999b7          1         1         0       3m47s
replicaset.apps/argocd-repo-server-8465d84869   1         1         0       3m47s
replicaset.apps/argocd-server-87b47d787         1         1         0       3m47s

NAME                                             READY   AGE
statefulset.apps/argocd-application-controller   0/1     3m47s
```
<p>And I look up one of the pods, the following errors appear.</p>
<pre class="lang-sh prettyprint-override"><code>Events:
  Type     Reason            Age                 From               Message
  ----     ------            ----                ----               -------
  Warning  FailedScheduling  70s (x4 over 4m2s)  default-scheduler  0/5 nodes are available: 5 node(s) had taint {eks.amazonaws.com/compute-type: fargate}, that the pod didn't tolerate.
</code>```

All pads have the same error.

What should I do?

答:
Your Fargate was created to run deployment to "dev-cluster" namespace:

```<code>{
  "fargateProfile": {
    "status": "ACTIVE",
    ...
    "selectors": [{
        "namespace": "dev-cluster"
    }]
  ...
</code>```

But you deploy argocd to another namespace:

$ kubectl create namespace argocd

$ kubectl apply -n argocd ...

Try apply your argocd to "dev-cluster" namespace instead.

Body:
I used the following command to install the Argo CD in the EKS fargate cluster.

$ VERSION=$(curl --silent "https://api.github.com/repos/argoproj/argo-cd/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
$ sudo curl --silent --location -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-linux-amd64
$ sudo chmod +x /usr/local/bin/argocd

$ kubectl create namespace argocd
$ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

And I look up the namespace resources, the state of the pad is pinging as follows.

NAME                                      READY   STATUS    RESTARTS   AGE
pod/argocd-application-controller-0       0/1     Pending   0          3m47s
pod/argocd-dex-server-65bf5f4fc7-dh4ql    0/1     Pending   0          3m47s
pod/argocd-redis-d486999b7-rn9g8          0/1     Pending   0          3m47s
pod/argocd-repo-server-8465d84869-jwj47   0/1     Pending   0          3m47s
pod/argocd-server-87b47d787-29mcp         0/1     Pending   0          3m47s

NAME                            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
service/argocd-dex-server       ClusterIP   172.20.30.228    <none>        5556/TCP,5557/TCP,5558/TCP   3m47s
service/argocd-metrics          ClusterIP   172.20.229.100   <none>        8082/TCP                     3m47s
service/argocd-redis            ClusterIP   172.20.240.101   <none>        6379/TCP                     3m47s
service/argocd-repo-server      ClusterIP   172.20.133.210   <none>        8081/TCP,8084/TCP            3m47s
service/argocd-server           ClusterIP   172.20.39.79     <none>        80/TCP,443/TCP               3m47s
service/argocd-server-metrics   ClusterIP   172.20.32.2      <none>        8083/TCP                     3m47s

NAME                                 READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/argocd-dex-server    0/1     1            0           3m47s
deployment.apps/argocd-redis         0/1     1            0           3m47s
deployment.apps/argocd-repo-server   0/1     1            0           3m47s
deployment.apps/argocd-server        0/1     1            0           3m47s

NAME                                            DESIRED   CURRENT   READY   AGE
replicaset.apps/argocd-dex-server-65bf5f4fc7    1         1         0       3m47s
replicaset.apps/argocd-redis-d486999b7          1         1         0       3m47s
replicaset.apps/argocd-repo-server-8465d84869   1         1         0       3m47s
replicaset.apps/argocd-server-87b47d787         1         1         0       3m47s

NAME                                             READY   AGE
statefulset.apps/argocd-application-controller   0/1     3m47s

And I look up one of the pods, the following errors appear.

Events:
  Type     Reason            Age                 From               Message
  ----     ------            ----                ----               -------
  Warning  FailedScheduling  70s (x4 over 4m2s)  default-scheduler  0/5 nodes are available: 5 node(s) had taint {eks.amazonaws.com/compute-type: fargate}, that the pod didn't tolerate.

All pads have the same error.

What should I do?

Body:
Your Fargate was created to run deployment to "dev-cluster" namespace:

{
  "fargateProfile": {
    "status": "ACTIVE",
    ...
    "selectors": [{
        "namespace": "dev-cluster"
    }]
  ...

But you deploy argocd to another namespace:

$ kubectl create namespace argocd

$ kubectl apply -n argocd ...

Try apply your argocd to "dev-cluster" namespace instead.


答:
You can use a case statement like this -

```<code>SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(A_Bill_ID , ' ', B_BILL_ID )
end AS BILL_ID
FROM `table.tmp_140222`
</code>```

If there are Null values in the initial columns, you can use IFNULL or COALEASE to replace that with an empty string. But in this case, I would suggest using this without a delimiter or writing multiple 'when' statements to avoid tailing spaces in the final column -

```<code>SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(IFNULL(A_Bill_ID), ''), "", IFNULL(B_BILL_ID, ''))
end AS BILL_ID
FROM `table.tmp_140222`
</code>```

Title: Sql Bigquery - concat two columns into a new column

Body:
You can use a case statement like this -

SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(A_Bill_ID , ' ', B_BILL_ID )
end AS BILL_ID
FROM `table.tmp_140222`

If there are Null values in the initial columns, you can use IFNULL or COALEASE to replace that with an empty string. But in this case, I would suggest using this without a delimiter or writing multiple 'when' statements to avoid tailing spaces in the final column -

SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(IFNULL(A_Bill_ID), ''), "", IFNULL(B_BILL_ID, ''))
end AS BILL_ID
FROM `table.tmp_140222`


问:
'Routes' is not defined react/jsx-no-undef
So I was following the React Crash Course on YouTube for Beginners from Academind. I was following everything along and everything was good until I came to the Routing part.
I followed every step, everything just perfectly (for the routing part) but after refreshing the page the following error occurs:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Aaand I did it, I wrapped my Route in Routes :

```<code>    import { Route } from 'react-router-dom';

import AllMeetupsPage from './Pages/AllMeetups';
import NewMeetupsPage from './Pages/NewMeetups';
import FavoritesPage from './Pages/Favorites';

function App() {
  return (
    <div>
      <Routes>
        <Route path='/'>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meets'>
          <NewMeetupsPage />
        </Route>

        <Route path='/favs'>
          <FavoritesPage />
        </Route>
      </Routes>
    </div>
  );
}

export default App;
</code>```

and then I get this:

'Routes' is not defined  react/jsx-no-undef

then I :

Tried to import Routes from react-router-dom - No success;

Tried to import Routes from react-router - No success;

Tried to import Routes also in different components - No success;

Trust me I tried every different scenario for Routes but couldnt achieve anything different.
I

Googled, researched and couldnt find the solution for this problem.. Now Im desperate and
stuck here and I cant continue my React learning journey if I dont fix this...

答: Try to run yarn add react-router, then import {Routes,Route} from 'react-router'

Body:
So I was following the React Crash Course on YouTube for Beginners from Academind. I was following everything along and everything was good until I came to the Routing part.
I followed every step, everything just perfectly (for the routing part) but after refreshing the page the following error occurs:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Aaand I did it, I wrapped my Route in Routes :

    import { Route } from 'react-router-dom';

import AllMeetupsPage from './Pages/AllMeetups';
import NewMeetupsPage from './Pages/NewMeetups';
import FavoritesPage from './Pages/Favorites';

function App() {
  return (

      <Routes>
        <Route path='/'>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meets'>
          <NewMeetupsPage />
        </Route>

        <Route path='/favs'>
          <FavoritesPage />
        </Route>
      </Routes>

  );
}

export default App;

and then I get this:

'Routes' is not defined  react/jsx-no-undef

then I :

Tried to import Routes from react-router-dom - No success;

Tried to import Routes from react-router - No success;

Tried to import Routes also in different components - No success;

Trust me I tried every different scenario for Routes but couldnt achieve anything different.
I

Googled, researched and couldnt find the solution for this problem.. Now Im desperate and
stuck here and I cant continue my React learning journey if I dont fix this...


问:
Training with spacy on full dataset
When I train my spacy model as follows

```<code>spacy train config.cfg --paths.train ./train.spacy --paths.dev ./dev.spacy
</code>```

the model gets trained on train.spacy data file, and scored on dev.spacy. Then output_updated/model-best is the model with the highest score.

Is this best model finally trained on a combination of both train and dev data? I understand, it makes sense to split those datasets to avoid overfitting, but given little training data, I would like the final model to be trained on all data I have at hand.

答:
No, spaCy does not automatically merge your datasets before training model-best. If you want to do that you would need to manually create a new training data set.

If you have so little data that seems like a good idea, you should probably prioritize getting more data.

Title: Training with spacy on full dataset

Body:
When I train my spacy model as follows

spacy train config.cfg --paths.train ./train.spacy --paths.dev ./dev.spacy

the model gets trained on train.spacy data file, and scored on dev.spacy. Then output_updated/model-best is the model with the highest score.

Is this best model finally trained on a combination of both train and dev data? I understand, it makes sense to split those datasets to avoid overfitting, but given little training data, I would like the final model to be trained on all data I have at hand.


问:
Is there "LoadComplete" such an event in Windows Forms?
I want my windows form to be loaded first, render its children and all. After that load heavy data in it. This is why I am looking for any event which I could use just after form loading is complete.

Any thoughts on this?

答:
I have never found a better solution than Activated; although that is raised every time the form receives focus - so you need to filter out all the times after the first:</p>

```<code>bool _firstActivation = true;
void Form1_Activated(object sender, EventArgs e)
{
    if (_firstActivation)
    {
        _firstActivation = false;
        OnFirstActivation();
    }
}

private void OnFirstActivation()
{

}
</code>```

Body:
I have never found a better solution than Activated; although that is raised every time the form receives focus - so you need to filter out all the times after the first:

bool _firstActivation = true;
void Form1_Activated(object sender, EventArgs e)
{
    if (_firstActivation)
    {
        _firstActivation = false;
        OnFirstActivation();
    }
}

private void OnFirstActivation()
{

}


问:
Laravel Sail rebuild default database
According to docs:

Also, when the MySQL container is starting, it will ensure a database exists whose name matches the value of your DB_DATABASE environment variable.

My .env file looks like this.

```<code>DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=
</code>```

Yet when I try to run the migrations via sail artisan migrate, I get back this error:
SQLSTATE[HY000] [1049] Unknown database 'test' (SQL: select * from information_schema.tables where table_schema = test and table_name = migrations and table_type = 'BASE TABLE')

What I've tried:

Removing the docker container and images all together.

Running sail build --no-cache (to try and rebuild everything altogether)

When running sail shell, I went into MySQL and showed all databases. I could see the default laravel database there.

How do you tell sail to create the correct DB_DATABASE?

My docker-compose.yml:

```<code># For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
    mysql:
        image: 'mysql:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
    mailhog:
        image: 'mailhog/mailhog:latest'
        ports:
            - 1025:1025
            - 8025:8025
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local
</code>```

答:
Your problem is that you created your database without DB_PASSWORD set in your .env file and also tried to start it as root user.

If you start your container with no password or with DB_USERNAME set to root you will get these errors when you run sail up respectively:

```<code>// Set DB_USERNAME to root will not create the database but you can still query mysql
bracing-mysql-1         | 2022-02-14 04:28:35+00:00 [ERROR] [Entrypoint]: MYSQL_USER="root", MYSQL_USER and MYSQL_PASSWORD are for configuring a regular user and cannot be used for the root user
bracing-mysql-1         |     Remove MYSQL_USER="root" and use one of the following to control the root user password:
bracing-mysql-1         |     - MYSQL_ROOT_PASSWORD
bracing-mysql-1         |     - MYSQL_ALLOW_EMPTY_PASSWORD
bracing-mysql-1         |     - MYSQL_RANDOM_ROOT_PASSWORD

// Did not set DB_PASSWORD results in the user not being created
bracing-mysql-1         | 2022-02-14 04:30:13+00:00 [Warn] [Entrypoint]: MYSQL_USER specified, but missing MYSQL_PASSWORD; MYSQL_USER will not be created
</code>```

The password error can be misleading because even if you set MYSQL_ALLOW_EMPTY_PASSWORD: 1 in your docker-compose.yml you still need to put a password in otherwise the user is not created.

Title: Laravel Sail rebuild default database

Body:
According to docs:

Also, when the MySQL container is starting, it will ensure a database exists whose name matches the value of your DB_DATABASE environment variable.

My .env file looks like this.

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

Yet when I try to run the migrations via sail artisan migrate, I get back this error:
SQLSTATE[HY000] [1049] Unknown database 'test' (SQL: select * from information_schema.tables where table_schema = test and table_name = migrations and table_type = 'BASE TABLE')

What I've tried:

Removing the docker container and images all together.

Running sail build --no-cache (to try and rebuild everything altogether)

When running sail shell, I went into MySQL and showed all databases. I could see the default laravel database there.

How do you tell sail to create the correct DB_DATABASE?

My docker-compose.yml:

# For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
    mysql:
        image: 'mysql:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
    mailhog:
        image: 'mailhog/mailhog:latest'
        ports:
            - 1025:1025
            - 8025:8025
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local

Body:
Your problem is that you created your database without DB_PASSWORD set in your .env file and also tried to start it as root user.

If you start your container with no password or with DB_USERNAME set to root you will get these errors when you run sail up respectively:

// Set DB_USERNAME to root will not create the database but you can still query mysql
bracing-mysql-1         | 2022-02-14 04:28:35+00:00 [ERROR] [Entrypoint]: MYSQL_USER="root", MYSQL_USER and MYSQL_PASSWORD are for configuring a regular user and cannot be used for the root user
bracing-mysql-1         |     Remove MYSQL_USER="root" and use one of the following to control the root user password:
bracing-mysql-1         |     - MYSQL_ROOT_PASSWORD
bracing-mysql-1         |     - MYSQL_ALLOW_EMPTY_PASSWORD
bracing-mysql-1         |     - MYSQL_RANDOM_ROOT_PASSWORD

// Did not set DB_PASSWORD results in the user not being created
bracing-mysql-1         | 2022-02-14 04:30:13+00:00 [Warn] [Entrypoint]: MYSQL_USER specified, but missing MYSQL_PASSWORD; MYSQL_USER will not be created

The password error can be misleading because even if you set MYSQL_ALLOW_EMPTY_PASSWORD: 1 in your docker-compose.yml you still need to put a password in otherwise the user is not created.


问:
Apply a Greasemonkey/Tampermonkey userscript to an iframe
How can I make a userscript run inside an iframe?

答:
iframe.contentWindow.document allows obtaining iframe content in FireMonkey, e.g.:

```<code>const iframeDocument = document.getElementById('iframe_id').contentWindow.document;
const iframeAnchors = iframeDocument.evaluate(
  '//a',
  iframeDocument,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null);
</code>```

Body:
iframe.contentWindow.document allows obtaining iframe content in FireMonkey, e.g.:

const iframeDocument = document.getElementById('iframe_id').contentWindow.document;
const iframeAnchors = iframeDocument.evaluate(
  '//a',
  iframeDocument,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null);


问:
RecyclerView ItemOnClickListener doesn't work
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?

My Adapter:

```<code>package com.example.practica1.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video

class MainAdapter(private val context: Context, private val videos: List<Video>,
                  val listener: MyOnClickListener
): RecyclerView.Adapter<MainAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val video = videos[position]
        holder.title.text = video.data.short_title
        holder.serieTitle.text = video.data.show.title
        holder.durationTitle.text = video.data.video.duration + " seg"
        Glide.with(context)
            .load(video.data.imagepath)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(400, 400)
            .centerCrop()
            .into(holder.imagePrev)

    }

    override fun getItemCount() = videos.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val title: TextView = itemView.findViewById(R.id.videoTitle)
        val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
        val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
        val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)

        init{
            itemView.setOnClickListener{
                val position = adapterPosition
                listener.onClick(position)
            }
        }

    }

    interface MyOnClickListener{
        fun onClick(position: Int)
    }
}
</code>```

The fragment in which I tried to implement the method (The toast message doesn't appear)

```<code>package com.example.practica1.fragments

import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MenuFragment : Fragment() {
    private var _binding: FragmentMenuBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentMenuBinding.inflate(inflater, container, false)

        val view = inflater.inflate(R.layout.fragment_menu, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val retrofit = Retrofit.Builder()
            .baseUrl("https://www.cartoonnetwork.com.co")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val api = retrofit.create(ApiInterface::class.java)
        showProgress()
        api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
            override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
                if (response.isSuccessful()) {
                    d("daniel", "onResponse ${response.body()!![0].id}")
                    if (response.body()!!.size > 0) {
                        showData(response.body()!!)
                        getResult(true, "Sucess")
                    } else
                        getResult(false, response.message())

                    hideProgress()
                }

            }

            override fun onFailure(call: Call<List<Video>>, t: Throwable) {
                d("daniel", "onFailure")
                getResult(false, "Request Timeout. Please Try Again!")
                hideProgress()
            }

        })

        binding.search.setOnClickListener { v -> showDialog(v) }
    }

    fun showData(videos: List<Video>){
        val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
        test.apply{
            adapter = MainAdapter(context, videos, object: MainAdapter.MyOnClickListener{
                override fun onClick(position: Int) {
                    Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
                }

            })
        }
    }

    fun showProgress(){
        binding.swipeRefresh.setRefreshing(true)
        binding.emptyView.setVisibility(View.GONE)
        binding.shimmer.startShimmer()
        binding.shimmer.setVisibility(View.VISIBLE)
        binding.recyclerViewMenu.setVisibility(View.GONE)
    }

     fun hideProgress(){
        binding.swipeRefresh.setRefreshing(false)
        binding.shimmer.stopShimmer()
        binding.shimmer.setVisibility(View.GONE)
        binding.recyclerViewMenu.setVisibility(View.VISIBLE)
    }

    fun getResult(status: Boolean, message: String){
        if(!status) {
            binding.emptyView.setVisibility(View.VISIBLE)
            binding.textEmptyErr.setText(message)
        }
        else
            binding.emptyView.setVisibility((View.GONE))
    }

    private fun showDialog(view: View){
        BottomFluxDialog.inputDialog(requireActivity())
            .setTextTitle("Input Title")
            .setTextMessage("This is an input message")
            .setRightButtonText("SUBMIT")
            .setInputListener(object : OnInputListener {
                override fun onSubmitInput(text: String?) {
                    val bundle = Bundle()
                    bundle.putString("search", text)
                    Navigation.findNavController(view)
                        .navigate(R.id.action_menuFragment_to_listFragment, bundle)
                }

                override fun onCancelInput() {}

            })

            .show()
    }

}

</code>```

Thanks!

答:
If your data is showing in the recycler view and you are getting crash on item click than

```<code> replace this toast link :-
 Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
</code>```

with this :-

```<code>Toast.makeText(requireContext(), "$position", Toast.LENGTH_SHORT).show()
</code>```

or if your video list is not visible in recycler view than you need to implement layout manager in recycler view you can add it on xml or in code also.

Body:
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?

My Adapter:

package com.example.practica1.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video

class MainAdapter(private val context: Context, private val videos: List<Video>,
                  val listener: MyOnClickListener
): RecyclerView.Adapter<MainAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val video = videos[position]
        holder.title.text = video.data.short_title
        holder.serieTitle.text = video.data.show.title
        holder.durationTitle.text = video.data.video.duration + " seg"
        Glide.with(context)
            .load(video.data.imagepath)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(400, 400)
            .centerCrop()
            .into(holder.imagePrev)

    }

    override fun getItemCount() = videos.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val title: TextView = itemView.findViewById(R.id.videoTitle)
        val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
        val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
        val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)

        init{
            itemView.setOnClickListener{
                val position = adapterPosition
                listener.onClick(position)
            }
        }

    }

    interface MyOnClickListener{
        fun onClick(position: Int)
    }
}

The fragment in which I tried to implement the method (The toast message doesn't appear)

package com.example.practica1.fragments

import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MenuFragment : Fragment() {
    private var _binding: FragmentMenuBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentMenuBinding.inflate(inflater, container, false)

        val view = inflater.inflate(R.layout.fragment_menu, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val retrofit = Retrofit.Builder()
            .baseUrl("https://www.cartoonnetwork.com.co")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val api = retrofit.create(ApiInterface::class.java)
        showProgress()
        api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
            override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
                if (response.isSuccessful()) {
                    d("daniel", "onResponse ${response.body()!![0].id}")
                    if (response.body()!!.size > 0) {
                        showData(response.body()!!)
                        getResult(true, "Sucess")
                    } else
                        getResult(false, response.message())

                    hideProgress()
                }

            }

            override fun onFailure(call: Call<List<Video>>, t: Throwable) {
                d("daniel", "onFailure")
                getResult(false, "Request Timeout. Please Try Again!")
                hideProgress()
            }

        })

        binding.search.setOnClickListener { v -> showDialog(v) }
    }

    fun showData(videos: List<Video>){
        val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
        test.apply{
            adapter = MainAdapter(context, videos, object: MainAdapter.MyOnClickListener{
                override fun onClick(position: Int) {
                    Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
                }

            })
        }
    }

    fun showProgress(){
        binding.swipeRefresh.setRefreshing(true)
        binding.emptyView.setVisibility(View.GONE)
        binding.shimmer.startShimmer()
        binding.shimmer.setVisibility(View.VISIBLE)
        binding.recyclerViewMenu.setVisibility(View.GONE)
    }

     fun hideProgress(){
        binding.swipeRefresh.setRefreshing(false)
        binding.shimmer.stopShimmer()
        binding.shimmer.setVisibility(View.GONE)
        binding.recyclerViewMenu.setVisibility(View.VISIBLE)
    }

    fun getResult(status: Boolean, message: String){
        if(!status) {
            binding.emptyView.setVisibility(View.VISIBLE)
            binding.textEmptyErr.setText(message)
        }
        else
            binding.emptyView.setVisibility((View.GONE))
    }

    private fun showDialog(view: View){
        BottomFluxDialog.inputDialog(requireActivity())
            .setTextTitle("Input Title")
            .setTextMessage("This is an input message")
            .setRightButtonText("SUBMIT")
            .setInputListener(object : OnInputListener {
                override fun onSubmitInput(text: String?) {
                    val bundle = Bundle()
                    bundle.putString("search", text)
                    Navigation.findNavController(view)
                        .navigate(R.id.action_menuFragment_to_listFragment, bundle)
                }

                override fun onCancelInput() {}

            })

            .show()
    }

}

Thanks!

Body:
If your data is showing in the recycler view and you are getting crash on item click than

 replace this toast link :-
 Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()

with this :-

Toast.makeText(requireContext(), "$position", Toast.LENGTH_SHORT).show()

or if your video list is not visible in recycler view than you need to implement layout manager in recycler view you can add it on xml or in code also.


问:
Modify large string
I have a large string in the following format -

```<code>   <a href="12345.html"><a href="12345.html"><a href="12345.html"><a href="12345.html">
   <a href="12345.html"><a href="12345.html"><a href="12345.html"><a href="12345.html">
</code>```

Id like to store all occurances of the value that occurs before .html. So above html becomes something like 12345.html,12345.html,12345.html,12345.html,12345.html,12345.html,12345.html,12345.html

Do I need a regular expression? or some kind of replace method.

Thanks

答:
You can use an HTML parser like Jsoup.

```<code>Document doc = Jsoup.parse(yourString);
Elements els = doc.select("a");
for(Element el: els){
    //this only if needs the number without the HTML
    //if not, only el.attr("href")
    if(el.attr("href").contains(".html")){
         String[] parts = el.attr("href").split(".html");
         System.out.println(parts[0]);
    }
}
</code>```

Don't use regex to parse HTML.

Title: Modify large string

Body:
I have a large string in the following format -

Id like to store all occurances of the value that occurs before .html. So above html becomes something like 12345.html,12345.html,12345.html,12345.html,12345.html,12345.html,12345.html,12345.html

Do I need a regular expression? or some kind of replace method.

Thanks

Body:
You can use an HTML parser like Jsoup.

Document doc = Jsoup.parse(yourString);
Elements els = doc.select("a");
for(Element el: els){
    //this only if needs the number without the HTML
    //if not, only el.attr("href")
    if(el.attr("href").contains(".html")){
         String[] parts = el.attr("href").split(".html");
         System.out.println(parts[0]);
    }
}

Don't use regex to parse HTML.


问:
spacy nlp - which algorithms, apis from spacy NLP are not thread-safe?
Are all algorithms and APIs from Spacy NLP are thread-safe?

If no, then which are those that are not thread-safe?

If yes, can we specify the thread pool size?

答:
My understanding is that workers created with python multiprocessing have properties that are passed by value, which means that the tagging/parsing models are duplicated. So, multithreading dilutes the entire purpose of increasing efficiency

Instead, consider calling nlp.pipe, which is a multithreaded call to the spaCy pipeline, instead of multi-threading the call to nlp.

```<code>    for doc in nlp.pipe(texts, n_threads=16, batch_size=10000):
        #do something to process the doc
</code>```

Body:
My understanding is that workers created with python multiprocessing have properties that are passed by value, which means that the tagging/parsing models are duplicated. So, multithreading dilutes the entire purpose of increasing efficiency

Instead, consider calling nlp.pipe, which is a multithreaded call to the spaCy pipeline, instead of multi-threading the call to nlp.

    for doc in nlp.pipe(texts, n_threads=16, batch_size=10000):
        #do something to process the doc