问:
422 error when submitting a POST request to REST API via R httr
I am trying to submit a POST request to a REST API (OpenET) in R.

The curl command below works successfully when run from the shell:

```<code>curl -X 'POST' \
  'https://openet.dri.edu/timeseries/features/monthly' \
  -H 'accept: application/json' \
  -H 'Authorization: 'bla' \
  -H 'Content-Type: application/json' \
  -d '{
  "feature_collection_name": "CA",
  "field_ids": "[\"06324308\"]",
  "model": "eemetric",
  "variable": "et",
  "start_date": "2021-01-01",
  "end_date": "2022-12-31",
  "output_format": "csv",
  "units": "english"
}'
</code>```

But this R code using httr returns an error 422: Unprocessable Entity (WebDAV; RFC 4918).

```<code>library(httr)
library(jsonlite)

api_key = 'bla'

url <- 'https://openet.dri.edu/timeseries/features/monthly'

request_body <- data.frame(
  feature_collection_name = 'CA',
  field_ids     = "[\"06324308\"]",
  model         = 'eemetric',
  variable      = 'et',
  start_date    = '2021-01-01',
  end_date      = '2022-09-01',
  units         = 'english',
  output_format = 'json')

request_body_json <- toJSON(request_body, pretty = T, autounbox = T)

response <- POST(url,
                 add_headers(`accept` = 'application/json',
                             `Authorization` = 'api_key',
                             `Content-Type` = 'application/json'),
                 body = request_body_json)
</code>```

I have also tried specifying the headers differently:

```<code>  response <- POST(url,
                   add_headers(accept = 'application/json',
                               Authorization = 'bla',
                               content_type = 'application/json'),
                   body = request_body_json)
</code>```

I'd just like to know if I am using toJSON and POST correctly to reproduce the curl command above.

Body:
I am trying to submit a POST request to a REST API (OpenET) in R.

The curl command below works successfully when run from the shell:

curl -X 'POST' \
  'https://openet.dri.edu/timeseries/features/monthly' \
  -H 'accept: application/json' \
  -H 'Authorization: 'bla' \
  -H 'Content-Type: application/json' \
  -d '{
  "feature_collection_name": "CA",
  "field_ids": "[\"06324308\"]",
  "model": "eemetric",
  "variable": "et",
  "start_date": "2021-01-01",
  "end_date": "2022-12-31",
  "output_format": "csv",
  "units": "english"
}'

But this R code using httr returns an error 422: Unprocessable Entity (WebDAV; RFC 4918).

library(httr)
library(jsonlite)

api_key = 'bla'

url <- 'https://openet.dri.edu/timeseries/features/monthly'

request_body <- data.frame(
  feature_collection_name = 'CA',
  field_ids     = "[\"06324308\"]",
  model         = 'eemetric',
  variable      = 'et',
  start_date    = '2021-01-01',
  end_date      = '2022-09-01',
  units         = 'english',
  output_format = 'json')

request_body_json <- toJSON(request_body, pretty = T, autounbox = T)

response <- POST(url,
                 add_headers(`accept` = 'application/json',
                             `Authorization` = 'api_key',
                             `Content-Type` = 'application/json'),
                 body = request_body_json)

I have also tried specifying the headers differently:

  response <- POST(url,
                   add_headers(accept = 'application/json',
                               Authorization = 'bla',
                               content_type = 'application/json'),
                   body = request_body_json)

I'd just like to know if I am using toJSON and POST correctly to reproduce the curl command above.


来源: stackexchange

问:
Interactive Brokers - I keep getting invalid consumer while requesting OAuth token
I have a valid consumer key and I'm unable to get Interactive Brokers Web API OAuth to work.

{"error":"id: 3931, error: invalid consumer","statusCode":401}

The endpoint I'm trying to get to work: https://www.interactivebrokers.com/webtradingapi/doc.html#tag/OAuth/paths/~1oauth~1request_token/post

OAuth v1.0a specification https://oauth.net/core/1.0a/#auth_header_authorization

Am I missing something in my implementation?

It's also on GitHub.

var httpClient = new HttpClient
{
    BaseAddress = new Uri("https://www.interactivebrokers.com/tradingapi/v1/")
};

var restClient = new IBRestClient(httpClient);
var response = await restClient.RequestTokenAsync("xxxxx");

Console.WriteLine($"Response: {response}");

Console.ReadLine();

public sealed class IBRestClient
{
    private readonly HttpClient _httpClient;

    public IBRestClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async ValueTask<string> RequestTokenAsync(string consumerKey)
    {
        const string requestUri = "oauth/request_token";

        var request = new HttpRequestMessage(HttpMethod.Post, requestUri);

        var baseUrl = _httpClient.BaseAddress!.AbsoluteUri;
        var authorizationHeader = OAuthHelper.GetAuthorizationHeader($"{baseUrl}{requestUri}", "POST", consumerKey);

        var authSplit = authorizationHeader.Split(' ');
        request.Headers.Authorization = new AuthenticationHeaderValue(authSplit[0], authSplit[1]);

        var response = await _httpClient.SendAsync(request);
        return await response.Content.ReadAsStringAsync();
    }
}
```
<pre class="lang-cs prettyprint-override"><code>public static class OAuthHelper
{
    private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();

    public static string GetAuthorizationHeader(string uri, string method, string consumerKey)
    {
        var oauthParameters = new Dictionary<string, string>
        {
            { "oauth_consumer_key", consumerKey },
            { "oauth_signature_method", "RSA-SHA256" },
            { "oauth_timestamp", GetTimestamp() },
            { "oauth_nonce", GetNonce() },
            { "oauth_callback", "oob" }
        };

        // The request parameters are collected, sorted and concatenated into a normalized string
        var queryParameters = ExtractQueryParams(uri);
        var oauthParamString = GetOAuthParamString(queryParameters, oauthParameters);
        var baseUri = GetBaseUriString(uri);

        // Signature Base String
        var signatureBaseString = GetSignatureBaseString(baseUri, method, oauthParamString);

        var pem = File.ReadAllText("private_encryption.pem");
        var signingKey = RSA.Create();
        signingKey.ImportFromPem(pem);

        var signature = SignSignatureBaseString(signatureBaseString, Encoding.UTF8, signingKey);
        oauthParameters.Add("oauth_signature", signature);

        // Constructs and returns the Authorization header
        var sb = new StringBuilder();
        foreach (var param in oauthParameters)
        {
            sb
                .Append(sb.Length == 0 ? "OAuth " : ",")
                .Append(param.Key)
                .Append("=\"")
                .Append(ToUriRfc3986(param.Value))
                .Append('"');
        }

        return sb.ToString();
    }

    /// <summary>
    ///     Parse query parameters out of the URL.
    /// </summary>
    private static Dictionary<string, List<string>> ExtractQueryParams(string uri)
    {
        var queryParamCollection = new Dictionary<string, List<string>>();
        var beginIndex = uri.IndexOf('?');
        if (beginIndex <= 0)
        {
            return queryParamCollection;
        }

        var rawQueryString = uri[beginIndex..];
        var decodedQueryString = Uri.UnescapeDataString(rawQueryString);
        var mustEncode = !decodedQueryString.Equals(rawQueryString);

        var queryParams = rawQueryString.Split('&', '?');
        foreach (var queryParam in queryParams)
        {
            if (string.IsNullOrEmpty(queryParam))
            {
                continue;
            }

            var separatorIndex = queryParam.IndexOf('=');
            var key = separatorIndex < 0 ? queryParam : Uri.UnescapeDataString(queryParam[..separatorIndex]);
            var value = separatorIndex < 0
                ? string.Empty
                : Uri.UnescapeDataString(queryParam[(separatorIndex + 1)..]);
            var encodedKey = mustEncode ? ToUriRfc3986(key) : key;
            var encodedValue = mustEncode ? ToUriRfc3986(value) : value;

            if (!queryParamCollection.ContainsKey(encodedKey))
            {
                queryParamCollection[encodedKey] = new List<string>();
            }

            queryParamCollection[encodedKey].Add(encodedValue);
        }

        return queryParamCollection;
    }

    /// <summary>
    ///     Lexicographically sorts all parameters and concatenates them into a string.
    /// </summary>
    private static string GetOAuthParamString(IDictionary<string, List<string>> queryParameters,
        IDictionary<string, string> oauthParameters)
    {
        var sortedParameters = new SortedDictionary<string, List<string>>(queryParameters, StringComparer.Ordinal);
        foreach (var oauthParameter in oauthParameters)
        {
            sortedParameters[oauthParameter.Key] = new List<string> { oauthParameter.Value };
        }

        // Build the OAuth parameter string
        var parameterString = new StringBuilder();
        foreach (var parameter in sortedParameters)
        {
            var values = parameter.Value;
            values.Sort(StringComparer.Ordinal); // Keys with same name are sorted by their values
            foreach (var value in values)
            {
                parameterString
                    .Append(parameterString.Length > 0 ? "&" : string.Empty)
                    .Append(parameter.Key)
                    .Append('=')
                    .Append(value);
            }
        }

        return parameterString.ToString();
    }

    /// <summary>
    ///     Normalizes the URL.
    /// </summary>
    private static string GetBaseUriString(string uriString)
    {
        var uri = new Uri(uriString);
        var lowerCaseScheme = uri.Scheme.ToLower();
        var lowerCaseAuthority = uri.Authority.ToLower();
        var path = uri.AbsolutePath;

        if (("http".Equals(lowerCaseScheme) && uri.Port == 80) || ("https".Equals(lowerCaseScheme) && uri.Port == 443))
        {
            // Remove port if it matches the default for scheme
            var index = lowerCaseAuthority.LastIndexOf(':');
            if (index >= 0)
            {
                lowerCaseAuthority = lowerCaseAuthority[..index];
            }
        }

        if (string.IsNullOrEmpty(path))
        {
            path = "/";
        }

        return $"{lowerCaseScheme}://{lowerCaseAuthority}{path}"; // Remove query and fragment
    }

    /// <summary>
    ///     The Signature Base String is a consistent reproducible concatenation of the request elements into a single string.
    /// </summary>
    private static string GetSignatureBaseString(string baseUri, string httpMethod, string oauthParamString)
    {
        return httpMethod.ToUpper() // Uppercase HTTP method
               + "&" + ToUriRfc3986(baseUri) // Base URI
               + "&" + ToUriRfc3986(oauthParamString); // OAuth parameter string
    }

    /// <summary>
    ///     Signs the signature base string using an RSA private key.
    /// </summary>
    private static string SignSignatureBaseString(string baseString, Encoding encoding, RSA privateKey)
    {
        var hash = Sha256Digest(baseString, encoding);
        var signedHashValue = privateKey.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        return Convert.ToBase64String(signedHashValue);
    }

    /// <summary>
    ///     Percent encodes entities.
    /// </summary>
    private static string ToUriRfc3986(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return input;
        }

        var escaped = new StringBuilder(Uri.EscapeDataString(input));
        string[] uriRfc3986EscapedChars = { "!", "*", "'", "(", ")" };
        foreach (var escapedChar in uriRfc3986EscapedChars)
        {
            escaped.Replace(escapedChar, UriHelper.HexEscape(escapedChar[0]));
        }

        return escaped.ToString();
    }

    /// <summary>
    ///     Returns a cryptographic hash of the given input.
    /// </summary>
    private static byte[] Sha256Digest(string input, Encoding encoding)
    {
        var inputBytes = encoding.GetBytes(input);
        return SHA256.HashData(inputBytes);
    }

    /// <summary>
    ///     Generates a 16 char random string for replay protection.
    /// </summary>
    private static string GetNonce()
    {
        var data = new byte[8];
        Random.GetBytes(data);
        return BitConverter.ToString(data).Replace("-", string.Empty).ToLower();
    }

    /// <summary>
    ///     Returns UNIX Timestamp.
    /// </summary>
    private static string GetTimestamp()
    {
        return DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
    }
}

internal static class UriHelper
{
    private static readonly char[] HexUpperChars =
    {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    internal static string HexEscape(char character)
    {
        if (character > '\xff')
        {
            throw new ArgumentOutOfRangeException(nameof(character));
        }

        var chars = new char[3];
        var pos = 0;
        EscapeAsciiChar(character, chars, ref pos);
        return new string(chars);
    }

    private static void EscapeAsciiChar(char ch, char[] to, ref int pos)
    {
        to[pos++] = '%';
        to[pos++] = HexUpperChars[(ch & 0xf0) >> 4];
        to[pos++] = HexUpperChars[ch & 0xf];
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a valid consumer key and I'm unable to get Interactive Brokers Web API OAuth to work.

{"error":"id: 3931, error: invalid consumer","statusCode":401}

The endpoint I'm trying to get to work: https://www.interactivebrokers.com/webtradingapi/doc.html#tag/OAuth/paths/~1oauth~1request_token/post

OAuth v1.0a specification https://oauth.net/core/1.0a/#auth_header_authorization

Am I missing something in my implementation?

It's also on GitHub.

var httpClient = new HttpClient
{
    BaseAddress = new Uri("https://www.interactivebrokers.com/tradingapi/v1/")
};

var restClient = new IBRestClient(httpClient);
var response = await restClient.RequestTokenAsync("xxxxx");

Console.WriteLine($"Response: {response}");

Console.ReadLine();

public sealed class IBRestClient
{
    private readonly HttpClient _httpClient;

    public IBRestClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async ValueTask<string> RequestTokenAsync(string consumerKey)
    {
        const string requestUri = "oauth/request_token";

        var request = new HttpRequestMessage(HttpMethod.Post, requestUri);

        var baseUrl = _httpClient.BaseAddress!.AbsoluteUri;
        var authorizationHeader = OAuthHelper.GetAuthorizationHeader($"{baseUrl}{requestUri}", "POST", consumerKey);

        var authSplit = authorizationHeader.Split(' ');
        request.Headers.Authorization = new AuthenticationHeaderValue(authSplit[0], authSplit[1]);

        var response = await _httpClient.SendAsync(request);
        return await response.Content.ReadAsStringAsync();
    }
}

public static class OAuthHelper
{
    private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();

    public static string GetAuthorizationHeader(string uri, string method, string consumerKey)
    {
        var oauthParameters = new Dictionary<string, string>
        {
            { "oauth_consumer_key", consumerKey },
            { "oauth_signature_method", "RSA-SHA256" },
            { "oauth_timestamp", GetTimestamp() },
            { "oauth_nonce", GetNonce() },
            { "oauth_callback", "oob" }
        };

        // The request parameters are collected, sorted and concatenated into a normalized string
        var queryParameters = ExtractQueryParams(uri);
        var oauthParamString = GetOAuthParamString(queryParameters, oauthParameters);
        var baseUri = GetBaseUriString(uri);

        // Signature Base String
        var signatureBaseString = GetSignatureBaseString(baseUri, method, oauthParamString);

        var pem = File.ReadAllText("private_encryption.pem");
        var signingKey = RSA.Create();
        signingKey.ImportFromPem(pem);

        var signature = SignSignatureBaseString(signatureBaseString, Encoding.UTF8, signingKey);
        oauthParameters.Add("oauth_signature", signature);

        // Constructs and returns the Authorization header
        var sb = new StringBuilder();
        foreach (var param in oauthParameters)
        {
            sb
                .Append(sb.Length == 0 ? "OAuth " : ",")
                .Append(param.Key)
                .Append("=\"")
                .Append(ToUriRfc3986(param.Value))
                .Append('"');
        }

        return sb.ToString();
    }

    ///
    ///     Parse query parameters out of the URL.
    ///
    private static Dictionary<string, List<string>> ExtractQueryParams(string uri)
    {
        var queryParamCollection = new Dictionary<string, List<string>>();
        var beginIndex = uri.IndexOf('?');
        if (beginIndex <= 0)
        {
            return queryParamCollection;
        }

        var rawQueryString = uri[beginIndex..];
        var decodedQueryString = Uri.UnescapeDataString(rawQueryString);
        var mustEncode = !decodedQueryString.Equals(rawQueryString);

        var queryParams = rawQueryString.Split('&', '?');
        foreach (var queryParam in queryParams)
        {
            if (string.IsNullOrEmpty(queryParam))
            {
                continue;
            }

            var separatorIndex = queryParam.IndexOf('=');
            var key = separatorIndex < 0 ? queryParam : Uri.UnescapeDataString(queryParam[..separatorIndex]);
            var value = separatorIndex < 0
                ? string.Empty
                : Uri.UnescapeDataString(queryParam[(separatorIndex + 1)..]);
            var encodedKey = mustEncode ? ToUriRfc3986(key) : key;
            var encodedValue = mustEncode ? ToUriRfc3986(value) : value;

            if (!queryParamCollection.ContainsKey(encodedKey))
            {
                queryParamCollection[encodedKey] = new List<string>();
            }

            queryParamCollection[encodedKey].Add(encodedValue);
        }

        return queryParamCollection;
    }

    ///
    ///     Lexicographically sorts all parameters and concatenates them into a string.
    ///
    private static string GetOAuthParamString(IDictionary<string, List<string>> queryParameters,
        IDictionary<string, string> oauthParameters)
    {
        var sortedParameters = new SortedDictionary<string, List<string>>(queryParameters, StringComparer.Ordinal);
        foreach (var oauthParameter in oauthParameters)
        {
            sortedParameters[oauthParameter.Key] = new List<string> { oauthParameter.Value };
        }

        // Build the OAuth parameter string
        var parameterString = new StringBuilder();
        foreach (var parameter in sortedParameters)
        {
            var values = parameter.Value;
            values.Sort(StringComparer.Ordinal); // Keys with same name are sorted by their values
            foreach (var value in values)
            {
                parameterString
                    .Append(parameterString.Length > 0 ? "&" : string.Empty)
                    .Append(parameter.Key)
                    .Append('=')
                    .Append(value);
            }
        }

        return parameterString.ToString();
    }

    ///
    ///     Normalizes the URL.
    ///
    private static string GetBaseUriString(string uriString)
    {
        var uri = new Uri(uriString);
        var lowerCaseScheme = uri.Scheme.ToLower();
        var lowerCaseAuthority = uri.Authority.ToLower();
        var path = uri.AbsolutePath;

        if (("http".Equals(lowerCaseScheme) && uri.Port == 80) || ("https".Equals(lowerCaseScheme) && uri.Port == 443))
        {
            // Remove port if it matches the default for scheme
            var index = lowerCaseAuthority.LastIndexOf(':');
            if (index >= 0)
            {
                lowerCaseAuthority = lowerCaseAuthority[..index];
            }
        }

        if (string.IsNullOrEmpty(path))
        {
            path = "/";
        }

        return $"{lowerCaseScheme}://{lowerCaseAuthority}{path}"; // Remove query and fragment
    }

    ///
    ///     The Signature Base String is a consistent reproducible concatenation of the request elements into a single string.
    ///
    private static string GetSignatureBaseString(string baseUri, string httpMethod, string oauthParamString)
    {
        return httpMethod.ToUpper() // Uppercase HTTP method
               + "&" + ToUriRfc3986(baseUri) // Base URI
               + "&" + ToUriRfc3986(oauthParamString); // OAuth parameter string
    }

    ///
    ///     Signs the signature base string using an RSA private key.
    ///
    private static string SignSignatureBaseString(string baseString, Encoding encoding, RSA privateKey)
    {
        var hash = Sha256Digest(baseString, encoding);
        var signedHashValue = privateKey.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        return Convert.ToBase64String(signedHashValue);
    }

    ///
    ///     Percent encodes entities.
    ///
    private static string ToUriRfc3986(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return input;
        }

        var escaped = new StringBuilder(Uri.EscapeDataString(input));
        string[] uriRfc3986EscapedChars = { "!", "*", "'", "(", ")" };
        foreach (var escapedChar in uriRfc3986EscapedChars)
        {
            escaped.Replace(escapedChar, UriHelper.HexEscape(escapedChar[0]));
        }

        return escaped.ToString();
    }

    ///
    ///     Returns a cryptographic hash of the given input.
    ///
    private static byte[] Sha256Digest(string input, Encoding encoding)
    {
        var inputBytes = encoding.GetBytes(input);
        return SHA256.HashData(inputBytes);
    }

    ///
    ///     Generates a 16 char random string for replay protection.
    ///
    private static string GetNonce()
    {
        var data = new byte[8];
        Random.GetBytes(data);
        return BitConverter.ToString(data).Replace("-", string.Empty).ToLower();
    }

    ///
    ///     Returns UNIX Timestamp.
    ///
    private static string GetTimestamp()
    {
        return DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
    }
}

internal static class UriHelper
{
    private static readonly char[] HexUpperChars =
    {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    internal static string HexEscape(char character)
    {
        if (character > '\xff')
        {
            throw new ArgumentOutOfRangeException(nameof(character));
        }

        var chars = new char[3];
        var pos = 0;
        EscapeAsciiChar(character, chars, ref pos);
        return new string(chars);
    }

    private static void EscapeAsciiChar(char ch, char[] to, ref int pos)
    {
        to[pos++] = '%';
        to[pos++] = HexUpperChars[(ch & 0xf0) >> 4];
        to[pos++] = HexUpperChars[ch & 0xf];
    }
}


问:
Unable to initialize com.vaadin.flow.spring.VaadinServletContextInitializer$VaadinAppShellContextListener
I have try to deploy my app to Heroku, but it's not working. I have try to follow the vaadin instructions, but it's not working. What's the problem?

Error on heroku logs:

Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener]

java.lang.RuntimeException: Unable to initialize com.vaadin.flow.spring.VaadinServletContextInitializer$VaadinAppShellContextListener
2023-01-04T22:30:36.972557+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$FailFastServletContextListener.contextInitialized(VaadinServletContextInitializer.java:192) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T22:30:36.972560+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.lambda$contextInitialized$0(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T22:30:36.972561+00:00 app[web.1]: at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
2023-01-04T22:30:36.972562+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
...
2023-01-04T20:56:40.962495+00:00 app[web.1]: 2023-01-04 21:56:40.962  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 35531 (http)
2023-01-04T20:56:40.981852+00:00 app[web.1]: 2023-01-04 21:56:40.981  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-01-04T20:56:40.982068+00:00 app[web.1]: 2023-01-04 21:56:40.981  INFO 4 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2023-01-04T20:56:41.145481+00:00 app[web.1]: 2023-01-04 21:56:41.145  INFO 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-01-04T20:56:41.145634+00:00 app[web.1]: 2023-01-04 21:56:41.145  INFO 4 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4610 ms
2023-01-04T20:56:41.391728+00:00 app[web.1]: 2023-01-04 21:56:41.391 ERROR 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener]
2023-01-04T20:56:41.391750+00:00 app[web.1]:
2023-01-04T20:56:41.391753+00:00 app[web.1]: java.lang.RuntimeException: Unable to initialize com.vaadin.flow.spring.VaadinServletContextInitializer$VaadinAppShellContextListener
2023-01-04T20:56:41.391773+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$FailFastServletContextListener.contextInitialized(VaadinServletContextInitializer.java:192) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391775+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.lambda$contextInitialized$0(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391776+00:00 app[web.1]: at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
2023-01-04T20:56:41.391776+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391778+00:00 app[web.1]: at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4767) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391778+00:00 app[web.1]: at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391779+00:00 app[web.1]: at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391779+00:00 app[web.1]: at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391780+00:00 app[web.1]: at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.68.jar!/:na]
...
2023-01-04T20:56:41.391815+00:00 app[web.1]: ... 50 common frames omitted
2023-01-04T20:56:41.391815+00:00 app[web.1]:
2023-01-04T20:56:41.392195+00:00 app[web.1]: 2023-01-04 21:56:41.392 ERROR 4 --- [           main] o.apache.catalina.core.StandardContext   : One or more listeners failed to start. Full details will be found in the appropriate container log file
2023-01-04T20:56:41.392932+00:00 app[web.1]: 2023-01-04 21:56:41.392 ERROR 4 --- [           main] o.apache.catalina.core.StandardContext   : Context [] startup failed due to previous errors
2023-01-04T20:56:41.446993+00:00 app[web.1]: 2023-01-04 21:56:41.446  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2023-01-04T20:56:41.452376+00:00 app[web.1]: 2023-01-04 21:56:41.452  WARN 4 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2023-01-04T20:56:41.464604+00:00 app[web.1]: 2023-01-04 21:56:41.464  INFO 4 --- [           main] ConditionEvaluationReportLoggingListener :
2023-01-04T20:56:41.464605+00:00 app[web.1]:
2023-01-04T20:56:41.464606+00:00 app[web.1]: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-01-04T20:56:41.509555+00:00 app[web.1]: 2023-01-04 21:56:41.509 ERROR 4 --- [           main] o.s.boot.SpringApplication               : Application run failed
...
2023-01-04T20:56:41.509566+00:00 app[web.1]: Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2023-01-04T20:56:41.509566+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:142) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509566+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509567+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:479) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509567+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:211) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509568+00:00 app[web.1]: at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:184) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509568+00:00 app[web.1]: at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:162) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509569+00:00 app[web.1]: ... 17 common frames omitted
2023-01-04T20:56:41.509569+00:00 app[web.1]: Caused by: java.lang.IllegalStateException: StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[] failed to start
2023-01-04T20:56:41.509570+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.rethrowDeferredStartupExceptions(TomcatWebServer.java:187) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509570+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:126) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509570+00:00 app[web.1]: ... 22 common frames omitted
2023-01-04T20:56:41.509571+00:00 app[web.1]:
2023-01-04T20:56:41.752738+00:00 heroku[web.1]: State changed from starting to crashed

```

On my computer is working perfectly and i don't receive any error message.

Body:
I have try to deploy my app to Heroku, but it's not working. I have try to follow the vaadin instructions, but it's not working. What's the problem?

Error on heroku logs:

Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener]

java.lang.RuntimeException: Unable to initialize com.vaadin.flow.spring.VaadinServletContextInitializer$VaadinAppShellContextListener
2023-01-04T22:30:36.972557+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$FailFastServletContextListener.contextInitialized(VaadinServletContextInitializer.java:192) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T22:30:36.972560+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.lambda$contextInitialized$0(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T22:30:36.972561+00:00 app[web.1]: at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
2023-01-04T22:30:36.972562+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
...
2023-01-04T20:56:40.962495+00:00 app[web.1]: 2023-01-04 21:56:40.962  INFO 4 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 35531 (http)
2023-01-04T20:56:40.981852+00:00 app[web.1]: 2023-01-04 21:56:40.981  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-01-04T20:56:40.982068+00:00 app[web.1]: 2023-01-04 21:56:40.981  INFO 4 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2023-01-04T20:56:41.145481+00:00 app[web.1]: 2023-01-04 21:56:41.145  INFO 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-01-04T20:56:41.145634+00:00 app[web.1]: 2023-01-04 21:56:41.145  INFO 4 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4610 ms
2023-01-04T20:56:41.391728+00:00 app[web.1]: 2023-01-04 21:56:41.391 ERROR 4 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener]
2023-01-04T20:56:41.391750+00:00 app[web.1]:
2023-01-04T20:56:41.391753+00:00 app[web.1]: java.lang.RuntimeException: Unable to initialize com.vaadin.flow.spring.VaadinServletContextInitializer$VaadinAppShellContextListener
2023-01-04T20:56:41.391773+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$FailFastServletContextListener.contextInitialized(VaadinServletContextInitializer.java:192) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391775+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.lambda$contextInitialized$0(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391776+00:00 app[web.1]: at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) ~[na:na]
2023-01-04T20:56:41.391776+00:00 app[web.1]: at com.vaadin.flow.spring.VaadinServletContextInitializer$CompositeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:214) ~[vaadin-spring-23.3.0.jar!/:na]
2023-01-04T20:56:41.391778+00:00 app[web.1]: at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4767) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391778+00:00 app[web.1]: at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391779+00:00 app[web.1]: at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391779+00:00 app[web.1]: at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.68.jar!/:na]
2023-01-04T20:56:41.391780+00:00 app[web.1]: at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.68.jar!/:na]
...
2023-01-04T20:56:41.391815+00:00 app[web.1]: ... 50 common frames omitted
2023-01-04T20:56:41.391815+00:00 app[web.1]:
2023-01-04T20:56:41.392195+00:00 app[web.1]: 2023-01-04 21:56:41.392 ERROR 4 --- [           main] o.apache.catalina.core.StandardContext   : One or more listeners failed to start. Full details will be found in the appropriate container log file
2023-01-04T20:56:41.392932+00:00 app[web.1]: 2023-01-04 21:56:41.392 ERROR 4 --- [           main] o.apache.catalina.core.StandardContext   : Context [] startup failed due to previous errors
2023-01-04T20:56:41.446993+00:00 app[web.1]: 2023-01-04 21:56:41.446  INFO 4 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2023-01-04T20:56:41.452376+00:00 app[web.1]: 2023-01-04 21:56:41.452  WARN 4 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2023-01-04T20:56:41.464604+00:00 app[web.1]: 2023-01-04 21:56:41.464  INFO 4 --- [           main] ConditionEvaluationReportLoggingListener :
2023-01-04T20:56:41.464605+00:00 app[web.1]:
2023-01-04T20:56:41.464606+00:00 app[web.1]: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-01-04T20:56:41.509555+00:00 app[web.1]: 2023-01-04 21:56:41.509 ERROR 4 --- [           main] o.s.boot.SpringApplication               : Application run failed
...
2023-01-04T20:56:41.509566+00:00 app[web.1]: Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2023-01-04T20:56:41.509566+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:142) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509566+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509567+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:479) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509567+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:211) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509568+00:00 app[web.1]: at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:184) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509568+00:00 app[web.1]: at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:162) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509569+00:00 app[web.1]: ... 17 common frames omitted
2023-01-04T20:56:41.509569+00:00 app[web.1]: Caused by: java.lang.IllegalStateException: StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[] failed to start
2023-01-04T20:56:41.509570+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.rethrowDeferredStartupExceptions(TomcatWebServer.java:187) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509570+00:00 app[web.1]: at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:126) ~[spring-boot-2.7.5.jar!/:2.7.5]
2023-01-04T20:56:41.509570+00:00 app[web.1]: ... 22 common frames omitted
2023-01-04T20:56:41.509571+00:00 app[web.1]:
2023-01-04T20:56:41.752738+00:00 heroku[web.1]: State changed from starting to crashed

On my computer is working perfectly and i don't receive any error message.


问:
How do I configure two instances of log4j2 to work in a Spring 5.3.18 project via web.xml file, hosted on Tomcat 9
I need to use two separate log4j loggers in my Spring project running on tomcat 9. I started by getting the dependencies and placing in my pom.xml:

```<code>    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>2.17.1</version>
    </dependency>
</code>```

Then I created the xml log configuration file, and afterwards in my web.xml I placed the following:

```<code><listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<context-param>
    <param-name>log4jContextName</param-name>
    <param-value>PersonLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:../conf/properties/PersonLogConfig.xml</param-value>
</context-param>
</code>```

Then, in my application I used it like so:

```<code>import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

static final Logger LOG = LogManager.getLogger("PersonLogger." + PersonAgentImpl.class);

LOG.info("working");
</code>```

This all worked without issue, the folder and log file were created and logged to as expected. However when I tried to add a second logger- it would not work. Neither folder/log file would be created. (they both work separately if I comment out one though)

This is how I attempted to set up two instances in my web.xml:

```<code><listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<!-- PersonLogger -->
<context-param>
    <param-name>log4jContextName1</param-name>
    <param-value>PersonLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration1</param-name>
    <param-value>file:../conf/properties/PersonLogConfig.xml</param-value>
</context-param>

<!-- AnimalLogger -->
<context-param>
    <param-name>log4jContextName2</param-name>
    <param-value>AnimalLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration2</param-name>
    <param-value>file:../conf/properties/AnimalLogConfig.xml</param-value>
</context-param>
</code>```

Any ideas on what might be wrong? From what I understand as long as the param names are different than 2 instances of log4j should be able to work at the same time- using the context name to specify which one is used.

Body:
I need to use two separate log4j loggers in my Spring project running on tomcat 9. I started by getting the dependencies and placing in my pom.xml:

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>2.17.1</version>
    </dependency>

Then I created the xml log configuration file, and afterwards in my web.xml I placed the following:

<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<context-param>
    <param-name>log4jContextName</param-name>
    <param-value>PersonLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:../conf/properties/PersonLogConfig.xml</param-value>
</context-param>

Then, in my application I used it like so:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

static final Logger LOG = LogManager.getLogger("PersonLogger." + PersonAgentImpl.class);

LOG.info("working");

This all worked without issue, the folder and log file were created and logged to as expected. However when I tried to add a second logger- it would not work. Neither folder/log file would be created. (they both work separately if I comment out one though)

This is how I attempted to set up two instances in my web.xml:

<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<filter>
    <filter-name>log4jServletFilter</filter-name>
    <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>log4jServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<context-param>
    <param-name>log4jContextName1</param-name>
    <param-value>PersonLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration1</param-name>
    <param-value>file:../conf/properties/PersonLogConfig.xml</param-value>
</context-param>

<context-param>
    <param-name>log4jContextName2</param-name>
    <param-value>AnimalLogger</param-value>
</context-param>
<context-param>
    <param-name>log4jConfiguration2</param-name>
    <param-value>file:../conf/properties/AnimalLogConfig.xml</param-value>
</context-param>

Any ideas on what might be wrong? From what I understand as long as the param names are different than 2 instances of log4j should be able to work at the same time- using the context name to specify which one is used.


问:
How to render portable block from sanity in vue app
I'm testing around with sanity right now and I am trying to display portable text of sanity on my vue frontend. Sadly it does not work as expected.

So i use the npm package sanity-blocks-vue-component to render the portable text and the normal fetch function which is privided in the docs of sanity.

This is my file where I fetch it successfully but the SanityBlock does nothing:

<template>

        <SanityBlocks :block="content.impressumContent" />

</template>

```
<p>And that's the scheme that I fetch:</p>
<pre class="lang-js prettyprint-override"><code>export default {
    name: 'impressum',
    type: 'document',
    title: 'Impressum',
    fields: [
        {
            name: 'impressumContent',
            title: 'Impressum Content',
            type: 'array',
            of: [
                {
                    type: 'block'
                },
            ]
        }
    ]
}
</code>```

I don't get my head around why this isn't working. Hopefully somone can help me.

Thaanks:))

Body:
I'm testing around with sanity right now and I am trying to display portable text of sanity on my vue frontend. Sadly it does not work as expected.

So i use the npm package sanity-blocks-vue-component to render the portable text and the normal fetch function which is privided in the docs of sanity.

This is my file where I fetch it successfully but the SanityBlock does nothing:

<template>

        <SanityBlocks :block="content.impressumContent" />

</template>

And that's the scheme that I fetch:

export default {
    name: 'impressum',
    type: 'document',
    title: 'Impressum',
    fields: [
        {
            name: 'impressumContent',
            title: 'Impressum Content',
            type: 'array',
            of: [
                {
                    type: 'block'
                },
            ]
        }
    ]
}

I don't get my head around why this isn't working. Hopefully somone can help me.

Thaanks:))


问:
Hovering over one element change style background color opacity of another element
I have this code:

        body  {
            background-color: darkgray;
            font-size: 2em;
         }

        div  {
            margin: 2em;
        }

        #outer  {
            background-color: purple;
            border: 2px solid transparent;
        }

        #outer:hover  {
            cursor: pointer;
            opacity: 40%;
            border: 2px solid yellow;
        }

        #first:hover  {
            color: red;
            font-weight: bold;
            cursor: pointer;
        }

        #first:hover #outer  {
            background-color: green;
            opacity: 100%;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="outer">
        Outer

        <div id="first">
            First
        </div>
    </div></code>```

It shows this:

When I hover over #outer it shows this:

When I hover over #first it shows this:

I'd like it to make the #outer background green and its opacity 100%, when the #first is hovered over.

However, it doesn't happen - when #first is hovered, the #outer background stays purple and its opacity stays 40%. How do I fix it?

EDIT:

I'm OK with updating all elements (for instance if there are more outer elements than one). And I don't want to use Javascript!

Body:
I have this code:

        body  {
            background-color: darkgray;
            font-size: 2em;
         }

        div  {
            margin: 2em;
        }

        #outer  {
            background-color: purple;
            border: 2px solid transparent;
        }

        #outer:hover  {
            cursor: pointer;
            opacity: 40%;
            border: 2px solid yellow;
        }

        #first:hover  {
            color: red;
            font-weight: bold;
            cursor: pointer;
        }

        #first:hover #outer  {
            background-color: green;
            opacity: 100%;
        }

        Outer

            First

It shows this:

When I hover over #outer it shows this:

When I hover over #first it shows this:

I'd like it to make the #outer background green and its opacity 100%, when the #first is hovered over.

However, it doesn't happen - when #first is hovered, the #outer background stays purple and its opacity stays 40%. How do I fix it?

EDIT:

I'm OK with updating all elements (for instance if there are more outer elements than one). And I don't want to use Javascript!


问:
Combination analysis help in R
Essentially, I have a dataframe of 300 patients each with 25 recorded variables. I am trying to work out the most common combinations of these variables using the UpsetR package which worked fine for me previously when I did the same for another dataframe with the same number of patients and 14 variables. However, now I keep getting an errors saying (as well as it taking 4hours to compile the code just for me to get this error:

```<code>
Error: vector memory exhausted (limit reached?)
Error during wrapup: vector memory exhausted (limit reached?)
Error: no more error handlers available (recursive errors?); invoking 'abort' restart
</code>```

Is this just due to the fact that there is too many combinations/ too many sets that it can't compute the combinations.

Here is the code:

```<code>
  UpSetR::upset(
    sets = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y"),
    order.by = "freq",
    empty.intersections = "on",
    nintersects = 10,
    nsets = 20,
    number.angles = 0,
    point.size = 3.5,
    line.size = 2,
    mainbar.y.label = "Professionals Combinations",
    sets.x.label = "Patient frequency")

</code>```

I am a newb with R and havent been able to understand completely what nsets and nintersects and empty.intersections mean from the documentation and unsure if this could have an underpinning to solving my problem. Could it be that I could change some of these functions which might allow me to actually calculate the combinations?

If this doesnt work, how would you try to go around this issue.

Any advice would be great.

Title: Combination analysis help in R

Body:
Essentially, I have a dataframe of 300 patients each with 25 recorded variables. I am trying to work out the most common combinations of these variables using the UpsetR package which worked fine for me previously when I did the same for another dataframe with the same number of patients and 14 variables. However, now I keep getting an errors saying (as well as it taking 4hours to compile the code just for me to get this error:

Error: vector memory exhausted (limit reached?)
Error during wrapup: vector memory exhausted (limit reached?)
Error: no more error handlers available (recursive errors?); invoking 'abort' restart

Is this just due to the fact that there is too many combinations/ too many sets that it can't compute the combinations.

Here is the code:

  UpSetR::upset(
    sets = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y"),
    order.by = "freq",
    empty.intersections = "on",
    nintersects = 10,
    nsets = 20,
    number.angles = 0,
    point.size = 3.5,
    line.size = 2,
    mainbar.y.label = "Professionals Combinations",
    sets.x.label = "Patient frequency")

I am a newb with R and havent been able to understand completely what nsets and nintersects and empty.intersections mean from the documentation and unsure if this could have an underpinning to solving my problem. Could it be that I could change some of these functions which might allow me to actually calculate the combinations?

If this doesnt work, how would you try to go around this issue.

Any advice would be great.


问:
How do I extract the type of a particular property in a given type?
So let's say I have a type Foo defined as:

```<code>type Foo = {
    bar: string;
    xxx: {
        abc: string;
        def: number;
    };
};
</code>```

How do I extract the type of my property xxx to define let's say a parameter of the same shape as the xxx property of my Foo type?

I've come up with this dirty hack, but I'm sure there has to be a proper way? I can't seem to find it in the documentation though!

```<code>const _ = "anything" as unknown as Foo;
type XXXType = typeof _.xxx;
</code>```

Body:
So let's say I have a type Foo defined as:

type Foo = {
    bar: string;
    xxx: {
        abc: string;
        def: number;
    };
};

How do I extract the type of my property xxx to define let's say a parameter of the same shape as the xxx property of my Foo type?

I've come up with this dirty hack, but I'm sure there has to be a proper way? I can't seem to find it in the documentation though!

const _ = "anything" as unknown as Foo;
type XXXType = typeof _.xxx;


问:
I can't see the output from Serial.print. Why?
I have been trying to setup a program analyzing stock-prices for quite some time. I didn't manage to get any output however, so I decided to do some testing with simpler programs... MUCH simple programs. Right now I can't even manage to get "Hello World" to work, using platformio. If someone could tell my why I would appreciate it a lot.

main.cpp:

```<code>#include <Arduino.h>

void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.print("Hello World!");
}
</code>```

platformio.ini:

```<code>[env:esp32-poe-iso]
platform = espressif32
board = esp32-poe-iso
framework = arduino
monitor_speed = 115200
</code>```

I have tried changing the baud-rate and setting different COM-ports as the monitor-port. I don't manage to get any good result / any result at all however, and I am running out of ideas to why

Body:
I have been trying to setup a program analyzing stock-prices for quite some time. I didn't manage to get any output however, so I decided to do some testing with simpler programs... MUCH simple programs. Right now I can't even manage to get "Hello World" to work, using platformio. If someone could tell my why I would appreciate it a lot.

main.cpp:

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.print("Hello World!");
}

platformio.ini:

[env:esp32-poe-iso]
platform = espressif32
board = esp32-poe-iso
framework = arduino
monitor_speed = 115200

I have tried changing the baud-rate and setting different COM-ports as the monitor-port. I don't manage to get any good result / any result at all however, and I am running out of ideas to why


问:
Ordinal Regression- error: infinite or missing values in x
I am trying to run an ordinal regression on a dataset that I removed the missing values from. When I try to get a summary of the model, I find the following error message:

error in svd (x): infinite or missing values in 'x'.

I am very new to rstudio, and not sure how to go about correcting this problem.

```<code>complete_model <- polr(hlthstat~  r_incomeall, train, Hess = TRUE)
summary(complete_model)
</code>```

this is what appears in the console when i run the code:

complete_model <- polr(hlthstat~  r_incomeall, train, Hess = TRUE)
Warning message:
glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(complete_model)
Error in svd(X) : infinite or missing values in 'x'

Body:
I am trying to run an ordinal regression on a dataset that I removed the missing values from. When I try to get a summary of the model, I find the following error message:

error in svd (x): infinite or missing values in 'x'.

I am very new to rstudio, and not sure how to go about correcting this problem.

complete_model <- polr(hlthstat~  r_incomeall, train, Hess = TRUE)
summary(complete_model)

this is what appears in the console when i run the code:

complete_model <- polr(hlthstat~  r_incomeall, train, Hess = TRUE)
Warning message:
glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(complete_model)
Error in svd(X) : infinite or missing values in 'x'


问:
Ho do I disallow urls for specific countries in robots.txt file?
I have multi-site in WordPress and have a setup like this

domain.com (main version for Australia)
domain.com/us
domain.com/eu
...

I want if Australian users to search on google, which should only show the main URL domain.com and if someone in USA and Canada searches, only domain.com/us should appear in google search results, similarly, all Europeans, should be able to see domain.com/eu version only.

What can be the best optimal approach?

Thanks.

Currently, I'm using a redirection plugin which I think blocks all the URLs to crawl on google. So, figured out that maybe the robots.txt file could fix the issue.


问:
How can I redirect the URL google OAuth in Unauthorized to the frontend nestjs?
i made a check if the user exist will return null but i can not redirect google/redirect URl to forntEnd with error handler user already exist


问:
R markdown PDF renders in Rstudio but not in R console
Update: After hours worth of trying stuff, I figured it out from this thread. Basically, I just had to detach the package KableExtra in between each call to render(), and all of the PDFs rendered in RConsole.

I have a series of R markdown documents that render in RStudio by clicking on the "Knit" button. I'm trying to write a script that will render all of the documents at once instead of waiting to click the button after each one renders, but when I run it in the Console, I keep getting errors.

Calls to render are as follows:
render(input="path/markdown_file.Rmd",output_format="pdf_document")

Here's what I know:

Both RStudio and R Console are running R version 4.2.2

Both are using pandoc version 2.19.2

Both have current versions of the rmarkdown package

Both are using pdflatex to render the PDFs

Both are rendering HTML files using html_document with no issues

The error message I'm getting in RConsole is:
`! Undefined control sequence.
 ...r}[t]{llrrrrrrrrrrrrrrrrl} \toprule \textbf {metric} & \textbf... l.693 \end{tabular}}

```<code>Error: LaTeX failed to compile markdown_file.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See markdown_file.log for more info.`
</code>```

The only difference I'm seeing is a slight difference in the calls to pandoc:

```<code>`"C:/Program Files/RStudio/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS markdown_file.knit.md --to latex --from markdown+autolink_bare_uris+tex_math_single_backslash --output markdown_file.tex --lua-filter "C:\Users\XXXXXXX\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\XXXXXXX\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\latex-div.lua" --embed-resources --standalone --highlight-style tango --pdf-engine pdflatex --variable graphics *--include-in-header "C:\Users\XXXXXXX\AppData\Local\Temp\RtmpoJICVK\rmarkdown-str196079161973.html"*`
</code>```

The Knit button in RStudio has the last part in italics, but the R Console does not. It's some reference to a temp file, but it gets deleted immediately so I can't see what's in it.

Any ideas on how to fix this?

Body:
Update: After hours worth of trying stuff, I figured it out from this thread. Basically, I just had to detach the package KableExtra in between each call to render(), and all of the PDFs rendered in RConsole.

I have a series of R markdown documents that render in RStudio by clicking on the "Knit" button. I'm trying to write a script that will render all of the documents at once instead of waiting to click the button after each one renders, but when I run it in the Console, I keep getting errors.

Calls to render are as follows:
render(input="path/markdown_file.Rmd",output_format="pdf_document")

Here's what I know:

Both RStudio and R Console are running R version 4.2.2

Both are using pandoc version 2.19.2

Both have current versions of the rmarkdown package

Both are using pdflatex to render the PDFs

Both are rendering HTML files using html_document with no issues

The error message I'm getting in RConsole is:
`! Undefined control sequence.
 ...r}[t]{llrrrrrrrrrrrrrrrrl} \toprule \textbf {metric} & \textbf... l.693 \end{tabular}}

Error: LaTeX failed to compile markdown_file.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See markdown_file.log for more info.`

The only difference I'm seeing is a slight difference in the calls to pandoc:

`"C:/Program Files/RStudio/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS markdown_file.knit.md --to latex --from markdown+autolink_bare_uris+tex_math_single_backslash --output markdown_file.tex --lua-filter "C:\Users\XXXXXXX\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\XXXXXXX\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\latex-div.lua" --embed-resources --standalone --highlight-style tango --pdf-engine pdflatex --variable graphics *--include-in-header "C:\Users\XXXXXXX\AppData\Local\Temp\RtmpoJICVK\rmarkdown-str196079161973.html"*`

The Knit button in RStudio has the last part in italics, but the R Console does not. It's some reference to a temp file, but it gets deleted immediately so I can't see what's in it.

Any ideas on how to fix this?


问:
Why is my CORS policy suddenly not allowing access to my server?

So my website, www.carpediction.com started blocking frontend (hosted on Netlify) requests to the backend node/express server (hosted on Heroku), with no code changes to the CORS setup.

Repo: https://github.com/relativelyIntuitive/CarpeDiction/

This is my CORS setup block in the 'server/server.js' file:

```<code> if (process.env.NODE_ENV === 'production') {
     app.use(cors({ credentials: true, origin:
          'https://www.carpediction.com' }));
 } else {
     app.use(cors({ credentials: true, origin:
          'http://localhost:3000' }));
 }
</code>```

This is the error message logged to the console when accessing www.carpediction.com:
"Access to XMLHttpRequest at 'https://carpe-diction.herokuapp.com/api/wotd/latest' from origin 'https://www.carpediction.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

My question is this: What is the issue with my current CORS policy setup? The origin listed as blocked in the error message is the same allowed-origin specified in the server's CORS setup, and yet the header is missing. No code was changed in my repo that initiated this issue, one day I just noticed my site wasn't working and investigated. My best guess is that some CORS syntax was changed, but I haven't been able to find any documentation of such a change that would break my server.

If there is any better information I can provide, please let me know! Thanks!

-Zack

P.S.

I even tried to allow all origins with CORS by specifying "*" as the origin in the policy. This still did not work. The error message was the same.

Body:
So my website, www.carpediction.com started blocking frontend (hosted on Netlify) requests to the backend node/express server (hosted on Heroku), with no code changes to the CORS setup.

Repo: https://github.com/relativelyIntuitive/CarpeDiction/

This is my CORS setup block in the 'server/server.js' file:

 if (process.env.NODE_ENV === 'production') {
     app.use(cors({ credentials: true, origin:
          'https://www.carpediction.com' }));
 } else {
     app.use(cors({ credentials: true, origin:
          'http://localhost:3000' }));
 }

This is the error message logged to the console when accessing www.carpediction.com:
"Access to XMLHttpRequest at 'https://carpe-diction.herokuapp.com/api/wotd/latest' from origin 'https://www.carpediction.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

My question is this: What is the issue with my current CORS policy setup? The origin listed as blocked in the error message is the same allowed-origin specified in the server's CORS setup, and yet the header is missing. No code was changed in my repo that initiated this issue, one day I just noticed my site wasn't working and investigated. My best guess is that some CORS syntax was changed, but I haven't been able to find any documentation of such a change that would break my server.

If there is any better information I can provide, please let me know! Thanks!

-Zack

P.S.

I even tried to allow all origins with CORS by specifying "*" as the origin in the policy. This still did not work. The error message was the same.


问:
Error: Could not find the correct Provider<Controller> above this DashBoardScreen Widget
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read is in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that DashBoardScreen is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

```<code>Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>().toString()),
  );
}
</code>```

consider using builder like so:

```<code>Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context, child) {
      // No longer throws
      return Text(context.watch<Example>().toString());
    }
  );
}

</code>```

Here i have attached main dart file.

```<code>import 'package:device_preview/device_preview.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:lifemaster/Components/app_constants.dart';
import 'package:lifemaster/Components/app_theme.dart';
import 'package:lifemaster/Screens/Dashboard/controllers/controller.dart';
import 'package:lifemaster/utility/language/localization_service.dart';
import 'package:lifemaster/utility/provider_logger.dart';
import 'package:lifemaster/view_router.dart';
import 'package:lifemaster/view_routes.dart';
import 'package:provider/provider.dart';

void main() async{
  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    ProviderScope(
        observers:  [ ProviderLogger()],
        child:DevicePreview(
          enabled: false,
          builder: (context) =>  MyApp() ,
        )),

  );
}

class MyApp extends HookWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
        title: AppConstant.appTitle,
        debugShowCheckedModeBanner: false,
        theme:  appPrimaryTheme(),
        locale: LocalizationService.currentLocale,
        fallbackLocale: LocalizationService.fallbackLocale,
        translations: LocalizationService(),
        initialRoute: ViewRoutes.initial,
        getPages: ViewRouter.routes,
    );

  }
}

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lifemaster/CommonUi/responsive.dart';
import 'package:lifemaster/Components/app_styles.dart';
import 'package:lifemaster/Components/asset_images.dart';
import 'package:lifemaster/Components/palette.dart';
import 'package:lifemaster/viewModel/authenticationViewModel.dart';
import 'package:lifemaster/view_routes.dart';

class LoginScreen extends HookConsumerWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context,WidgetRef ref) {
    var _formKey = GlobalKey<FormState>();
    var userNameController = TextEditingController();
    var passwordController= TextEditingController();
    final state = ref.watch(authenticationViewModel);
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Palette.backColor,
      body: SizedBox(
        height: height,
        width: width,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Responsive.isMobile(context) ? const SizedBox() : Expanded(
              child: Container(
                height: height,
                color: Palette.backgroundColor,
                child: Center(
                  child: Image.asset(AssetPNGImages.logop,
                    width: 300,
                  )
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: height,
                margin: EdgeInsets.symmetric(horizontal: Responsive.isMobile(context)? height * 0.032 : height * 0.12),
                color: Palette.backColor,
                child: SingleChildScrollView(
                  padding: const EdgeInsets.only(bottom: 40.0),
                    child: Form(
                      key: _formKey,
                    child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(height: height * 0.2),

                      SizedBox(height: height * 0.02),

                      SizedBox(height: height * 0.064),

                      Padding(
                        padding: const EdgeInsets.only(left: 16.0),
                        child: Text('User Name',
                          style: ralewayStyle.copyWith(
                            fontSize: 14.0,
                            color: Palette.textBlackTitle,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      const SizedBox(height: 6.0),
                      Container(
                        height: 50.0,
                        width: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16.0),
                          color: Palette.textBox,
                        ),
                        child: TextFormField(
                          cursorColor: Palette.appColor,
                          controller: userNameController,
                          style: ralewayStyle.copyWith(
                            fontWeight: FontWeight.w400,
                            color: Colors.black,
                            fontSize: 12.0,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            prefixIcon: const Icon(
                              Icons.account_circle,
                              color: Palette.appColor,
                            ),
                            contentPadding: const EdgeInsets.only(top: 16.0),
                            hintText: 'Enter User Name',
                            hintStyle: ralewayStyle.copyWith(
                              fontWeight: FontWeight.w400,
                              fontSize: 12.0,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.014),
                      Padding(
                        padding: const EdgeInsets.only(left: 16.0),
                        child: Text('Password',
                          style: ralewayStyle.copyWith(
                            fontSize: 14.0,
                            color: Palette.textBlackTitle,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      const SizedBox(height: 6.0),
                      Container(
                        height: 50.0,
                        width: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16.0),
                          color: Palette.textBox,
                        ),
                        child: TextFormField(
                          cursorColor: Palette.cursor,
                          controller: passwordController,
                          style: ralewayStyle.copyWith(
                            fontWeight: FontWeight.w400,
                           /* color: AppColors.blueDarkColor,*/
                            fontSize: 12.0,
                          ),
                          obscureText: true,

                          decoration: InputDecoration(
                            border: InputBorder.none,
                            suffixIcon: IconButton(
                              onPressed: (){
                              },
                              icon: const Icon(
                                Icons.visibility_off,
                                color: Palette.icon,
                              ),
                            ),
                            prefixIcon: const Icon(
                              Icons.lock,
                              color: Palette.icon,
                            ),
                            contentPadding: const EdgeInsets.only(top: 16.0),
                            hintText: 'Enter Password',
                            hintStyle: ralewayStyle.copyWith(
                              fontWeight: FontWeight.w400,
                              /*color: AppColors.blueDarkColor.withOpacity(0.5),*/
                              fontSize: 12.0,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.03),
                      Align(
                        alignment: Alignment.centerRight,
                        child: TextButton(
                          onPressed: (){},
                          child: Text('Forgot Password?',
                            style: ralewayStyle.copyWith(
                              fontSize: 12.0,
                              color: Colors.black,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.05),
                      Material(
                        color: Colors.transparent,
                        child: InkWell(
                          onTap: (){
                            /*if(_formKey.currentState!.validate()){
                              ref.read(authenticationViewModel.notifier).apiLoginCall(LoginRequestModel(userName: userNameController.text.toString(),password: passwordController.text.toString()));
                            }*/
                           //if(state is SuccessState){

                              Navigator.pushNamed(context, ViewRoutes.dashBoardPage);
                          //  }
                          },
                          borderRadius: BorderRadius.circular(16.0),
                          child: Ink(
                            padding: const EdgeInsets.symmetric(horizontal: 70.0, vertical: 18.0),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16.0),
                              color: Palette.button,
                            ),
                            child: Text('Login',
                              style: ralewayStyle.copyWith(
                                fontWeight: FontWeight.w700,
                                color: Palette.textSubTitleWhite,
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:lifemaster/CommonUi/responsive.dart';
import 'package:lifemaster/Screens/Dashboard/components/dashboard_content.dart';
import 'package:lifemaster/Screens/Dashboard/constants/constants.dart';
import 'package:lifemaster/Screens/Dashboard/controllers/controller.dart';
import 'package:provider/provider.dart';
import 'components/drawer_menu.dart';

class DashBoardScreen extends StatelessWidget {
  const DashBoardScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgColor,
      drawer: const DrawerMenu(),
      key: context.read<Controller>().scaffoldKey,
      body: SafeArea(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (Responsive.isDesktop(context)) const Expanded(child: DrawerMenu(),),
            const Expanded(
              flex: 5,
              child: DashboardContent(),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

The provider you are trying to read is in a different route.

Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

Make sure that DashBoardScreen is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.

For example, instead of:

Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>().toString()),
  );
}

consider using builder like so:

Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context, child) {
      // No longer throws
      return Text(context.watch<Example>().toString());
    }
  );
}

Here i have attached main dart file.

import 'package:device_preview/device_preview.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:lifemaster/Components/app_constants.dart';
import 'package:lifemaster/Components/app_theme.dart';
import 'package:lifemaster/Screens/Dashboard/controllers/controller.dart';
import 'package:lifemaster/utility/language/localization_service.dart';
import 'package:lifemaster/utility/provider_logger.dart';
import 'package:lifemaster/view_router.dart';
import 'package:lifemaster/view_routes.dart';
import 'package:provider/provider.dart';

void main() async{
  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    ProviderScope(
        observers:  [ ProviderLogger()],
        child:DevicePreview(
          enabled: false,
          builder: (context) =>  MyApp() ,
        )),

  );
}

class MyApp extends HookWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
        title: AppConstant.appTitle,
        debugShowCheckedModeBanner: false,
        theme:  appPrimaryTheme(),
        locale: LocalizationService.currentLocale,
        fallbackLocale: LocalizationService.fallbackLocale,
        translations: LocalizationService(),
        initialRoute: ViewRoutes.initial,
        getPages: ViewRouter.routes,
    );

  }
}

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lifemaster/CommonUi/responsive.dart';
import 'package:lifemaster/Components/app_styles.dart';
import 'package:lifemaster/Components/asset_images.dart';
import 'package:lifemaster/Components/palette.dart';
import 'package:lifemaster/viewModel/authenticationViewModel.dart';
import 'package:lifemaster/view_routes.dart';

class LoginScreen extends HookConsumerWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context,WidgetRef ref) {
    var _formKey = GlobalKey<FormState>();
    var userNameController = TextEditingController();
    var passwordController= TextEditingController();
    final state = ref.watch(authenticationViewModel);
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Palette.backColor,
      body: SizedBox(
        height: height,
        width: width,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Responsive.isMobile(context) ? const SizedBox() : Expanded(
              child: Container(
                height: height,
                color: Palette.backgroundColor,
                child: Center(
                  child: Image.asset(AssetPNGImages.logop,
                    width: 300,
                  )
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: height,
                margin: EdgeInsets.symmetric(horizontal: Responsive.isMobile(context)? height * 0.032 : height * 0.12),
                color: Palette.backColor,
                child: SingleChildScrollView(
                  padding: const EdgeInsets.only(bottom: 40.0),
                    child: Form(
                      key: _formKey,
                    child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(height: height * 0.2),

                      SizedBox(height: height * 0.02),

                      SizedBox(height: height * 0.064),

                      Padding(
                        padding: const EdgeInsets.only(left: 16.0),
                        child: Text('User Name',
                          style: ralewayStyle.copyWith(
                            fontSize: 14.0,
                            color: Palette.textBlackTitle,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      const SizedBox(height: 6.0),
                      Container(
                        height: 50.0,
                        width: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16.0),
                          color: Palette.textBox,
                        ),
                        child: TextFormField(
                          cursorColor: Palette.appColor,
                          controller: userNameController,
                          style: ralewayStyle.copyWith(
                            fontWeight: FontWeight.w400,
                            color: Colors.black,
                            fontSize: 12.0,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            prefixIcon: const Icon(
                              Icons.account_circle,
                              color: Palette.appColor,
                            ),
                            contentPadding: const EdgeInsets.only(top: 16.0),
                            hintText: 'Enter User Name',
                            hintStyle: ralewayStyle.copyWith(
                              fontWeight: FontWeight.w400,
                              fontSize: 12.0,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.014),
                      Padding(
                        padding: const EdgeInsets.only(left: 16.0),
                        child: Text('Password',
                          style: ralewayStyle.copyWith(
                            fontSize: 14.0,
                            color: Palette.textBlackTitle,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      const SizedBox(height: 6.0),
                      Container(
                        height: 50.0,
                        width: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16.0),
                          color: Palette.textBox,
                        ),
                        child: TextFormField(
                          cursorColor: Palette.cursor,
                          controller: passwordController,
                          style: ralewayStyle.copyWith(
                            fontWeight: FontWeight.w400,
                           /* color: AppColors.blueDarkColor,*/
                            fontSize: 12.0,
                          ),
                          obscureText: true,

                          decoration: InputDecoration(
                            border: InputBorder.none,
                            suffixIcon: IconButton(
                              onPressed: (){
                              },
                              icon: const Icon(
                                Icons.visibility_off,
                                color: Palette.icon,
                              ),
                            ),
                            prefixIcon: const Icon(
                              Icons.lock,
                              color: Palette.icon,
                            ),
                            contentPadding: const EdgeInsets.only(top: 16.0),
                            hintText: 'Enter Password',
                            hintStyle: ralewayStyle.copyWith(
                              fontWeight: FontWeight.w400,
                              /*color: AppColors.blueDarkColor.withOpacity(0.5),*/
                              fontSize: 12.0,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.03),
                      Align(
                        alignment: Alignment.centerRight,
                        child: TextButton(
                          onPressed: (){},
                          child: Text('Forgot Password?',
                            style: ralewayStyle.copyWith(
                              fontSize: 12.0,
                              color: Colors.black,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: height * 0.05),
                      Material(
                        color: Colors.transparent,
                        child: InkWell(
                          onTap: (){
                            /*if(_formKey.currentState!.validate()){
                              ref.read(authenticationViewModel.notifier).apiLoginCall(LoginRequestModel(userName: userNameController.text.toString(),password: passwordController.text.toString()));
                            }*/
                           //if(state is SuccessState){

                              Navigator.pushNamed(context, ViewRoutes.dashBoardPage);
                          //  }
                          },
                          borderRadius: BorderRadius.circular(16.0),
                          child: Ink(
                            padding: const EdgeInsets.symmetric(horizontal: 70.0, vertical: 18.0),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16.0),
                              color: Palette.button,
                            ),
                            child: Text('Login',
                              style: ralewayStyle.copyWith(
                                fontWeight: FontWeight.w700,
                                color: Palette.textSubTitleWhite,
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:lifemaster/CommonUi/responsive.dart';
import 'package:lifemaster/Screens/Dashboard/components/dashboard_content.dart';
import 'package:lifemaster/Screens/Dashboard/constants/constants.dart';
import 'package:lifemaster/Screens/Dashboard/controllers/controller.dart';
import 'package:provider/provider.dart';
import 'components/drawer_menu.dart';

class DashBoardScreen extends StatelessWidget {
  const DashBoardScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgColor,
      drawer: const DrawerMenu(),
      key: context.read<Controller>().scaffoldKey,
      body: SafeArea(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (Responsive.isDesktop(context)) const Expanded(child: DrawerMenu(),),
            const Expanded(
              flex: 5,
              child: DashboardContent(),
            )
          ],
        ),
      ),
    );
  }
}


问:
Is there a function for linear-link NB1 regression in python?
I would like to build a linear link negative binomial 1 glm model for some data (where negative binomial 1 means that the dispersion parameter is of the form (1 + a)*mean).  This means I need to simultaneously control both the link function form and the dispersion parameter form.

Is there a library/function I can use to control both?

Python's statsmodels negative binomial regression implementation is an NB2 model, which assumes dispersion is of the form mean + a*mean^2 (see https://www.statsmodels.org/stable/glm.html), and I don't see a way to change this.

I am also aware of NegativeBinomialP, which allows me to specify a form for the dispersion parameter, but not for the link function, which defaults to log-link.


问:
Mentioning people by ID on telegram via telethon doesnt work
I've been trying to automate mentions by using telethon. However, I had some issues with users who don't have a username.

Currently I am mentioning them by their ID like so:
await client.send_message('me', '[name](tg://user?id=1234567890)')
However, for some users it seems to work, while for others, it doesn't.

It works for this one for example. Here a message is send which says "name" which is a link to the person:

```<code>User(id=1234567890, is_self=False, contact=False, mutual_contact=False, deleted=False, bot=False, bot_chat_history=False, bot_nochats=False, verified=False, restricted=False, min=False, bot_inline_geo=False, support=False, scam=False, apply_min_photo=True, fake=False, bot_attach_menu=False, premium=False, attach_menu_enabled=False, access_hash=1981206873891957364, first_name='A', last_name='A', username=None, phone=None, photo=UserProfilePhoto(photo_id=5208509202147465385, dc_id=2, has_video=False, stripped_thumb=b'\x01\x08\x08\xa2S\xe4\x04\x0d\x9c\xbd\x14QM\r\xb3'), status=UserStatusRecently(), bot_info_version=None, restriction_reason=[], bot_inline_placeholder=None, lang_code=None, emoji_status=None, usernames=[])
</code>```

However, for this it does not work, even tho it's mostly the same:

```<code>User(id=0987654321, is_self=False, contact=False, mutual_contact=False, deleted=False, bot=False, bot_chat_history=False, bot_nochats=False, verified=False, restricted=False, min=False, bot_inline_geo=False, support=False, scam=False, apply_min_photo=True, fake=False, bot_attach_menu=False, premium=False, attach_menu_enabled=False, access_hash=-221428125202661083, first_name='B', last_name='B', username=None, phone=None, photo=None, status=UserStatusRecently(), bot_info_version=None, restriction_reason=[], bot_inline_placeholder=None, lang_code=None, emoji_status=None, usernames=[])
</code>```

I've even asked ChatGPT. I ensured that:

The IDs are correct

The user has not blocked me

The user is a member of the group

The group is not a supergroup or channel

Syntax is correct according to the telegram documentation

I have no idea what the issue could be

Body:
I've been trying to automate mentions by using telethon. However, I had some issues with users who don't have a username.

Currently I am mentioning them by their ID like so:
await client.send_message('me', '[name](tg://user?id=1234567890)')
However, for some users it seems to work, while for others, it doesn't.

It works for this one for example. Here a message is send which says "name" which is a link to the person:

User(id=1234567890, is_self=False, contact=False, mutual_contact=False, deleted=False, bot=False, bot_chat_history=False, bot_nochats=False, verified=False, restricted=False, min=False, bot_inline_geo=False, support=False, scam=False, apply_min_photo=True, fake=False, bot_attach_menu=False, premium=False, attach_menu_enabled=False, access_hash=1981206873891957364, first_name='A', last_name='A', username=None, phone=None, photo=UserProfilePhoto(photo_id=5208509202147465385, dc_id=2, has_video=False, stripped_thumb=b'\x01\x08\x08\xa2S\xe4\x04\x0d\x9c\xbd\x14QM\r\xb3'), status=UserStatusRecently(), bot_info_version=None, restriction_reason=[], bot_inline_placeholder=None, lang_code=None, emoji_status=None, usernames=[])

However, for this it does not work, even tho it's mostly the same:

User(id=0987654321, is_self=False, contact=False, mutual_contact=False, deleted=False, bot=False, bot_chat_history=False, bot_nochats=False, verified=False, restricted=False, min=False, bot_inline_geo=False, support=False, scam=False, apply_min_photo=True, fake=False, bot_attach_menu=False, premium=False, attach_menu_enabled=False, access_hash=-221428125202661083, first_name='B', last_name='B', username=None, phone=None, photo=None, status=UserStatusRecently(), bot_info_version=None, restriction_reason=[], bot_inline_placeholder=None, lang_code=None, emoji_status=None, usernames=[])

I've even asked ChatGPT. I ensured that:

The IDs are correct

The user has not blocked me

The user is a member of the group

The group is not a supergroup or channel

Syntax is correct according to the telegram documentation

I have no idea what the issue could be


问:
How do you download "Open Source" software when a vendor sends you to github
I'm trying to download javascript software for a javascript timepicker and I get directed from the vendor site to github. After downloading source code, the supplied example pages link to a "/dist" folder that doesn't seem to exist. I was expecting something like jquery where you download or link to .js and .css software for your project. I must be missing something. How do I get the software files for the github projects?

Any help greatly appreciated.