问:
Firebase database rules that prevent any write but only allow delete?
Is there any option to create a rule that prevent any writes or updates, but only allow delete nodes ?

My example is that i want to create cupon codes for game, so if i create a cupon in database, everyone will be able to read this and access it but when first person will use it in-game he will also delete this cupon in database. I can create that but in this case everyone can also create new nodes in database, and i dont want that because everyone can fully spam my base.

Hope anyone will understand what i mean.

Edit: i'm working in realtime db

Regards

答:
same results, cant delete, I tried a lot of combinations and noone works, and because of that i just ask here if there is maybe another option. if write is enabled i delete node after i get it:</p>

```<code>private void PromoCodeDB()
{
    RestClient.Get<PromoCodeData>(codesDbURL + codeTextNum.text + ".json").Then(response =>
    {
        promoCodes = response;
        UpdateGold();
        Debug.Log("Code accepted");

        DeletePromoCodeDB();

    }).Catch(error =>
    {
        Debug.Log("Code does not exist.");
    });
}

private void DeletePromoCodeDB()
{
    RestClient.Delete(codesDbURL + codeTextNum.text + ".json").Then(response => {
        Debug.Log("Promo code deleted");
    }).Catch(error =>
    {
        Debug.Log("Cannot be deleted");
    });
}
</code>```

Body:
same results, cant delete, I tried a lot of combinations and noone works, and because of that i just ask here if there is maybe another option. if write is enabled i delete node after i get it:

private void PromoCodeDB()
{
    RestClient.Get<PromoCodeData>(codesDbURL + codeTextNum.text + ".json").Then(response =>
    {
        promoCodes = response;
        UpdateGold();
        Debug.Log("Code accepted");

        DeletePromoCodeDB();

    }).Catch(error =>
    {
        Debug.Log("Code does not exist.");
    });
}

private void DeletePromoCodeDB()
{
    RestClient.Delete(codesDbURL + codeTextNum.text + ".json").Then(response => {
        Debug.Log("Promo code deleted");
    }).Catch(error =>
    {
        Debug.Log("Cannot be deleted");
    });
}


来源: stackexchange

问:
migrating flask web application currently using uWSGI web server to ASGI web server(uvicorn)
I currently have a flask web application using uWSGI web server that implements the WSGI standard and need to migrate this app to uvicorn web server that implements the ASGI standard.

If I choose to use uvicorn web server from the many available options say, Hypercorn, Daphne, then which web microframework(instead of flask) should I opt for from the available options say, Starlette, Quart, Django/Channels to get this migration done smoothly?

The hierarchy is like:

```<code>  Uvicorn: an ASGI server

        Starlette: (uses Uvicorn) a web microframework

             FastAPI: (uses Starlette) an API microframework with several
                      additional features for building APIs, with data validation, etc.
</code>```

As what I have read so far,

Quart is a Python web microframework based on Asyncio. It is intended
to provide the easiest way to use asyncio in a web context, especially
with existing Flask apps.

and

FastAPI has shown to be a Python web framework with one of the best
performances, as measured by third-party benchmarks, thanks to being
based on and powered by Starlette. https://fastapi.tiangolo.com/benchmarks/

Please suggest with the best approach

答:
I'm not sure there is a right answer for this, as it mainly depends on personal opinions.

I personally believe that Quart would provide the easiest migration from an existing Flask app. This is because I've intentionally made the Quart API the same as the Flask API thereby ensuring that everything you already understand about Flask apps still applies to Quart apps. My hope is that this would allow you to focus on learning async/await concepts instead of the framework.

I think you'll find your answer though by considering what you need to do that is beyond the framework and whether extensions exist for you to be able to do it. Compared to the Flask ecosystem all the ASGI frameworks' ecosystems are smaller.

ContentLicense: CC BY-SA 4.0

Body:
I currently have a flask web application using uWSGI web server that implements the WSGI standard and need to migrate this app to uvicorn web server that implements the ASGI standard.

If I choose to use uvicorn web server from the many available options say, Hypercorn, Daphne, then which web microframework(instead of flask) should I opt for from the available options say, Starlette, Quart, Django/Channels to get this migration done smoothly?

The hierarchy is like:

  Uvicorn: an ASGI server

        Starlette: (uses Uvicorn) a web microframework

             FastAPI: (uses Starlette) an API microframework with several
                      additional features for building APIs, with data validation, etc.

As what I have read so far,

Quart is a Python web microframework based on Asyncio. It is intended
to provide the easiest way to use asyncio in a web context, especially
with existing Flask apps.

and

FastAPI has shown to be a Python web framework with one of the best
performances, as measured by third-party benchmarks, thanks to being
based on and powered by Starlette. https://fastapi.tiangolo.com/benchmarks/

Please suggest with the best approach


问:
SAS YYMMDD10. works but YYMMDDn10 doesn't
This is my data (sorry for no script, it's just proc create table from mssql):

```<code>testdb.testtable
id - numeric
date_from - numeric (datetime from mssql)
date_to - numeric (datetime from mssql)
base_id - numeric
base_id2 - string (length 64)
</code>```

What I tried to do was:

```<code>proc sql;
update testdb.testtable tt
set base_id2 = CATX('_',
    ('data from other table'),
    put(datepart(date_from),yymmddn10.),
    put(datepart(date_to),yymmddn10.),
    put(base_id,z4.)
)
where (....)
;
quit;
</code>```

And I get this error:

```<code>The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
</code>```

What I really don't understand is that when I use format with separators, YYMMDD10., it works.

When i run:

```<code>proc sql;
select datepart(date_from) format=yymmddn10. from testdb.testtable;
quit;
</code>```

It returns 20191227 - It's great. When I run

```<code>proc sql;
select put(datepart(date_from),yymmddn10.) from testdb.testtable;
quit;
</code>```

It fails with the same error.

What do I miss?

答:
The number in format is the given width. Format YYMMDDn has 8 chars, so I should have used YYMMDDn8. And it worked.

I was having a long struggle with it and I still don't understand why did it work in format= and not in put().

Body:
This is my data (sorry for no script, it's just proc create table from mssql):

testdb.testtable
id - numeric
date_from - numeric (datetime from mssql)
date_to - numeric (datetime from mssql)
base_id - numeric
base_id2 - string (length 64)

What I tried to do was:

proc sql;
update testdb.testtable tt
set base_id2 = CATX('_',
    ('data from other table'),
    put(datepart(date_from),yymmddn10.),
    put(datepart(date_to),yymmddn10.),
    put(base_id,z4.)
)
where (....)
;
quit;

And I get this error:

The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
The width value for YYMMDDN is out of bounds. It should be between 2 and 8.

What I really don't understand is that when I use format with separators, YYMMDD10., it works.

When i run:

proc sql;
select datepart(date_from) format=yymmddn10. from testdb.testtable;
quit;

It returns 20191227 - It's great. When I run

proc sql;
select put(datepart(date_from),yymmddn10.) from testdb.testtable;
quit;

It fails with the same error.

What do I miss?


问:
can't execute rsDriver (connection refused)
I can't get anywhere with R selenium. Here's the first step and my output:

```<code>library(RSelenium)
rD <- rsDriver()
# checking Selenium Server versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking chromedriver versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking geckodriver versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking phantomjs versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# [1] "Connecting to remote server"
# Error in checkError(res) :
#   Undefined error in httr call. httr output: Failed to connect to localhost port 4567: Connection refused
# In addition: Warning message:
#   In rsDriver() : Could not determine server status.
</code>```

What did I miss ?

答:
Per the Cran vignette I had to run:

```<code>shell("docker-machine ip")
</code>```

Then set the remoteServerAddr to the IP which was returned.

ContentLicense: CC BY-SA 3.0

Body:
I can't get anywhere with R selenium. Here's the first step and my output:

library(RSelenium)
rD <- rsDriver()
# checking Selenium Server versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking chromedriver versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking geckodriver versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# checking phantomjs versions:
#   BEGIN: PREDOWNLOAD
# BEGIN: DOWNLOAD
# BEGIN: POSTDOWNLOAD
# [1] "Connecting to remote server"
# Error in checkError(res) :
#   Undefined error in httr call. httr output: Failed to connect to localhost port 4567: Connection refused
# In addition: Warning message:
#   In rsDriver() : Could not determine server status.

What did I miss ?

Body:
Per the Cran vignette I had to run:

shell("docker-machine ip")

Then set the remoteServerAddr to the IP which was returned.


问:
Correct usage of the SQLite ON CONFLICT clause
I have a SQLite database which, amongst other things, has the following table.

```<code>CREATE TABLE IF NOT EXISTS biases
(
 data INTEGER NOT NULL,
 link INTEGER DEFAULT 0,
 bias_type INTEGER,
 ignores INTEGER DEFAULT 0,
 desists INTEGER DEFAULT 0,
 encashes INTEGER DEFAULT 0,
 accesses INTEGER DEFAULT 0,
 scraps INTEGER DEFAULT 0,
 CONSTRAINT pk_bias_mix PRIMARY KEY(data,link,bias_type)
);
</code>```

The constraint pk_bias_mix is being used to ensure that no two rows can have the same values for all three columns data, link and bias_type columns.  So suppose I do

```<code>INSERT INTO biases (data,link,bias_type,ignores) VALUES(1,1,1,1);
</code>```

things work as expected - a new row is inserted in the table.  If I issue the same INSERT again I get the error

UNIQUE CONSTRAINT FAILED: biases.data,biases.link,biases.bias_type

just as expected.  I tried to use the SQLite ON CONFLICT clause thus

```<code>INSERT INTO biases (data,link,bias_type,ignores) VALUES(1,1,1,1)
ON CONFLICT(data,link,bias_type) DO UPDATE SET ignores = ignores + 1;
</code>```

and it worked as I had hoped - instead of adding a new row or throwing up an error SQLite incremented the value of the ignores column in the row with the matching data, link and bias_type values.

However, this is just the result of an experiment.  It is not immediately clear to me from the SQLite docs that this is indeed how ON CONFLICT is supposed to behave - i.e it can be given two or more conflict constraints to be checked.  What I mean by two or more constraints is specifying multiple, comma separated, columns inside CONFLICT(...) as I have done in the example above.

I suspect that this is the right usage since I am merely specifying a CONFLICT condition that replicates my indicated CONSTRAINT. However, I cannot see this explained explicitly anywhere in the docs. I'd be much obliged to anyone who might be able to confirm this.

答:
From UPSERT:

UPSERT is a special syntax addition to INSERT that causes the INSERT
  to behave as an UPDATE or a no-op if the INSERT would violate a
  uniqueness constraint.

and:

The special UPSERT processing happens only for uniqueness constraint
  on the table that is receiving the INSERT.

So the DO UPDATE part is not triggered by any constraint conflict but only by a unique constraint violation.

Also:

The syntax that occurs in between the "ON CONFLICT" and "DO" keywords
  is called the "conflict target". The conflict target specifies a
  specific uniqueness constraint that will trigger the upsert.

So it is not possible to have two or more conflict constraints to be checked in one statement.

However you can use separate UPSERT statements to check for 2 different unique constraint violations.

See a simplified demo where I added 1 more UNIQUE constraint to your table:

```<code>CONSTRAINT con_scraps UNIQUE(scraps)
</code>```

Body:
I have a SQLite database which, amongst other things, has the following table.

CREATE TABLE IF NOT EXISTS biases
(
 data INTEGER NOT NULL,
 link INTEGER DEFAULT 0,
 bias_type INTEGER,
 ignores INTEGER DEFAULT 0,
 desists INTEGER DEFAULT 0,
 encashes INTEGER DEFAULT 0,
 accesses INTEGER DEFAULT 0,
 scraps INTEGER DEFAULT 0,
 CONSTRAINT pk_bias_mix PRIMARY KEY(data,link,bias_type)
);

The constraint pk_bias_mix is being used to ensure that no two rows can have the same values for all three columns data, link and bias_type columns.  So suppose I do

INSERT INTO biases (data,link,bias_type,ignores) VALUES(1,1,1,1);

things work as expected - a new row is inserted in the table.  If I issue the same INSERT again I get the error

UNIQUE CONSTRAINT FAILED: biases.data,biases.link,biases.bias_type

just as expected.  I tried to use the SQLite ON CONFLICT clause thus

INSERT INTO biases (data,link,bias_type,ignores) VALUES(1,1,1,1)
ON CONFLICT(data,link,bias_type) DO UPDATE SET ignores = ignores + 1;

and it worked as I had hoped - instead of adding a new row or throwing up an error SQLite incremented the value of the ignores column in the row with the matching data, link and bias_type values.

However, this is just the result of an experiment.  It is not immediately clear to me from the SQLite docs that this is indeed how ON CONFLICT is supposed to behave - i.e it can be given two or more conflict constraints to be checked.  What I mean by two or more constraints is specifying multiple, comma separated, columns inside CONFLICT(...) as I have done in the example above.

I suspect that this is the right usage since I am merely specifying a CONFLICT condition that replicates my indicated CONSTRAINT. However, I cannot see this explained explicitly anywhere in the docs. I'd be much obliged to anyone who might be able to confirm this.

Body:
From UPSERT:

UPSERT is a special syntax addition to INSERT that causes the INSERT
  to behave as an UPDATE or a no-op if the INSERT would violate a
  uniqueness constraint.

and:

The special UPSERT processing happens only for uniqueness constraint
  on the table that is receiving the INSERT.

So the DO UPDATE part is not triggered by any constraint conflict but only by a unique constraint violation.

Also:

The syntax that occurs in between the "ON CONFLICT" and "DO" keywords
  is called the "conflict target". The conflict target specifies a
  specific uniqueness constraint that will trigger the upsert.

So it is not possible to have two or more conflict constraints to be checked in one statement.

However you can use separate UPSERT statements to check for 2 different unique constraint violations.

See a simplified demo where I added 1 more UNIQUE constraint to your table:

CONSTRAINT con_scraps UNIQUE(scraps)


问:
issue in query params in angular 8
I have a problem with the query parameters in angular 8. This is the code:

```<code>headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }
</code>```

I also tried

```<code>let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);
</code>```

and

```<code>let params = new HttpParams().set('username', username).set('password', password);
</code>```

and

```<code>let params = new HttpParams().append('username', username).append('password', password);
</code>```

The backend server get username and password as undefined, previously I had this code that worked correctly:

```<code> login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}
</code>```

What's wrong? Thanks

答:
Try send js object after url. For exaple :

Let obj = {username:"username",password:"password"};

this.http.post("your url here",obj).subscribe(your arrow function here);

Good luck!

Title: issue in query params in angular 8

Body:
I have a problem with the query parameters in angular 8. This is the code:

headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }

I also tried

let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);

and

let params = new HttpParams().set('username', username).set('password', password);

and

let params = new HttpParams().append('username', username).append('password', password);

The backend server get username and password as undefined, previously I had this code that worked correctly:

 login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}

What's wrong? Thanks


问:
How to "flatten" or "index" 3D-array in 1D array?
I am trying to flatten 3D array into 1D array for "chunk" system in my game. It's a 3D-block game and basically I want the chunk system to be almost identical to Minecraft's system (however, this isn't Minecraft clone by any measure). In my previous 2D-games I have accessed the flattened array with following algorithm:

```<code>Tiles[x + y * WIDTH]
</code>```

However, this obviously doesn't work with 3D since it's missing the Z-axis. I have no idea how to implement this sort of algorithm in 3D-space. Width, height and depth are all constants (and width is just as large as height).

Is it just x + y*WIDTH + Z*DEPTH ? I am pretty bad with math and I am just beginning 3D-programming so I am pretty lost :|

PS. The reason for this is that I am looping and getting stuff by index from it quite a lot. I know that 1D arrays are faster than multi-dimensional arrays (for reasons I cant remember :P ). Even though this may not be necessary, I want as good performance as possible :)

答:
The forward and reverse transforms of Samuel Kerrien above are almost correct. A more concise (R-based) transformation maps are included below with an example (the "a %% b" is the modulo operator representing the remainder of the division of a by b):

```<code>dx=5; dy=6; dz=7  # dimensions
x1=1; y1=2; z1=3  # 3D point example
I = dx*dy*z1+dx*y1+x1; I  # corresponding 2D index
# [1] 101
x= I %% dx; x  # inverse transform recovering the x index
# [1] 1
y = ((I - x)/dx) %% dy; y  # inverse transform recovering the y index
# [1] 2
z= (I-x -dx*y)/(dx*dy); z  # inverse transform recovering the z index
# [1] 3
</code>```

Mind the division (/) and module (%%) operators.

Body:
I am trying to flatten 3D array into 1D array for "chunk" system in my game. It's a 3D-block game and basically I want the chunk system to be almost identical to Minecraft's system (however, this isn't Minecraft clone by any measure). In my previous 2D-games I have accessed the flattened array with following algorithm:

Tiles[x + y * WIDTH]

However, this obviously doesn't work with 3D since it's missing the Z-axis. I have no idea how to implement this sort of algorithm in 3D-space. Width, height and depth are all constants (and width is just as large as height).

Is it just x + y*WIDTH + Z*DEPTH ? I am pretty bad with math and I am just beginning 3D-programming so I am pretty lost :|

PS. The reason for this is that I am looping and getting stuff by index from it quite a lot. I know that 1D arrays are faster than multi-dimensional arrays (for reasons I cant remember :P ). Even though this may not be necessary, I want as good performance as possible :)

Body:
The forward and reverse transforms of Samuel Kerrien above are almost correct. A more concise (R-based) transformation maps are included below with an example (the "a %% b" is the modulo operator representing the remainder of the division of a by b):

dx=5; dy=6; dz=7  # dimensions
x1=1; y1=2; z1=3  # 3D point example
I = dx*dy*z1+dx*y1+x1; I  # corresponding 2D index
# [1] 101
x= I %% dx; x  # inverse transform recovering the x index
# [1] 1
y = ((I - x)/dx) %% dy; y  # inverse transform recovering the y index
# [1] 2
z= (I-x -dx*y)/(dx*dy); z  # inverse transform recovering the z index
# [1] 3

Mind the division (/) and module (%%) operators.


问:
Groupby mutate equivalent in pandas/python using tidydata principles
My dataframe resembles the following:

```<code>group_var1 = ['A1','A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2']
group_var2 = ['B1', 'B1', 'B1', 'B1', 'B2', 'B2', 'B2', 'B2', 'B1', 'B1', 'B1', 'B1', 'B2', 'B2', 'B2', 'B2']
group_var3 = ['C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2']

value = np.arange(len(group_var1))

ex_df = pd.DataFrame({
    'group_var1' : group_var1,
    'group_var2' : group_var2,
    'group_var3' : group_var3,
    'value' : value
})

</code>```

which should produce the following when called:

```<code>    group_va1   group_va2   group_va3   value
0   A1  B1  C1  0
1   A1  B1  C2  1
2   A1  B1  C1  2
3   A1  B1  C2  3
4   A1  B2  C1  4
5   A1  B2  C2  5
6   A1  B2  C1  6
7   A1  B2  C2  7
8   A2  B1  C1  8
9   A2  B1  C2  9
10  A2  B1  C1  10
11  A2  B1  C2  11
12  A2  B2  C1  12
13  A2  B2  C2  13
14  A2  B2  C1  14
15  A2  B2  C2  15

</code>```

My goal is to group the DataFrame by columns group_var1, group_var2, and group_var3, and then calculate the mean value within each group, and add a new row mean_ex to this existing DataFrame with these results. In R this could be accomplished by ex_df %>% group_by(c(group_var1, group_var2, group_var3)) %>% mutate(mean_ex = mean(value)) which automatically handles assigning the new value to the respective rows.

I have found ways to summarize the DataFrame by aggregating all of the values within each group into only the mean value (ex_df.groupby(['group_var1', 'group_var2', 'group_var3']).mean()), but I want the mean value to be a new column in my existing DataFrame, not a df of smaller dimensions. My desired output can be found below, and was achieved by using pd.merge() on my original df and my previously described undesired aggregated table:

```<code>
    group_var1  group_var2  group_var3  value   mean_ex
0   A1  B1  C1  0   1
1   A1  B1  C2  1   2
2   A1  B1  C1  2   1
3   A1  B1  C2  3   2
4   A1  B2  C1  4   5
5   A1  B2  C2  5   6
6   A1  B2  C1  6   5
7   A1  B2  C2  7   6
8   A2  B1  C1  8   9
9   A2  B1  C2  9   10
10  A2  B1  C1  10  9
11  A2  B1  C2  11  10
12  A2  B2  C1  12  13
13  A2  B2  C2  13  14
14  A2  B2  C1  14  13
15  A2  B2  C2  15  14

</code>```

My question is, is there any way to achieve this desired output without having to create a separate dataframe that then gets merged back onto the original? Thanks.

答:
Use transform and assign:

```<code>ex_df.assign(
    mean_val =
    ex_df
    .groupby(["group_var1", "group_var2",  "group_var3"])
    .value
    .transform('mean')
)

   group_var1 group_var2 group_var3  value  mean_val
0          A1         B1         C1      0         1
1          A1         B1         C2      1         2
2          A1         B1         C1      2         1
3          A1         B1         C2      3         2
4          A1         B2         C1      4         5
5          A1         B2         C2      5         6
6          A1         B2         C1      6         5
7          A1         B2         C2      7         6
8          A2         B1         C1      8         9
9          A2         B1         C2      9        10
10         A2         B1         C1     10         9
11         A2         B1         C2     11        10
12         A2         B2         C1     12        13
13         A2         B2         C2     13        14
14         A2         B2         C1     14        13
15         A2         B2         C2     15        14
</code>```

Explanation

Pandas assign is the rough equivalent of dplyr::mutate, and transform broadcasts the grouping operation across all the initial rows of an input, rather than simply calling an aggregation function after groupby.

Something like df.groupby('a').x.mean() will result in a single value per grouped index, set, which is the analog to dplyr::summarise.

Body:
My dataframe resembles the following:

group_var1 = ['A1','A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2', 'A2']
group_var2 = ['B1', 'B1', 'B1', 'B1', 'B2', 'B2', 'B2', 'B2', 'B1', 'B1', 'B1', 'B1', 'B2', 'B2', 'B2', 'B2']
group_var3 = ['C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2']

value = np.arange(len(group_var1))

ex_df = pd.DataFrame({
    'group_var1' : group_var1,
    'group_var2' : group_var2,
    'group_var3' : group_var3,
    'value' : value
})

which should produce the following when called:

    group_va1   group_va2   group_va3   value
0   A1  B1  C1  0
1   A1  B1  C2  1
2   A1  B1  C1  2
3   A1  B1  C2  3
4   A1  B2  C1  4
5   A1  B2  C2  5
6   A1  B2  C1  6
7   A1  B2  C2  7
8   A2  B1  C1  8
9   A2  B1  C2  9
10  A2  B1  C1  10
11  A2  B1  C2  11
12  A2  B2  C1  12
13  A2  B2  C2  13
14  A2  B2  C1  14
15  A2  B2  C2  15

My goal is to group the DataFrame by columns group_var1, group_var2, and group_var3, and then calculate the mean value within each group, and add a new row mean_ex to this existing DataFrame with these results. In R this could be accomplished by ex_df %>% group_by(c(group_var1, group_var2, group_var3)) %>% mutate(mean_ex = mean(value)) which automatically handles assigning the new value to the respective rows.

I have found ways to summarize the DataFrame by aggregating all of the values within each group into only the mean value (ex_df.groupby(['group_var1', 'group_var2', 'group_var3']).mean()), but I want the mean value to be a new column in my existing DataFrame, not a df of smaller dimensions. My desired output can be found below, and was achieved by using pd.merge() on my original df and my previously described undesired aggregated table:

    group_var1  group_var2  group_var3  value   mean_ex
0   A1  B1  C1  0   1
1   A1  B1  C2  1   2
2   A1  B1  C1  2   1
3   A1  B1  C2  3   2
4   A1  B2  C1  4   5
5   A1  B2  C2  5   6
6   A1  B2  C1  6   5
7   A1  B2  C2  7   6
8   A2  B1  C1  8   9
9   A2  B1  C2  9   10
10  A2  B1  C1  10  9
11  A2  B1  C2  11  10
12  A2  B2  C1  12  13
13  A2  B2  C2  13  14
14  A2  B2  C1  14  13
15  A2  B2  C2  15  14

My question is, is there any way to achieve this desired output without having to create a separate dataframe that then gets merged back onto the original? Thanks.

Body:
Use transform and assign:

ex_df.assign(
    mean_val =
    ex_df
    .groupby(["group_var1", "group_var2",  "group_var3"])
    .value
    .transform('mean')
)

   group_var1 group_var2 group_var3  value  mean_val
0          A1         B1         C1      0         1
1          A1         B1         C2      1         2
2          A1         B1         C1      2         1
3          A1         B1         C2      3         2
4          A1         B2         C1      4         5
5          A1         B2         C2      5         6
6          A1         B2         C1      6         5
7          A1         B2         C2      7         6
8          A2         B1         C1      8         9
9          A2         B1         C2      9        10
10         A2         B1         C1     10         9
11         A2         B1         C2     11        10
12         A2         B2         C1     12        13
13         A2         B2         C2     13        14
14         A2         B2         C1     14        13
15         A2         B2         C2     15        14

Explanation

Pandas assign is the rough equivalent of dplyr::mutate, and transform broadcasts the grouping operation across all the initial rows of an input, rather than simply calling an aggregation function after groupby.

Something like df.groupby('a').x.mean() will result in a single value per grouped index, set, which is the analog to dplyr::summarise.


问:
How to display text depending on the number in UILabel
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

```<code>If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big
</code>```

I hope you understood what i mean. Thank you! Sorry for my english.

答:
You can use this Code</p>

```<code> lblFirst.text = txtField.text;
 int intValue = [lblFirst.text intValue];
 if (intValue < 20) {
    lblSecond.text = @"Small";
 } else if (intValue >= 20 && intValue <= 30) {
    lblSecond.text = @"Normal";
 } else if (intValue > 40) {
    lblSecond.text = @"Big";
 }
</code>```

Body:
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big

I hope you understood what i mean. Thank you! Sorry for my english.

Body:
You can use this Code

 lblFirst.text = txtField.text;
 int intValue = [lblFirst.text intValue];
 if (intValue < 20) {
    lblSecond.text = @"Small";
 } else if (intValue >= 20 && intValue <= 30) {
    lblSecond.text = @"Normal";
 } else if (intValue > 40) {
    lblSecond.text = @"Big";
 }


问:
I have used this code for text to speech via pyttx3 and get this error I dont know how to solve it
```<code>import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
</code>```

Error:

```<code>return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 1863, in <module>
    ISpeechWaveFormatEx._methods_ = [
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported.
</code>```

答: just use downgrade python version like 3.8.0 or before</p>

Body:
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()

Error:

return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 1863, in <module>
    ISpeechWaveFormatEx._methods_ = [
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\Karan\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported.


问:
How to write quotient_graph result to file
Here is a MWE to create the "issue"

>>> A = nx.complete_bipartite_graph(2, 3)
>>> same_neighbors = lambda u, v: (u not in A[v] and v not in A[u] and A[u] == A[v])
>>> B = nx.quotient_graph(A, same_neighbors)
>>> B.nodes()
NodeView((frozenset({0, 1}), frozenset({2, 3, 4})))
>>> B[frozenset({0, 1})]
AtlasView({frozenset({2, 3, 4}): {'weight': 6}})
>>> B.nodes[frozenset({0, 1})]
{'graph': <networkx.classes.graph.Graph object at 0x12b066e80>, 'nnodes': 2, 'nedges': 0, 'density': 0}
```

<p>I believe this <code>graph</code> attribute on the node is specifying the subgraph which this node comes from in the original graph, but I'm not sure. If someone could verify that would be nice.</p>

<p>Either way though, this <code>graph</code> attribute prevents me from using the <code>nx.write_graphml</code> function because subgraphs cannot be used as data formats. In particular it raises</p>

```networkx.exception.NetworkXError: GraphML writer does not support <class 'networkx.classes.graph.Graph'> as data values.
```

Now I don't actually need the subgraph in the graphml file, so just dropping that data is probably the best way for me to get the graph written to a file. What is the best way to do this?

答:
I believe this graph attribute on the node is specifying the subgraph which this node comes from in the original graph, but I'm not sure. If someone could verify that would be nice.

Yes, you are right in assuming that the graph attribute is actually specifying the subgraph based on the original graph. It is mentioned in the documentation for quotient graph . Check out the description of node_data, you will find that:

```<code>node_data (function) – This function takes one argument, B, a set of
nodes in G, and must return a dictionary representing the node data
attributes to set on the node representing B in the quotient graph. If
None, the following node attributes will be set:

- graph, the subgraph of the graph G that this block represents,
- nnodes, the number of nodes in this block,
- nedges, the number of edges within this block,
- density, the density of the subgraph of G that this block represents.
</code>```

You can also check out the subgraph yourself, by typing

```<code>for node in B.nodes():
    print("Information for subgraph ", node)
    print(B.nodes[node]['graph'].nodes())

# Output:
# Information for subgraph  frozenset({0, 1})
# Nodes are  [0, 1]
# Information for subgraph  frozenset({2, 3, 4})
# Nodes are  [2, 3, 4]
</code>```

Now I don't actually need the subgraph in the graphml file, so just
  dropping that data is probably the best way for me to get the graph
  written to a file. What is the best way to do this?

You can simply create a new graph and add only the nodes and edges, and discard any other data. (Again, you are right in assuming that this information is irrelevant for writing data in GraphML format as you only need the nodes and edges).

Let's check the EdgeView of the Quotient graph, before going further:

```<code>B.edges(data=True)
# EdgeDataView([(frozenset({0, 1}), frozenset({2, 3, 4}), {'weight': 6})])
</code>```

Notice, how the data for the edge is dictionary with weight as key. This info. will be useful in the subsequent code.

Now, create a new graph, and add the edges directly from the quotient graph.

```<code>H = nx.Graph()

# Here B is the quotient graph
for u,v,d in B.edges(data=True):
    # Notice how the weight is assigned to the new graph
    H.add_edge(u, v, weight=d['weight'])
</code>```

If you want to verify that the new graph has the same structure, you can check it out using nx.is_isomorphic

```<code>nx.is_isomorphic(H, B)
# True
</code>```

Now you can simply write your graph into GraphML format

```<code>nx.readwrite.graphml.write_graphml(H, "my_graph.graphml")
</code>```

For more information, you can check out this Google Colab Notebook, with the above working code.

References:

NetworkX - Quotient Graph

write_graphml

NetworkX - is_isomorphic

Body:
Here is a MWE to create the "issue"

>>> A = nx.complete_bipartite_graph(2, 3)
>>> same_neighbors = lambda u, v: (u not in A[v] and v not in A[u] and A[u] == A[v])
>>> B = nx.quotient_graph(A, same_neighbors)
>>> B.nodes()
NodeView((frozenset({0, 1}), frozenset({2, 3, 4})))
>>> B[frozenset({0, 1})]
AtlasView({frozenset({2, 3, 4}): {'weight': 6}})
>>> B.nodes[frozenset({0, 1})]
{'graph': <networkx.classes.graph.Graph object at 0x12b066e80>, 'nnodes': 2, 'nedges': 0, 'density': 0}

I believe this graph attribute on the node is specifying the subgraph which this node comes from in the original graph, but I'm not sure. If someone could verify that would be nice.

Either way though, this graph attribute prevents me from using the nx.write_graphml function because subgraphs cannot be used as data formats. In particular it raises

networkx.exception.NetworkXError: GraphML writer does not support <class 'networkx.classes.graph.Graph'> as data values.

Now I don't actually need the subgraph in the graphml file, so just dropping that data is probably the best way for me to get the graph written to a file. What is the best way to do this?

Body:
I believe this graph attribute on the node is specifying the subgraph which this node comes from in the original graph, but I'm not sure. If someone could verify that would be nice.

Yes, you are right in assuming that the graph attribute is actually specifying the subgraph based on the original graph. It is mentioned in the documentation for quotient graph . Check out the description of node_data, you will find that:

node_data (function) – This function takes one argument, B, a set of
nodes in G, and must return a dictionary representing the node data
attributes to set on the node representing B in the quotient graph. If
None, the following node attributes will be set:

- graph, the subgraph of the graph G that this block represents,
- nnodes, the number of nodes in this block,
- nedges, the number of edges within this block,
- density, the density of the subgraph of G that this block represents.

You can also check out the subgraph yourself, by typing

for node in B.nodes():
    print("Information for subgraph ", node)
    print(B.nodes[node]['graph'].nodes())

# Output:
# Information for subgraph  frozenset({0, 1})
# Nodes are  [0, 1]
# Information for subgraph  frozenset({2, 3, 4})
# Nodes are  [2, 3, 4]

Now I don't actually need the subgraph in the graphml file, so just
  dropping that data is probably the best way for me to get the graph
  written to a file. What is the best way to do this?

You can simply create a new graph and add only the nodes and edges, and discard any other data. (Again, you are right in assuming that this information is irrelevant for writing data in GraphML format as you only need the nodes and edges).

Let's check the EdgeView of the Quotient graph, before going further:

B.edges(data=True)
# EdgeDataView([(frozenset({0, 1}), frozenset({2, 3, 4}), {'weight': 6})])

Notice, how the data for the edge is dictionary with weight as key. This info. will be useful in the subsequent code.

Now, create a new graph, and add the edges directly from the quotient graph.

H = nx.Graph()

# Here B is the quotient graph
for u,v,d in B.edges(data=True):
    # Notice how the weight is assigned to the new graph
    H.add_edge(u, v, weight=d['weight'])

If you want to verify that the new graph has the same structure, you can check it out using nx.is_isomorphic

nx.is_isomorphic(H, B)
# True

Now you can simply write your graph into GraphML format

nx.readwrite.graphml.write_graphml(H, "my_graph.graphml")

For more information, you can check out this Google Colab Notebook, with the above working code.

References:

NetworkX - Quotient Graph

write_graphml

NetworkX - is_isomorphic


问:
How to get the placeholder and the text to begin from the start of the textarea?
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="comment-label" for="comments">Comments</label>
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></code>```

OUTPUT

答:
If you change your HTML to using the textarea element it will work as you want it to. Input elements are not intended to be used that way.</p>

```<code><label class="comment-label" for="comments">Comments</label>
<textarea name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></textarea>```

</code>```

Body:
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}

Comments
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required>

OUTPUT

Body:
If you change your HTML to using the textarea element it will work as you want it to. Input elements are not intended to be used that way.

<label class="comment-label" for="comments">Comments</label>
<textarea name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></textarea>```


问:
How to insert my 1:100 draw from Autocad into a Word document
I must to insert an 1:100 image I did in Autocad inside a Word document. I just printed in PDF format and it fits a A4. I could do a print screen, paste it on the Word page and crop the boundaries, but it need some very sketchy adjusts to put it back into the correct scale. Also the lines does not render very well. I believe there is a better and correct way to do.</p>

答:
I guess my first question would be, "Why do you need to insert the file into a word document?"

If you must insert it into a word document, you should use the Insert Object process described here -->PDF into Word Doc.

This would never be my preferred method though. I would rather convert the word document to PDF and then insert my scaled PDF drawing into the exported word doc PDF. This would keep the integrity of your drawing scale intact.

Just my two cents, which won't get you much.


问:
How to close the router opened in new tab on logout in angular8
Hi i have used anchor tag for opening the routerLink in new tab. Now if i click on logout, the routerLink in the new tab remains same, if there is any API hit then the routerLink redrirects to login page. But i want all the tabs to close as soon i logout, as the other router pages doesnt have header in the screen.

Header.component.ts:

```<code>public logout() {
    this.authservice.logOutSuccess(true);
    this.router.navigate(["/login"]);
    this.cookieService.delete(TPIConstants.AUTH_TOKEN);
  }
</code>```

Here in the header component, if i click on logout i am clearing the cookie, so the screen redirects to login page.

But in the landing page, i have add new button, when i click on that it opens the router in the new tab,

Landing.html:

```<code> <a class="btn btn-light" target="_blank" [routerLink]="['/profile']"> Add New</a>
</code>```

Profile Screen opens in new Tab now.

So, i have used a common service called auth.service in which i have used subject

auth.service.ts:

```<code> public  detectLogOutSubject = new Subject<any>();
  logOutConfirmed$ = this.detectLogOutSubject.asObservable();

 logOutSuccess(value) {
    this.detectLogOutSubject.next(value);
  }
</code>```

so when i click on logout, it comes to the authservice and triggers this event, and in profile page i have written like this in the constructor method

profile.component.ts: and app.component.ts

```<code>constructor(){
    this.subscription = this.authService.logOutConfirmed$.subscribe(
      res => {
        alert(res)
    });
   }
</code>```

Profile.html:

```<code><div>
                <button class="btn btn-secondary" onclick="window.close();" title="Close Window">
                    <i class="fas fa-times fa-1x"></i>
                </button>
            </div>
</code>```

In profile html, i have the above div section, if that click triggered also, it will close the tab, but i am not able to get the event from logout function to profile screen/app.component also, i am struck, no where getting how to proceed

答:
Because you aren't using a window.open() to open the new tab, your Javascript will not have permission to close the tab. If closing the tab is important, then you need to use window.open() to open the tab and then you can use window.close() to close it when you are ready.

More discussion about the security and permissions can be found here.

Body:
Hi i have used anchor tag for opening the routerLink in new tab. Now if i click on logout, the routerLink in the new tab remains same, if there is any API hit then the routerLink redrirects to login page. But i want all the tabs to close as soon i logout, as the other router pages doesnt have header in the screen.

Header.component.ts:

public logout() {
    this.authservice.logOutSuccess(true);
    this.router.navigate(["/login"]);
    this.cookieService.delete(TPIConstants.AUTH_TOKEN);
  }

Here in the header component, if i click on logout i am clearing the cookie, so the screen redirects to login page.

But in the landing page, i have add new button, when i click on that it opens the router in the new tab,

Landing.html:

  Add New

Profile Screen opens in new Tab now.

So, i have used a common service called auth.service in which i have used subject

auth.service.ts:

 public  detectLogOutSubject = new Subject<any>();
  logOutConfirmed$ = this.detectLogOutSubject.asObservable();

 logOutSuccess(value) {
    this.detectLogOutSubject.next(value);
  }

so when i click on logout, it comes to the authservice and triggers this event, and in profile page i have written like this in the constructor method

profile.component.ts: and app.component.ts

constructor(){
    this.subscription = this.authService.logOutConfirmed$.subscribe(
      res => {
        alert(res)
    });
   }

Profile.html:

                <button class="btn btn-secondary" onclick="window.close();" title="Close Window">

                </button>

In profile html, i have the above div section, if that click triggered also, it will close the tab, but i am not able to get the event from logout function to profile screen/app.component also, i am struck, no where getting how to proceed


问:
Monitor chattr changes
I would like to get notified within a C program, when someone changes a directory or file attributes via command line: chattr.

e.g.:

```<code>mkdir -p /tmp/test
sudo chattr +i /tmp/test
</code>```

I would like to write a program that detects when /tmp/test directory has become inmutable and reacts to.
I have found inotify, but it will detect only chmod, setxattr... changes, but not chattr.

答:
```<code>struct ev_loop* loop = nullptr;
int fd = 0;
void
sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
  else if (signo == SIGTERM)
    printf("received SIGTERM\n");
  else if (signo == SIGBUS)
    printf("received SIGBUS\n");
  else if (signo == SIGABRT)
    printf("received SIGABRT\n");
  if (loop != nullptr) {
    std::cout << "Stopping event loop" << std::endl;
    ev_break(EV_A_ EVBREAK_ONE);
  }
}
void
monitoring(struct ev_loop* loop, struct ev_io* io, int revents)
{
  struct audit_reply reply;

  audit_get_reply(fd, &reply, GET_REPLY_NONBLOCKING, 0);

  if (reply.type != AUDIT_EOE && reply.type != AUDIT_PROCTITLE &&
      reply.type != AUDIT_PATH) {
    char* buf = new char[MAX_AUDIT_MESSAGE_LENGTH];

    snprintf(buf,
             MAX_AUDIT_MESSAGE_LENGTH,
             "Type=%s Message=%.*s",
             audit_msg_type_to_name(reply.type),
             reply.len,
             reply.message);

    printf("EVENT: %s\n", buf);
  }
}

int
main()
{
  std::cout << "Starting up..." << std::endl;

  if (signal(SIGINT, sig_handler) == SIG_ERR) {
    printf("can't catch SIGINT\n");
  }
  if (signal(SIGTERM, sig_handler) == SIG_ERR) {
    printf("can't catch SIGTERM\n");
  }
  if (signal(SIGBUS, sig_handler) == SIG_ERR) {
    printf("can't catch SIGBUS\n");
  }
  if (signal(SIGABRT, sig_handler) == SIG_ERR) {
    printf("can't catch SIGABRT\n");
  }

  struct ev_io monitor;
  fd = audit_open();

  audit_set_pid(fd, getpid(), WAIT_YES);
  struct audit_rule_data* rule = new audit_rule_data();

  std::cout << "Add watch dir..." << std::endl;
  audit_add_watch_dir(AUDIT_DIR, &rule, "test");

  // setting rule.
  audit_add_rule_data(fd, rule, AUDIT_FILTER_EXIT, AUDIT_ALWAYS);

  loop = EV_DEFAULT;

  ev_io_init(&monitor, monitoring, fd, EV_READ);

  std::cout << "Enable audit..." << std::endl;
  audit_set_enabled(fd, 1);
  std::cout << "Start io monitor..." << std::endl;
  ev_io_start(loop, &monitor);
  std::cout << "Start event loop..." << std::endl;
  // now wait for events to arrive
  ev_run(loop, 0);
  std::cout << "Closing audit..." << std::endl;
  audit_close(fd);
  delete rule;

  std::cout << "Bye" << std::endl;
  return 0;
}
</code>```

Title: Monitor chattr changes

Body:
I would like to get notified within a C program, when someone changes a directory or file attributes via command line: chattr.

e.g.:

mkdir -p /tmp/test
sudo chattr +i /tmp/test

I would like to write a program that detects when /tmp/test directory has become inmutable and reacts to.
I have found inotify, but it will detect only chmod, setxattr... changes, but not chattr.


问:
How to write an asynchronous recursive walkdir function with an asynchronous callback
I'm trying to write an async function that will traverse the filesystem tree, recursively, and calls an asynchronous callback for each file found.
This is for a learning effort, I have no real use case.

Here is what I have so far:

```<code>use async_std::{
    fs::{self, *},
    path::*,
    prelude::*,
}; // 1.5.0, features = ["unstable"]
use futures::{
    executor::block_on,
    future::{BoxFuture, FutureExt},
}; // 0.3.4
use std::{marker::Sync, pin::Pin};

fn main() {
    fn walkdir<F>(path: String, cb: &'static F) -> BoxFuture<'static, ()>
    where
        F: Fn(&DirEntry) -> BoxFuture<()> + Sync + Send,
    {
        async move {
            let mut entries = fs::read_dir(&path).await.unwrap();
            while let Some(path) = entries.next().await {
                let entry = path.unwrap();
                let path = entry.path().to_str().unwrap().to_string();
                if entry.path().is_file().await {
                    cb(&entry).await
                } else {
                    walkdir(path, cb).await
                }
            }
        }
        .boxed()
    }

    let foo = async {
        walkdir(".".to_string(), &|entry: &DirEntry| async {
            async_std::println!(">> {}\n", &entry.path().to_str().unwrap()).await
        })
        .await
    };

    block_on(foo);
}
</code>```

I get this far by some sort of trial and error, but now I'm stuck on async closure callback with this error

warning: unused import: `path::*`
 --> src/main.rs:3:5
  |
3 |     path::*,
  |     ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `pin::Pin`
  --> src/main.rs:10:25
   |
10 | use std::{marker::Sync, pin::Pin};
   |                         ^^^^^^^^

error[E0308]: mismatched types
  --> src/main.rs:33:54
   |
33 |           walkdir(".".to_string(), &|entry: &DirEntry| async {
   |  ______________________________________________________^
34 | |             async_std::println!(">> {}\n", &entry.path().to_str().unwrap()).await
35 | |         })
   | |_________^ expected struct `std::pin::Pin`, found opaque type
   |
   = note:   expected struct `std::pin::Pin<std::boxed::Box<dyn core::future::future::Future<Output = ()> + std::marker::Send>>`
           found opaque type `impl core::future::future::Future`
```

答:
```<code>use async_std::{
    fs::{self, *},
    path::*,
    prelude::*,
}; // 1.5.0
use futures::{future::{Future, FutureExt, LocalBoxFuture}, executor}; // 0.3.4

fn main() {
    async fn walkdir<R>(path: impl AsRef<Path>, mut cb: impl FnMut(DirEntry) -> R)
    where
        R: Future<Output = ()>,
    {
        fn walkdir_inner<'a, R>(path: &'a Path, cb: &'a mut dyn FnMut(DirEntry) -> R) -> LocalBoxFuture<'a, ()>
        where
            R: Future<Output = ()>,
        {
            async move {
                let mut entries = fs::read_dir(path).await.unwrap();

                while let Some(path) = entries.next().await {
                    let entry = path.unwrap();
                    let path = entry.path();
                    if path.is_file().await {
                        cb(entry).await
                    } else {
                        walkdir_inner(&path, cb).await
                    }
                }
            }.boxed_local()
        }

        walkdir_inner(path.as_ref(), &mut cb).await
    }

    executor::block_on({
        walkdir(".", |entry| async move {
            async_std::println!(">> {}", entry.path().display()).await
        })
    });
}
</code>```

Notable changes:

Take in AsRef<Path> instead of a String and a generic closure instead of a trait object reference

Change the closure type to be FnMut as it's more permissive

The closure returns any type that is a future.

There's an inner implementation function that hides the ugly API required for recursive async functions.

The callback takes the DirEntry by value instead of by reference.

See also:

How to asynchronously explore a directory and its sub-directories?

How to using async fn callback in rust

Body:
I'm trying to write an async function that will traverse the filesystem tree, recursively, and calls an asynchronous callback for each file found.
This is for a learning effort, I have no real use case.

Here is what I have so far:

use async_std::{
    fs::{self, *},
    path::*,
    prelude::*,
}; // 1.5.0, features = ["unstable"]
use futures::{
    executor::block_on,
    future::{BoxFuture, FutureExt},
}; // 0.3.4
use std::{marker::Sync, pin::Pin};

fn main() {
    fn walkdir<F>(path: String, cb: &'static F) -> BoxFuture<'static, ()>
    where
        F: Fn(&DirEntry) -> BoxFuture<()> + Sync + Send,
    {
        async move {
            let mut entries = fs::read_dir(&path).await.unwrap();
            while let Some(path) = entries.next().await {
                let entry = path.unwrap();
                let path = entry.path().to_str().unwrap().to_string();
                if entry.path().is_file().await {
                    cb(&entry).await
                } else {
                    walkdir(path, cb).await
                }
            }
        }
        .boxed()
    }

    let foo = async {
        walkdir(".".to_string(), &|entry: &DirEntry| async {
            async_std::println!(">> {}\n", &entry.path().to_str().unwrap()).await
        })
        .await
    };

    block_on(foo);
}

I get this far by some sort of trial and error, but now I'm stuck on async closure callback with this error

warning: unused import: `path::*`
 --> src/main.rs:3:5
  |
3 |     path::*,
  |     ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `pin::Pin`
  --> src/main.rs:10:25
   |
10 | use std::{marker::Sync, pin::Pin};
   |                         ^^^^^^^^

error[E0308]: mismatched types
  --> src/main.rs:33:54
   |
33 |           walkdir(".".to_string(), &|entry: &DirEntry| async {
   |  ______________________________________________________^
34 | |             async_std::println!(">> {}\n", &entry.path().to_str().unwrap()).await
35 | |         })
   | |_________^ expected struct `std::pin::Pin`, found opaque type
   |
   = note:   expected struct `std::pin::Pin<std::boxed::Box<dyn core::future::future::Future<Output = ()> + std::marker::Send>>`
           found opaque type `impl core::future::future::Future`

Body:
use async_std::{
    fs::{self, *},
    path::*,
    prelude::*,
}; // 1.5.0
use futures::{future::{Future, FutureExt, LocalBoxFuture}, executor}; // 0.3.4

fn main() {
    async fn walkdir<R>(path: impl AsRef<Path>, mut cb: impl FnMut(DirEntry) -> R)
    where
        R: Future<Output = ()>,
    {
        fn walkdir_inner<'a, R>(path: &'a Path, cb: &'a mut dyn FnMut(DirEntry) -> R) -> LocalBoxFuture<'a, ()>
        where
            R: Future<Output = ()>,
        {
            async move {
                let mut entries = fs::read_dir(path).await.unwrap();

                while let Some(path) = entries.next().await {
                    let entry = path.unwrap();
                    let path = entry.path();
                    if path.is_file().await {
                        cb(entry).await
                    } else {
                        walkdir_inner(&path, cb).await
                    }
                }
            }.boxed_local()
        }

        walkdir_inner(path.as_ref(), &mut cb).await
    }

    executor::block_on({
        walkdir(".", |entry| async move {
            async_std::println!(">> {}", entry.path().display()).await
        })
    });
}

Notable changes:

Take in AsRef<Path> instead of a String and a generic closure instead of a trait object reference

Change the closure type to be FnMut as it's more permissive

The closure returns any type that is a future.

There's an inner implementation function that hides the ugly API required for recursive async functions.

The callback takes the DirEntry by value instead of by reference.

See also:

How to asynchronously explore a directory and its sub-directories?

How to using async fn callback in rust


问:
How to dynamically apply a tooltip to part of an element's dynamic text content in Angular?
So I have this json file containing a dictionary.

definitions.json

```<code>{
  "word": "Some definition.",
  "an expression": "Some other definition."
}
</code>```

And I have components throughout my app that may be similar to this.

my.component.ts

```<code>  @Component({
    selector: 'my',
    template: `
      <h1>{{ someTitleText }}</h1>
      <p>{{ someText }}</p>
    `

  })
  export class MyComponent {
    @Input() someTitleText: string;
    @Input() myText: string;
  }
</code>```

I want to display a tooltip when the user will hover over a word that is present in the dictionary file and I need the tooltip to display the corresponding definition.

Making a parsing function to detect if and where a word or expression is present in a string is relatively trivial. Where I specifically need help is in figuring out the Angular way of adding the tooltip behavior to that specific word or expression inside the element once it has been detected.

ngx-bootstrap already has a tooltip and I would like to use that one rather than implement one from scratch.

What I need is the ability to somehow (structural directive, attribute directive, pipe, other???) selectively designate elements all over my app as having this behavior.

In other words, I need a reusable way to tell Angular "Hey, this element right here, I want you to check if it has some text content, and if some of that text is present in my dictionary, and if it is I want you to make it possible for the user to hover over that word or expression and for a tooltip to appear containing the appropriate definition for that word or expression."

答:
It is easy to create an Angular component dynamically at run-time compared to an Angular directive. All you have to do is to create a wrapper Angular component (say, TooltipComponent that takes 2 inputs namely displayText and tooltipText) that applies the ngx-bootstrap tooltip directive to some HTML element of your choice. Then render this wrapper component dynamically for the word that is present in your dictionary.

I believe everything in the below code snippet is self-explanatory.

app.component.ts

```<code>@Component({
  selector: "demo-tooltip-basic",
  template: `<p #para></p>`
})
export class AppComponent implements AfterViewInit {
  @ViewChild("para", { static: false }) para: ElementRef<HTMLElement>;

  text = `I'm in love with the shape of you!`;
  dict = {
    love: "like something",
    shape: "blah!!!",
    something: "..."
  };

  ...

  ngAfterViewInit() {
    this.text.split(" ").forEach(word => {
      if (this.dict[word]) {
        let factory = this.resolver.resolveComponentFactory(TooltipComponent);
        let ref = factory.create(this.injector);
        ref.instance.text = `${word} `;
        ref.instance.tooltip = this.dict[word];
        ref.changeDetectorRef.detectChanges();
        this.renderer.appendChild(
          this.para.nativeElement,
          ref.location.nativeElement
        );
      } else {
        this.renderer.appendChild(
          this.para.nativeElement,
          this.renderer.createText(`${word} `)
        );
      }
    });
  }
}
</code>```

To view the complete code of this app, use this stackblitz link (https://stackblitz.com/edit/dynamic-tooltips).

I hope you can further improve this basic implementation to suit your needs. For more information on creating Angular components dynamically, view this article.

Note: It is recommended to use Renderer2 API provided by the Angular to safely create HTML elements at runtime.

Body:
So I have this json file containing a dictionary.

definitions.json

{
  "word": "Some definition.",
  "an expression": "Some other definition."
}

And I have components throughout my app that may be similar to this.

my.component.ts

  @Component({
    selector: 'my',
    template: `

{{ someTitleText }}

{{ someText }}

    `

  })
  export class MyComponent {
    @Input() someTitleText: string;
    @Input() myText: string;
  }

I want to display a tooltip when the user will hover over a word that is present in the dictionary file and I need the tooltip to display the corresponding definition.

Making a parsing function to detect if and where a word or expression is present in a string is relatively trivial. Where I specifically need help is in figuring out the Angular way of adding the tooltip behavior to that specific word or expression inside the element once it has been detected.

ngx-bootstrap already has a tooltip and I would like to use that one rather than implement one from scratch.

What I need is the ability to somehow (structural directive, attribute directive, pipe, other???) selectively designate elements all over my app as having this behavior.

In other words, I need a reusable way to tell Angular "Hey, this element right here, I want you to check if it has some text content, and if some of that text is present in my dictionary, and if it is I want you to make it possible for the user to hover over that word or expression and for a tooltip to appear containing the appropriate definition for that word or expression."

Body:
It is easy to create an Angular component dynamically at run-time compared to an Angular directive. All you have to do is to create a wrapper Angular component (say, TooltipComponent that takes 2 inputs namely displayText and tooltipText) that applies the ngx-bootstrap tooltip directive to some HTML element of your choice. Then render this wrapper component dynamically for the word that is present in your dictionary.

I believe everything in the below code snippet is self-explanatory.

app.component.ts

@Component({
  selector: "demo-tooltip-basic",
  template: `<p #para></p>`
})
export class AppComponent implements AfterViewInit {
  @ViewChild("para", { static: false }) para: ElementRef<HTMLElement>;

  text = `I'm in love with the shape of you!`;
  dict = {
    love: "like something",
    shape: "blah!!!",
    something: "..."
  };

  ...

  ngAfterViewInit() {
    this.text.split(" ").forEach(word => {
      if (this.dict[word]) {
        let factory = this.resolver.resolveComponentFactory(TooltipComponent);
        let ref = factory.create(this.injector);
        ref.instance.text = `${word} `;
        ref.instance.tooltip = this.dict[word];
        ref.changeDetectorRef.detectChanges();
        this.renderer.appendChild(
          this.para.nativeElement,
          ref.location.nativeElement
        );
      } else {
        this.renderer.appendChild(
          this.para.nativeElement,
          this.renderer.createText(`${word} `)
        );
      }
    });
  }
}

To view the complete code of this app, use this stackblitz link (https://stackblitz.com/edit/dynamic-tooltips).

I hope you can further improve this basic implementation to suit your needs. For more information on creating Angular components dynamically, view this article.

Note: It is recommended to use Renderer2 API provided by the Angular to safely create HTML elements at runtime.


问:
Why does Array(repeating: Dog(), count: 7) make an array of 7 elements pointing to the same Dog instance?
Assuming Dog is a class

```<code>let arr = Array(repeating: Dog(), count: 7)
</code>```

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

```<code>var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}
</code>```

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

答:
It works as documented - repeats single value. In your case a value is pointer to once created instance of class Dog.

```<code>/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
///     let fiveZs = Array(repeating: "Z", count: 5)
///     print(fiveZs)
///     // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
///   - repeatedValue: The element to repeat.
///   - count: The number of times to repeat the value passed in the
///     `repeating` parameter. `count` must be zero or greater.
@inlinable public init(repeating repeatedValue: Element, count: Int)
</code>```

Body:
Assuming Dog is a class

let arr = Array(repeating: Dog(), count: 7)

Why do all the elements in the array point to the same dog instance ?
Now, I know to run a normal for loop and create 7 instances like

var arr = [Dog]()
for i in 1...7 {
   arr[i] = Dog()
}

But that's not the point. I wanna understand the init(repeating:count:) function at a deeper level. Please share any insights you have !

Body:
It works as documented - repeats single value. In your case a value is pointer to once created instance of class Dog.

/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
///     let fiveZs = Array(repeating: "Z", count: 5)
///     print(fiveZs)
///     // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
///   - repeatedValue: The element to repeat.
///   - count: The number of times to repeat the value passed in the
///     `repeating` parameter. `count` must be zero or greater.
@inlinable public init(repeating repeatedValue: Element, count: Int)


问:
how to replace name with an ID in javascript
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<head>

<title>Test</title>
</head>

<body>
  <div class = "container">
   <div id="checkBoxes">
  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
    </div>
   <button id="btn">Calculate</button>

    <div id="Sums">
      <p id="ItemTotal"> Item Total: </p>
      <p id="Tax"> Tax: </p>
      <p id="TotalWithTax">Total with Tax: </p>

    </div>
  </div>

</body>

</html></code>```

答:
If you have more than one its not correct to use same ID.

you can use de class and select it with document.querySelectorAll('.items')

Body:
I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used   name="items[]" to get the values i was wondering if there is a way to use ID  or Class instead of the name.Any help would be appreciated in advance .

var count = 0;
var tax = 0.05;

var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

function Calculate()
{
  initVariable();

 for(var i =0 ;i< checks.length;i++)
   {
     if(checks[i].checked)
       {
         count+=parseFloat(checks[i].value);
       }
   }
  ItemTotal.innerHTML +=count;
  taxFeild.innerHTML+=(parseFloat(tax*count));
  Total.innerHTML+= (tax*count) + count;
}

btn.addEventListener('click',Calculate);

function initVariable()
{
  count =0;
  ItemTotal.innerHTML="Item Total: ";
  taxFeild.innerHTML =" Tax: ";
  Total.innerHTML ="Total with Tax: ";
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>

<title>Test</title>

  <input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)

  <input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)

  <input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)

   <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:


问:
Custom SwiftUI view with a two-way binding
I'm struggling to implement a custom view which can take Binding as an argument and implement two-way updates of that value.

So basically I'm implementing my custom slider and want its initializer to be like this:

MySlider(value: <Binding<Float>)

What I'm struggling with:

How do I subscribe to remote updates of the binding value so that I can update the view's state?

Is there any nice way to bind a Binding with @State property?

Here's my current implementation so far which is not perfect.

```<code>struct MySlider: View {

    @Binding var selection: Float?
    @State private var selectedValue: Float?

    init(selection: Binding<Float?>) {
        self._selection = selection

        // https://stackoverflow.com/a/58137096
        _selectedValue = State(wrappedValue: selection.wrappedValue)
    }

    var body: some View {
         HStack(spacing: 3) {
             ForEach(someValues) { (v) in
                 Item(value: v,
                      isSelected: v == self.selection)
                     .onTapGesture {
                         // No idea how to do that other way so I don't have to set it twice
                         self.selection = v
                         self.selectedValue = v
                    }
             }
         }
    }
}
</code>```

Edit 1:
I suppose my problem is that the underlying model object comes from Core Data and wasn't owned by any SwiftUI view which would observe its changes. The model object was owned by the UIKit ViewController and I was passing only a Binding to the SwiftUI view which is not enough.
My solution now is to pass the model object also to the SwiftUI View so that it can marked it as an @ObservedObject.

```<code>struct MySlider<T>: View where T: ObservableObject {

    @ObservedObject var object: T
    @Binding var selection: Float?

    var body: some View {
        return ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 3) {
                ForEach(values) { (v) in
                    Item(value: v,
                         isSelected: v == self.selection)
                        .onTapGesture {
                            self.selection = v
                    }
                }
            }
        }
    }
}
</code>```

答:
The definition of @Binding is essentially a two-way connection to an underlying data item, such a a @State variable that's owned by another View. As stated by Apple:

Use a binding to create a two-way connection between a view and its underlying model.

If it's a binding, SwiftUI will already update its views automatically if the value changes; so (in answer to your first question), you don't need to do any sort of subscriptions to update your custom view - that will happen automatically.

Similarly (regarding your second question), because the binding is the state from another view, you shouldn't be declaring it as a state for your view as well, and I also don't believe it's possible. State is something that should be a purely internal value to your view (Apple strongly recommend that all @State properties are declared private).

This all ties back to the 'Single Source of Truth' concept Apple stressed when unveiling SwiftUI: The parent view where that binding's already @State is what owns the information, so it's not something your view should also declare as a state.

For your code, I think all you need to do is take out that second state property, because it's not required. Just make sure the binding you pass is a @State property in whatever parent view owns your custom view, and pass it in using the $ syntax to create that binding. This article covers the idea in more detail if you need.

```<code>struct MySlider: View {

    @Binding var selection: Float?

    init(selection: Binding<Float?>) {
        self._selection = selection
    }

    var body: some View {
         HStack(spacing: 3) {
             ForEach(someValues) { (v) in
                 Item(value: v, isSelected: v == self.selection)
                     .onTapGesture {
                         self.selection = v
                    }
             }
         }
    }
}
</code>```

Body:
I'm struggling to implement a custom view which can take Binding as an argument and implement two-way updates of that value.

So basically I'm implementing my custom slider and want its initializer to be like this:

MySlider(value: <Binding<Float>)

What I'm struggling with:

How do I subscribe to remote updates of the binding value so that I can update the view's state?

Is there any nice way to bind a Binding with @State property?

Here's my current implementation so far which is not perfect.

struct MySlider: View {

    @Binding var selection: Float?
    @State private var selectedValue: Float?

    init(selection: Binding<Float?>) {
        self._selection = selection

        // https://stackoverflow.com/a/58137096
        _selectedValue = State(wrappedValue: selection.wrappedValue)
    }

    var body: some View {
         HStack(spacing: 3) {
             ForEach(someValues) { (v) in
                 Item(value: v,
                      isSelected: v == self.selection)
                     .onTapGesture {
                         // No idea how to do that other way so I don't have to set it twice
                         self.selection = v
                         self.selectedValue = v
                    }
             }
         }
    }
}

Edit 1:
I suppose my problem is that the underlying model object comes from Core Data and wasn't owned by any SwiftUI view which would observe its changes. The model object was owned by the UIKit ViewController and I was passing only a Binding to the SwiftUI view which is not enough.
My solution now is to pass the model object also to the SwiftUI View so that it can marked it as an @ObservedObject.

struct MySlider<T>: View where T: ObservableObject {

    @ObservedObject var object: T
    @Binding var selection: Float?

    var body: some View {
        return ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 3) {
                ForEach(values) { (v) in
                    Item(value: v,
                         isSelected: v == self.selection)
                        .onTapGesture {
                            self.selection = v
                    }
                }
            }
        }
    }
}

Body:
The definition of @Binding is essentially a two-way connection to an underlying data item, such a a @State variable that's owned by another View. As stated by Apple:

Use a binding to create a two-way connection between a view and its underlying model.

If it's a binding, SwiftUI will already update its views automatically if the value changes; so (in answer to your first question), you don't need to do any sort of subscriptions to update your custom view - that will happen automatically.

Similarly (regarding your second question), because the binding is the state from another view, you shouldn't be declaring it as a state for your view as well, and I also don't believe it's possible. State is something that should be a purely internal value to your view (Apple strongly recommend that all @State properties are declared private).

This all ties back to the 'Single Source of Truth' concept Apple stressed when unveiling SwiftUI: The parent view where that binding's already @State is what owns the information, so it's not something your view should also declare as a state.

For your code, I think all you need to do is take out that second state property, because it's not required. Just make sure the binding you pass is a @State property in whatever parent view owns your custom view, and pass it in using the $ syntax to create that binding. This article covers the idea in more detail if you need.

struct MySlider: View {

    @Binding var selection: Float?

    init(selection: Binding<Float?>) {
        self._selection = selection
    }

    var body: some View {
         HStack(spacing: 3) {
             ForEach(someValues) { (v) in
                 Item(value: v, isSelected: v == self.selection)
                     .onTapGesture {
                         self.selection = v
                    }
             }
         }
    }
}


问:
Difference between AuthorizationServerConfigurerAdapter vs WebSecurityConfigurerAdapter
Whats are the difference between these classes? I know that WebSecurityConfigurerAdapter is used to customize "security" on our apps.

Whats I've done:

```<code>public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
</code>```

But i don't understand the meaning of AuthorizationServerConfigurerAdapter.

I read a couple of articles but I don't get it.

答: if you want to use a third party authenticater, this means at the same time OAuth, then you must use AuthorizationServerConfigurerAdapter with WebSecurityConfigurerAdapter at OAuth serverside. If not so, WebSecurityConfigurerAdapter is enough for ordinary authentication</p>

Body:
Whats are the difference between these classes? I know that WebSecurityConfigurerAdapter is used to customize "security" on our apps.

Whats I've done:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

But i don't understand the meaning of AuthorizationServerConfigurerAdapter.

I read a couple of articles but I don't get it.


问:
Date Conversion from value in C#
Does anyone possibly recognize the following value "40195.315752" as a date?  I need to convert/format this value-based date to a System.DateTime object, but don't understand it's format.

Thanks.

答:
the value you have displayed is a double...

```<code>var val = 40195.315752;
            var span = System.TimeSpan.FromMilliseconds(val);
            var time = new DateTime(span.Ticks);
</code>```

above will convert it to Datetime but besure to note that System.Timespan continas several overloads to load span you need to identify which one is that you want...

Title: Date Conversion from value in C#

Body:
the value you have displayed is a double...

var val = 40195.315752;
            var span = System.TimeSpan.FromMilliseconds(val);
            var time = new DateTime(span.Ticks);

above will convert it to Datetime but besure to note that System.Timespan continas several overloads to load span you need to identify which one is that you want...


问:
How can I call a method as background worker by adding it into Startup in .netcore 2.1?
I am creating a simple logging system by using Nest and C#. I have a log producer for collecting logs inside of blockingcollection. Also I have a consumer. But I stumpled upon with an issue. How can I use my comsumer in startup or is there any way to create background servise which was listening queue of blockingcollection? What is best practice of it? I am confusing how to call AsyncConsumer or consumer when application startup.</p>

```<code> public class SimpleLog
    {
        public string Header { get; set; }
        public string LogDate { get; set; }
        public string Sessionid { get; set; }
        public string Userid { get; set; }
        public string Correlationid { get; set; }
        public int Status { get; set; }
        public string UrlQueryString { get; set; }
        public string UrlPath { get; set; }
        public string UrlMethod { get; set; }
        public string Environment { get; set; }
        public string IndexName { get; set; }
        public string IndexType { get; set; }

    }
    public class QuickLog
    {
        private static BlockingCollection<SimpleLog> data = new BlockingCollection<SimpleLog>();

        public static void Producer(SimpleLog pageviewLog)
        {
            data.TryAdd(pageviewLog, TimeSpan.FromSeconds(10));
        }

        public static void Consumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }

            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();

            var response = _client.IndexMany(logs, log.IndexName, log.IndexType);

            if (!response.IsValid)
                throw response.OriginalException;

        }

        public async Task AsyncConsumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }
            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();
            var response = await _client.IndexManyAsync(logs, log.IndexName, log.IndexType).ConfigureAwait(false);

            if (!response.IsValid)
                throw response.OriginalException;

            await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
        }
    }
    public static class ElasticConfig
    {
        private static IElasticClient _client;
        static ElasticConfig()
        {
            var esurl = LogSettings.Url;
            string[] urls = esurl.Split(',');
            var nodes = new Uri[2];

            for (int i = 0; i < urls.Length; i++)
            {
                nodes.SetValue(new Uri(urls[i]), i);
            }

            var connectionPool = new SniffingConnectionPool(nodes);
            var connectionSettings = new ConnectionSettings(connectionPool).RequestTimeout(
                TimeSpan.FromSeconds(60))
                .PingTimeout(TimeSpan.FromSeconds(60))
                .MaxRetryTimeout(TimeSpan.FromSeconds(60))
                .MaxDeadTimeout(TimeSpan.FromSeconds(60))
                .DeadTimeout(TimeSpan.FromSeconds(60)).DisablePing()
                                .SniffOnConnectionFault(false)
                                .SniffOnStartup(false)
                                .SniffLifeSpan(TimeSpan.FromMinutes(1));
            _client = new ElasticClient(connectionSettings);
        }
        public static IElasticClient GetClient()
        {
            return _client;
        }
    }
</code>```

答:
IHostedService is solution for you.

You can crate new class and inherit from this class https://gist.github.com/davidfowl/a7dd5064d9dcf35b6eae1a7953d615e3

Then your new class will be something like this

```<code>public class LogService : HostedService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public LogBackgroundService (IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            await new QuickLog().AsyncConsumer(cancellationToken);
            await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
        }
    }
}
</code>```

Finally update your Startup.cs:

```<code>services.AddSingleton<IHostedService, LogService>();
</code>```

Body:
I am creating a simple logging system by using Nest and C#. I have a log producer for collecting logs inside of blockingcollection. Also I have a consumer. But I stumpled upon with an issue. How can I use my comsumer in startup or is there any way to create background servise which was listening queue of blockingcollection? What is best practice of it? I am confusing how to call AsyncConsumer or consumer when application startup.

 public class SimpleLog
    {
        public string Header { get; set; }
        public string LogDate { get; set; }
        public string Sessionid { get; set; }
        public string Userid { get; set; }
        public string Correlationid { get; set; }
        public int Status { get; set; }
        public string UrlQueryString { get; set; }
        public string UrlPath { get; set; }
        public string UrlMethod { get; set; }
        public string Environment { get; set; }
        public string IndexName { get; set; }
        public string IndexType { get; set; }

    }
    public class QuickLog
    {
        private static BlockingCollection<SimpleLog> data = new BlockingCollection<SimpleLog>();

        public static void Producer(SimpleLog pageviewLog)
        {
            data.TryAdd(pageviewLog, TimeSpan.FromSeconds(10));
        }

        public static void Consumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }

            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();

            var response = _client.IndexMany(logs, log.IndexName, log.IndexType);

            if (!response.IsValid)
                throw response.OriginalException;

        }

        public async Task AsyncConsumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }
            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();
            var response = await _client.IndexManyAsync(logs, log.IndexName, log.IndexType).ConfigureAwait(false);

            if (!response.IsValid)
                throw response.OriginalException;

            await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
        }
    }
    public static class ElasticConfig
    {
        private static IElasticClient _client;
        static ElasticConfig()
        {
            var esurl = LogSettings.Url;
            string[] urls = esurl.Split(',');
            var nodes = new Uri[2];

            for (int i = 0; i < urls.Length; i++)
            {
                nodes.SetValue(new Uri(urls[i]), i);
            }

            var connectionPool = new SniffingConnectionPool(nodes);
            var connectionSettings = new ConnectionSettings(connectionPool).RequestTimeout(
                TimeSpan.FromSeconds(60))
                .PingTimeout(TimeSpan.FromSeconds(60))
                .MaxRetryTimeout(TimeSpan.FromSeconds(60))
                .MaxDeadTimeout(TimeSpan.FromSeconds(60))
                .DeadTimeout(TimeSpan.FromSeconds(60)).DisablePing()
                                .SniffOnConnectionFault(false)
                                .SniffOnStartup(false)
                                .SniffLifeSpan(TimeSpan.FromMinutes(1));
            _client = new ElasticClient(connectionSettings);
        }
        public static IElasticClient GetClient()
        {
            return _client;
        }
    }

Body:
IHostedService is solution for you.

You can crate new class and inherit from this class https://gist.github.com/davidfowl/a7dd5064d9dcf35b6eae1a7953d615e3

Then your new class will be something like this

public class LogService : HostedService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public LogBackgroundService (IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            await new QuickLog().AsyncConsumer(cancellationToken);
            await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
        }
    }
}

Finally update your Startup.cs:

services.AddSingleton<IHostedService, LogService>();


问:
How to replace() an item in Qml StackView that is not on the top of the stack?
According to the Qt docs I should be able to call:

Item replace(target, item, properties, operation)

Replaces one or more items on the stack with the specified item and
operation, and optionally applies a set of properties on the item. The
item can be an Item, Component, or a url. Returns the item that became
current.

So if I were to enact:

```<code>stackView.replace(stackView.get(stackView.depth - 3), mycomponent)
</code>```

I would expect the item, located at the stackView index 2 less than the largest index, to replace with mycomponent. However, this is not the case; it seems that index depth - 1 and depth - 2 and depth - 3 are popped off the stack, then an instance of mycomponent is added. How do I replace index of depth - 3 without losing the higher-stacked objects?

MVP:
In the following code, if I push, push, push, then replace, I would expect Depth at onCompleted: 4 to be the value for Current Index: 1. Instead, I get Depth at onCompleted: 2

```<code>import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    id: window

    Component {
        id: mycomponent
        Row {
            spacing: 2
            Button {
                text: "Push"
                onClicked: push(mycomponent)
            }
            Button {
                text: "Pop"
                onClicked: pop()
            }
            Button {
                text: "Replace"
                onClicked: stackView.replace(stackView.get(stackView.depth - 3), mycomponent)
            }
            Text {
                text: "Current Index: " + (stackView.depth - 1)
            }
            Text {
                Component.onCompleted: text = "Depth at onCompleted: " + stackView.depth
            }
        }
    }

    StackView {
        id: stackView
        initialItem: mycomponent
    }
}
</code>```

答:
Not that the described behaviour is correctly documented (second paragraph):

If the target argument is specified, all items down to the item will be replaced. If target is null, all items in the stack will be replaced. If not specified, only the top item will be replaced.

A solution may be to first pop 3 items (and store the two top items), push your new component and at the end push the stored items:

```<code>...
Button {
    text: "Replace"
    onClicked: {
        var item1 = stackView.pop();
        var item2 = stackView.pop();
        stackView.pop();
        stackView.push(mycomponent);
        stackView.push(item2);
        stackView.push(item1);
    }
}
...
</code>```

Body:
According to the Qt docs I should be able to call:

Item replace(target, item, properties, operation)

Replaces one or more items on the stack with the specified item and
operation, and optionally applies a set of properties on the item. The
item can be an Item, Component, or a url. Returns the item that became
current.

So if I were to enact:

stackView.replace(stackView.get(stackView.depth - 3), mycomponent)

I would expect the item, located at the stackView index 2 less than the largest index, to replace with mycomponent. However, this is not the case; it seems that index depth - 1 and depth - 2 and depth - 3 are popped off the stack, then an instance of mycomponent is added. How do I replace index of depth - 3 without losing the higher-stacked objects?

MVP:
In the following code, if I push, push, push, then replace, I would expect Depth at onCompleted: 4 to be the value for Current Index: 1. Instead, I get Depth at onCompleted: 2

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    id: window

    Component {
        id: mycomponent
        Row {
            spacing: 2
            Button {
                text: "Push"
                onClicked: push(mycomponent)
            }
            Button {
                text: "Pop"
                onClicked: pop()
            }
            Button {
                text: "Replace"
                onClicked: stackView.replace(stackView.get(stackView.depth - 3), mycomponent)
            }
            Text {
                text: "Current Index: " + (stackView.depth - 1)
            }
            Text {
                Component.onCompleted: text = "Depth at onCompleted: " + stackView.depth
            }
        }
    }

    StackView {
        id: stackView
        initialItem: mycomponent
    }
}

Body:
Not that the described behaviour is correctly documented (second paragraph):

If the target argument is specified, all items down to the item will be replaced. If target is null, all items in the stack will be replaced. If not specified, only the top item will be replaced.

A solution may be to first pop 3 items (and store the two top items), push your new component and at the end push the stored items:

...
Button {
    text: "Replace"
    onClicked: {
        var item1 = stackView.pop();
        var item2 = stackView.pop();
        stackView.pop();
        stackView.push(mycomponent);
        stackView.push(item2);
        stackView.push(item1);
    }
}
...