问:
Row wise by group sum with conditions
The aim is for an ID to be treated as a group and sum the rows of the distinct ID based on a set of conditions row wise.

The data is time dependent for any item_ID, we are interested to see if at the check_date of a given item_ID, do all item_IDs (including the row selected) of that ID group have start_dates less than the given item_ID AND the fail_dates are either greater than the check_date of the given item_ID OR NA. When these conditions are met, sum the value column whilst maintaining the ID grouping.

Using the example below and starting at row 1 then iterating down rows, sum the row values of an ID's item_IDs when either:

df$fail_date == NA AND df$check_date[1] >= start_date, OR

df$fail_date > df$check_date[1] AND df$check_date[1] >= start_date

where df$start_date[1] is the first row of check_date which gets iterated down rows

Example data:

```<code>df <- data.frame(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
                 start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
                 check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
                 fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
                 value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15))
</code>```

The desired output would be:

```<code>   ID   item_ID start_date check_date fail_date value conditional_sum
1   1  B874_20K      44107      44121        NA    30              55
2   1 BB849_21E      44107      44121        NA    25              55
3   1 BB842_21E      44107      44121     44114    60              55
4   1  B873_20K      44226      44240        NA    20             105
5   1  B875_21E      44233      44247     44328    30             105
6   1 BB848_20K      44289      44303        NA    15             120
7   2  BD49_21K      44107      44121     44207    50              70
8   2  BU44_20J      44107      44121     44196    20              70
9   2  DD93_21E      44226      44240        NA    15              15
10  3  B874_20K      44107      44121        NA    30             105
11  3 BB849_21E      44107      44121        NA    25             105
12  3  B873_20K      44107      44121        NA    20             105
13  3  B875_21E      44107      44121        NA    30             105
14  3  B873_20K      44233      44247        NA    20             210
15  3  BD49_21K      44233      44247        NA    50             210
16  3  BU44_20J      44233      44247        NA    20             210
17  3 BB848_20K      44233      44247        NA    15             210
</code>```

I'm really not sure how to crack this, my usual toolkit of dplyr group_by and summarise doesn't fit the bill. Any direction is greatly appreciated!

答:
How about this?

```<code>library(tidyverse)

df <- tibble(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
             start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
             check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
             fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
             value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15)) %>%
    mutate(item_ID = row_number())

df_no_na <- df %>% replace_na(list(fail_date = max(df$check_date) + 1))

conditional_sum_by_ID_and_check_date <- function(this_ID, this_check_date){
    df_no_na %>%
        filter(ID == this_ID,
               fail_date > this_check_date,
               start_date <= this_check_date) %>%
        summarize(conditional_sum = sum(value)) %>%
        pull()
}

output_frame <- df %>%
    distinct(ID, check_date) %>%
    mutate(conditional_sum = map2_dbl(ID, check_date, conditional_sum_by_ID_and_check_date)) %>%
    right_join(df, by = c("ID", "check_date"))
</code>```

The basic idea is to map over the pairs of ID/check_date, compute your sum, and then join back to the original table.

You could avoid the df_no_na bit by complicating the filter expression.

Benchmarking

I was curious about how much faster Greg's answer would be when the data size increased.  I created 1000 lines of test data using:

```<code>library(tidyverse)
library(runner)

num_id <- 100L
num_item <- 10L
num_days <- 100L

df <- tibble(ID = rep(1:num_id, each = num_item),
             item_ID = sample(1:num_item, num_id*num_item, replace = TRUE),
             start_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             fail_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             check_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             value = sample(1:num_days, num_id*num_item, replace = TRUE))
</code>```

Using the exact same benchmarking command from Greg's answer, you can see that his function is 215 times faster.

```<code>Unit: milliseconds
    expr       min         lq       mean     median         uq        max neval
 michael 3099.1283 3290.19973 3664.69723 3571.61724 3840.92476 5581.34401   100
    greg   13.2958   15.36794   17.29367   15.92426   18.22314   25.93559   100
</code>```

Title: Row wise by group sum with conditions

Body:
The aim is for an ID to be treated as a group and sum the rows of the distinct ID based on a set of conditions row wise.

The data is time dependent for any item_ID, we are interested to see if at the check_date of a given item_ID, do all item_IDs (including the row selected) of that ID group have start_dates less than the given item_ID AND the fail_dates are either greater than the check_date of the given item_ID OR NA. When these conditions are met, sum the value column whilst maintaining the ID grouping.

Using the example below and starting at row 1 then iterating down rows, sum the row values of an ID's item_IDs when either:

df$fail_date == NA AND df$check_date[1] >= start_date, OR

df$fail_date > df$check_date[1] AND df$check_date[1] >= start_date

where df$start_date[1] is the first row of check_date which gets iterated down rows

Example data:

df <- data.frame(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
                 start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
                 check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
                 fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
                 value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15))

The desired output would be:

   ID   item_ID start_date check_date fail_date value conditional_sum
1   1  B874_20K      44107      44121        NA    30              55
2   1 BB849_21E      44107      44121        NA    25              55
3   1 BB842_21E      44107      44121     44114    60              55
4   1  B873_20K      44226      44240        NA    20             105
5   1  B875_21E      44233      44247     44328    30             105
6   1 BB848_20K      44289      44303        NA    15             120
7   2  BD49_21K      44107      44121     44207    50              70
8   2  BU44_20J      44107      44121     44196    20              70
9   2  DD93_21E      44226      44240        NA    15              15
10  3  B874_20K      44107      44121        NA    30             105
11  3 BB849_21E      44107      44121        NA    25             105
12  3  B873_20K      44107      44121        NA    20             105
13  3  B875_21E      44107      44121        NA    30             105
14  3  B873_20K      44233      44247        NA    20             210
15  3  BD49_21K      44233      44247        NA    50             210
16  3  BU44_20J      44233      44247        NA    20             210
17  3 BB848_20K      44233      44247        NA    15             210

I'm really not sure how to crack this, my usual toolkit of dplyr group_by and summarise doesn't fit the bill. Any direction is greatly appreciated!

Body:
How about this?

library(tidyverse)

df <- tibble(ID = c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
             start_date = c(44107, 44107, 44107, 44226, 44233, 44289, 44107, 44107, 44226, 44107, 44107, 44107, 44107, 44233, 44233, 44233, 44233),
             check_date = c(44121, 44121, 44121, 44240, 44247, 44303, 44121, 44121, 44240, 44121, 44121, 44121, 44121, 44247, 44247, 44247, 44247),
             fail_date = c(NA, NA, 44114, NA, 44328, NA, 44207, 44196, NA, NA, NA, NA, NA, NA, NA, NA, NA),
             value = c(30, 25, 60, 20, 30, 15, 50, 20, 15, 30, 25, 20, 30, 20, 50, 20, 15)) %>%
    mutate(item_ID = row_number())

df_no_na <- df %>% replace_na(list(fail_date = max(df$check_date) + 1))

conditional_sum_by_ID_and_check_date <- function(this_ID, this_check_date){
    df_no_na %>%
        filter(ID == this_ID,
               fail_date > this_check_date,
               start_date <= this_check_date) %>%
        summarize(conditional_sum = sum(value)) %>%
        pull()
}

output_frame <- df %>%
    distinct(ID, check_date) %>%
    mutate(conditional_sum = map2_dbl(ID, check_date, conditional_sum_by_ID_and_check_date)) %>%
    right_join(df, by = c("ID", "check_date"))

The basic idea is to map over the pairs of ID/check_date, compute your sum, and then join back to the original table.

You could avoid the df_no_na bit by complicating the filter expression.

Benchmarking

I was curious about how much faster Greg's answer would be when the data size increased.  I created 1000 lines of test data using:

library(tidyverse)
library(runner)

num_id <- 100L
num_item <- 10L
num_days <- 100L

df <- tibble(ID = rep(1:num_id, each = num_item),
             item_ID = sample(1:num_item, num_id*num_item, replace = TRUE),
             start_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             fail_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             check_date = sample(1:num_days, num_id*num_item, replace = TRUE),
             value = sample(1:num_days, num_id*num_item, replace = TRUE))

Using the exact same benchmarking command from Greg's answer, you can see that his function is 215 times faster.

Unit: milliseconds
    expr       min         lq       mean     median         uq        max neval
 michael 3099.1283 3290.19973 3664.69723 3571.61724 3840.92476 5581.34401   100
    greg   13.2958   15.36794   17.29367   15.92426   18.22314   25.93559   100


来源: stackexchange

问:
How to play an mp3 once onClick in react?
i have a  that i want to play a very small mp3 once that is in my public folder in my react app, there are so many different solutions to playing audio but none that are simple for react, i tried react-360 but there was a problem with one of the modules.

i've tried some react audio libraries, but they seem to be for audio players, i dont need a play button and a pause and a volume and all that. just want a simple sound effect

```<code>class App extends Component {
  render() {

    var audio = new Audio("../public/sound.mp3")

    return (
      <Container>
            <img src={dwight} onClick={ audio.play() }/>
      </Container>
    );
  }
}
</code>```

(sound to play when click the image)

答:
```<code>import { Fragment } from 'react';
export default function PlaySound(props) {
    var savingCurrencySound = props.soundFile ?? 'https://example.com/audio/sound.mp3';
    var playCurrencySound = () => {
        var audio = new Audio(savingCurrencySound);
        audio.play();
    }
    return (
        <Fragment>
            <img src={dwight} onClick={ () => playCurrencySound() }/>
        </Fragment>
    );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have a  that i want to play a very small mp3 once that is in my public folder in my react app, there are so many different solutions to playing audio but none that are simple for react, i tried react-360 but there was a problem with one of the modules.

i've tried some react audio libraries, but they seem to be for audio players, i dont need a play button and a pause and a volume and all that. just want a simple sound effect

class App extends Component {
  render() {

    var audio = new Audio("../public/sound.mp3")

    return (
      <Container>

      </Container>
    );
  }
}

(sound to play when click the image)


问:
Download doc for only one Maven dependency in IntelliJ
In IntelliJ IDEA 2017.2, the Maven Projects panel offers a menu for downloading source code and/or documentation for all the dependencies. Discussed in this other Question. Nice to have, but sometimes overkill. I want the doc for only one dependency.

➠ Is there a way to easily download source and/or documentation for individual libraries rather than all?

And is there a way to browse what dependencies currently have source and/or documentation downloaded?

答:
<classifier> tag in POM

You can also do this in the POM, using the <classifier> element. See Maven reference page.

For Javadoc

Copy your dependency and add <classifier>javadoc</classifier> to it.

For source-code

Similarly, one can add <classifier>sources</classifier> to download the source code. Note the plural form of sources, not source.

Example:

```<code>        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.8</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.8</version>
            <classifier>sources</classifier>  <!-- ⟸ Use `sources` to download source-code for this dependency. -->
        </dependency>
</code>```

Body:
<classifier> tag in POM

You can also do this in the POM, using the <classifier> element. See Maven reference page.

For Javadoc

Copy your dependency and add <classifier>javadoc</classifier> to it.

For source-code

Similarly, one can add <classifier>sources</classifier> to download the source code. Note the plural form of sources, not source.

Example:

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.8</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.8</version>
            <classifier>sources</classifier>  <!-- ⟸ Use `sources` to download source-code for this dependency. -->
        </dependency>


问:
curl facebook authorize
Facebook has updated their authorize method, now use

```<code>https://graph.facebook.com/oauth/authorize?
client_id="APPID"
&redirect_uri="CALLBACK_URL
&response_type=token
&response_type=code%20token
</code>```

can get the token more easier than before. I tried into the browser, the url address could return:

```<code>http://localhost/facebook/#access_token=140***&expires_in=5381&code=AQDx8SXR***
</code>```

So I tired use curl, but result is 1, so how to do correctly? Thanks.

```<code><?php header('Content-type:text/html; charset=utf-8'); ?>
<?php
$appid= "**MY APP ID**";
$callback_url= "** CALLBACK URL **";
$token_url = "https://graph.facebook.com/oauth/authorize?client_id=".$appid."&redirect_uri=".urlencode($callback_url)."&response_type=token&response_type=code%20token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$token_url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/src/fb_ca_chain_bundle.crt');
$result = curl_exec($curl);
curl_close($curl);
echo $result;
?>
</code>```

答:
try to add

```<code>curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
</code>```

between other OPTS

ContentLicense: CC BY-SA 3.0

Title: curl facebook authorize

Body:
Facebook has updated their authorize method, now use

https://graph.facebook.com/oauth/authorize?
client_id="APPID"
&redirect_uri="CALLBACK_URL
&response_type=token
&response_type=code%20token

can get the token more easier than before. I tried into the browser, the url address could return:

http://localhost/facebook/#access_token=140***&expires_in=5381&code=AQDx8SXR***

So I tired use curl, but result is 1, so how to do correctly? Thanks.

<?php header('Content-type:text/html; charset=utf-8'); ?>
<?php
$appid= "**MY APP ID**";
$callback_url= "** CALLBACK URL **";
$token_url = "https://graph.facebook.com/oauth/authorize?client_id=".$appid."&redirect_uri=".urlencode($callback_url)."&response_type=token&response_type=code%20token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$token_url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/src/fb_ca_chain_bundle.crt');
$result = curl_exec($curl);
curl_close($curl);
echo $result;
?>

Body:
try to add

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

between other OPTS


问:
AcquireTokenSilentAsync never using tokens from the cache
I have a class that acts as a wrapper for the MS Graph SDK. Fairly simple purpose, inside the class there are methods for getting various data sets out of Graph for a particular user.

EDIT: this runs under the context of an application, so no user creds are ever used.

All of that part works fine, what isn't working is the DelegateAuthenticationProvider never finds the access token in the cache. Each call to a graph endpoint gets a new token, even in the same instance of the class. Within the class I'm using a singleton pattern for the GraphServiceClient.

Here is the code I'm using to handle the client:

private static GraphServiceClient _graphServiceClient;
private static AuthenticationContext _authContext;
private static readonly object _locker = new();

private GraphServiceClient GetClient(M365ServiceOptions options)
{
    if (_graphServiceClient == null)
    {
        lock (_locker)
        {
            if (_graphServiceClient == null)
            {
                _authContext = new AuthenticationContext($"https://login.microsoftonline.com/{options.TenantId}/");
                var provider = new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    AuthenticationResult accessToken;
                    try
                    {
                        //Use Token from cache or refresh token
                        accessToken = await _authContext.AcquireTokenSilentAsync(options.GraphURL, options.ClientId);
                        _logger.LogDebug("Cache Hit");
                    }
                    catch (AdalSilentTokenAcquisitionException)
                    {
                        //If no cached token, get a new one
                        _logger.LogDebug($"Cache Miss: {_authContext.TokenCache?.Count}");
                        var credentials = new ClientCredential(options.ClientId, options.ClientSecret);
                        accessToken = _authContext.AcquireTokenAsync(options.GraphURL, credentials).Result;
                    }
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.AccessToken);
                });
                _graphServiceClient = new GraphServiceClient(provider);
            }
        }
    }
    return _graphServiceClient;
}
```

While debugging it is clear the token cache has an item in it, and the details all seem to match, but no matter what, the AcquireTokenSilentAsync always throws the AdalSilentTokenAcquisitionException exception and forces it to get a new token for each call. This is impacting performance as no matter what, each call to the graph gets a new token.

Thank you for any assistance.

答:
Please try this class. First call AuthenticationHelper.GetAuthenticatedClient() to get the a GraphServiceClient, then you this to access the user information.</p>
```<code>public class AuthenticationHelper
    {
        static readonly string clientId = "";
        public static string[] Scopes = { "User.Read" };

        public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);

        public static string TokenForUser = null;
        public static DateTimeOffset Expiration;

        private static GraphServiceClient graphClient = null;

        // Get an access token for the given context and resourced. An attempt is first made to
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static GraphServiceClient GetAuthenticatedClient()
        {
            if (graphClient == null)
            {
                // Create Microsoft Graph client.
                try
                {
                    graphClient = new GraphServiceClient(
                        "https://graph.microsoft.com/v1.0",
                        new DelegateAuthenticationProvider(
                            async (requestMessage) =>
                            {
                                var token = await GetTokenForUserAsync();
                                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

                                requestMessage.Headers.Add("SampleID", "MSGraphConsoleApp");

                            }));
                    return graphClient;
                }

                catch (Exception ex)
                {
                    Debug.WriteLine("Could not create a graph client: " + ex.Message);
                }
            }

            return graphClient;
        }

        public static async Task<string> GetTokenForUserAsync()
        {
            AuthenticationResult authResult;
            try
            {
                authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, IdentityClientApp.GetAccountsAsync().Result.First());
                TokenForUser = authResult.AccessToken;
            }

            catch (Exception)
            {
                if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
                {
                    authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);

                    TokenForUser = authResult.AccessToken;
                    Expiration = authResult.ExpiresOn;
                }
            }

            return TokenForUser;
        }

        public static void SignOut()
        {
            foreach (var user in IdentityClientApp.GetAccountsAsync().Result)
            {
                IdentityClientApp.RemoveAsync(user);
            }
            graphClient = null;
            TokenForUser = null;

        }

    }

</code>```

Body:
I have a class that acts as a wrapper for the MS Graph SDK. Fairly simple purpose, inside the class there are methods for getting various data sets out of Graph for a particular user.

EDIT: this runs under the context of an application, so no user creds are ever used.

All of that part works fine, what isn't working is the DelegateAuthenticationProvider never finds the access token in the cache. Each call to a graph endpoint gets a new token, even in the same instance of the class. Within the class I'm using a singleton pattern for the GraphServiceClient.

Here is the code I'm using to handle the client:

private static GraphServiceClient _graphServiceClient;
private static AuthenticationContext _authContext;
private static readonly object _locker = new();

private GraphServiceClient GetClient(M365ServiceOptions options)
{
    if (_graphServiceClient == null)
    {
        lock (_locker)
        {
            if (_graphServiceClient == null)
            {
                _authContext = new AuthenticationContext($"https://login.microsoftonline.com/{options.TenantId}/");
                var provider = new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    AuthenticationResult accessToken;
                    try
                    {
                        //Use Token from cache or refresh token
                        accessToken = await _authContext.AcquireTokenSilentAsync(options.GraphURL, options.ClientId);
                        _logger.LogDebug("Cache Hit");
                    }
                    catch (AdalSilentTokenAcquisitionException)
                    {
                        //If no cached token, get a new one
                        _logger.LogDebug($"Cache Miss: {_authContext.TokenCache?.Count}");
                        var credentials = new ClientCredential(options.ClientId, options.ClientSecret);
                        accessToken = _authContext.AcquireTokenAsync(options.GraphURL, credentials).Result;
                    }
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.AccessToken);
                });
                _graphServiceClient = new GraphServiceClient(provider);
            }
        }
    }
    return _graphServiceClient;
}

While debugging it is clear the token cache has an item in it, and the details all seem to match, but no matter what, the AcquireTokenSilentAsync always throws the AdalSilentTokenAcquisitionException exception and forces it to get a new token for each call. This is impacting performance as no matter what, each call to the graph gets a new token.

Thank you for any assistance.

Body:
Please try this class. First call AuthenticationHelper.GetAuthenticatedClient() to get the a GraphServiceClient, then you this to access the user information.

public class AuthenticationHelper
    {
        static readonly string clientId = "";
        public static string[] Scopes = { "User.Read" };

        public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);

        public static string TokenForUser = null;
        public static DateTimeOffset Expiration;

        private static GraphServiceClient graphClient = null;

        // Get an access token for the given context and resourced. An attempt is first made to
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static GraphServiceClient GetAuthenticatedClient()
        {
            if (graphClient == null)
            {
                // Create Microsoft Graph client.
                try
                {
                    graphClient = new GraphServiceClient(
                        "https://graph.microsoft.com/v1.0",
                        new DelegateAuthenticationProvider(
                            async (requestMessage) =>
                            {
                                var token = await GetTokenForUserAsync();
                                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

                                requestMessage.Headers.Add("SampleID", "MSGraphConsoleApp");

                            }));
                    return graphClient;
                }

                catch (Exception ex)
                {
                    Debug.WriteLine("Could not create a graph client: " + ex.Message);
                }
            }

            return graphClient;
        }

        public static async Task<string> GetTokenForUserAsync()
        {
            AuthenticationResult authResult;
            try
            {
                authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, IdentityClientApp.GetAccountsAsync().Result.First());
                TokenForUser = authResult.AccessToken;
            }

            catch (Exception)
            {
                if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
                {
                    authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);

                    TokenForUser = authResult.AccessToken;
                    Expiration = authResult.ExpiresOn;
                }
            }

            return TokenForUser;
        }

        public static void SignOut()
        {
            foreach (var user in IdentityClientApp.GetAccountsAsync().Result)
            {
                IdentityClientApp.RemoveAsync(user);
            }
            graphClient = null;
            TokenForUser = null;

        }

    }


问:
Can data.table's fread() skip second empty row and keep first row headers?
I am trying to read a CSV where column headers are on row 1, but then row 2 is empty and data starts in row 3. I tried the various options below, but always end up with generic V# column names. Any ideas on how to retain column headers?

fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      header = F)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      skip = 0)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      skip = 1)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      blank.lines.skip = T)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      skip = 0, blank.lines.skip = T)
fread("https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv",
      header = F, skip = 0, blank.lines.skip = T)

```

答:
```<code>url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"
df = fread(url,header=F)
headers = names(fread(url, nrows=0))
setnames(df, old=1:length(headers), new = headers)
</code>```

I notice that there are 20 headers, but 22 columns returned. Therefore, I named the first 20 columns with the 20 names in headers.

As suggested by r2evans in comments, to avoid the double download/read, you could do something like this:

```<code>url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"

# download file
tfile = tempfile()
curl::curl_download(url,destfile = tfile)

# read to get headers
headers = names(fread(tfile, nrows=0))

# read to get data
df = fread(tfile, header=F)

# set the names based on `headers`
setnames(df, old=1:length(headers), new = headers)

# remove the file
file.remove(tfile)
</code>```

Body:
url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"
df = fread(url,header=F)
headers = names(fread(url, nrows=0))
setnames(df, old=1:length(headers), new = headers)

I notice that there are 20 headers, but 22 columns returned. Therefore, I named the first 20 columns with the 20 names in headers.

As suggested by r2evans in comments, to avoid the double download/read, you could do something like this:

url ="https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2013-08.csv"

# download file
tfile = tempfile()
curl::curl_download(url,destfile = tfile)

# read to get headers
headers = names(fread(tfile, nrows=0))

# read to get data
df = fread(tfile, header=F)

# set the names based on `headers`
setnames(df, old=1:length(headers), new = headers)

# remove the file
file.remove(tfile)


问:
GitHub Actions: Error 401 Unauthorized in JIB maven plugin

Introduction

I am currently to create a composite GitHub Actions that build a container from Java project with JIB and publish it automatically to a GitHub Packages and Maven Central.

Problematic

But I got this error when I try to run it:

```<code>[INFO]
[INFO] Containerizing application to gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5...
Warning:  Base image 'eclipse-temurin:17-jre' does not use a specific image digest - build may not be reproducible
[INFO] Using credentials from <to><auth> for gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5
[INFO] Getting manifest for base image eclipse-temurin:17-jre...
[INFO] Building dependencies layer...
[INFO] Building resources layer...
[INFO] Building classes layer...
[INFO] Building jvm arg files layer...
[INFO] The base image requires auth. Trying again for eclipse-temurin:17-jre...
[INFO] Using credentials from Docker config (/home/runner/.docker/config.json) for eclipse-temurin:17-jre
[INFO] Using base image with digest: sha256:e7a4a45b88525250e668cc6149b95b3952a8e9cba8c341b70c4d34c4e4d5eed5
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.272 s
[INFO] Finished at: 2022-02-09T00:37:22Z
[INFO] ------------------------------------------------------------------------
Error:  Failed to execute goal com.google.cloud.tools:jib-maven-plugin:3.2.0:build (default-cli) on project codingame-puzzles-stats-saver: Build image failed, perhaps you should make sure your credentials for 'gcr.io/mathieusoysal/codingame-puzzles-stats-saver' are set up correctly. See https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md#what-should-i-do-when-the-registry-responds-with-unauthorized for help: Unauthorized for gcr.io/mathieusoysal/codingame-puzzles-stats-saver: 401 Unauthorized
Error:  {"errors":[{"code":"UNAUTHORIZED","message":"Not Authorized."}]}
Error:  -> [Help 1]
Error:
Error:  To see the full stack trace of the errors, re-run Maven with the -e switch.
Error:  Re-run Maven using the -X switch to enable full debug logging.
Error:
Error:  For more information about the errors and possible solutions, please read the following articles:
Error:  [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Error: Process completed with exit code 1.
</code>```

Affected code:

name: JIB container publish
description: "Build automatically container with JIB and publish it to GitHub Packages."
branding:
  icon: "package"
  color: "gray-dark"

inputs:
  # Use docker.io for Docker Hub if empty
  REGISTRY:
    description: "Registry of the image to publish"
    required: true
    default: ghcr.io
  # github.repository as <account>/<repo>
  IMAGE_NAME:
    description: "Name of the image to publish"
    required: true
    default: ${{ github.repository }}
  # Username to login to registry
  USERNAME:
    description: "Username to login to registry"
    required: true
    default: ${{ github.actor }}
  # Password to login to registry
  PASSWORD:
    description: "Password to login to registry"
    required: true
  # Name of the tag to publish
  tag-name:
    description: "Tag name of the image to publish"
    required: true
    default: "latest"
  # Java version to use
  java-version:
    description: "Java version to use"
    required: true
    default: "17"

runs:
  using: "composite"
  steps:
    - id: downcase
      uses: ASzc/change-string-case-action@v2
      with:
        string: ${{ inputs.IMAGE_NAME }}

    - uses: actions/checkout@v2
    - name: Set up JDK 17
      uses: actions/setup-java@v2
      with:
        distribution: "adopt"
        java-version: ${{ inputs.java-version }}

    - name: Buil JIB container and publish to GitHub Packages
      run: |
        mvn compile com.google.cloud.tools:jib-maven-plugin:3.2.0:build \
        -Djib.to.image=${{ inputs.REGISTRY }}/${{ steps.downcase.outputs.lowercase }}:${{ inputs.tag-name }} \
        -Djib.to.auth.username=${{ inputs.USERNAME }} \
        -Djib.to.auth.password=${{ inputs.PASSWORD }}
      shell: bash
```
<h2>Code that execute the GitHub Actions in question:</h2>
<pre class="lang-yaml prettyprint-override"><code>name: Deploy Javadoc

on:
name: JIB container publish

on:
  release:
    types: [created]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: JIB container build and publish
        uses: MathieuSoysal/jib-container-publish.yml@v2.0.7
        with:
          # Use docker.io for Docker Hub if empty
          REGISTRY: gcr.io
          # github.repository as <your-account>/<your-repo>
          IMAGE_NAME: ${{ github.repository }}
          # Tag name of the image to publish
          tag-name: ${{ github.event.release.tag_name }}
          # Username to login to registry
          USERNAME: ${{ github.actor }}
          # Password to login to registry
          PASSWORD: ${{ secrets.GITHUB_TOKEN }}
          java-version: 17
</code>```

Question

Anyone have an idea to solve this problem?

Link of the repo: https://github.com/MathieuSoysal/jib-container-publish.yml

答:
Everything looks good. Jib retrieved credentials from -Dto.auth.{username|password}.

```<code>Using credentials from <to><auth> for gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5
</code>```

I suspect that you are just not passing the right "username" and "password" for gcr.io (Google Container Registry, which is different from ghcr.io). From this doc,

Note: This method of authentication should be used only as a last resort, as it is insecure to make your password visible in plain text. Note that often cloud registries (for example, Google GCR, Amazon ECR, and Azure ACR) do not accept "user credentials" (such as Gmail account name and password) but require different forms of credentials. For example, you may use oauth2accesstoken or _json_key as the username for GCR, and AWS for ECR. For ACR, you may use a service principle.

AFAICT, for GCR, to.auth.username would be either oath2accesstoken or _json_key literally. It doesn't make sense that the username is ${{ github.actor }}.

Aside, you should make sure that the auth arguments you pass on the command-line is not logged or shown for security. Take a look at this Stack Overflow answer to understand general registry authentication.

Also, typically you'll want auth for both the "from" image and "to" image.

Body:
Introduction

I am currently to create a composite GitHub Actions that build a container from Java project with JIB and publish it automatically to a GitHub Packages and Maven Central.

Problematic

But I got this error when I try to run it:

[INFO]
[INFO] Containerizing application to gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5...
Warning:  Base image 'eclipse-temurin:17-jre' does not use a specific image digest - build may not be reproducible
[INFO] Using credentials from <to><auth> for gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5
[INFO] Getting manifest for base image eclipse-temurin:17-jre...
[INFO] Building dependencies layer...
[INFO] Building resources layer...
[INFO] Building classes layer...
[INFO] Building jvm arg files layer...
[INFO] The base image requires auth. Trying again for eclipse-temurin:17-jre...
[INFO] Using credentials from Docker config (/home/runner/.docker/config.json) for eclipse-temurin:17-jre
[INFO] Using base image with digest: sha256:e7a4a45b88525250e668cc6149b95b3952a8e9cba8c341b70c4d34c4e4d5eed5
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.272 s
[INFO] Finished at: 2022-02-09T00:37:22Z
[INFO] ------------------------------------------------------------------------
Error:  Failed to execute goal com.google.cloud.tools:jib-maven-plugin:3.2.0:build (default-cli) on project codingame-puzzles-stats-saver: Build image failed, perhaps you should make sure your credentials for 'gcr.io/mathieusoysal/codingame-puzzles-stats-saver' are set up correctly. See https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md#what-should-i-do-when-the-registry-responds-with-unauthorized for help: Unauthorized for gcr.io/mathieusoysal/codingame-puzzles-stats-saver: 401 Unauthorized
Error:  {"errors":[{"code":"UNAUTHORIZED","message":"Not Authorized."}]}
Error:  -> [Help 1]
Error:
Error:  To see the full stack trace of the errors, re-run Maven with the -e switch.
Error:  Re-run Maven using the -X switch to enable full debug logging.
Error:
Error:  For more information about the errors and possible solutions, please read the following articles:
Error:  [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Error: Process completed with exit code 1.

Affected code:

name: JIB container publish
description: "Build automatically container with JIB and publish it to GitHub Packages."
branding:
  icon: "package"
  color: "gray-dark"

inputs:
  # Use docker.io for Docker Hub if empty
  REGISTRY:
    description: "Registry of the image to publish"
    required: true
    default: ghcr.io
  # github.repository as <account>/<repo>
  IMAGE_NAME:
    description: "Name of the image to publish"
    required: true
    default: ${{ github.repository }}
  # Username to login to registry
  USERNAME:
    description: "Username to login to registry"
    required: true
    default: ${{ github.actor }}
  # Password to login to registry
  PASSWORD:
    description: "Password to login to registry"
    required: true
  # Name of the tag to publish
  tag-name:
    description: "Tag name of the image to publish"
    required: true
    default: "latest"
  # Java version to use
  java-version:
    description: "Java version to use"
    required: true
    default: "17"

runs:
  using: "composite"
  steps:
    - id: downcase
      uses: ASzc/change-string-case-action@v2
      with:
        string: ${{ inputs.IMAGE_NAME }}

    - uses: actions/checkout@v2
    - name: Set up JDK 17
      uses: actions/setup-java@v2
      with:
        distribution: "adopt"
        java-version: ${{ inputs.java-version }}

    - name: Buil JIB container and publish to GitHub Packages
      run: |
        mvn compile com.google.cloud.tools:jib-maven-plugin:3.2.0:build \
        -Djib.to.image=${{ inputs.REGISTRY }}/${{ steps.downcase.outputs.lowercase }}:${{ inputs.tag-name }} \
        -Djib.to.auth.username=${{ inputs.USERNAME }} \
        -Djib.to.auth.password=${{ inputs.PASSWORD }}
      shell: bash

Code that execute the GitHub Actions in question:

name: Deploy Javadoc

on:
name: JIB container publish

on:
  release:
    types: [created]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: JIB container build and publish
        uses: MathieuSoysal/jib-container-publish.yml@v2.0.7
        with:
          # Use docker.io for Docker Hub if empty
          REGISTRY: gcr.io
          # github.repository as <your-account>/<your-repo>
          IMAGE_NAME: ${{ github.repository }}
          # Tag name of the image to publish
          tag-name: ${{ github.event.release.tag_name }}
          # Username to login to registry
          USERNAME: ${{ github.actor }}
          # Password to login to registry
          PASSWORD: ${{ secrets.GITHUB_TOKEN }}
          java-version: 17

Question

Anyone have an idea to solve this problem?

Link of the repo: https://github.com/MathieuSoysal/jib-container-publish.yml

Body:
Everything looks good. Jib retrieved credentials from -Dto.auth.{username|password}.

Using credentials from <to><auth> for gcr.io/mathieusoysal/codingame-puzzles-stats-saver:v1.0.2.5

I suspect that you are just not passing the right "username" and "password" for gcr.io (Google Container Registry, which is different from ghcr.io). From this doc,

Note: This method of authentication should be used only as a last resort, as it is insecure to make your password visible in plain text. Note that often cloud registries (for example, Google GCR, Amazon ECR, and Azure ACR) do not accept "user credentials" (such as Gmail account name and password) but require different forms of credentials. For example, you may use oauth2accesstoken or _json_key as the username for GCR, and AWS for ECR. For ACR, you may use a service principle.

AFAICT, for GCR, to.auth.username would be either oath2accesstoken or _json_key literally. It doesn't make sense that the username is ${{ github.actor }}.

Aside, you should make sure that the auth arguments you pass on the command-line is not logged or shown for security. Take a look at this Stack Overflow answer to understand general registry authentication.

Also, typically you'll want auth for both the "from" image and "to" image.


问:
how to correctly configure ngrok docker container for node or react app?
I'm trying to use ngrok for exposing my localhost to share my node backend with a friend.
The problem I face is that whenever I start node backend the ngrok container couldn't work cause it trys to map the same port as being used by node.

```<code>node:events:371
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (node:net:1319:16)
    at listenInCluster (node:net:1367:12)
    at Server.listen (node:net:1454:7)
    at Function.listen (C:\Users\928941\node_backends\express-for-react\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\928941\node_backends\express-for-react\app.js:27:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1346:8)
  code: 'EADDRINUSE',
  errno: -4091,
  syscall: 'listen',
  address: '::',
  port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...
</code>```

the above error simply means that port 5000 is currently in use(i.e., by ngrok docker container).

If I run the node app first and try to run the docker container after that I get this error from docker.

```<code>[+] Running 1/0
 - Container docker-compose_for_ngrok_ngrok_1  Created                                                             0.0s
Attaching to ngrok_1
Error response from daemon: Ports are not available: listen tcp 0.0.0.0:5000: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.
</code>```

This is my docker-compose.yml file

```<code>version: '3'

services:
  ngrok:
    image: ngrok/ngrok:alpine
    ports:
      - 4040:4040
      - 5000:5000
    environment:
      - NGROK_AUTHTOKEN=my_authentication_token
    command: http 5000
</code>```

the compose file is same as this docker run command so anyone can be used.

```<code>docker run -d -p 4040:4040 -p 5000:5000 -e NGROK_AUTHTOKEN=my_token ngrok/ngrok:alpine http 5000
</code>```

Port 4040 is default ngrok port for dashboard and it works fine for me.

I'm also facing this issue with react app as well.

答:
I'm not sure if you are running on linux, but you might not need to do any port forwarding if you use the --net=host option. See the examples in https://hub.docker.com/r/ngrok/ngrok/

The equivalent for a docker compose file is network_mode:https://docs.docker.com/compose/compose-file/compose-file-v3/#network_mode

So your docker compose would be:

```<code>version: '3'

services:
  ngrok:
    image: ngrok/ngrok:alpine
    environment:
      - NGROK_AUTHTOKEN=my_authentication_token
    command: http 5000
    network_mode: "host"
</code>```

Assuming your node is running on localhost:5000, if you start a docker container and use the same network, then you don't need to open any ports.

If you are using mac or windows, you will need to use the workaround here:
https://docs.docker.com/desktop/mac/networking/#use-cases-and-workarounds

Which is to use command: http host.docker.internal:5000 instead.

Body:
I'm trying to use ngrok for exposing my localhost to share my node backend with a friend.
The problem I face is that whenever I start node backend the ngrok container couldn't work cause it trys to map the same port as being used by node.

node:events:371
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (node:net:1319:16)
    at listenInCluster (node:net:1367:12)
    at Server.listen (node:net:1454:7)
    at Function.listen (C:\Users\928941\node_backends\express-for-react\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\928941\node_backends\express-for-react\app.js:27:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1346:8)
  code: 'EADDRINUSE',
  errno: -4091,
  syscall: 'listen',
  address: '::',
  port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...

the above error simply means that port 5000 is currently in use(i.e., by ngrok docker container).

If I run the node app first and try to run the docker container after that I get this error from docker.

[+] Running 1/0
 - Container docker-compose_for_ngrok_ngrok_1  Created                                                             0.0s
Attaching to ngrok_1
Error response from daemon: Ports are not available: listen tcp 0.0.0.0:5000: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

This is my docker-compose.yml file

version: '3'

services:
  ngrok:
    image: ngrok/ngrok:alpine
    ports:
      - 4040:4040
      - 5000:5000
    environment:
      - NGROK_AUTHTOKEN=my_authentication_token
    command: http 5000

the compose file is same as this docker run command so anyone can be used.

docker run -d -p 4040:4040 -p 5000:5000 -e NGROK_AUTHTOKEN=my_token ngrok/ngrok:alpine http 5000

Port 4040 is default ngrok port for dashboard and it works fine for me.

I'm also facing this issue with react app as well.

Body:
I'm not sure if you are running on linux, but you might not need to do any port forwarding if you use the --net=host option. See the examples in https://hub.docker.com/r/ngrok/ngrok/

The equivalent for a docker compose file is network_mode:https://docs.docker.com/compose/compose-file/compose-file-v3/#network_mode

So your docker compose would be:

version: '3'

services:
  ngrok:
    image: ngrok/ngrok:alpine
    environment:
      - NGROK_AUTHTOKEN=my_authentication_token
    command: http 5000
    network_mode: "host"

Assuming your node is running on localhost:5000, if you start a docker container and use the same network, then you don't need to open any ports.

If you are using mac or windows, you will need to use the workaround here:
https://docs.docker.com/desktop/mac/networking/#use-cases-and-workarounds

Which is to use command: http host.docker.internal:5000 instead.


问:
ValueError: write() requires mode 'w', 'x', or 'a' in Python zipfile
I am trying to open a specific file in the archive and then write some content to it. I am using the zipfile.open() function to get access to the file:

```<code>import zipfile

my_zip = zipfile.ZipFile('D:\\files\\acrhive.zip')

with my_zip.open('hello.txt', 'w') as my_file:
     my_file.write(b'Hello')

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

However, it gives me a warning about duplicate file called 'hello.txt'. After that I get the following error:

```<code>ValueError: write() requires mode 'w', 'x', or 'a'
</code>```

What am I doing wrong here?

My full traceback:

```<code>D:\python\lib\zipfile.py:1506: UserWarning: Duplicate name: 'hello.txt'
  return self._open_to_write(zinfo, force_zip64=force_zip64)
Traceback (most recent call last):
  File "D:\files\python.py", line 8, in <module>
    with my_zip.open(file, 'w') as my_file:
  File "D:\python\lib\zipfile.py", line 1506, in open
    return self._open_to_write(zinfo, force_zip64=force_zip64)
  File "D:\python\lib\zipfile.py", line 1598, in _open_to_write
    self._writecheck(zinfo)
  File "D:\python\lib\zipfile.py", line 1699, in _writecheck
    raise ValueError("write() requires mode 'w', 'x', or 'a'")
ValueError: write() requires mode 'w', 'x', or 'a'
</code>```

答:
Right now you're opening the file in the archive file for writing, but the archive file itself only for reading (the default mode).

The key here is that to the file system, the files inside the archive do not really exist as real files. To the file system they are just bytes inside the archive file. The zipfile library, like many file managers, just goes out of its way to give them to you as virtual files - something that mostly looks and works like a normal file to make it easier to work with them the same way.

So try opening the zip file itself for writing too:

zipfile.ZipFile('D:\\files\\archive.zip', 'w')
```
<p>Couple notes:</p>
<ol>
<li><em>Both</em> zip file and the file in the zip file should be opened for writing.</li>
<li>In the question code you posted, it looks like you have a typo in the zip file name: <code>acrhive.zip</code> vs <code>archive.zip</code>. If my answer code starts failing for you with "file not found", that might be why.</li>
<li>You should just open the zip file with a context manager too, just as with other files and file-like things.</li>
</ol>
<p>So putting it all together:</p>
<pre class="lang-py prettyprint-override"><code>with zipfile.ZipFile('D:\\files\\archive.zip', 'w') as my_zip:
    with my_zip.open('hello.txt', 'w') as my_file:
        my_file.write(b'Hello')
</code>```

Body:
I am trying to open a specific file in the archive and then write some content to it. I am using the zipfile.open() function to get access to the file:

import zipfile

my_zip = zipfile.ZipFile('D:\\files\\acrhive.zip')

with my_zip.open('hello.txt', 'w') as my_file:
     my_file.write(b'Hello')

my_zip.close()

However, it gives me a warning about duplicate file called 'hello.txt'. After that I get the following error:

ValueError: write() requires mode 'w', 'x', or 'a'

What am I doing wrong here?

My full traceback:

D:\python\lib\zipfile.py:1506: UserWarning: Duplicate name: 'hello.txt'
  return self._open_to_write(zinfo, force_zip64=force_zip64)
Traceback (most recent call last):
  File "D:\files\python.py", line 8, in <module>
    with my_zip.open(file, 'w') as my_file:
  File "D:\python\lib\zipfile.py", line 1506, in open
    return self._open_to_write(zinfo, force_zip64=force_zip64)
  File "D:\python\lib\zipfile.py", line 1598, in _open_to_write
    self._writecheck(zinfo)
  File "D:\python\lib\zipfile.py", line 1699, in _writecheck
    raise ValueError("write() requires mode 'w', 'x', or 'a'")
ValueError: write() requires mode 'w', 'x', or 'a'

Body:
Right now you're opening the file in the archive file for writing, but the archive file itself only for reading (the default mode).

The key here is that to the file system, the files inside the archive do not really exist as real files. To the file system they are just bytes inside the archive file. The zipfile library, like many file managers, just goes out of its way to give them to you as virtual files - something that mostly looks and works like a normal file to make it easier to work with them the same way.

So try opening the zip file itself for writing too:

zipfile.ZipFile('D:\\files\\archive.zip', 'w')

Couple notes:

Both zip file and the file in the zip file should be opened for writing.

In the question code you posted, it looks like you have a typo in the zip file name: acrhive.zip vs archive.zip. If my answer code starts failing for you with "file not found", that might be why.

You should just open the zip file with a context manager too, just as with other files and file-like things.

So putting it all together:

with zipfile.ZipFile('D:\\files\\archive.zip', 'w') as my_zip:
    with my_zip.open('hello.txt', 'w') as my_file:
        my_file.write(b'Hello')


问:
Rust mutable references working in some cases but not in other cases
I've encountered a problem that I cannot understand involving mutable references and borrow checker.
I am writing a naive binary search tree using safe rust. Full code can be seen here: https://github.com/adensur/rust_learning/blob/master/bst/src/lib.rs

This is the node and the tree itself:

```<code>struct Node {
 key: i64,
 left_ptr: Option<Box<Node>>,
 right_ptr: Option<Box<Node>>,
}

#[derive(Default)]
pub struct BstSet {
 root: Option<Box<Node>>,
 len: usize,
}
</code>```

Here is the insert function (similar to HashSet::insert()), and it works:

```<code>pub fn insert(&mut self, key: i64) -> bool {
        let mut node_ptr = &mut self.root;
        while let Some(node) = node_ptr {
            match node.key.cmp(&key) {
                Ordering::Equal => return false,
                Ordering::Less => {
                    node_ptr = &mut node.right_ptr;
                }
                Ordering::Greater => {
                    node_ptr = &mut node.left_ptr;
                }
            }
        }
        *node_ptr = Some(Box::new(Node {
            key,
            left_ptr: None,
            right_ptr: None,
        }));
        self.len += 1;
        true
    }
</code>```

I try to move this code to a function for some code reuse, and it doesn't compile:

```<code>fn find_node_mut(&mut self, key: i64) -> &mut Option<Box<Node>> {
        let mut node_ptr = &mut self.root;
        while let Some(node) = node_ptr {
            match node.key.cmp(&key) {
                Ordering::Equal => break,
                Ordering::Less => {
                    //node_ptr = &mut node_ptr.as_mut().unwrap().right_ptr;
                    node_ptr = &mut node.right_ptr;
                }
                Ordering::Greater => {
                    // node_ptr = &mut node_ptr.as_mut().unwrap().left_ptr;
                    node_ptr = &mut node.left_ptr;
                }
            }
        }
        node_ptr
    }
</code>```

Giving me this error:

```<code>error[E0499]: cannot borrow `*node_ptr` as mutable more than once at a time
  --> src/lib.rs:61:9
   |
46 |     fn find_node_mut(&mut self, key: i64) -> &mut Option<Box<Node>> {
   |                      - let's call the lifetime of this reference `'1`
47 |         let mut node_ptr = &mut self.root;
48 |         while let Some(node) = node_ptr {
   |                        ---- first mutable borrow occurs here
...
61 |         node_ptr
   |         ^^^^^^^^
   |         |
   |         second mutable borrow occurs here
   |         returning this value requires that `node_ptr.0` is borrowed for `'1`

For more information about this error, try `rustc --explain E0499`.
</code>```

Why does it work in one case but not the other?
What is the correct way to reason about this to be able to predict what the compiler would say?

After fiddling about with the code I've found a (somewhat more messy) way to write it so that it works (the commented lines in the code), but the fact that I don't understand why this is happening is bothering me.

答:
Seems like this thread Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in? that refers to a known issue https://github.com/rust-lang/rust/issues/21906#issuecomment-73296543 answers my question.
Running my program with Polonius borrow checker also seems to work:

```<code>RUSTFLAGS="-Z polonius" cargo +nightly test
</code>```

And here is the perfect video explaining just the thing: https://www.youtube.com/watch?v=_agDeiWek8w

How to properly reason about this to determine why does insert function compile, and find_node_mut doesn't:

In both functions, node and node_ptr are used interchangeably, so their scope sort of "overlaps".
In insert function, the compiler is able to properly determine the "liveness" of the loans: the variable is "dead" if it is about to get written to (current value cannot be referenced in the future). That way, even though the two mutable references have overlapping scopes, their 'lifetimes', represented by a set of lines, do not overlap.

In find_node_mut, the reference is returned from the function, blowing out the lifetime of the reference from a small set of lines to  some "unknown" lifetime 'a, covering at least the entire function body.

Body:
I've encountered a problem that I cannot understand involving mutable references and borrow checker.
I am writing a naive binary search tree using safe rust. Full code can be seen here: https://github.com/adensur/rust_learning/blob/master/bst/src/lib.rs

This is the node and the tree itself:

struct Node {
 key: i64,
 left_ptr: Option<Box<Node>>,
 right_ptr: Option<Box<Node>>,
}

#[derive(Default)]
pub struct BstSet {
 root: Option<Box<Node>>,
 len: usize,
}

Here is the insert function (similar to HashSet::insert()), and it works:

pub fn insert(&mut self, key: i64) -> bool {
        let mut node_ptr = &mut self.root;
        while let Some(node) = node_ptr {
            match node.key.cmp(&key) {
                Ordering::Equal => return false,
                Ordering::Less => {
                    node_ptr = &mut node.right_ptr;
                }
                Ordering::Greater => {
                    node_ptr = &mut node.left_ptr;
                }
            }
        }
        *node_ptr = Some(Box::new(Node {
            key,
            left_ptr: None,
            right_ptr: None,
        }));
        self.len += 1;
        true
    }

I try to move this code to a function for some code reuse, and it doesn't compile:

fn find_node_mut(&mut self, key: i64) -> &mut Option<Box<Node>> {
        let mut node_ptr = &mut self.root;
        while let Some(node) = node_ptr {
            match node.key.cmp(&key) {
                Ordering::Equal => break,
                Ordering::Less => {
                    //node_ptr = &mut node_ptr.as_mut().unwrap().right_ptr;
                    node_ptr = &mut node.right_ptr;
                }
                Ordering::Greater => {
                    // node_ptr = &mut node_ptr.as_mut().unwrap().left_ptr;
                    node_ptr = &mut node.left_ptr;
                }
            }
        }
        node_ptr
    }

Giving me this error:

error[E0499]: cannot borrow `*node_ptr` as mutable more than once at a time
  --> src/lib.rs:61:9
   |
46 |     fn find_node_mut(&mut self, key: i64) -> &mut Option<Box<Node>> {
   |                      - let's call the lifetime of this reference `'1`
47 |         let mut node_ptr = &mut self.root;
48 |         while let Some(node) = node_ptr {
   |                        ---- first mutable borrow occurs here
...
61 |         node_ptr
   |         ^^^^^^^^
   |         |
   |         second mutable borrow occurs here
   |         returning this value requires that `node_ptr.0` is borrowed for `'1`

For more information about this error, try `rustc --explain E0499`.

Why does it work in one case but not the other?
What is the correct way to reason about this to be able to predict what the compiler would say?

After fiddling about with the code I've found a (somewhat more messy) way to write it so that it works (the commented lines in the code), but the fact that I don't understand why this is happening is bothering me.

Body:
Seems like this thread Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in? that refers to a known issue https://github.com/rust-lang/rust/issues/21906#issuecomment-73296543 answers my question.
Running my program with Polonius borrow checker also seems to work:

RUSTFLAGS="-Z polonius" cargo +nightly test

And here is the perfect video explaining just the thing: https://www.youtube.com/watch?v=_agDeiWek8w

How to properly reason about this to determine why does insert function compile, and find_node_mut doesn't:

In both functions, node and node_ptr are used interchangeably, so their scope sort of "overlaps".
In insert function, the compiler is able to properly determine the "liveness" of the loans: the variable is "dead" if it is about to get written to (current value cannot be referenced in the future). That way, even though the two mutable references have overlapping scopes, their 'lifetimes', represented by a set of lines, do not overlap.

In find_node_mut, the reference is returned from the function, blowing out the lifetime of the reference from a small set of lines to  some "unknown" lifetime 'a, covering at least the entire function body.


问:
.split() returns list of individual charachters instead of splitting it as the spaces
```<code>n = input("input n: ")
n.split()
print(n, len(n))
</code>```

Say the input is: 100 400, seperated by a space, .split() returns a list of all the individual digits, as well as the space between them, instead of the two numbers such that len(n) = 7, and n[0] = 1 instead of 100.

答:
You aren't replacing n with the return value of n.split().

```<code>>>> n = "100 400"
>>> n.split()
['100', '400']
>>> n
"100 400"
</code>```

You need to save that return value.

```<code>>>> x = n.split()
>>> print(x, len(x))
['100', '400'] 2
</code>```

You can, of course, assign the result back to the name n (although that can cause some issues if you are using mypy to check  your code, as it will infer a static type of str for n and complain about an attempt to assign a list to the name).

Body:
n = input("input n: ")
n.split()
print(n, len(n))

Say the input is: 100 400, seperated by a space, .split() returns a list of all the individual digits, as well as the space between them, instead of the two numbers such that len(n) = 7, and n[0] = 1 instead of 100.

Body:
You aren't replacing n with the return value of n.split().

>>> n = "100 400"
>>> n.split()
['100', '400']
>>> n
"100 400"

You need to save that return value.

>>> x = n.split()
>>> print(x, len(x))
['100', '400'] 2

You can, of course, assign the result back to the name n (although that can cause some issues if you are using mypy to check  your code, as it will infer a static type of str for n and complain about an attempt to assign a list to the name).


问:
Still need cache-busting on CSS file in Blazor WebAssembly site?
I read this but still am having trouble:

I have my Blazor WebAssembly site, with a static index.html file that bootstraps Blazor in a normal way. In its , I have <link href="css/app.min.css" rel="stylesheet" />.  That file is built from SCSS using a Dockerfile RUN step on deployment.

According to that issue, I don't need cache-busting URLs, as Blazor will automatically request a fresh one as needed.  Yet when I deploy my site and open it in Firefox, I get the old styles and see in Firefox developer tools network tab that app.min.css is retrieved from disk cache.  I have to press Ctrl+F5 to get the new styles.

So what is going wrong in this chain?  It seems to me that I still need cache-busting URL for my CSS on each deployment.  What needs to be set up so that my CSS will be downloaded when the site binaries change, in the way Steve Sanderson suggests in that issue?

答:
My project is a Blazor Wasm .Net 6 project.  I've removed the link for the isolated css file(<link href="ProjectName.styles.css" rel="stylesheet"/>) from the head in the index.html file and added the below javascript on that same page.  It will now inject the link in the head, with in this case, a version of YYYYMMDDHHMISSsss.

```<code>var date = new Date();
var version = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours() ).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2) + ("00" + date.getMilliseconds()).slice(-3);
if(!document.getElementById('mainCss')) {
    var link = document.createElement('link');
    link.id = 'mainCss';
    link.rel = 'stylesheet';
    link.href = 'ProjectName.styles.css' + "?version=" + version;
    document.head.appendChild(link);
}
</code>```

Body:
My project is a Blazor Wasm .Net 6 project.  I've removed the link for the isolated css file(<link href="ProjectName.styles.css" rel="stylesheet"/>) from the head in the index.html file and added the below javascript on that same page.  It will now inject the link in the head, with in this case, a version of YYYYMMDDHHMISSsss.

var date = new Date();
var version = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2) + ("0" + date.getHours() ).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2) + ("00" + date.getMilliseconds()).slice(-3);
if(!document.getElementById('mainCss')) {
    var link = document.createElement('link');
    link.id = 'mainCss';
    link.rel = 'stylesheet';
    link.href = 'ProjectName.styles.css' + "?version=" + version;
    document.head.appendChild(link);
}


问:
python regex named captured group with specific terminating substrings
I have a python regex that splits a line of text into firstname, lastname, employer, street address,city,state, country, income and bonus as follows:

```<code>myreg=re.compile(r'\'(?P<first_name>.*)\',\'(?P<last_name>.*)\',\'(?P<employer>.*)\',\'(?P<street_address>.*)\',\'(?P<city>.*)\',\'(?P<state>.*)\',\'(?P<country>[A-Z]{2})?\',\'(?P<phone>[\d\+\-]*)\',\'(?P<email>[A-Za-z0-9\@\-\_\.]*)\',\'(?P<income>[\d\.]*)\',\'(?P<bonus>[\d\.]*)\'')
m=myreg.search(line)
print(m.groupdict())
</code>```

This works fine if the input line is:

'john','doe','searchers','some street','some city','some
state','HE','000-00-00','missing@123.abc','0.00','0'

Output is:

{'first_name': 'john', 'last_name': 'doe', 'employer': 'searchers',
'street_address': 'some street', 'city': 'some city', 'state': 'some
state', 'country': 'HE', 'phone': '000-00-00', 'email':
'missing@123.abc', 'income': '0.00', 'bonus': '0'}

However, things don't work if a line has empty fields such as:

'','','testemployer','','','a very long city's
nameaaaaaaaaaaaaaa','','HE','','','',''

For the above, the output becomes:

{'first_name': "','", 'last_name': 'testemployer', 'employer': '',
'street_address': '', 'city': "a very long city's nameaaaaaaaaaaaaaa",
'state': '', 'country': 'HE', 'phone': '', 'email': '', 'income': '',
'bonus': ''}

I tried setting the names as [^']*, but some names have apostrophes, and some employers can contain apostrophes and commas such as "O'Toole, McGyver and Scrooge Law".  However, from the data I saw, fields are definitely separated by "','". Given this, is there a way to have a regex pattern that would ensure that the captured groups do not contain "','"?

答:
I spent a very long time on what I thought would be a correct regex, but I still could not get it to correctly process accept your string:

```<code>'','','testemployer','','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''
</code>```

And then it dawned upon me that it appears you have an extra empty field before the city field (i.e. there should only be one field, the street_address, between the employer and city fields but you seem to have two. If this is truly how the data appears, then there is nothing I can do about it. But if you just made an error in copying the the problematic input, then ...

First of all, I have used a double-quote (") to code your regex string. This removes the necessity of having to escape all those single quote characters. There is also no need to escape special characters such as +, - and - when they appear within character class specifications. Finally, I have replaced \d with [0-9], which is different when you are dealing with Unicode. The former includes many values from languages that you might not find on telephones or currencies that you are interested in, such as ०१२३४५६७८९. But if you need \d instead of the usual digit 0 .. 9, then please just revert back.

Anyway, to handle the city field and fields like it that might have an embedded quote character, the way I have handled it is to use a negative lookahead assertion:

```<code>'(?P<field_name>(?:[^']|'(?!,))*)'
</code>```

' - Matches a quote.

(?: - Start of a non-capturing group.

[^'] - Matches any non-quote character.

| - or

'(?!,) - Matches a quote if the next character is not a comma. In other words match a quote if this does not appear to be the closing quote that describes a field.

) - End of the non-capturing group.

* - Matches 0 or more characters defined by items 2 through 6 above.

' - Matches a quote.

The code:

import re

lines = [
    "'john','doe','searchers','some street','some city','some state','HE','000-00-00','missing@123.abc','0.00','0'",
    "'','','testemployer','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''"
    ]

myreg = re.compile(r"'(?P<first_name>(?:[^']|'(?!,))*)','(?P<last_name>(?:[^']|'(?!,))*)','(?P<employer>(?:[^']|'(?!,))*)','(?P<street_address>(?:[^']|'(?!,))*)','(?P<city>(?:[^']|'(?!,))*)','(?P<state>(?:[^']|'(?!,))*)','(?P<country>[A-Z]{2})?','(?P<phone>[0-9+-]*)','(?P<email>[A-Za-z0-9\@\-\_\.]*)','(?P<income>[0-9.]*)','(?P<bonus>[0-9.]*)'")
for line in lines:
    m = myreg.search(line)
    print(line)
    for k, v in m.groupdict().items():
        print (f'{k} -> {v}')
    print()
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>'john','doe','searchers','some street','some city','some state','HE','000-00-00','missing@123.abc','0.00','0'
first_name -> john
last_name -> doe
employer -> searchers
street_address -> some street
city -> some city
state -> some state
country -> HE
phone -> 000-00-00
email -> missing@123.abc
income -> 0.00
bonus -> 0

'','','testemployer','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''
first_name ->
last_name ->
employer -> testemployer
street_address ->
city -> a very long city's nameaaaaaaaaaaaaaa
state ->
country -> HE
phone ->
email ->
income ->
bonus ->
</code>```

Body:
I have a python regex that splits a line of text into firstname, lastname, employer, street address,city,state, country, income and bonus as follows:

myreg=re.compile(r'\'(?P<first_name>.*)\',\'(?P<last_name>.*)\',\'(?P<employer>.*)\',\'(?P<street_address>.*)\',\'(?P<city>.*)\',\'(?P<state>.*)\',\'(?P<country>[A-Z]{2})?\',\'(?P<phone>[\d\+\-]*)\',\'(?P<email>[A-Za-z0-9\@\-\_\.]*)\',\'(?P<income>[\d\.]*)\',\'(?P<bonus>[\d\.]*)\'')
m=myreg.search(line)
print(m.groupdict())

This works fine if the input line is:

'john','doe','searchers','some street','some city','some
state','HE','000-00-00','missing@123.abc','0.00','0'

Output is:

{'first_name': 'john', 'last_name': 'doe', 'employer': 'searchers',
'street_address': 'some street', 'city': 'some city', 'state': 'some
state', 'country': 'HE', 'phone': '000-00-00', 'email':
'missing@123.abc', 'income': '0.00', 'bonus': '0'}

However, things don't work if a line has empty fields such as:

'','','testemployer','','','a very long city's
nameaaaaaaaaaaaaaa','','HE','','','',''

For the above, the output becomes:

{'first_name': "','", 'last_name': 'testemployer', 'employer': '',
'street_address': '', 'city': "a very long city's nameaaaaaaaaaaaaaa",
'state': '', 'country': 'HE', 'phone': '', 'email': '', 'income': '',
'bonus': ''}

I tried setting the names as [^']*, but some names have apostrophes, and some employers can contain apostrophes and commas such as "O'Toole, McGyver and Scrooge Law".  However, from the data I saw, fields are definitely separated by "','". Given this, is there a way to have a regex pattern that would ensure that the captured groups do not contain "','"?

Body:
I spent a very long time on what I thought would be a correct regex, but I still could not get it to correctly process accept your string:

'','','testemployer','','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''

And then it dawned upon me that it appears you have an extra empty field before the city field (i.e. there should only be one field, the street_address, between the employer and city fields but you seem to have two. If this is truly how the data appears, then there is nothing I can do about it. But if you just made an error in copying the the problematic input, then ...

First of all, I have used a double-quote (") to code your regex string. This removes the necessity of having to escape all those single quote characters. There is also no need to escape special characters such as +, - and - when they appear within character class specifications. Finally, I have replaced \d with [0-9], which is different when you are dealing with Unicode. The former includes many values from languages that you might not find on telephones or currencies that you are interested in, such as ०१२३४५६७८९. But if you need \d instead of the usual digit 0 .. 9, then please just revert back.

Anyway, to handle the city field and fields like it that might have an embedded quote character, the way I have handled it is to use a negative lookahead assertion:

'(?P<field_name>(?:[^']|'(?!,))*)'

' - Matches a quote.

(?: - Start of a non-capturing group.

[^'] - Matches any non-quote character.

| - or

'(?!,) - Matches a quote if the next character is not a comma. In other words match a quote if this does not appear to be the closing quote that describes a field.

) - End of the non-capturing group.

* - Matches 0 or more characters defined by items 2 through 6 above.

' - Matches a quote.

The code:

import re

lines = [
    "'john','doe','searchers','some street','some city','some state','HE','000-00-00','missing@123.abc','0.00','0'",
    "'','','testemployer','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''"
    ]

myreg = re.compile(r"'(?P<first_name>(?:[^']|'(?!,))*)','(?P<last_name>(?:[^']|'(?!,))*)','(?P<employer>(?:[^']|'(?!,))*)','(?P<street_address>(?:[^']|'(?!,))*)','(?P<city>(?:[^']|'(?!,))*)','(?P<state>(?:[^']|'(?!,))*)','(?P<country>[A-Z]{2})?','(?P<phone>[0-9+-]*)','(?P<email>[A-Za-z0-9\@\-\_\.]*)','(?P<income>[0-9.]*)','(?P<bonus>[0-9.]*)'")
for line in lines:
    m = myreg.search(line)
    print(line)
    for k, v in m.groupdict().items():
        print (f'{k} -> {v}')
    print()

Prints:

'john','doe','searchers','some street','some city','some state','HE','000-00-00','missing@123.abc','0.00','0'
first_name -> john
last_name -> doe
employer -> searchers
street_address -> some street
city -> some city
state -> some state
country -> HE
phone -> 000-00-00
email -> missing@123.abc
income -> 0.00
bonus -> 0

'','','testemployer','','a very long city's nameaaaaaaaaaaaaaa','','HE','','','',''
first_name ->
last_name ->
employer -> testemployer
street_address ->
city -> a very long city's nameaaaaaaaaaaaaaa
state ->
country -> HE
phone ->
email ->
income ->
bonus ->


答:
You might get the expected results if you do this:</p>
```<code>n = input("input n: ")
n = n.split()
print(n, len(n))
</code>```

Title: .split() returns list of individual charachters instead of splitting it as the spaces

Body:
You might get the expected results if you do this:

n = input("input n: ")
n = n.split()
print(n, len(n))


问:
C++ Initializer lists
I have to fill a std::vector with elements of type struct MHD_OptionItem.
This struct have this implementation:

```<code>struct MHD_OptionItem
{
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
 };
</code>```

I have tried this way:

```<code> vector<struct MHD_OptionItem> iov;
 if(...)
     iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
 if(...)
     iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
 [....]
</code>```

but the g++ compiler, as expected, says to me:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I know that I can initialize a temporary struct and then pass it to the vector, but this method seems to me to be inefficient and not so elegant.

I can't change the struct inserting a constructor because this is not my code but a library included.

There is an elegant way to do this without using c++0x syntax?

答:
May be you can provide a constructor taking all the 3 parameters and then create it as follows:</p>

```<code>iov.push_back(MHD_OptionItem( MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
</code>```

Title: C++ Initializer lists

Body:
I have to fill a std::vector with elements of type struct MHD_OptionItem.
This struct have this implementation:

struct MHD_OptionItem
{
    enum MHD_OPTION option;
    intptr_t value;
    void *ptr_value;
 };

I have tried this way:

 vector<struct MHD_OptionItem> iov;
 if(...)
     iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
 if(...)
     iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
 [....]

but the g++ compiler, as expected, says to me:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I know that I can initialize a temporary struct and then pass it to the vector, but this method seems to me to be inefficient and not so elegant.

I can't change the struct inserting a constructor because this is not my code but a library included.

There is an elegant way to do this without using c++0x syntax?

Body:
May be you can provide a constructor taking all the 3 parameters and then create it as follows:

iov.push_back(MHD_OptionItem( MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));


问:
Detect mobile device in ASP.NET Core
I have an application which uses mobile views and desktop views as different html pages. Now I am moving that to Asp.Net core. I am not thinking about Bootstrap due to some technical reasons. I have to detect the request is from Mobile or not in StartUp to load respective Layout page. How can I achieve that ? Looking for something similar to IsMobileDevice. Already tried MvcDeviceDetector 0.1.0-t00349acaa. It didn't worked as I am using .net version 4.6.1.

答:
Simple solution

```<code>     public static class Extentions
        {
            public static bool IsMobile(string userAgent)
            {
                if (string.IsNullOrEmpty(userAgent))
                    return false;
    //tablet
                if (Regex.IsMatch(userAgent, "(tablet|ipad|playbook|silk)|(android(?!.*mobile))", RegexOptions.IgnoreCase))
                    return true;
    //mobile
                const string mobileRegex =
                    "blackberry|iphone|mobile|windows ce|opera mini|htc|sony|palm|symbianos|ipad|ipod|blackberry|bada|kindle|symbian|sonyericsson|android|samsung|nokia|wap|motor";

                if (Regex.IsMatch(userAgent, mobileRegex, RegexOptions.IgnoreCase)) return true;
   //not mobile
                return false;
            }
        }
</code>```

use:

```<code>var isMobile = Extentions.IsMobile(Context.Request.Headers["user-agent"].ToString());
</code>```

Title: Detect mobile device in ASP.NET Core

Body:
Simple solution

     public static class Extentions
        {
            public static bool IsMobile(string userAgent)
            {
                if (string.IsNullOrEmpty(userAgent))
                    return false;
    //tablet
                if (Regex.IsMatch(userAgent, "(tablet|ipad|playbook|silk)|(android(?!.*mobile))", RegexOptions.IgnoreCase))
                    return true;
    //mobile
                const string mobileRegex =
                    "blackberry|iphone|mobile|windows ce|opera mini|htc|sony|palm|symbianos|ipad|ipod|blackberry|bada|kindle|symbian|sonyericsson|android|samsung|nokia|wap|motor";

                if (Regex.IsMatch(userAgent, mobileRegex, RegexOptions.IgnoreCase)) return true;
   //not mobile
                return false;
            }
        }

use:

var isMobile = Extentions.IsMobile(Context.Request.Headers["user-agent"].ToString());


问:
How to set environment variable in node.js process when deploying with github action
I am trying to build an CI pipeline for my node.js server using github actions.

I just need to solve one issue.
I need to set environment variable, so that my node.js server can access the env variable via process.env

Below is the github action workflow file.

```<code>name: Build and Deploy to GKE

on:
  pull_request:
    branches:
      - master

# Environment variables available to all jobs and steps in this workflow
env:
  ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}

jobs:
  setup-build-publish-deploy:
    name: Setup, Build, Publish, and Deploy
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Apollo Schema Update
        env:
          ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}
        run: |
          sudo npm install
          sudo npm install -g apollo
          sudo npm run dev &
          sleep 3
          sudo apollo service:push --serviceURL=http://auth-cluster-ip-service --serviceName=auth --tag=master --endpoint=http://localhost:3051

</code>```

I have tried declaring environment variable both workflow level and job's level, but when I console.log(process.env.ENGINE_API_KEY), it returns undefined.

I also tried ENGINE_API_KEY=$ENGINE_API_KEY npm run dev & instead of npm run dev &. This works on my macbook, but with github action, it still returns undefined.

(I did store ENGINE_API_KEY in settings -> secret. worked fine for other variables)

答:
To run a Node.js script that accesses variables from process.env in your Github Action, use the following syntax:

```<code>- name: Create .env with Github Secrets and run script
  run: |
    touch .env
    echo ENV_VAR_1=$ENV_VAR_1 >> .env
    echo ENV_VAR_2=$ENV_VAR_2 >> .env
    npm run script-that-accesses-env-vars
  env:
    ENV_VAR_1: ${{ secrets.ENV_VAR_1 }}
    ENV_VAR_2: ${{ secrets.ENV_VAR_2 }}
</code>```

Echoing the ${{ secrets.ENV_VAR_1 }} directly to the .env file, instead of declaring the variables with the env key, didn't copy the correct value for me.

Body:
I am trying to build an CI pipeline for my node.js server using github actions.

I just need to solve one issue.
I need to set environment variable, so that my node.js server can access the env variable via process.env

Below is the github action workflow file.

name: Build and Deploy to GKE

on:
  pull_request:
    branches:
      - master

# Environment variables available to all jobs and steps in this workflow
env:
  ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}

jobs:
  setup-build-publish-deploy:
    name: Setup, Build, Publish, and Deploy
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Apollo Schema Update
        env:
          ENGINE_API_KEY: ${{ secrets.ENGINE_API_KEY }}
        run: |
          sudo npm install
          sudo npm install -g apollo
          sudo npm run dev &
          sleep 3
          sudo apollo service:push --serviceURL=http://auth-cluster-ip-service --serviceName=auth --tag=master --endpoint=http://localhost:3051

I have tried declaring environment variable both workflow level and job's level, but when I console.log(process.env.ENGINE_API_KEY), it returns undefined.

I also tried ENGINE_API_KEY=$ENGINE_API_KEY npm run dev & instead of npm run dev &. This works on my macbook, but with github action, it still returns undefined.

(I did store ENGINE_API_KEY in settings -> secret. worked fine for other variables)

Body:
To run a Node.js script that accesses variables from process.env in your Github Action, use the following syntax:

- name: Create .env with Github Secrets and run script
  run: |
    touch .env
    echo ENV_VAR_1=$ENV_VAR_1 >> .env
    echo ENV_VAR_2=$ENV_VAR_2 >> .env
    npm run script-that-accesses-env-vars
  env:
    ENV_VAR_1: ${{ secrets.ENV_VAR_1 }}
    ENV_VAR_2: ${{ secrets.ENV_VAR_2 }}

Echoing the ${{ secrets.ENV_VAR_1 }} directly to the .env file, instead of declaring the variables with the env key, didn't copy the correct value for me.


问:
Python ImageTk.PhotoImage slow loading of png with alphachannel
I wrote a little programm to load and show images.
Everything worked fine until i get to
the png file in the example (shade.png).

It takes 7 seven seconds to show this little pic.

Is there a bug in PhotoImage or did i miss some
parameter?

Here is my example code:

```<code>from PIL import Image, ImageTk
from six.moves import tkinter

import time
start = time.process_time()
print(time.process_time() - start)

root = tkinter.Tk()

img = Image.open('shade.png')
img = img.convert("RGBA")  # make sure, it has alphachannel

print(time.process_time() - start, "after image.open")

img = ImageTk.PhotoImage(img)
print(time.process_time() - start, "after PhotoImage")
</code>```

答:
On my research, i found out that this

is an old known bug in Tk() especially in Tk_PhotoPutBlock.
https://core.tcl-lang.org/tk/tktview/b9827ece14da1cd186c5816dc45abc29cf9b8a9c

As i found a workaround that helps in some cases,

i want to post it here.

For further testing
and bug hunting.

```<code>import time  # only to stop the time

from PIL import Image, ImageTk, ImageDraw
from six.moves import tkinter

HAVE_PIC = "no"  # "yes" # or let create a pic if you have none

root = tkinter.Tk()

def masking_1(image):  # faster

    mask = image.copy()
    mask.putalpha(1)

    mask.paste(image, (0, 0), image)

    # img.paste(img,(0, 0), mask)

    image = mask.copy()
    return image

def masking_2(image):  # better quality

    datas = image.getdata()

    newData = []
    for item in datas:
        if item[3] == 0:
            newData.append((item[0], item[1], item[2], 1))
        else:
            newData.append(item)

    image.putdata(newData)

    return image

def image_draw():  # creates the test pic

    width = 300  # the bigger the slower
    height = 300
    colour = "green"  # "#519ae7"
    image = Image.new('RGBA', (width, height))
    imd = ImageDraw.Draw(image, 'RGBA')

    y = 0
    while y < height:
        x = y % 2
        while x < width:
            imd.point((x, y), colour)
            x += 2
        y += 1
    return image

if HAVE_PIC == "yes":
    img = Image.open('shade.png')  # insert your problem pic
    img = img.convert("RGBA")  # make sure, it has alphachannel
else:
    img = image_draw()  # creates test pic

start = time.process_time()
print(time.process_time() - start, "after image.open")
# img.show()  # to show that it is the same image
photo_image = ImageTk.PhotoImage(img, master=root)  # too slow
print(time.process_time() - start, "after PhotoImage")

start = time.process_time()
print(time.process_time() - start, "before masking_1")
pic = masking_1(img)
# pic.show()
photo_image = ImageTk.PhotoImage(pic, master=root)
print(time.process_time() - start, "after masking_1")

start = time.process_time()
print(time.process_time() - start, "before masking_2")
pic = masking_2(img)
# pic.show()
photo_image = ImageTk.PhotoImage(pic, master=root)
print(time.process_time() - start, "after masking_2")
</code>```

Output on my PC:

0.0 after image.open

9.734375 after PhotoImage

0.0 before masking_1

0.0 after masking_1

0.0 before masking_2

0.03125 after masking_2

Body:
I wrote a little programm to load and show images.
Everything worked fine until i get to
the png file in the example (shade.png).

It takes 7 seven seconds to show this little pic.

Is there a bug in PhotoImage or did i miss some
parameter?

Here is my example code:

from PIL import Image, ImageTk
from six.moves import tkinter

import time
start = time.process_time()
print(time.process_time() - start)

root = tkinter.Tk()

img = Image.open('shade.png')
img = img.convert("RGBA")  # make sure, it has alphachannel

print(time.process_time() - start, "after image.open")

img = ImageTk.PhotoImage(img)
print(time.process_time() - start, "after PhotoImage")

Body:
On my research, i found out that this

is an old known bug in Tk() especially in Tk_PhotoPutBlock.
https://core.tcl-lang.org/tk/tktview/b9827ece14da1cd186c5816dc45abc29cf9b8a9c

As i found a workaround that helps in some cases,

i want to post it here.

For further testing
and bug hunting.

import time  # only to stop the time

from PIL import Image, ImageTk, ImageDraw
from six.moves import tkinter

HAVE_PIC = "no"  # "yes" # or let create a pic if you have none

root = tkinter.Tk()

def masking_1(image):  # faster

    mask = image.copy()
    mask.putalpha(1)

    mask.paste(image, (0, 0), image)

    # img.paste(img,(0, 0), mask)

    image = mask.copy()
    return image

def masking_2(image):  # better quality

    datas = image.getdata()

    newData = []
    for item in datas:
        if item[3] == 0:
            newData.append((item[0], item[1], item[2], 1))
        else:
            newData.append(item)

    image.putdata(newData)

    return image

def image_draw():  # creates the test pic

    width = 300  # the bigger the slower
    height = 300
    colour = "green"  # "#519ae7"
    image = Image.new('RGBA', (width, height))
    imd = ImageDraw.Draw(image, 'RGBA')

    y = 0
    while y < height:
        x = y % 2
        while x < width:
            imd.point((x, y), colour)
            x += 2
        y += 1
    return image

if HAVE_PIC == "yes":
    img = Image.open('shade.png')  # insert your problem pic
    img = img.convert("RGBA")  # make sure, it has alphachannel
else:
    img = image_draw()  # creates test pic

start = time.process_time()
print(time.process_time() - start, "after image.open")
# img.show()  # to show that it is the same image
photo_image = ImageTk.PhotoImage(img, master=root)  # too slow
print(time.process_time() - start, "after PhotoImage")

start = time.process_time()
print(time.process_time() - start, "before masking_1")
pic = masking_1(img)
# pic.show()
photo_image = ImageTk.PhotoImage(pic, master=root)
print(time.process_time() - start, "after masking_1")

start = time.process_time()
print(time.process_time() - start, "before masking_2")
pic = masking_2(img)
# pic.show()
photo_image = ImageTk.PhotoImage(pic, master=root)
print(time.process_time() - start, "after masking_2")

Output on my PC:

0.0 after image.open

9.734375 after PhotoImage

0.0 before masking_1

0.0 after masking_1

0.0 before masking_2

0.03125 after masking_2


答:
Assuming you cannot change the struct or you want to leave it a POD:

```<code>void f()
{
    struct {
        MHD_OptionItem operator ()(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) {
            MHD_OptionItem x = {opt, val, ptr};
            return x;
        }
    } gen;

     vector<struct MHD_OptionItem> iov;
     if(...)
         iov.push_back(gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
     if(...)
         iov.push_back(gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout));
     [....]
}
</code>```

Another solution:

```<code>    struct Gen : MHD_OptionItem {
        Gen(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) {
            option = opt;
            value = val;
            ptr_value ptr;
        }
    };

     vector<struct MHD_OptionItem> iov;
     if(...)
         iov.push_back(Gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
     if(...)
         iov.push_back(Gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout));
     [....]
</code>```

Title: C++ Initializer lists

Body:
Assuming you cannot change the struct or you want to leave it a POD:

void f()
{
    struct {
        MHD_OptionItem operator ()(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) {
            MHD_OptionItem x = {opt, val, ptr};
            return x;
        }
    } gen;

     vector<struct MHD_OptionItem> iov;
     if(...)
         iov.push_back(gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
     if(...)
         iov.push_back(gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout));
     [....]
}

Another solution:

    struct Gen : MHD_OptionItem {
        Gen(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) {
            option = opt;
            value = val;
            ptr_value ptr;
        }
    };

     vector<struct MHD_OptionItem> iov;
     if(...)
         iov.push_back(Gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL));
     if(...)
         iov.push_back(Gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout));
     [....]